4.2 Trailing stop, break-even and ATR
A fixed stop loss is a good start. But many strategies get better when the stop loss follows the price, or when the distance adapts to how volatile the market is.
Break-even
When the trade has moved a certain number of pips in your favour, the stop loss is moved to the entry price. Then the trade can no longer make a loss (except on price gaps).
Trailing stop
The stop loss follows the price at a fixed distance – but is never moved back. This must be checked on every price change, which is why the code sits in OnTick() before the check for a new candle.
input double InpTrailingPips = 20;
void TrailPositions()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0) continue;
if(PositionGetString(POSITION_SYMBOL) != _Symbol ||
PositionGetInteger(POSITION_MAGIC) != (long)InpMagic) continue;
double sl = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
double newSl = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID) - InpTrailingPips * pip, _Digits);
if(newSl > sl) trade.PositionModify(ticket, newSl, tp); // only upwards
}
else
{
double newSl = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK) + InpTrailingPips * pip, _Digits);
if(sl == 0 || newSl < sl) trade.PositionModify(ticket, newSl, tp); // only downwards
}
}
}In cTrader you do the same with position.ModifyStopLossPrice(...) inside a foreach loop over Positions.FindAll(Label, SymbolName).
ATR instead of pips
A 30-pip stop loss can be too little on a volatile day and too much on a quiet day. With the ATR the robot measures how much the price normally moves, and sets the stop loss accordingly:
int hAtr = iATR(_Symbol, _Period, 14); // in OnInit
double atr = Value(hAtr, 1); // ATR on candle 1
double slDistance = atr * 1.5; // stop loss = 1.5 × ATR
double tpDistance = atr * 3.0; // take profit = 3 × ATRCombined with the position size from the previous lesson, you get a robot that risks the same amount of money every time – however far away the stop loss is.
Respect the broker’s minimum distance
The broker can require a minimum distance between the price and the stop loss (the stops level). If the robot moves the stop loss closer than that, the change is rejected. Check SYMBOL_TRADE_STOPS_LEVEL in MQL5 or MODE_STOPLEVEL in MQL4 before you move it.
Try it yourself
Test the robot with and without a trailing stop. Which version gave the best balance between profit and drawdown?
Key takeaways
- Break-even moves the stop loss to the entry after a certain profit.
- A trailing stop is checked on every price change and only moved in your favour.
- The ATR gives a stop loss and take profit that adapt to volatility.
65% of retail investor accounts lose money when trading CFDs with this provider.