//+------------------------------------------------------------------+ // AdvancedBoSEAMT5.mq5 // Author: Luc…
- User
//+------------------------------------------------------------------+ //| Advanced_BoS_EA_MT5.mq5 | //| Author: LucienWP | //| Version: 1.6 | //| Published: 2025-06-XX | //| Description: Break Of Structure EA | //| with dynamic lot sizing, dynamic trailing stops (market structure| //| or ATR or hybrid), throttling and safety buffers | //+------------------------------------------------------------------+ #property copyright "LucienWP" #property version "1.6" #property strict #property script_show_inputs
#include <Trade\Trade.mqh>
input double inpLot = 0.05; // Fixed lot size per trade input bool useRiskPercent = false; // Use risk % to calculate lot size input double riskPercent = 1.0; // Risk % per trade if enabled
input int sl_atr_mult = 3; // SL multiplier for ATR (initial SL distance) input double r2r_ratio = 2.0; // Risk-to-Reward ratio (TP = SL * r2r_ratio) input ENUM_TIMEFRAMES volatilityTF = PERIOD_M5; // ATR timeframe input int atrPeriod = 14; // ATR period input int swingLookback = 20; // Bars lookback for swing detection (trade entries) input ENUM_TIMEFRAMES swingTF = PERIOD_M1; // Swing detection timeframe for entries input int maPeriod = 50; // EMA period for trend filter input ENUM_TIMEFRAMES maTimeframe = PERIOD_M15; // EMA timeframe input int tradeStartHour = 7; // Trading start hour (server) input int tradeEndHour = 22; // Trading end hour (server) input int maxPositions = 1; // Max simultaneous EA positions (0=no limit) input uint inpMagicNumber = 123456; // Magic number for EA positions (uint for compatibility)
// Trailing stop enable and mode input bool enableTrailingSL = true; // Enable trailing stop
enum ENUM_TrailingStopMode { TrailingNone = 0, // No trailing stop TrailingMarketStructure = 1, // Trailing by market structure swings TrailingATR = 2, // Trailing by ATR-based stop loss TrailingHybrid = 3 // Hybrid trailing: market structure + ATR }; input ENUM_TrailingStopMode trailingStopMode = TrailingHybrid; // Trailing stop mode selector
// New inputs for trailing settings (separate from entry/trade) input int ms_swingLookback = 20; // Swing trailing lookback bars (separate from trade entry) input double atr_trail_mult = 2.5; // ATR trailing multiplier (can differ from SL multiplier)
// Trailing enhancements input uint TrailUpdateIntervalSec = 15; // Minimum seconds between trailing stop updates per position input double MinSLBufferATRMult = 1.0; // Minimum SL distance buffer in ATR multiples input double TrailingProfitTriggerPerc = 0.5; // Trailing activates once price moves this fraction of SL distance in profit
// New input for reverse entry logic input bool enableReverseEntries = false; // Reverse trade entry logic (Sell on swing high break, Buy on swing low break)
// New input for max risk per trade (% of account balance) input double maxRiskPerTradePercent = 1.0; // Max risk per trade as % of account balance
// --- NEW input: MAX DAILY LOSS in absolute dollars for combined equity drawdown --- input double maxDailyLossAmount = 500.0; // Max combined daily loss $ amount (equity drawdown)
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[];
// --- Global static variables to hold initial equity and last reset day --- static double g_initialEquity = 0.0; static datetime g_lastResetDay = 0;
//+------------------------------------------------------------------+ // Reset initial equity once per day at midnight server time 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); }} //+------------------------------------------------------------------+
void OnInit() { PrintFormat("AdvancedBoS_EA_MT5 v%s - Starting Initialization", DATE); PrintFormat("MagicNumber=%u, SwingTF=%d, ATR period=%d, SL ATR Mult=%d", inpMagicNumber, swingTF, atrPeriod, sl_atr_mult);
ma_handle = iMA(_Symbol, maTimeframe, maPeriod, 0, MODE_EMA, PRICE_CLOSE); if(ma_handle == INVALID_HANDLE) { Print("Failed to create EMA handle"); return; }
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod); if(atr_handle == INVALID_HANDLE) { Print("Failed to create ATR handle"); IndicatorRelease(ma_handle); return; }
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0)) { Print("Failed to create swing high line"); IndicatorRelease(ma_handle); IndicatorRelease(atr_handle); return; } 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; } 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); } //+------------------------------------------------------------------+ 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; } } //+------------------------------------------------------------------+ // Calculate lot size, capped by max risk per trade percent double CalculateLotSize(double sl_distance_price) { double balance = AccountInfoDouble(ACCOUNT_BALANCE); if(balance <= 0 || sl_distance_price <= 0) { Print("Invalid inputs for lot size calculation"); return inpLot; }
double maxRiskMoney = balance * (maxRiskPerTradePercent / 100.0);
double lot = 0.0;
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); lot = inpLot; if(lot < min_lot) lot = min_lot; if(lot > max_lot) lot = max_lot; lot = MathFloor(lot / lot_step) * lot_step; } 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) { Print("Invalid symbol trade parameters for lot calc."); 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 lotMaxRisk = maxRiskMoney / (sl_distance_price * point_value * contract_size); lot = MathMin(calculatedLot, lotMaxRisk); double lot_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double min_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double max_lot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); lot = MathFloor(lot / 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; // No valid TP set, skip trailing if(!CanUpdateTrailing(position_ticket)) return; // throttle updates 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; // throttle updates 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) { PrintFormat("ATR data copy failed in trailing ATR for position %I64d", position_ticket); 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; // throttle trailing updates
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) { PrintFormat("ATR data copy failed in trailing update for position %I64d", position_ticket); 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; // fallback
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; // not enough profit to start trailing
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; // no valid new SL
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; // stop trading if combined drawdown hit } 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); } } } } int openPosCount = 0; 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) { openPosCount++; } } } if(maxPositions > 0 && openPosCount >= maxPositions) return; MqlDateTime tm; TimeToStruct(TimeCurrent(), tm); if(tm.hour < tradeStartHour || tm.hour >= tradeEndHour) return; double ma_buf[]; ArrayResize(ma_buf, 1); if(CopyBuffer(ma_handle, 0, 1, 1, ma_buf) <= 0) { PrintFormat("EMA data copy failed, error %d", GetLastError()); return; } double atr_buf[]; ArrayResize(atr_buf, 1); if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf) <= 0) { PrintFormat("ATR data copy failed, error %d", GetLastError()); return; } double ma = ma_buf[0]; double atr = atr_buf[0]; if(atr <= 0) { atr = 10.0 * _Point; Print("ATR value invalid or zero, falling back to 10 points"); } 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) { Print("Error getting swing high/low bars"); 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 { if(ask > lastSwingHigh && is_uptrend) { 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_downtrend) { 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); } } }}
- Assistant
Your provided Advanced_BoS_EA_MT5.mq5 code is a comprehensive Break of Structure (BoS) Expert Advisor for MT5 with several advanced features such as dynamic lot sizing, multiple trailing stop methods, throttling trailing updates, max daily drawdown stop, reverse entry logic, and configurable timeframes.
Below is a detailed review with some improvements, clarifications, and potential bug fixes suggestions that can further enhance the robustness and correctness of your EA. If you want an overall code review or specific features explained or modified, please let me know.
General code review & improvement suggestions
1. Initialization and deinitialization print time
PrintFormat("AdvancedBoS_EA_MT5 v%s - Starting Initialization", __DATE__);__DATE__is the compilation date, but the string version%sexpects a string. It's okay, but you might prefer something like a direct version string or a timestamp of start.
2. Creating horizontal lines (
OBJ_HLINE) at zero price0inOnInit()ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, 0, 0)- Ideally, initialize the horizontal lines at a valid price, maybe the current high/low or close price of the last bar to avoid zero lines.
- After creation, you promptly update via
ObjectSetDouble(0, swingHighLineName, OBJPROP_PRICE, lastSwingHigh);later inOnTick()so it's less critical.
3. Use of
intfor Magic Number inPositionGetInteger(...) == (long)inpMagicNumbercastinginpMagicNumberis defined asuint, but at places you cast it to(long).- This is okay because the API expects
long, but be sure the magic number is within the correct range (0 to 2^31-1).
4. Use of
CopyBufferfor ATR and EMA in tick- You fetch ATR and EMA values on each tick with
CopyBuffer(handle, 0, 1, 1, array). - This is generally fine, but consider caching the data and only copying every
nseconds or at bar close for performance. atr_buf[0]corresponds to the value of the indicator for the current (uncompleted) bar, it may be better to use[index 1], i.e. the last completed bar, for more stable data.
5.
CalculateLotSize()- Critical code that respects risk percent and max risk per trade limits, and then floors the lot size by symbol min/max.
- Good detail on trade contract size, tick value, and point value.
- Consider adding a print if returned lot is less than minimum lot size; you silently skip the trade in
OnTick().
Specific code correctness and possible bugs or improvements
Problem in
UpdateTrailingStopByMarketStructure()Code extracts lowest/ highest bar in
iLowest()oriHighest():int lowestBar = iLowest(symbol, PERIOD_CURRENT, MODE_LOW, ms_swingLookback, 0);- The last parameter offset is
0, means "current bar" (unclosed bar), which may be volatile. - More common is to use offset of
1or higher to get last closed candle for stability. - Similarly for highestBar in sell side.
The buffer on new SL:
double buffer = 2*point;is good but consider making this buffer configurable by input.Possible logical error in
UpdateTrailingStopByMarketStructure()For Buy positions, you check:
if(bid < half_tp_level) return;Meaning you only proceed if price passed half the way to take profit (i.e. at least 50% in profit).
Similarly for Sell it says:
if(ask > half_tp_level) return;You want trailing only if profit > 50% SL distance (actually more properly: use
TrailingProfitTriggerPercinput).But these hardcoded
0.5values here choosen instead of the configurableTrailingProfitTriggerPercinput you defined. For consistency, use that input instead.In
UpdateTrailingStopByATR()if(new_sl < (current_price - min_sl_dist)) new_sl = current_price - min_sl_dist;For Buy, you enforce a minimum SL distance
min_sl_dist.Similarly for Sell:
if(new_sl > (current_price + min_sl_dist)) new_sl = current_price + min_sl_dist;- It seems both are trying to prevent the SL from moving too close to price.
- But the check and assignment look contradictory—usually, you want SL at least
min_sl_distaway from current price. - But here, for Buy: if new_sl < current_price - min_sl_dist (meaning SL is further away), you "push" it closer to
current_price - min_sl_dist? This could move it closer than before. - Recommend reviewing the logic to ensure SL never moves closer than
min_sl_distor too close to current price.
Hybrid trailing
UpdateTrailingStopHybrid()seems logically consistent but could use:- Use
TrailingProfitTriggerPercinput already in data for profit trigger, butUpdateTrailingStopByMarketStructure()uses constant 0.5. - Consistency helps.
IsPositionOpen()only returnstrueif at least one position of the specified type exists for the symbol and magic number:- Good to prevent multiple trades of same type.
- But if you want to allow scaling or multiple entries, you may want to change this or make it an input.
Missing aspects or possible future improvements:
-
Entry pattern validity checks:
It’s typical in BoS trading EAs to verify price action conditions, candle closes, or volume before entry.
-
Delay logic between trades:
To avoid frequent entries, introducing a minimum time between trades can help.
-
Logging improvements:
Currently your
PrintFormatlogs extensively, which can clutter the Journal. Consider conditional debug logging controlled by an input booldebug. -
Safety on OrderSend:
It is generally good to check trade context by wrapping OrderSend calls with a retry mechanism or error code guards to handle trading context busy errors.
Summary
Your EA is well-structured and incorporates many advanced features. Here are recommended fixes and improvements:
-
Use
TrailingProfitTriggerPercinput parameter consistently inUpdateTrailingStopByMarketStructure()instead of hard-coded 0.5. -
Change offset parameter in
iHighest()andiLowest()from0(unclosed candle) to1(last closed candle) in trailing functions, for stability. -
Improve minimum stop loss distance enforcement logic in ATR trailing to ensure SL is never moved closer to price than allowed buffer.
-
Consider initializing swing lines at valid prices in
OnInit()or when first created. -
Optionally optimize repeated indicator value fetching (ATR, EMA) so to avoid
CopyBufferon every tick or use bar close values. -
Add comments where logic branches, especially reverse entries, to easily maintain the code.
-
Add debugging controls to turn off verbose logging in live trading.
-
Add retry or error checks around
OrderSend()especially for common issues like trade context busy (err 145).
If you want, I can help you implement these fixes or provide example changes for any part of the code. Just let me know!
- User
can you explain me how is working stop loss with these settings: enableTrailingSL=true trailingStopMode=3 ms_swingLookback=20 atr_trail_mult=1.0 TrailUpdateIntervalSec=13 MinSLBufferATRMult=2.0 TrailingProfitTriggerPerc=1.0
- Assistant
Certainly! Let me explain how the stop loss behavior works with your specific trailing stop settings when:
- enableTrailingSL = true
- trailingStopMode = 3 (TrailingHybrid)
- ms_swingLookback = 20 bars
- atr_trail_mult = 1.0
- TrailUpdateIntervalSec = 13 seconds
- MinSLBufferATRMult = 2.0
- TrailingProfitTriggerPerc = 1.0 (100%)
What is the hybrid trailing mode (
TrailingHybrid = 3)?The hybrid trailing combines Market Structure-based trailing stop and ATR-based trailing stop to decide the new Stop Loss (SL) position. It tries to find the best (most protective) SL between:
- Swing lows/highs of recent bars (market structure)
- ATR volatility-based distance from current price
You cannot simply move stop loss blindly; it usually moves only when the price has moved sufficiently in your favor.
Step-by-step behavior of stop loss with your settings:
1. When does trailing start?
-
The trailing SL only activates once your trade is at least 100% profitable relative to the initial stop loss size because of:
TrailingProfitTriggerPerc = 1.0 -
This means: your price must have moved in your favor by at least the initial SL distance (the whole SL distance you placed on entry).
-
For example, if SL was 50 pips away from entry, price must move 50 pips in profit before trailing activates.
2. How often does the trailing update?
-
The updates to the trailing stop for any given position are throttled to at most once every 13 seconds because of:
TrailUpdateIntervalSec = 13 -
This avoids flooding with too many modification requests and provides CPU/terminal performance efficiency.
3. Market structure trailing stop part (ms_swingLookback = 20)
-
The EA looks back over the last 20 bars (on
PERIOD_CURRENT, meaning chart’s timeframe) to find the relevant extrema to base SL on:- For a BUY position: the EA finds the lowest low in the last 20 bars.
- For a SELL position: the EA finds the highest high in the last 20 bars.
-
It shifts this value 2 points away (buffer) to avoid being triggered prematurely.
-
This swing low/high defines a potential new protective SL.
4. ATR-based trailing stop part (
atr_trail_mult = 1.0andMinSLBufferATRMult = 2.0)-
The EA gets the current ATR (average true range) value on the chosen ATR timeframe (
volatilityTFinput). -
It computes a minimum SL buffer place relative to current price:
MinSLBufferATRMult = 2.0means the new SL must be at least 2 ATRs away from current price to avoid being set too tight.
-
The ATR-based trailing SL attempts to place SL at:
-
BUY:
current_price - (ATR * atr_trail_mult)
Here,atr_trail_mult = 1.0, so that's 1 ATR below current price. -
But because of
MinSLBufferATRMult=2.0, if this would move SL inside of 2 ATRs from current price, it gets adjusted back to 2 ATRs distance.
-
-
The result is that your ATR-based SL will never be set nearer than 2 ATRs from current price, no matter what.
5. How is the new SL chosen between ATR and Market Structure?
-
The EA selects the better (safer) SL between these two:
-
For BUY positions:
new_sl = MathMax(ms_new_sl, atr_new_sl);So among the market structure SL and the ATR SL (both below current price), the higher value (closer to price) is chosen to maximize protection but avoid too tight stop.
-
For SELL positions:
new_sl = MathMin(ms_new_sl, atr_new_sl);Among the two candidate SLs (both above current price), the lower value (tighter stop but protects better) is chosen.
-
6. When does the stop loss update?
-
The SL update happens only if the new SL is better than the current SL and still not worse than current price.
-
For BUY:
-
Update if:
new_sl > current_sl (move SL up) AND new_sl < current_price
-
-
For SELL:
-
Update if:
new_sl < current_sl (move SL down) AND new_sl > current_price
-
This prevents SL from being moved backward or tight against the current price.
Summary: How your stop loss behaves with these settings:
Condition/Step Description Trailing Activation Only activates after price moves 100% (TrailingProfitTriggerPerc=1.0) of initial SL distance in profit Trailing Update Frequency Updates at most every 13 seconds (TrailUpdateIntervalSec) Market Structure SL Calculation Finds swing low (buy) or swing high (sell) across last 20 bars (ms_swingLookback=20) ATR SL Calculation Trailing SL based on current price minus/add ATR × 1 (atr_trail_mult = 1.0), but not closer than 2 ATRs away (MinSLBufferATRMult=2.0) Final SL Selection Chooses better protective SL from Market Structure and ATR SL according to trade direction SL Movement Constraints SL moves only closer to profit but never tighter than current price and only improves protection
Example for BUY trade:
- Initial SL is set at entry price minus, say, 50 points (initial SL).
- Price moves up by 50 points or more (100% of SL distance).
- EA looks at the lowest low in last 20 bars, subtracts 2 points buffer, proposes that as
ms_new_sl. - EA calculates ATR, say ATR=20 points, ATR SL based on 1.0×ATR = 20 points below current price. But must be ≥ 2×ATR = 40 points away, so ATR SL at current price - 40 points minimum.
- EA takes max of
ms_new_sland ATR SL. - If result is higher than current SL but below current price, it moves SL there.
- The trailing updates happen at most every 13 seconds.
Why these parameters?
- ms_swingLookback=20: looks back 20 bars for swing levels; enough to smooth out noise but still reactive.
- atr_trail_mult=1.0: SL trails 1×ATR away from price, reactive to volatility.
- MinSLBufferATRMult=2.0: enforces that your SL is never too close to current price (at least 2× ATR away), avoiding false stops on noise.
- TrailingProfitTriggerPerc=1.0: trailing only starts after you have full risk amount locked in profit (conservative trailing).
- TrailUpdateIntervalSec=13: throttles updates—no too frequent SL modifications.
If you want I can make a simplified explanation or diagram of this trailing logic. Would you like that?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.