trailing stop not working

 

I'm trying to insert a trailing stop function in my EA, but somehow i don't get it working properly.

I am trying to do as below:

void MoveTrailingStop()
{
   int cnt, total;
   bool move=false;
   double Trailer_buy, Trailer_sell;
   double sl=OrderStopLoss();
   
   Trailer_buy=NormalizeDouble(Bid-(TrailPip_Buy*pips2dbl),Digits); 
   Trailer_sell=NormalizeDouble(Ask+(TrailPip_Sell*pips2dbl),Digits);

   total=OrdersTotal();
   for(cnt=0;cnt<total;cnt++)
   {
    OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
    if( OrderMagicNumber()==MagicNumber)
    {
     if(OrderType()==OP_BUY)
     {
      if (Bid >= OrderOpenPrice() + (TrailPip_Buy*pips2dbl))
                {
                 if (OrderStopLoss() == 0) sl = OrderOpenPrice();
                 if (Bid > sl +  (TrailPip_Buy*pips2dbl))
                 {
                  sl= Bid - (TrailPip_Buy*pips2dbl);
        move=OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
        if(!move) Print("Error on Modify - Buy");
       }
      }
     }
     if(OrderType()==OP_SELL)
     {
      if (Ask <= OrderOpenPrice() - (TrailPip_Sell*pips2dbl))
                {
                 if (OrderStopLoss() == 0) sl = OrderOpenPrice();
                 if (Ask < sl -  (TrailPip_Sell*pips2dbl))
                 {
             sl= Ask + (TrailPip_Sell*pips2dbl);
        move=OrderModify(OrderTicket(),OrderOpenPrice(),sl,OrderTakeProfit(),0,CLR_NONE);
        if(!move) Print("Error on Modify - Sell");
       }
      }
     }
   }}       
}

But when i backtest and look in the results, it places the stop loss not right (like order 1 below):

What am i doing wrong in the code? Who can help me?

Reason: