Join & EARN

FOREX ALGOS { }

Trailing Stop Logic

A dynamic method for protecting profits by moving the stop-loss level as the trade becomes profitable. A trailing stop “sequentially shifts Stop Loss at a better price as the favorable trend continues”. In code, this typically runs on each tick (or bar) and modifies the stop if price has advanced.

  • Definition: Automated adjustment of the stop-loss to lock in gains. E.g. “move SL to breakeven after 20 pips profit, then trail by 10 pips.”

  • Context: Often implemented in OnTick() or with a loop checking current price vs. last adjusted level. In MQL5, one might use a custom trailing stop class (as shown in the MQL5 AlgoBook). In NinjaScript or cAlgo, one can use built-in trailing stop methods or manual logic.

  • Example Pseudo-code (MQL5):

    // Called every tick in OnTick():
    for(each open position)
    {
    double newStop = SymbolInfoDouble(_Symbol, SYMBOL_BID) - trailPips*Point;
    if(newStop > PositionGetDouble(POSITION_PRICE_OPEN) + trailPips*Point)
    trade.PositionModify(positionTicket, newStop, currentTakeProfit);
    }
  • Example (NinjaScript):

    // NinjaScript has built-in methods, e.g.:
    SetTrailStop(CalculationMode.Pips, 20);
    This tells NinjaTrader to automatically update the stop as price moves.