Certainly! Below is the full, complete EA code including everything you provided, with the fractal-based market structure trend detection fully integrated, your risk management, cooldowns, ADX filter, and all trailing stop functions included as per your original version.
//+------------------------------------------------------------------+
//| Break of Structure EA with floating risk cap and fractal trend |
//| Added ADX filter, losing streak filter, cooldowns, trailing SL |
//| Reverse entries as liquidity grab, multi TF market structure |
//+------------------------------------------------------------------+
#property copyright ""
#property version "1.8"
#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 ENUM_TIMEFRAMES marketStructureTrendTF = PERIOD_M15;
input int marketStructureLookback = 3;
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;
input int adxPeriod = 14;
input double adxThreshold = 25.0;
input ENUM_TIMEFRAMES adxTimeframe = PERIOD_M15;
input int maxLosingStreak = 3;
input int postCloseCooldownSeconds = 60;
CTrade trade;
int atr_handle = INVALID_HANDLE;
int adx_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;
static int g_currentLosingStreak = 0;
static datetime g_lastLosingStreakResetDay = 0;
static ulong g_lastHistoryTickTime = 0;
datetime lastTradeCandleTime = 0;
ENUM_TIMEFRAMES cooldownTimeframe = swingTF;
datetime lastTradeOpenTime = 0;
int tradeIntervalSeconds = 60;
//+------------------------------------------------------------------+
void ResetDailyEquityIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm;
TimeToStruct(now, tm);
MqlDateTime todayMidnight = {tm.year, tm.mon, tm.day, 0,0,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 ResetLosingStreakIfNewDay()
{
datetime now = TimeCurrent();
MqlDateTime tm;
TimeToStruct(now, tm);
MqlDateTime todayMidnight = {tm.year, tm.mon, tm.day, 0,0,0};
datetime midnightTime = StructToTime(todayMidnight);
if(g_lastLosingStreakResetDay != midnightTime)
{
g_lastLosingStreakResetDay = midnightTime;
g_currentLosingStreak = 0;
PrintFormat("Losing streak reset at new day %s",
TimeToString(now, TIME_DATE|TIME_SECONDS));
}
}
//+------------------------------------------------------------------+
void UpdateLosingStreak()
{
datetime now = TimeCurrent();
if(!HistorySelect(now - 86400, now))
{
Print("HistorySelect failed");
return;
}
ulong maxClosedTime=0;
int total=HistoryDealsTotal();
for(int i=total-1; i>=0; i--)
{
ulong ticket=HistoryDealGetTicket(i);
datetime closeTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(closeTime <= g_lastHistoryTickTime) continue;
maxClosedTime=MathMax(maxClosedTime, (ulong)closeTime);
string symbol = HistoryDealGetString(ticket, DEAL_SYMBOL);
ulong magic = HistoryDealGetInteger(ticket, DEAL_MAGIC);
if(symbol!=_Symbol || magic!=inpMagicNumber) continue;
long entryType=HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(entryType != DEAL_ENTRY_OUT) continue;
double profit=HistoryDealGetDouble(ticket, DEAL_PROFIT);
if(profit<0)
{
g_currentLosingStreak++;
PrintFormat("Losing trade detected (ticket %I64d, profit %.2f). Current losing streak: %d", ticket, profit, g_currentLosingStreak);
}
else
{
if(g_currentLosingStreak>0)
PrintFormat("Winning trade detected (ticket %I64d, profit %.2f). Resetting losing streak.", ticket, profit);
g_currentLosingStreak=0;
}
}
if(maxClosedTime>0)
g_lastHistoryTickTime=maxClosedTime;
}
//+------------------------------------------------------------------+
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 lot=(balance*(riskPercent/100.0))/(sl_distance_price*point_value*contract_size);
if(lot<=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);
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;
}
//+------------------------------------------------------------------+
bool IsFractalHigh(string symbol, ENUM_TIMEFRAMES timeframe, int index)
{
double high = iHigh(symbol, timeframe, index);
for(int offset=-2;offset<=2;offset++)
{
if(offset==0) continue;
int chk=index+offset;
if(chk<0 || chk>=Bars(symbol, timeframe)) continue;
if(iHigh(symbol, timeframe, chk)>=high)
return false;
}
return true;
}
//+------------------------------------------------------------------+
bool IsFractalLow(string symbol, ENUM_TIMEFRAMES timeframe, int index)
{
double low=iLow(symbol, timeframe, index);
for(int offset=-2; offset<=2; offset++)
{
if(offset==0) continue;
int chk=index+offset;
if(chk<0 || chk>=Bars(symbol, timeframe)) continue;
if(iLow(symbol, timeframe, chk)<=low)
return false;
}
return true;
}
//+------------------------------------------------------------------+
int GetMarketStructureTrend()
{
double swingHighs[];
double swingLows[];
ArrayResize(swingHighs, marketStructureLookback);
ArrayResize(swingLows, marketStructureLookback);
int foundHighs=0, foundLows=0;
int maxSearch=100;
for(int i=1;i<maxSearch && (foundHighs<marketStructureLookback || foundLows<marketStructureLookback);i++)
{
if(foundHighs<marketStructureLookback && IsFractalHigh(_Symbol, marketStructureTrendTF, i))
{
swingHighs[foundHighs]=iHigh(_Symbol, marketStructureTrendTF, i);
foundHighs++;
}
if(foundLows<marketStructureLookback && IsFractalLow(_Symbol, marketStructureTrendTF, i))
{
swingLows[foundLows]=iLow(_Symbol, marketStructureTrendTF, i);
foundLows++;
}
}
if(foundHighs < marketStructureLookback || foundLows < marketStructureLookback)
{
PrintFormat("Insufficient fractal swings found (Highs=%d, Lows=%d)", foundHighs, foundLows);
return 0;
}
bool higherHighs=true, higherLows=true, lowerHighs=true, lowerLows=true;
for(int j=1; j<marketStructureLookback; j++)
{
if(swingHighs[j] <= swingHighs[j-1]) higherHighs=false;
if(swingLows[j] <= swingLows[j-1]) higherLows=false;
if(swingHighs[j] >= swingHighs[j-1]) lowerHighs=false;
if(swingLows[j] >= swingLows[j-1]) lowerLows=false;
}
if(higherHighs && higherLows)
return 1;
if(lowerHighs && lowerLows)
return -1;
return 0;
}
//+------------------------------------------------------------------+
int OnInit()
{
atr_handle = iATR(_Symbol, volatilityTF, atrPeriod);
if(atr_handle == INVALID_HANDLE)
{
Print("Failed to create ATR handle");
return INIT_FAILED;
}
adx_handle = iADX(_Symbol, adxTimeframe, adxPeriod);
if(adx_handle == INVALID_HANDLE)
{
Print("Failed to create ADX handle");
IndicatorRelease(atr_handle);
return INIT_FAILED;
}
if(!ObjectCreate(0, swingHighLineName, OBJ_HLINE, 0, TimeCurrent(), 0) ||
!ObjectCreate(0, swingLowLineName, OBJ_HLINE, 0, TimeCurrent(), 0))
{
Print("Failed to create swing lines");
IndicatorRelease(atr_handle);
IndicatorRelease(adx_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);
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(atr_handle != INVALID_HANDLE)
IndicatorRelease(atr_handle);
if(adx_handle != INVALID_HANDLE)
IndicatorRelease(adx_handle);
}
//+------------------------------------------------------------------+
void OnTick()
{
datetime now = TimeCurrent();
if(postCloseCooldownSeconds > 0 && IsRecentPositionClose(postCloseCooldownSeconds))
{
PrintFormat("Post-close cooldown active, skipping trades at %s", TimeToString(now));
return;
}
ResetDailyEquityIfNewDay();
ResetLosingStreakIfNewDay();
UpdateLosingStreak();
if(maxLosingStreak > 0 && g_currentLosingStreak >= maxLosingStreak)
{
PrintFormat("Current losing streak %d >= max allowed %d. No new trades allowed now.", g_currentLosingStreak, maxLosingStreak);
return;
}
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;
}
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);
}
}
}
}
}
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 totalPositions=PositionsTotal();
for(int i=0; i<totalPositions; 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;
if(lastTradeOpenTime != 0 && (now - lastTradeOpenTime) < tradeIntervalSeconds)
return;
MqlRates candleRates[];
if(CopyRates(_Symbol, cooldownTimeframe, 1, 1, candleRates)!=1)
{
Print("Failed to get last closed candle data for cooldown check");
return;
}
datetime currentCandleTime = candleRates[0].time;
if(currentCandleTime == lastTradeCandleTime)
return;
double atr_buf[];
if(CopyBuffer(atr_handle, 0, 1, 1, atr_buf)<=0)
return;
double atr = atr_buf[0];
if(atr <= 0)
atr = 10.0 * _Point;
double adx_buf[];
if(adx_handle == INVALID_HANDLE)
{
Print("ADX handle invalid");
return;
}
if(CopyBuffer(adx_handle, 0, 1, 1, adx_buf)<=0)
{
Print("Failed to copy ADX buffer");
return;
}
double adx_value = adx_buf[0];
if(adx_value < adxThreshold)
{
PrintFormat("ADX=%.2f below threshold %.2f, skipping new entries", adx_value, adxThreshold);
return;
}
int marketTrend = GetMarketStructureTrend();
if(marketTrend == 0)
return;
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 sl_dist = atr * sl_atr_mult;
double tp_dist = sl_dist * r2r_ratio;
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(marketTrend == 1)
{
if(ask > lastSwingHigh && !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);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
}
else if(marketTrend == -1)
{
if(bid < lastSwingLow && !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);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
}
}
else
{
if(marketTrend == 1)
{
if(bid < lastSwingLow && !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);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
}
else if(marketTrend == -1)
{
if(ask > lastSwingHigh && !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);
lastTradeCandleTime = currentCandleTime;
lastTradeOpenTime = now;
}
}
}
}
}
//+------------------------------------------------------------------+
// IsRecentPositionClose function
bool IsRecentPositionClose(uint cooldownSecs)
{
datetime now = TimeCurrent();
if(!HistorySelect(now - cooldownSecs - 10, now))
{
Print("HistorySelect failed");
return false;
}
int totalDeals=HistoryDealsTotal();
for(int i=totalDeals-1; i>=0; i--)
{
ulong ticket=HistoryDealGetTicket(i);
if(ticket==0) continue;
datetime dealTime = (datetime)HistoryDealGetInteger(ticket, DEAL_TIME);
if(dealTime == 0 || (now - dealTime) > cooldownSecs)
continue;
string symbol=HistoryDealGetString(ticket, DEAL_SYMBOL);
ulong magic=HistoryDealGetInteger(ticket, DEAL_MAGIC);
long entry=HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(symbol == _Symbol && magic == inpMagicNumber && entry == DEAL_ENTRY_OUT)
{
PrintFormat("Recent position close detected at %s, cooldown active.", TimeToString(dealTime));
return true;
}
}
return false;
}
//+------------------------------------------------------------------+
// --- Trailing SL functions ---
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=MathAbs(entry_price-sl);
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-2*point, 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+2*point, 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);
}
}
//+------------------------------------------------------------------+
You can copy this full code into your MetaEditor, compile and test. Let me know if you want me to assist with debugging, parameter tuning, or adding logs!
Happy trading! 🚀