BuyStop order is not expiring where it should

 

Hello All,

I am new to MQL5 so please forgive my ignorance. I am trying create EA that places a BuyStop order at the very beginning of each new candle with Price = the High of the previous candle and SL = the Low of previous candle. This order must expire at the end of current candle. However, when I do backtesting some orders don't expire at the end of the current candle but they stay for longer, then they are fulfilled at the wrong (outdated) Buy Stop / SL values. On the other habd, some BuyStop orders do not get fulfilled even if the current price hits the Buy Stop / SL values! Clearly I am doing something wrong so I would appreciate your advice. Thanks in advance

#include<Trade\Trade.mqh>
CTrade trade;

void OnTick()
  {
   MqlRates PriceData[]; //create price array to hold prices
   ArraySetAsSeries(PriceData,true);//sort prices in the array from the current candle downwards
   CopyRates(_Symbol,_Period,0,3,PriceData);//copy candle prices starting from current candle, 0, and copy the price for 3 candles into price array
   static int CandleCounter; 
   static datetime TimeStampLastChecked;
   datetime TimeStampCurrentCandle;
   double ClosePriceLatestCandle;
   TimeStampCurrentCandle=PriceData[0].time; //it can be used instead of TimeCurrent() in Expiration formula. Start time of the current candle.  
   
   if (TimeStampCurrentCandle!=TimeStampLastChecked) //already started to form a new candle
      {
         TimeStampLastChecked=TimeStampCurrentCandle;
         CandleCounter=CandleCounter+1;
                  
         trade.BuyStop(0.01,PriceData[1].high,NULL,PriceData[1].low,0,ORDER_TIME_SPECIFIED,(TimeCurrent() + 10*60),NULL); //the order must expire at the end of current candle (10 minutes candle)   
      }   

  }
Reason: