Mql4 Code Trailing Stop Loss not Moving on time

 

//+------------------------------------------------------------------+
//|                                              CANDLE_HIGH_LOW.mq4 |
//|                                                      Hariprasath |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Hariprasath"
#property link      ""
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
double Lots = 0.01;
double minStopLossLevel = MarketInfo(_Symbol, MODE_STOPLEVEL) * Point;
double bidPrice = MarketInfo(Symbol(), MODE_BID);
double askPrice = MarketInfo(Symbol(), MODE_ASK);
double priceDifferece = askPrice-bidPrice;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   gettingPriceData();
   creatingLines();
   placeOrder();
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double gettingRecentHigh()
  {

   if(High[1] > High[2])
     {
      return High[1];
     }
   else
      return High[2];
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double gettingRecentLow()
  {

   if(Low[1] > Low[2])
     {
      return Low[2];
     }
   else
      return Low[1];
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void placeOrder()
  {
   double HighValue = gettingRecentHigh();
   double LowValue = gettingRecentLow();
   if(Ask > HighValue)
     {
      buyOrder();
      buyTrailingStopLoss();
     }

   if(Bid<LowValue)
     {
      sellOrder();
      selltrailingStopLoss();
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void gettingPriceData()
  {
   double recentHigh = gettingRecentHigh();
   double previousLow = gettingRecentLow();
   double AccountEquityBalance = AccountInfoDouble(ACCOUNT_EQUITY);
   double AccountProfitBalance = AccountInfoDouble(ACCOUNT_PROFIT);

//Display price
   ObjectCreate("bidPrice",OBJ_LABEL,0,0,0);
   ObjectSet("bidPrice",OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSet("bidPrice",OBJPROP_XDISTANCE,20);
   ObjectSet("bidPrice",OBJPROP_YDISTANCE,10);
   ObjectSetText("bidPrice","Bid Price : " + DoubleToStr(bidPrice,Digits),15,"Arial",White);

   ObjectCreate("askPrice",OBJ_LABEL,0,0,0);
   ObjectSet("askPrice",OBJPROP_CORNER,CORNER_LEFT_UPPER);
   ObjectSet("askPrice",OBJPROP_XDISTANCE,20);
   ObjectSet("askPrice",OBJPROP_YDISTANCE,40);
   ObjectSetText("askPrice","Ask Price : " + DoubleToStr(askPrice,Digits),15,"Arial",White);

   ObjectCreate("recentHigh",OBJ_LABEL,0,0,0);
   ObjectSet("recentHigh",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
   ObjectSet("recentHigh",OBJPROP_XDISTANCE,20);
   ObjectSet("recentHigh",OBJPROP_YDISTANCE,10);
   ObjectSetText("recentHigh","Recent High : " + DoubleToStr(recentHigh,Digits),15,"Arial",White);


   ObjectCreate("previousLow",OBJ_LABEL,0,0,0);
   ObjectSet("previousLow",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
   ObjectSet("previousLow",OBJPROP_XDISTANCE,20);
   ObjectSet("previousLow",OBJPROP_YDISTANCE,40);
   ObjectSetText("previousLow","Previous Low : " + DoubleToStr(previousLow,Digits),15,"Arial",White);

   ObjectCreate("minStopLossLevel",OBJ_LABEL,0,0,0);
   ObjectSet("minStopLossLevel",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
   ObjectSet("minStopLossLevel",OBJPROP_XDISTANCE,20);
   ObjectSet("minStopLossLevel",OBJPROP_YDISTANCE,70);
   ObjectSetText("minStopLossLevel","MinStopLossLevel : " + DoubleToStr(minStopLossLevel,Digits),15,"Arial",White);

   ObjectCreate("priceDifferece",OBJ_LABEL,0,0,0);
   ObjectSet("priceDifferece",OBJPROP_CORNER,CORNER_RIGHT_UPPER);
   ObjectSet("priceDifferece",OBJPROP_XDISTANCE,20);
   ObjectSet("priceDifferece",OBJPROP_YDISTANCE,100);
   ObjectSetText("priceDifferece","PriceDifferece : " + DoubleToStr(priceDifferece,Digits),15,"Arial",White);

   ObjectCreate("AccountEquityBalance",OBJ_LABEL,0,0,0);
   ObjectSet("AccountEquityBalance",OBJPROP_CORNER,CORNER_LEFT_LOWER);
   ObjectSet("AccountEquityBalance",OBJPROP_XDISTANCE,50);
   ObjectSet("AccountEquityBalance",OBJPROP_YDISTANCE,10);
   ObjectSetText("AccountEquityBalance","Account Equity Balance : " + DoubleToStr(AccountEquityBalance,Digits),15,"Arial",White);

   ObjectCreate("AccountProfitBalance",OBJ_LABEL,0,0,0);
   ObjectSet("AccountProfitBalance",OBJPROP_CORNER,CORNER_LEFT_LOWER);
   ObjectSet("AccountProfitBalance",OBJPROP_XDISTANCE,50);
   ObjectSet("AccountProfitBalance",OBJPROP_YDISTANCE,30);
   ObjectSetText("AccountProfitBalance","Account Profit Balance : " + DoubleToStr(AccountProfitBalance,Digits),15,"Arial",White);
  }

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void creatingLines()
  {

//Delete If existing lien
   ObjectDelete("RecentHighLine");

//Creating line
   ObjectCreate("RecentHighLine",OBJ_HLINE,0,Time[0], gettingRecentHigh());
   ObjectSet("RecentHighLine", OBJPROP_COLOR, clrGreen); // Line color
   ObjectSet("RecentHighLine", OBJPROP_WIDTH, 2); // Line width
   ObjectSet("RecentHighLine", OBJPROP_RAY_LEFT, false); // Do not extend to the left
   ObjectSet("RecentHighLine", OBJPROP_RAY_RIGHT, true); // Extend to the right

//Delete If existing lien
   ObjectDelete("PreviousLowLine");

//Creating line
   ObjectCreate("PreviousLowLine",OBJ_HLINE,0,Time[0], gettingRecentLow());
   ObjectSet("PreviousLowLine", OBJPROP_COLOR, clrRed); // Line color
   ObjectSet("PreviousLowLine", OBJPROP_WIDTH, 2); // Line width
   ObjectSet("PreviousLowLine", OBJPROP_RAY_LEFT, false); // Do not extend to the left
   ObjectSet("PreviousLowLine", OBJPROP_RAY_RIGHT, true); // Extend to the right

  }
//+------------------------------------------------------------------+
void buyOrder()
  {
   if(OrdersTotal() < 1)
     {
      // To place order
      int buyTicket =    OrderSend(
                            _Symbol,     //Currency Pair
                            OP_BUY,       // Order Type
                            Lots,       // Lot Size
                            Ask,         // Buying price
                            3,         // Slipage or tolorance
                            0,    //Stop loss
                            0,      //Profit
                            "BUY ORDER PLACED",    // Comments
                            0,            // Magic Number
                            0,                 // Expiation
                            Green             //Arrow allowed
                         );
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void buyTrailingStopLoss()
  {
   double HighValue = gettingRecentHigh();
   double LowValue = gettingRecentLow();

// To count total orders
   for(int a = OrdersTotal()-1; a>=0; a--)
     {
      //To select the orders
      if(OrderSelect(a,SELECT_BY_POS,MODE_TRADES))
         //Check order with current order
         if(OrderSymbol() == Symbol())
            //To find the buy orders
            if(OrderType() == OP_BUY)
               //Fix the stop loss
               //   if(OrderStopLoss() < Ask)
               // Check and update the stop loss
               if(OrderStopLoss() != LowValue)
                  //We modify the stoploss
                  OrderModify(
                     OrderTicket(),    //For the current order
                     OrderOpenPrice(),   // Opended for the open price
                     LowValue,  //Set stop loss
                     OrderTakeProfit(), //Order Take profit
                     0,    //Expiration
                     Red
                  );
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void sellOrder()
  {
   if(OrdersTotal() < 1)
     {
      // To place order
      int sellTicket =    OrderSend(
                             _Symbol,     //Currency Pair
                             OP_SELL,       // Order Type
                             Lots,       // Lot Size
                             Bid,         // Buying price
                             3,         // Slipage or tolorance
                             0,    //Stop loss
                             0,      //Profit
                             "SELL ORDER PLACED",    // Comments
                             0,            // Magic Number
                             0,                 // Expiation
                             Red             //Arrow allowed
                          );
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void selltrailingStopLoss()
  {
     double HighValue = gettingRecentHigh();
   double LowValue = gettingRecentLow();
  // To count total orders
   for(int b = OrdersTotal()-1; b>=0; b--)
     {
      //To select the orders
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
         //Check order with current order
         if(OrderSymbol() == Symbol())
            //To find the buy orders
            if(OrderType() == OP_SELL)
               //Fix the stop loss
               //     if(OrderStopLoss() > Bid)
               //We modify the stoploss
               // Check and update the stop loss
               if(OrderStopLoss() != HighValue)
                  Alert("SELL WORKING");
      OrderModify(
         OrderTicket(),    //For the current order
         OrderOpenPrice(),   // Opended for the open price
         HighValue,  //Set stop loss
         OrderTakeProfit(), //Order Take profit
         0,    //Expiration
         Red
      );
     }
  }
//+------------------------------------------------------------------+

Stoploss should be moved to green line but is not working properly working lately.

Like wise for buy order also expected SL is for red line but its coming below on that value

How to handle this kind of issues?

Files:
SL.png  144 kb
 
Your topic has been moved to the section: MQL4 and MetaTrader 4
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
  1.       //To select the orders
          if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
             //Check order with current order
             if(OrderSymbol() == Symbol())
                //To find the buy orders
                if(OrderType() == OP_SELL)
                   //Fix the stop loss
                   //     if(OrderStopLoss() > Bid)
                   //We modify the stoploss
                   // Check and update the stop loss
                   if(OrderStopLoss() != HighValue)
                      Alert("SELL WORKING");
          OrderModify(

    All those if statements only apply to the Alert. You try to modify all orders on all charts.

  2.      double HighValue = gettingRecentHigh();
       ⋮
          OrderModify(
             OrderTicket(),    //For the current order
             OrderOpenPrice(),   // Opended for the open price
             HighValue,  //Set stop loss

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  3.    if(OrdersTotal() < 1)

    Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
              Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
              PositionClose is not working - MQL5 programming forum (2020)
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
              Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
              Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)

    You need one Magic Number for each symbol/timeframe/strategy.
         Trade current timeframe, one strategy, and filter by symbol requires one MN.
         If trading multiple timeframes, and filter by symbol requires use a range of MN (base plus timeframe).
              Why are MT5 ENUM_TIMEFRAMES strange? - General - MQL5 programming forum - Page 2 #11 (2020)

  4. Check your return codes, and report your errors (including market prices and your variables). Don't look at GLE/LE unless you have an error. Don't just silence the compiler (MT5 / MT4+strict), it is trying to help you.
              What are Function return values ? How do I use them ? - MQL4 programming forum (2012)
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles (2014)