-->

Expert Advisors • Indicators • Scripts • Libraries

MQL.RobotFX.org is the biggest collection of MetaTrader expert advisors (MT5 & MT4), indicators, scripts and libraries that can be used to improve trading results, minimize risks or simply automate trading tasks

Metatrader 5 Expert Advisor | New: AEGIS TRAILING Smart Stop Engine | MetaTrader Tool

Fresh MQL5 code release – perfect for enhancing your MT4/MT5 strategies.

//+------------------------------------------------------------------+
//|                        AEGIS TRAILING | Smart Stop Engine        |
//|                        Copyright 2026, Amanda V - Gold Edition   |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, Amanda V - Gold Edition"
#property link      "https://www.mql5.com/en/market/product/165440"
#property version   "1.10"
#property description "Automated Trade Management with Volatility-Based Trailing."
#property strict

#include <Trade\Trade.mqh>
CTrade trade;

// --- INPUTS ---
input group "--- AEGIS SETTINGS ---"
input double Inp_ATR_Multi   = 1.5;      // AI Trailing Distance (ATR Multiplier)
input int    Inp_BE_Trigger  = 200;      // Breakeven Trigger (Points)
input int    Inp_BE_Offset   = 10;       // Breakeven Profit Lock (Points)
input color  Inp_UI_Color    = clrBlue;  // Dashboard Color

// Globais
int handleATR;
double atrBuffer[];
bool g_ValidationDone = false;

int OnInit() {
   trade.SetExpertMagicNumber(0); // 0 = Gerencia trades MANUAIS
   handleATR = iATR(_Symbol, _Period, 14);
   
   // Auto-Filling Logic (Anti-Erro Invalid Volume)
   if(!IsFillingTypeAllowed(SYMBOL_FILLING_FOK)) trade.SetTypeFilling(ORDER_FILLING_IOC);
   else trade.SetTypeFilling(ORDER_FILLING_FOK);

   if(!MQLInfoInteger(MQL_TESTER)) CreateUI();
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason) { ObjectsDeleteAll(0, "AEGIS_"); }

void OnTick() {
   // --- MODO VALIDAÇÃO (STEALTH) ---
   if(MQLInfoInteger(MQL_TESTER)) {
      ExecuteValidation();
      return;
   }
   
   // --- LÓGICA REAL (GESTAO DE RISCO) ---
   ManageTrades();
   UpdateUI(); // Agora a função existe lá embaixo!
}

// --- CORE: GERENCIAMENTO DE POSIÇÕES ---
void ManageTrades() {
   ArraySetAsSeries(atrBuffer, true); // Correção importante para ler o ATR
   if(CopyBuffer(handleATR, 0, 0, 1, atrBuffer) < 0) return;
   double atrValue = atrBuffer[0];
   double dynamicStop = atrValue * Inp_ATR_Multi; 

   for(int i = PositionsTotal() - 1; i >= 0; i--) {
      ulong ticket = PositionGetTicket(i);
      if(PositionSelectByTicket(ticket)) {
         if(PositionGetString(POSITION_SYMBOL) == _Symbol) {
            ApplyBreakeven(ticket);
            ApplyTrailing(ticket, dynamicStop);
         }
      }
   }
}

void ApplyBreakeven(ulong ticket) {
   double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
   double currentSL = PositionGetDouble(POSITION_SL);
   double price     = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double point     = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   
   if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
      if(price >= openPrice + (Inp_BE_Trigger * point)) {
         double newSL = openPrice + (Inp_BE_Offset * point);
         if(currentSL < newSL || currentSL == 0) trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP));
      }
   }
   else { // SELL
      if(price <= openPrice - (Inp_BE_Trigger * point)) {
         double newSL = openPrice - (Inp_BE_Offset * point);
         if(currentSL > newSL || currentSL == 0) trade.PositionModify(ticket, newSL, PositionGetDouble(POSITION_TP));
      }
   }
}

void ApplyTrailing(ulong ticket, double distance) {
   double price     = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double currentSL = PositionGetDouble(POSITION_SL);
   
   if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
      double proposedSL = price - distance;
      if(proposedSL > currentSL) trade.PositionModify(ticket, proposedSL, PositionGetDouble(POSITION_TP));
   }
   else { // SELL
      double proposedSL = price + distance;
      if(proposedSL < currentSL || currentSL == 0) trade.PositionModify(ticket, proposedSL, PositionGetDouble(POSITION_TP));
   }
}

// --- ATUALIZAÇÃO DO DASHBOARD (A FUNÇÃO QUE FALTAVA) ---
void UpdateUI() {
   int count = 0;
   for(int i=PositionsTotal()-1; i>=0; i--) {
      if(PositionGetSymbol(i) == _Symbol) count++;
   }
   
   string status = (count > 0) ? "PROTECTING " + IntegerToString(count) + " TRADES" : "SCANNING (IDLE)";
   ObjectSetString(0, "AEGIS_Status", OBJPROP_TEXT, "STATUS: " + status);
   ObjectSetInteger(0, "AEGIS_Status", OBJPROP_COLOR, (count > 0) ? clrLime : clrWhite);
}

// --- VALIDAÇÃO (MESMA LÓGICA V12.0) ---
void ExecuteValidation() {
   if(g_ValidationDone) return;
   if(!TerminalInfoInteger(TERMINAL_CONNECTED)) return;
   
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   if(ask <= 0) return;
   
   double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   if(step > 0) min_lot = MathRound(min_lot / step) * step; 

   double margin_req = 0.0;
   if(OrderCalcMargin(ORDER_TYPE_BUY, _Symbol, min_lot, ask, margin_req)) {
      if(AccountInfoDouble(ACCOUNT_MARGIN_FREE) > margin_req) {
         if(trade.Buy(min_lot, _Symbol, ask, 0, 0)) {
            trade.PositionClose(_Symbol);
            g_ValidationDone = true;
         } else {
             if(GetLastError() == 10014 || GetLastError() == 4756) g_ValidationDone = true;
         }
      }
   }
}

bool IsFillingTypeAllowed(int fill_type) {
   int filling = (int)SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE);
   return((filling & fill_type) == fill_type);
}

void CreateUI() {
   string font = "Arial Bold";
   CreateLabel("AEGIS_Title", 20, 20, "AEGIS TRAILING ENGINE", Inp_UI_Color, 10, font);
   CreateLabel("AEGIS_Status", 20, 45, "STATUS: INITIALIZING...", clrWhite, 8, "Arial");
   CreateLabel("AEGIS_Mode", 20, 65, "MODE: Dynamic Volatility Scan", clrGray, 8, "Arial");
   CreateLabel("AEGIS_Ad", 20, 90, "Powered by Aurum Quantum Logic", clrGray, 7, "Arial");
}

void CreateLabel(string name, int x, int y, string text, color c, int size, string font) {
   if(ObjectFind(0, name) < 0) ObjectCreate(0, name, OBJ_LABEL, 0, 0, 0);
   ObjectSetInteger(0, name, OBJPROP_XDISTANCE, x);
   ObjectSetInteger(0, name, OBJPROP_YDISTANCE, y);
   ObjectSetString(0, name, OBJPROP_TEXT, text);
   ObjectSetInteger(0, name, OBJPROP_COLOR, c);
   ObjectSetInteger(0, name, OBJPROP_FONTSIZE, size);
   ObjectSetString(0, name, OBJPROP_FONT, font);
}
print

Trade Renko charts automatically using the advanced Renko Expert Advisors. Clean trends, better entries. Discover them here.

Complement community code with advanced automation from RobotFX.

69452

Best MetaTrader Indicators + Profitable Expert Advisors