Full EA code attached below.
Code: Select all
void ApplyTrailingStop()
{
if(!PositionSelect(Symbol())) return; // If no position for this symbol, exit the function
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
double currentPrice = SymbolInfoDouble(Symbol(), (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SYMBOL_BID : SYMBOL_ASK);
double trailingStopInPoints = 10; // 15 pips = 150 points
double distanceToTrail = trailingStopInPoints * SymbolInfoDouble(Symbol(), SYMBOL_POINT);
double currentStopLoss = PositionGetDouble(POSITION_SL);
double newStopLoss = 0;
if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
newStopLoss = currentPrice - distanceToTrail;
if(currentStopLoss < newStopLoss || currentStopLoss == 0)
{
trade.PositionModify(Symbol(), newStopLoss, PositionGetDouble(POSITION_TP));
}
}
else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
newStopLoss = currentPrice + distanceToTrail;
if(currentStopLoss > newStopLoss || currentStopLoss == 0)
{
trade.PositionModify(Symbol(), newStopLoss, PositionGetDouble(POSITION_TP));
}
}
}