Trailing stop loss only work in next bar, not every single tick as intended.

Ka Ho  

Hello everyone!

So I have a stop loss check in the Ontick function like this:

Some part of the code is hide away for simplicity.

//| Expert tick function                                             |
void OnTick(void)

//--- Calculate entry price
   double now_price = NormalizeDouble(SymbolInfoDouble(_Symbol,order==ORDER_TYPE_SELL ? SYMBOL_BID:SYMBOL_ASK), _Digits);

   CheckTrailingStop(now_price, ATRtrail*sign_for_stop_loss*STOPLOSS[1], sign_for_stop_loss);

The trailing is as follow, I want the trail to trigger when a threshold is reached. And it should be checked every single tick. If the threshold is reached, we move the stop loss to the current price.

void CheckTrailingStop(double now_price, double SLTrigger, double sign_for_stop_loss){

  double SL = NormalizeDouble(now_price - SLTrigger, _Digits);

  for(int i =PositionsTotal()-1;i>=0;i--)
   string symbol=PositionGetSymbol(i);
      ulong PositionTicket=PositionGetInteger(POSITION_TICKET);
      double CurrentStopLoss=PositionGetDouble(POSITION_SL);
      double position_prize = PositionGetDouble(POSITION_PRICE_OPEN);
      if(CurrentStopLoss<SL && now_price > position_prize + sign_for_stop_loss*90/MathPow(10,_Digits) )
         ExtTrade.PositionModify(PositionTicket, now_price - sign_for_stop_loss*10/MathPow(10,_Digits) ,0);

The stop loss is kind of working, except that it is doing its work only after a bar is closed and move onto the next bar. A proof is in the attached diagram

If you look at the red circle, you can see that the position is closed one bar late, hence, the stop loss is working one bar late.

Thank you for your precious time. Any help would be appreciated.

Basic Principles - Trading Operations - MetaTrader 5 Help
Basic Principles - Trading Operations - MetaTrader 5 Help
is an instruction given to a broker to buy or sell a financial instrument. There are two main types of orders: Market and Pending. In addition, there are special Take Profit and Stop Loss levels. is the commercial exchange (buying or selling) of a financial security. Buying is executed at the demand price (Ask), and Sell is performed at the...
trailing.png  98 kb