void TrailingStopLoss(int TrailingStopLoss_magic)
{
int StopLevel_TrailingGap = Trailing_Gap < gStopLevel_OnTick ? gStopLevel_OnTick + 5 : Trailing_Gap;
int StopLevel_TrailingTP = gStopLevel_OnTick > 0 ? gStopLevel_OnTick + 5 : 10;
// Loop through all open orders
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
double TrailingStopLoss_entryPrice = OrderOpenPrice();
// Check if the order is a buy order with magic number 1
if(OrderSymbol() == Symbol() && OrderMagicNumber() == TrailingStopLoss_magic && OrderType() == OP_BUY)
{
if(Bid - (TrailingStopLoss_entryPrice + StopLevel_TrailingTP * gPips) > gPips * StopLevel_TrailingGap)
{
if(OrderStopLoss() < Bid - gPips * StopLevel_TrailingGap || OrderStopLoss() == 0)
{
ResetLastError();
RefreshRates();
gModify = OrderModify(OrderTicket(), OrderOpenPrice(), Bid - gPips * StopLevel_TrailingGap, OrderTakeProfit(), 0, clrNONE);
if((_LastError != ERR_NO_ERROR && _LastError != ERR_NO_MQLERROR) || !gModify)
Print(__FUNCTION__ + " => Buy Order Error Code : " + GetLastError());
}
}
}
// Check if the order is a sell order with magic number 2
if(OrderSymbol() == Symbol() && OrderMagicNumber() == TrailingStopLoss_magic && OrderType() == OP_SELL)
{
if((TrailingStopLoss_entryPrice - StopLevel_TrailingTP * gPips) - Ask > gPips * StopLevel_TrailingGap)
{
if(OrderStopLoss() > Ask + gPips * StopLevel_TrailingGap || OrderStopLoss() == 0)
{
ResetLastError();
RefreshRates();
gModify = OrderModify(OrderTicket(), OrderOpenPrice(), Ask + gPips * StopLevel_TrailingGap, OrderTakeProfit(), 0, clrNONE);
if((_LastError != ERR_NO_ERROR && _LastError != ERR_NO_MQLERROR) || !gModify)
Print(__FUNCTION__ + " => Sell Order Error Code : " + GetLastError());
}
}
}
}
}
}