Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

I want to optimize a mt5 ea for consistency, monthly Profit withdrawals. How to back…

  1. User

    I want to optimize a mt5 ea for consistency, monthly Profit withdrawals. How to back test and optimize? On what period/interval? I will use this with prop firm capital and these are the conditions: 4% daily loss , 8% overall loss.

  2. Assistant

    Optimizing an EA on MT5 for consistent monthly profit and to comply with strict prop firm rules (4% daily loss, 8% overall loss) requires a careful balance between profitability, low drawdowns, and robustness. Here’s a detailed step-by-step guide on how to backtest and optimize your EA with these objectives and constraints in mind.


    1. Understanding the Prop Firm Conditions

    • 4% daily loss limit: Your EA should not draw down more than 4% in a single trading day.
    • 8% overall loss limit: Your maximum drawdown over the entire testing/forward trading period should not exceed 8%.

    2. Data and Time Period Selection

    • Quality Data: Use high-quality, 99% tick data or at least 1-minute data with error correction for backtesting.

    • Backtest Timeframe:

      • Minimum 2-3 years historical data to include various market regimes (trending, ranging, volatile, news events).
      • Split data:
        • In-sample (training): 70-80% of the data (e.g., first 2 years).
        • Out-of-sample (testing): 20-30% of the data (e.g., last 6-9 months).
    • Optimization timeframe: Choose the in-sample to perform strategy optimization and parameter tuning, then validate using out-of-sample data to avoid curve-fitting.


    3. Choosing Optimization Parameters

    • Select parameters that have a direct impact on risk and trade frequency, such as:

      • Stop loss / Take profit levels
      • Position sizing parameters (fixed lot, % risk, etc.)
      • Entry signal parameters (moving average periods, indicator thresholds, etc.)
      • Trailing stop parameters
    • Avoid optimizing parameters that might cause overfitting or unrealistic trading behaviors.


    4. Parameter Constraints Based on Prop Firm Rules

    • Implement risk management in the EA code or as parameters, for example:
      • Max daily loss check (EA stops trading or reduces position size if loss approaches 4%)
      • Max drawdown check (use account equity monitoring inside EA)
      • Position sizing to keep risk per trade small (e.g., 0.5% or less of equity)

    5. Backtesting Setup in MT5

    • Use the Strategy Tester in MT5 with Every Tick based on real ticks to get the most accurate simulation.
    • Enable visualization to monitor trade behavior.
    • Set deposit according to prop firm account size.
    • Disable or enable spread as per realistic market conditions (use actual historical spreads).
    • Use correct commission settings.

    6. Optimization Criteria and Metrics

    • Key metrics to optimize for consistency:

      • Net profit (monthly or total)
      • Max drawdown (must be ≤ 8%)
      • Max daily drawdown (must be ≤ 4%)
      • Profit factor (aim for >1.5)
      • Sharpe ratio or other risk-adjusted returns (if available)
      • Number of consecutive losing days (lower is better)
      • Drawdown duration (short drawdowns preferred)
      • Average monthly profit consistency (small standard deviation)
    • Use Custom Optimization Criteria in MT5 if possible (via code modification) to penalize excessive drawdowns and daily loss violations.


    7. Optimization Process

    • Start with a coarse optimization over a wide range of parameters.
    • Select a subset of best performing sets with low drawdown and good profit.
    • Perform a refined optimization on those parameter subsets.
    • Check complexity to avoid overfitting (few parameters, stable ranges).

    8. Forward/Walk-Forward Testing

    • After optimization on in-sample data, test the best parameter sets on out-of-sample data without changing parameters.
    • Monitor if the drawdowns exceed the prop firm limits.
    • Consider walk-forward optimization if possible: re-optimize periodically on a moving window.

    9. Monthly Withdrawal Fitness

    • Check monthly balance curves:

      • Are profits consistent every month or too volatile?
      • Are there months with large losses?
    • If there are large monthly drawdowns, consider adjusting risk or stopping trading during volatile sessions/news.


    10. Practical Tips

    • Consider max risk per trade around 0.2-0.5% to keep daily losses manageable.
    • Allow the EA to stop trading once day’s unrealized loss approaches 3-3.5% to avoid hitting 4% max.
    • Use position scaling or gradual position sizing.
    • Avoid martingale or high-risk strategies that may violate drawdown limits.
    • Save detailed logs to monitor daily and monthly profit/loss.

    Summary Example Setup

    StepDetails
    Data3 years 1-min bars, tick data if available
    Backtest Period2019-2021 (in-sample), 2022 (out-of-sample)
    Optimization VariablesSL, TP, risk %, indicator thresholds
    Risk ManagementMax daily loss stop, max DD check inside EA
    Metrics to optimizeNet profit, max DD ≤ 8%, max daily loss ≤ 4%
    Testing SpeedUse MT5 Genetic or Slow Complete Algorithm
    Final TestForward test on last 6-12 months

    If you share your EA code, I can help configure optimization criteria or risk controls for prop firm rules inside the EA as well.


    Additional Resources

    • MT5 strategy tester guide
    • Prop firm rules risk management strategy design guides.
    • Articles on walk-forward optimization and overfitting.

    Feel free to ask for more help on specific steps!

  3. User

    i'll send you my ea code

  4. Assistant

    Great! Please go ahead and send me your EA code. Once I have the code, I can help you:

    • Review the existing risk management logic for prop firm constraints (4% daily loss, 8% max overall loss),
    • Suggest or implement code additions for daily loss monitoring and position sizing,
    • Help set up optimization parameters in the code,
    • Create custom optimization criteria if needed,
    • And generally help you structure the backtesting and optimization for those prop firm rules.

    Looking forward to your code!

  5. User

    //+------------------------------------------------------------------+ //| Break of Structure EA with floating risk cap (full, compile) | //+------------------------------------------------------------------+ #property copyright "" #property version "1.0" #property strict #include <Trade\Trade.mqh>

    input double inpLot = 0.05; input bool useRiskPercent = false; input double riskPercent = 1.0; // Position risk % per trade input int sl_atr_mult = 3; input double r2r_ratio = 2.0; input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; input int atrPeriod = 14; input int swingLookback = 20; input ENUM_TIMEFRAMES swingTF = PERIOD_M1; input int maPeriod = 50; input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; input int tradeStartHour = 7; input int tradeEndHour = 22; input int maxPositions = 1; input uint inpMagicNumber = 123456;

    input bool enableTrailingSL = true; enum ENUM_TrailingStopMode { TrailingNone = 0, TrailingMarketStructure = 1, TrailingATR = 2, TrailingHybrid = 3 }; input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid; input int ms_swingLookback = 20; input double atr_trail_mult = 2.5; input uint TrailUpdateIntervalSec = 15; input double MinSLBufferATRMult = 1.0; input double TrailingProfitTriggerPerc = 0.5; input bool enableReverseEntries = false; input double maxRiskPerTradePercent = 1.0; // Floating loss cap only! input double maxDailyLossAmount = 500.0;

    CTrade trade;

    int ma_handle = INVALID_HANDLE; int atr_handle = INVALID_HANDLE; string swingHighLineName = "SwingHighLine"; string swingLowLineName = "SwingLowLine";

    struct TrailingUpdateInfo { ulong position_ticket; datetime last_update; }; TrailingUpdateInfo g_trailingUpdateInfo[];

    static double g_initialEquity = 0.0; static datetime g_lastResetDay = 0;

    //+------------------------------------------------------------------+ void ResetDailyEquityIfNewDay() { datetime now = TimeCurrent(); MqlDateTime tm; TimeToStruct(now, tm);

    MqlDateTime todayMidnight = {};
    todayMidnight.year = tm.year;
    todayMidnight.mon  = tm.mon;
    todayMidnight.day  = tm.day;
    todayMidnight.hour = 0;
    todayMidnight.min  = 0;
    todayMidnight.sec  = 0;
    datetime midnightTime = StructToTime(todayMidnight);
    
    if(g_lastResetDay != midnightTime)
    {
        g_lastResetDay = midnightTime;
        g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        PrintFormat("Daily equity reset at %s new initialEquity=%.2f", TimeToString(now, TIME_DATE|TIME_SECONDS), g_initialEquity);
    }
    

    }

    //+------------------------------------------------------------------+ int OnInit() { ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE); if(ma_handle == INVALID_HANDLE) { Print("Failed to create EMA handle"); return INIT_FAILED; }

    atr_handle = iATR(_Symbol, volatilityTF, atrPeriod); if(atr_handle == INVALID_HANDLE) { Print("Failed to create ATR handle"); IndicatorRelease(ma_handle); return INIT_FAILED; }

    if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0)) { Print("Failed to create swing high line"); IndicatorRelease(ma_handle); IndicatorRelease(atr_handle); return INIT_FAILED; } ObjectSetInteger(0, swingHighLineName, OBJPROP_COLOR, clrGreen); ObjectSetInteger(0, swingHighLineName, OBJPROP_WIDTH, 2); ObjectSetInteger(0, swingHighLineName, OBJPROP_BACK, true); ObjectSetInteger(0, swingHighLineName, OBJPROP_RAY_RIGHT, true);

    if(!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, 0, 0)) { Print("Failed to create swing low line"); ObjectDelete(0, swingHighLineName); IndicatorRelease(ma_handle); IndicatorRelease(atr_handle); return INIT_FAILED; } ObjectSetInteger(0, swingLowLineName, OBJPROP_COLOR, clrRed); ObjectSetInteger(0, swingLowLineName, OBJPROP_WIDTH, 2); ObjectSetInteger(0, swingLowLineName, OBJPROP_BACK, true); ObjectSetInteger(0, swingLowLineName, OBJPROP_RAY_RIGHT, true); return INIT_SUCCEEDED; }

    //+------------------------------------------------------------------+ void OnDeinit(const int reason) { ObjectDelete(0, swingHighLineName); ObjectDelete(0, swingLowLineName);

    if(ma_handle != INVALID_HANDLE) { IndicatorRelease(ma_handle); ma_handle = INVALID_HANDLE; } if(atr_handle != INVALID_HANDLE) { IndicatorRelease(atr_handle); atr_handle = INVALID_HANDLE; } }

    //+------------------------------------------------------------------+ double CalculateLotSize(double sl_distance_price) { double balance = AccountInfoDouble(ACCOUNT_BALANCE); if(balance <= 0 || sl_distance_price <= 0) return inpLot;

    if(!useRiskPercent) { double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); double lot = inpLot; if(lot < min_lot) lot = min_lot; if(lot > max_lot) lot = max_lot; lot = MathFloor(lot / lot_step) * lot_step; return lot; } else { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double contract_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_CONTRACT_SIZE);

      if(tick_value <= 0 || tick_size <= 0 || contract_size <= 0)
         return inpLot;
    
      double point_value = tick_value / tick_size;
      double calculatedLot = (balance * (riskPercent / 100.0)) / (sl_distance_price * point_value * contract_size);
    
      if(calculatedLot <= 0)
         return inpLot;
    
      double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
      double min_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
      double max_lot  = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
    
      double lot = MathFloor(calculatedLot / lot_step) * lot_step;
    
      if(lot < min_lot) lot = min_lot;
      if(lot > max_lot) lot = max_lot;
      return lot;
    

    } }

    //+------------------------------------------------------------------+ bool IsPositionOpen(ENUM_POSITION_TYPE type) { int total = PositionsTotal(); for(int i = 0; i < total; i++) { ulong ticket = PositionGetTicket(i); if(PositionSelectByTicket(ticket)) { if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol) { ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); if(pos_type == type) return true; } } } return false; }

    //+------------------------------------------------------------------+ bool CanUpdateTrailing(ulong ticket) { datetime now = TimeCurrent(); int count = ArraySize(g_trailingUpdateInfo); for(int i=0; i<count; i++) { if(g_trailingUpdateInfo[i].position_ticket == ticket) { if(now - g_trailingUpdateInfo[i].last_update < (int)TrailUpdateIntervalSec) return false; g_trailingUpdateInfo[i].last_update = now; return true; } } ArrayResize(g_trailingUpdateInfo, count + 1); g_trailingUpdateInfo[count].position_ticket = ticket; g_trailingUpdateInfo[count].last_update = now; return true; }

    //+------------------------------------------------------------------+ void UpdateTrailingStopByMarketStructure(ulong position_ticket) { if(!PositionSelectByTicket(position_ticket)) return;

    ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
    double current_sl = PositionGetDouble(POSITION_SL);
    double current_tp = PositionGetDouble(POSITION_TP);
    double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
    string symbol = PositionGetString(POSITION_SYMBOL);
    
    if(current_tp <= 0)
        return;
    
    if(!CanUpdateTrailing(position_ticket))
        return;
    
    double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
    int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
    double bid = SymbolInfoDouble(symbol, SYMBOL_BID);
    double ask = SymbolInfoDouble(symbol, SYMBOL_ASK);
    if(bid <= 0 || ask <= 0)
        return;
    
    if(pos_type == POSITION_TYPE_BUY)
    {
        double half_tp_level = entry_price + 0.5 * (current_tp - entry_price);
        if(bid < half_tp_level)
            return;
    
        int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);
        if(lowestBar < 0)
            return;
    
        double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar);
        double buffer = 2 * point;
        double new_sl = NormalizeDouble(swing_low - buffer, digits);
    
        if(new_sl > current_sl && new_sl < entry_price)
        {
            MqlTradeRequest req = {};
            MqlTradeResult res = {};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = current_tp;
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("Trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    else if(pos_type == POSITION_TYPE_SELL)
    {
        double half_tp_level = entry_price - 0.5 * (entry_price - current_tp);
        if(ask > half_tp_level)
            return;
    
        int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0);
        if(highestBar < 0)
            return;
    
        double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar);
        double buffer = 2 * point;
        double new_sl = NormalizeDouble(swing_high + buffer, digits);
    
        if(new_sl < current_sl && new_sl > entry_price)
        {
            MqlTradeRequest req = {};
            MqlTradeResult res = {};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = current_tp;
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("Failed to update trailing SL for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("Trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("Trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    

    }

    //+------------------------------------------------------------------+ void UpdateTrailingStopByATR(ulong position_ticket) { if(!PositionSelectByTicket(position_ticket)) return;

    ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
    double current_sl = PositionGetDouble(POSITION_SL);
    double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
    string symbol = PositionGetString(POSITION_SYMBOL);
    
    if(!CanUpdateTrailing(position_ticket))
        return;
    
    double point = SymbolInfoDouble(symbol, SYMBOL_POINT);
    int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
    
    double atr_buf[];
    if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
        return;
    double atr = atr_buf[0];
    if(atr <= 0)
        return;
    
    double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) 
                                                           : SymbolInfoDouble(symbol, SYMBOL_ASK);
    if(current_price <= 0) return;
    
    double new_sl = 0;
    if(pos_type == POSITION_TYPE_BUY)
    {
        new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits);
        double min_sl_dist = atr * MinSLBufferATRMult;
        if(new_sl < (current_price - min_sl_dist))
            new_sl = current_price - min_sl_dist;
    
        if(new_sl > current_sl && new_sl < current_price)
        {
            MqlTradeRequest req={};
            MqlTradeResult res={};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = PositionGetDouble(POSITION_TP);
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("ATR trailing SL moved up for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    else if(pos_type == POSITION_TYPE_SELL)
    {
        new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits);
        double min_sl_dist = atr * MinSLBufferATRMult;
        if(new_sl > (current_price + min_sl_dist))
            new_sl = current_price + min_sl_dist;
    
        if(new_sl < current_sl && new_sl > current_price)
        {
            MqlTradeRequest req={};
            MqlTradeResult res={};
            req.action = TRADE_ACTION_SLTP;
            req.position = position_ticket;
            req.symbol = symbol;
            req.sl = new_sl;
            req.tp = PositionGetDouble(POSITION_TP);
            req.deviation = 10;
    
            if(!OrderSend(req, res))
                PrintFormat("ATR trailing SL update failed for position %I64d, error %d", position_ticket, GetLastError());
            else if(res.retcode != TRADE_RETCODE_DONE)
                PrintFormat("ATR trailing SL update rejected for position %I64d, retcode %d", position_ticket, res.retcode);
            else
                PrintFormat("ATR trailing SL moved down for position %I64d: new SL=%.5f", position_ticket, new_sl);
        }
    }
    

    }

    //+------------------------------------------------------------------+ void UpdateTrailingStopHybrid(ulong position_ticket) { if(!PositionSelectByTicket(position_ticket)) return;

    if(!CanUpdateTrailing(position_ticket)) return;

    ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE); double sl = PositionGetDouble(POSITION_SL); double tp = PositionGetDouble(POSITION_TP); double entry_price = PositionGetDouble(POSITION_PRICE_OPEN); string symbol = PositionGetString(POSITION_SYMBOL);

    double point = SymbolInfoDouble(symbol, SYMBOL_POINT); int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);

    double atr_buf[]; if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0) return; double atr = atr_buf[0]; if(atr <= 0) return;

    double min_sl_distance = atr * MinSLBufferATRMult; double initial_sl_dist = (pos_type == POSITION_TYPE_BUY) ? (entry_price - sl) : (sl - entry_price); if(initial_sl_dist <= 0) initial_sl_dist = atr * sl_atr_mult;

    double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(symbol, SYMBOL_BID) : SymbolInfoDouble(symbol, SYMBOL_ASK); if(current_price <= 0) return;

    double move_in_profit = (pos_type == POSITION_TYPE_BUY) ? (current_price - entry_price) : (entry_price - current_price); if(move_in_profit < TrailingProfitTriggerPerc * initial_sl_dist) return;

    double ms_new_sl = 0; bool ms_sl_valid = false; if(pos_type == POSITION_TYPE_BUY) { int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0); if(lowestBar >= 0) { double swing_low = iLow(symbol, PERIOD_CURRENT, lowestBar); ms_new_sl = NormalizeDouble(swing_low - 2point, digits); ms_sl_valid = (ms_new_sl > sl) && (ms_new_sl < entry_price); } } else if(pos_type == POSITION_TYPE_SELL) { int highestBar = iHighest(symbol, PERIOD_CURRENT, MODE_HIGH, ms_swingLookback, 0); if(highestBar >= 0) { double swing_high = iHigh(symbol, PERIOD_CURRENT, highestBar); ms_new_sl = NormalizeDouble(swing_high + 2point, digits); ms_sl_valid = (ms_new_sl < sl) && (ms_new_sl > entry_price); } }

    double atr_new_sl = 0; if(pos_type == POSITION_TYPE_BUY) { atr_new_sl = NormalizeDouble(current_price - atr * atr_trail_mult, digits); atr_new_sl = MathMax(atr_new_sl, current_price - min_sl_distance); atr_new_sl = (atr_new_sl > sl && atr_new_sl < current_price) ? atr_new_sl : 0; } else if(pos_type == POSITION_TYPE_SELL) { atr_new_sl = NormalizeDouble(current_price + atr * atr_trail_mult, digits); atr_new_sl = MathMin(atr_new_sl, current_price + min_sl_distance); atr_new_sl = (atr_new_sl < sl && atr_new_sl > current_price) ? atr_new_sl : 0; }

    double new_sl = 0; if(ms_sl_valid && atr_new_sl > 0) { if(pos_type == POSITION_TYPE_BUY) new_sl = MathMax(ms_new_sl, atr_new_sl); else new_sl = MathMin(ms_new_sl, atr_new_sl); } else if(ms_sl_valid) new_sl = ms_new_sl; else if(atr_new_sl > 0) new_sl = atr_new_sl; else return;

    bool update_sl = false; if(pos_type == POSITION_TYPE_BUY) update_sl = (new_sl > sl && new_sl < current_price); else update_sl = (new_sl < sl && new_sl > current_price);

    if(update_sl) { MqlTradeRequest req={}; MqlTradeResult res={}; req.action = TRADE_ACTION_SLTP; req.position = position_ticket; req.symbol = symbol; req.sl = new_sl; req.tp = tp; req.deviation = 10;

      if(!OrderSend(req,res))
         PrintFormat("Trailing SL update failed for position %I64d, err=%d", position_ticket, GetLastError());
      else if(res.retcode != TRADE_RETCODE_DONE)
         PrintFormat("Trailing SL update rejected for position %I64d, retcode=%d", position_ticket, res.retcode);
      else
         PrintFormat("Trailing SL updated for position %I64d: old SL=%.5f new SL=%.5f", position_ticket, sl, new_sl);
    

    } }

    //+------------------------------------------------------------------+ void OnTick() { ResetDailyEquityIfNewDay(); if(g_initialEquity == 0.0) g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);

    double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    double equityDrawdown = g_initialEquity - currentEquity;
    
    if(equityDrawdown >= maxDailyLossAmount)
    {
        PrintFormat("Max combined daily loss $%.2f exceeded (drawdown=%.2f). No new trades allowed.", maxDailyLossAmount, equityDrawdown);
        return;
    }
    
    //--- FLOATING RISK CLOSE LOGIC ---
    if(maxRiskPerTradePercent > 0.0)
    {
        int total = PositionsTotal();
        double balance = AccountInfoDouble(ACCOUNT_BALANCE);
        double maxLossMoney = balance * (maxRiskPerTradePercent / 100.0);
    
        for(int i=total-1; i>=0; i--)
        {
            ulong ticket = PositionGetTicket(i);
            if(PositionSelectByTicket(ticket))
            {
                if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber &&
                   PositionGetString(POSITION_SYMBOL) == _Symbol)
                {
                    double currentProfit = PositionGetDouble(POSITION_PROFIT);
                    if(currentProfit < 0 && MathAbs(currentProfit) >= maxLossMoney)
                    {
                        PrintFormat("Closing position %I64d as floating loss reached %.2f (cap is %.2f)",
                                    ticket, MathAbs(currentProfit), maxLossMoney);
                        trade.PositionClose(ticket);
                    }
                }
            }
        }
    }
    
    //--- TRAILING SL ---
    if(enableTrailingSL && trailingStopMode != TrailingNone)
    {
       int total = PositionsTotal();
       for(int i=0; i<total; i++)
       {
          ulong ticket = PositionGetTicket(i);
          if(PositionSelectByTicket(ticket))
          {
             if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
             {
                if(trailingStopMode == TrailingMarketStructure)
                   UpdateTrailingStopByMarketStructure(ticket);
                else if(trailingStopMode == TrailingATR)
                   UpdateTrailingStopByATR(ticket);
                else if(trailingStopMode == TrailingHybrid)
                   UpdateTrailingStopHybrid(ticket);
             }
          }
       }
    }
    
    //--- POSITION LIMIT CHECK ---
    int openPosCount = 0, total = PositionsTotal();
    for(int i=0; i<total; i++)
    {
        ulong ticket = PositionGetTicket(i);
        if(PositionSelectByTicket(ticket))
        {
            if(PositionGetInteger(POSITION_MAGIC) == (long)inpMagicNumber && PositionGetString(POSITION_SYMBOL) == _Symbol)
            {
                openPosCount++;
            }
        }
    }
    if(maxPositions > 0 && openPosCount >= maxPositions)
        return;
    
    //--- TRADING TIME ---
    MqlDateTime tm;
    TimeToStruct(TimeCurrent(), tm);
    if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour)
        return;
    
    //--- INDICATORS ---
    double ma_buf[];
    ArrayResize(ma_buf, 1);
    if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0)
        return;
    
    double atr_buf[];
    ArrayResize(atr_buf, 1);
    if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0)
        return;
    
    double ma = ma_buf[0];
    double atr = atr_buf[0];
    if(atr <= 0)
        atr = 10.0 * _Point;
    
    double sl_dist = atr * sl_atr_mult;
    double tp_dist = sl_dist * r2r_ratio;
    
    int highestBar = iHighest(_Symbol, swingTF, MODE_HIGH, swingLookback, 1);
    int lowestBar = iLowest(_Symbol, swingTF, MODE_LOW, swingLookback, 1);
    if(highestBar < 0 || lowestBar < 0)
        return;
    
    double lastSwingHigh = iHigh(_Symbol, swingTF, highestBar);
    double lastSwingLow = iLow(_Symbol, swingTF, lowestBar);
    
    ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);
    ObjectSetDouble(0, swingLowLineName, OBJPROP_PRICE, lastSwingLow);
    
    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    if(ask <= 0 || bid <= 0)
        return;
    
    double price_htf = iClose(_Symbol, maTimeframe, 1);
    if(price_htf <= 0 || ma <= 0)
        return;
    
    bool is_uptrend = (price_htf > ma);
    bool is_downtrend = (price_htf < ma);
    int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    
    double lot = CalculateLotSize(sl_dist);
    if(lot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN))
        return;
    
    MqlTradeRequest request = {};
    MqlTradeResult result = {};
    request.symbol = _Symbol;
    request.volume = lot;
    request.deviation = 10;
    request.magic = inpMagicNumber;
    
    if(!enableReverseEntries)
    {
        if(ask > lastSwingHigh && is_uptrend)
        {
            if(!IsPositionOpen(POSITION_TYPE_BUY))
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_BUY;
                request.price  = ask;
                request.sl     = NormalizeDouble(ask - sl_dist, digits);
                request.tp     = NormalizeDouble(ask + tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Buy order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Buy order rejected, retcode %d", result.retcode);
                else
                    PrintFormat("Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
            }
        }
        else if(bid < lastSwingLow && is_downtrend)
        {
            if(!IsPositionOpen(POSITION_TYPE_SELL))
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_SELL;
                request.price  = bid;
                request.sl     = NormalizeDouble(bid + sl_dist, digits);
                request.tp     = NormalizeDouble(bid - tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Sell order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Sell order rejected, retcode %d", result.retcode);
                else
                    PrintFormat("Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
            }
        }
    }
    else
    {
        // -- REVERSE LOGIC --
        if(ask > lastSwingHigh && is_downtrend)
        {
            if(!IsPositionOpen(POSITION_TYPE_SELL))
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_SELL;
                request.price  = bid;
                request.sl     = NormalizeDouble(bid + sl_dist, digits);
                request.tp     = NormalizeDouble(bid - tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Reverse Sell order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Reverse Sell order rejected, retcode %d", result.retcode);
                else
                    PrintFormat("Reverse Sell opened @ %.5f lot %.2f SL %.5f TP %.5f", bid, lot, request.sl, request.tp);
            }
        }
        else if(bid < lastSwingLow && is_uptrend)
        {
            if(!IsPositionOpen(POSITION_TYPE_BUY))
            {
                request.action = TRADE_ACTION_DEAL;
                request.type   = ORDER_TYPE_BUY;
                request.price  = ask;
                request.sl     = NormalizeDouble(ask - sl_dist, digits);
                request.tp     = NormalizeDouble(ask + tp_dist, digits);
    
                if(!OrderSend(request, result))
                    PrintFormat("Reverse Buy order send failed, error %d", GetLastError());
                else if(result.retcode != TRADE_RETCODE_DONE)
                    PrintFormat("Reverse Buy order rejected, retcode %d", result.retcode);
                else
                    PrintFormat("Reverse Buy opened @ %.5f lot %.2f SL %.5f TP %.5f", ask, lot, request.sl, request.tp);
            }
        }
    }
    

    } //+------------------------------------------------------------------+

  6. Assistant

    Thanks for providing your EA code! It’s a solid Break of Structure EA with built-in trailing stops and floating risk caps.


    How your EA already fits prop firm risk rules:

    • Daily Drawdown Tracking:
      You have ResetDailyEquityIfNewDay() to store equity at the start of each day and check daily drawdown with:

      double equityDrawdown = g_initialEquity - currentEquity;  
      if(equityDrawdown >= maxDailyLossAmount) { /* stop new trades */ }  
      

      where maxDailyLossAmount is user input (default 500.0).

    • Floating Max Risk per Trade:
      You close any position exceeding maxRiskPerTradePercent loss dynamically.


    What you need to focus on to fully optimize and enforce strict Prop Firm Rules:

    Prop Firm RuleWhat to do / check in your EA
    4% Daily Maximum LossSet maxDailyLossAmount based on 4% of initial balance:maxDailyLossAmount = AccountBalance() * 0.04 Make sure ResetDailyEquityIfNewDay() resets g_initialEquity daily.Also check that no new trades occur once hit.
    8% Max Overall DrawdownThis needs monitoring across the entire test period:- Create a similar global equity drawdown check in OnTick or OnTester to stop trading.- Consider storing peak equity and monitoring drawdown relative to peak to stop new trades if exceeded.- You can add this logic using static/global variables at runtime or track equity peaks.
    Consistent Monthly ProfitsAfter backtesting, analyze monthly balance reports on report or logs.In optimization, favor parameter sets that minimize monthly equity drawdown volatility.

    Suggested improvements / additions to your EA code:

    1) Add Max Overall Drawdown check in OnTick

    Add a static or global variable to track max historical equity (equity peak), then measure drawdown relative to that peak and stop trading if exceed 8%.

    Example snippet to place in OnTick() near daily loss check:

    static double maxEquityPeak = 0.0;
    double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    
    if(maxEquityPeak < currentEquity)
        maxEquityPeak = currentEquity;
    
    double overallDrawdown = (maxEquityPeak - currentEquity) / maxEquityPeak * 100.0; // %
    
    if(overallDrawdown >= 8.0)
    {
        PrintFormat("Max overall drawdown 8%% exceeded (%.2f%%). No new trades allowed.", overallDrawdown);
        return;
    }
    

    This will stop new trades if the drawdown exceeds 8%.


    2) Change maxDailyLossAmount default based on 4% of balance

    Instead of a fixed 500 USD, initialize dynamically:

    input double maxDailyLossPercent = 4.0;  // 4% daily loss limit
    double maxDailyLossAmount = 0.0;
    
    void ResetDailyEquityIfNewDay()
    {
        datetime now = TimeCurrent();
        MqlDateTime tm;
        TimeToStruct(now, tm);
    
        MqlDateTime todayMidnight = {};
        todayMidnight.year = tm.year;
        todayMidnight.mon  = tm.mon;
        todayMidnight.day  = tm.day;
        todayMidnight.hour = 0;
        todayMidnight.min  = 0;
        todayMidnight.sec  = 0;
        datetime midnightTime = StructToTime(todayMidnight);
    
        if(g_lastResetDay != midnightTime)
        {
            g_lastResetDay = midnightTime;
            g_initialEquity = AccountInfoDouble(ACCOUNT_EQUITY);
            maxDailyLossAmount = g_initialEquity * (maxDailyLossPercent / 100.0);
            PrintFormat("Daily equity reset at %s new initialEquity=%.2f maxDailyLoss=%.2f", TimeToString(now, TIME_DATE|TIME_SECONDS), g_initialEquity, maxDailyLossAmount);
        }
    }
    

    3) Add a max daily consecutive loss days limit check (optional)

    To increase consistency, you can monitor number of losing days in a row and stop trading if it exceeds some threshold (e.g., 4 days).

    This requires storing persistent state (in files or global variables) but is optional.


    4) Add configurable optimization parameters

    To help optimization, expose more parameters such as:

    • sl_atr_mult (stop loss multiplier)
    • r2r_ratio (reward:risk ratio)
    • riskPercent (risk per trade)
    • tradeStartHour, tradeEndHour
    • maxPositions

    5) Optimization inside MT5 Strategy Tester

    Backtest period / forward testing recommendation:

    • Use 3 years or more data; optimize on first 2 years (in-sample).
    • Validate on last 6-12 months (out-of-sample).
    • Use Every tick based on real ticks mode for max accuracy.
    • Use genetic algorithm optimization first for speed.
    • Check metrics:
      • Monthly return consistency (export report for Excel analysis)
      • Max daily loss never above 4%
      • Max overall drawdown never above 8%
      • Profit factor > 1.5
      • Sharpe Ratio (if implemented)

    Summary of Additions

    Here’s a minimal example integrating the max overall drawdown and dynamic daily loss %:

    input double maxDailyLossPercent = 4.0;
    static double maxEquityPeak = 0.0;
    
    void OnTick()
    {
        ResetDailyEquityIfNewDay();
    
        double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        if(maxEquityPeak < currentEquity)
            maxEquityPeak = currentEquity;
    
        double overallDrawdown = (maxEquityPeak - currentEquity) / maxEquityPeak * 100.0; // in %
    
        if(overallDrawdown >= 8.0)
        {
            PrintFormat("Max overall drawdown 8%% exceeded (%.2f%%). Stopping new trades.", overallDrawdown);
            return;
        }
    
        double equityDrawdown = g_initialEquity - currentEquity;
        if(equityDrawdown >= maxDailyLossAmount)
        {
            PrintFormat("Max daily loss %.2f%% exceeded. Stopping new trades.", maxDailyLossPercent);
            return;
        }
    
        // [YOUR EA MAIN LOGIC CONTINUES HERE]
        ...
    }
    

    Additional recommendation

    • Log daily performance in a file to analyze later.
    • If possible, make your EA stop trading entirely when hit loss limits, or disable order placing but allow trailing updates.
    • Consider adding manual reset for loss counters (or auto reset monthly).

    If you want, I can help you integrate the above into your full source code and assist with MT5 optimization setup. Just ask!

  7. User

    explaine me this : Use 3 years or more data; optimize on first 2 years (in-sample). Validate on last 6-12 months (out-of-sample).

  8. Assistant

    Certainly! This concept relates to robust strategy development and is key to avoid "curve-fitting" (over-optimizing your EA to past data that doesn’t generalize well).


    Explanation of In-Sample and Out-of-Sample Data Split

    When you want to optimize and validate your Expert Advisor (EA) settings, you don’t just run a backtest on all available data. Instead, you separate your historical data into two parts:


    1. In-Sample Data (Training Period) — e.g. First 2 Years

    • This is the historical period where you optimize your EA parameters (like stop loss multiplier, risk percent, take profit, trailing stops, etc.).
    • The EA “learns” or identifies the best set of parameters on this data.
    • Optimization algorithms (like MT5 Genetic Algorithm or Complete Search) try many parameter combinations here.
    • Your goal: find parameter sets that perform well according to your chosen metrics (profit, drawdown, consistency).

    2. Out-of-Sample Data (Validation Period) — e.g. Last 6-12 Months

    • This is the unseen period immediately following the in-sample.
    • After choosing optimized parameters from the in-sample phase, you run a forward test without changing parameters on out-of-sample data.
    • This validates whether your parameter set generalizes well — i.e., will it work on new, unseen market behavior?
    • If your strategy performs well here (stable profits, acceptable drawdowns), it’s more likely to be robust.

    Why Do This?

    • Prevent Overfitting:
      Optimizing parameters on all data risks tuning your EA to noise or very specific market conditions that won’t persist.

    • Check Robustness:
      If the EA only performs well in the in-sample but fails badly on out-of-sample, it’s not a reliable system.

    • Better Real-World Expectation:
      You want your trading to succeed in future unseen conditions, so out-of-sample testing simulates that.


    Example Timeline

    YearData StatusUsage
    2019In-SampleEA parameter optimization
    2020In-SampleEA parameter optimization
    2021Out-of-SampleForward test/validation period

    What to look for in these phases?

    • In-Sample: Maximize profit, minimize drawdown, improve consistency.
    • Out-of-Sample: Confirm profitability and drawdowns similar or better than in-sample.
    • If out-of-sample performance is poor → refine EA, change logic, or select different parameters.

    How to apply in MT5

    1. For In-Sample optimization, set your backtest date range from (e.g.) 1-Jan-2019 to 31-Dec-2020.
    2. Run optimization in MT5 Strategy Tester using this range.
    3. Select your best parameters (check drawdown and profit metrics).
    4. Then run a pure backtest (no optimization) on out-of-sample data: 1-Jan-2021 to 31-Dec-2021 using your optimized parameters.
    5. Check if the EA performs well (especially with max daily loss and max overall drawdown limits respected).

    Feel free to ask if you'd like help setting these date ranges in MT5 or advice on how to analyze out-of-sample results!

  9. User

    give me an order of imputs to optime acording to my ea

  10. Assistant

    Certainly! To optimize your EA effectively and efficiently, you want to start with the most impactful inputs that affect risk and trade triggers, then narrow down to finer tuning parameters for trailing stops and timing.


    Recommended Order of Inputs to Optimize for Your EA:

    PriorityInput ParameterDescription / Why Optimize FirstSuggested Range / Notes
    1riskPercentControls position sizing risk per trade (critical for drawdowns)e.g., 0.1% to 1.5% (step 0.1%)
    2sl_atr_multStop Loss size in ATR multiples — defines protective stop2.0 to 5.0 (step 0.2)
    3r2r_ratioReward-to-risk ratio (take profit multiplier) — affects profit targets1.5 to 3.0 (step 0.1 or 0.2)
    4swingLookbackLook-back bars for swing high/low detection — entry signals10 to 50 bars (step 5-10)
    5maPeriodMoving average period for trend filter — trend direction20 to 100 (step 5 or 10)
    6tradeStartHourStart hour of trading window — controls time of day tradinge.g., 0 to 23 (step 1)
    7tradeEndHourEnd hour of trading windowe.g., 1 to 23 (step 1)
    8maxPositionsMaximum open positions at once — controls exposure1 to 3
    9atr_trail_multATR multiplier for trailing stop (used only if trailing enabled)1.0 to 4.0 (step 0.2)
    10TrailingProfitTriggerPercMinimum profit % before trailing activates0.1 to 1.0 (step 0.1)
    11maxRiskPerTradePercentFloating floating loss close % per trade — safety cap0.5% to 2.0%
    12enableReverseEntriesBoolean — consider optimizing if you want to allow reverse tradesTrue / False

    Optimization Strategy

    • Step 1: Optimize only high-impact parameters (riskPercent, sl_atr_mult, r2r_ratio) together first.
    • Step 2: Add swingLookback and maPeriod after fixing risk and reward parameters.
    • Step 3: Tune trading hours and position limits.
    • Step 4: Optimize trailing stop parameters last, as these can be subtle refinements.

    —

    Why this order?

    1. Risk and protection (stop loss size and position sizing) affect drawdown and daily loss most.
    2. Entry filters define frequency and quality of trades.
    3. Trade hours and position limits help manage exposure and avoid bad timeframes.
    4. Trailing stop tuning refines exits but less impact than stop loss or lot sizing.

    How to do this in MT5 Strategy Tester

    • At each optimization “phase,” only enable those parameters to optimize.
    • Fix other parameters at reasonable defaults.
    • Narrow ranges as you get better sets.
    • Always validate top results on out-of-sample data!

    If you want, I can provide an example .set file or a textual list for MT5 optimizer or help you configure your Strategy Tester accordingly.

  11. User

    Optimize only high-impact parameters (riskPercent, sl_atr_mult, r2r_ratio) , together or one by one?

  12. Assistant

    Great question!


    Should you optimize riskPercent, sl_atr_mult, r2r_ratio together or one by one?

    Optimizing Them Together (Multivariate Optimization) — Recommended

    • These parameters are highly interdependent:

      • riskPercent affects how big your positions are.
      • sl_atr_mult defines the stop loss distance — changing this changes the actual risk in price terms.
      • r2r_ratio defines your take profit relative to stop loss — affects reward side.
    • Optimizing them together lets the optimizer explore combinations that balance position size, stop loss distance, and profit target optimally.

    • This approach may find better parameter sets that deliver the best equity curve, drawdown, and profit factor.

    • MT5 genetic optimization is efficient for this kind of combined search.


    Optimizing Them One by One (Sequential Optimization)

    • You optimize one parameter fixing others, then move to the next.

    • This has disadvantages:

      • You might miss good parameter combinations because parameters affect each other.
      • Risk sizing and stop losses have nonlinear interactions, so fixing one could limit optimization of others.
    • Could be useful for quick sanity checks or if the parameter space is very large and you want to simplify initially.


    Bottom line

    • Start by optimizing riskPercent, sl_atr_mult, and r2r_ratio together over reasonable ranges.

    • Keep other parameters fixed.

    • After getting good results, you can do fine-tuning or sequential passes for secondary parameters.


    Practical tip in MT5:

    • Select these three inputs only when setting up your optimization pass.

    • Use Genetic algorithm to efficiently search combinations.

    • Limit total steps to reasonable counts (e.g., 10-15 steps per parameter) to keep optimization time manageable.


    If you want, I can help draft an example optimizer setup for you!