Issues with my TrailingStop

 
Hi guys, I'm a trader new to coding and I am trying to learn different MQL4 functions. But I have found it challenging when it comes to Trailing Stop Loss part, below is my code and if anyone can let me know the mistakes made so I can make the trailing stop work on both buy, sell orders will appreciate. Thanks in advance.
//+------------------------------------------------------------------+
//|                                                        Test2.mq4 |
//|                                   Copyright 2021, Testing      . |
//|                                     https://www.testing.com      |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, Black Royalty."
#property link      "https://www.blackroyalty.com"
#property version   "1.00"
#property strict
#include <BR_Functions.mqh>
#define MAX_ORDERS 0
extern bool UseTrailingStop= true;
extern int WhenToTrail= 100;
extern int TrailAmount= 50;
input int InpMagicNumber= 34034;
input int TrailingStopPoint= 50;
input double InpVolume= 1;
input bool Monday= true;
input bool Tuesday= true;
input bool Wednesday= true;
input bool Thursday= true;
input bool Friday= true;
double pips;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
  double ticksize= MarketInfo(Symbol(),MODE_TICKSIZE);
  if( ticksize==0.00001 || ticksize==0.001)
    pips= ticksize*10;
     else pips=ticksize;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
int start()
  {
//---
   if(UseTrailingStop)AdjustTrail();
   return(0);  
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
     if(OrdersTotal()<=MAX_ORDERS)
   {
  if((DayOfWeek()==1)&& (Monday))
    {
    datetime time=TimeLocal();
    string HoursAndMinutes= TimeToString(time,TIME_MINUTES);
    if(StringSubstr(HoursAndMinutes,0,5)=="15:00")
     {
     RefreshRates();
     BuyTrades(Symbol(),InpVolume,InpMagicNumber);
     AdjustTrail();
     }
    } 
  if((DayOfWeek()==2)&& (Tuesday))
    {
    datetime time=TimeLocal();
    string HoursAndMinutes= TimeToString(time,TIME_MINUTES);
    if(StringSubstr(HoursAndMinutes,0,5)=="15:30")
     {
     RefreshRates();
     SellTrades(Symbol(),InpVolume,InpMagicNumber);
     AdjustTrail();
     }
    } 
  if((DayOfWeek()==3)&& (Wednesday))
    {
    datetime time=TimeLocal();
    string HoursAndMinutes= TimeToString(time,TIME_MINUTES);
    if(StringSubstr(HoursAndMinutes,0,5)=="16:00")
     {
     RefreshRates();
     BuyTrades(Symbol(),InpVolume,InpMagicNumber);
     AdjustTrail();
     }
    } 
  if((DayOfWeek()==4)&& (Thursday))
    {
    datetime time=TimeLocal();
    string HoursAndMinutes= TimeToString(time,TIME_MINUTES);
    if(StringSubstr(HoursAndMinutes,0,5)=="16:30")
     {
     RefreshRates();
     SellTrades(Symbol(),InpVolume,InpMagicNumber);
     AdjustTrail();
     }
    }  
  if((DayOfWeek()==5)&& (Friday))
    {
    datetime time=TimeLocal();
    string HoursAndMinutes= TimeToString(time,TIME_MINUTES);
    if(StringSubstr(HoursAndMinutes,0,5)=="17:00")
     {
     RefreshRates();
     BuyTrades(Symbol(),InpVolume,InpMagicNumber);
     AdjustTrail();
     }
    }    
  }
  }

//+------------------------------------------------------------------+
void AdjustTrail(){
   for(int b=OrdersTotal()-1;b>=0;b--)
     {
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
        if(OrderMagicNumber()==InpMagicNumber)
         if(OrderSymbol()==Symbol())
          if(OrderType()==OP_BUY)
           if(Bid-OrderOpenPrice()>WhenToTrail*pips)
            if(OrderStopLoss()<Bid-TrailAmount*pips)
             OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(pips*TrailAmount),OrderTakeProfit(),0,CLR_NONE);
     }
   for(int s=OrdersTotal()-1;s>=0;s--)
     {
      if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
        if(OrderMagicNumber()==InpMagicNumber)
         if(OrderSymbol()==Symbol())
          if(OrderType()==OP_SELL)
           if(OrderOpenPrice()-Ask>WhenToTrail*pips)
            if(OrderStopLoss()>Ask+TrailAmount*pips)
             OrderModify(OrderTicket(),OrderOpenPrice(),Ask+(pips*TrailAmount),OrderTakeProfit(),0,CLR_NONE);
     }     
  }

//+------------------------------------------------------------------+
//| Create Buy Order                                                 |
//+------------------------------------------------------------------+
void BuyTrades( string symbol, double volume, int MagicNumber){
   int BuyCount= 0;
   int Count= OrdersTotal();
   for(int i=Count -1; i>=0;i--){
     if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
       if(OrderSymbol()==symbol && OrderMagicNumber()==MagicNumber){
         if(OrderType()==OP_BUY) BuyCount++;
         }
       }
     }
    if(BuyCount==0){
       if(OrderSend(symbol,OP_BUY,volume,Ask,0,0,0,NULL,MagicNumber)) {}
       }
}

//+------------------------------------------------------------------+
//| Create Sell Order                                                |
//+------------------------------------------------------------------+
void SellTrades( string symbol, double volume, int MagicNumber){
   int SellCount= 0;
   int Count= OrdersTotal();
   for(int i=Count -1; i>=0;i--){
     if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
       if(OrderSymbol()==symbol && OrderMagicNumber()==MagicNumber){
         if(OrderType()==OP_SELL) SellCount++;
         }
       }
     }
    if(SellCount==0){   
       if(OrderSend(symbol,OP_SELL,volume,Bid,0,0,0,NULL,MagicNumber)) {}
       }
}

//+------------------------------------------------------------------+
//| Create Both Buy & Sell Orders                                    |
//+------------------------------------------------------------------+
void CreateTrades( string symbol, double volume, int MagicNumber){
   int BuyCount= 0;
   int SellCount= 0;
   int Count= OrdersTotal();
   for(int i=Count -1; i>=0;i--){
     if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
       if(OrderSymbol()==symbol && OrderMagicNumber()==MagicNumber){
         if(OrderType()==OP_BUY) BuyCount++;
         if(OrderType()==OP_SELL) SellCount++;
         }
       }
     }
    if(BuyCount==0){
       if(OrderSend(symbol,OP_BUY,volume,0,0,0,0,NULL,MagicNumber)) {}
       }
    if(SellCount==0){   
       if(OrderSend(symbol,OP_SELL,volume,0,0,0,0,NULL,MagicNumber)) {}
       }
}
 

Only post the relevant parts of your code.

I've done it for you here, but please do it yourself in the future:

extern int WhenToTrail= 100;
extern int TrailAmount= 50;

int OnInit()
  {
//---
  double ticksize= MarketInfo(Symbol(),MODE_TICKSIZE);
  if( ticksize==0.00001 || ticksize==0.001)
    pips= ticksize*10;
     else pips=ticksize;
//---
   return(INIT_SUCCEEDED);
  }

void AdjustTrail(){
   for(int b=OrdersTotal()-1;b>=0;b--)
     {
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
        if(OrderMagicNumber()==InpMagicNumber)
         if(OrderSymbol()==Symbol())
          if(OrderType()==OP_BUY)
           if(Bid-OrderOpenPrice()>WhenToTrail*pips)
            if(OrderStopLoss()<Bid-TrailAmount*pips)
             OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(pips*TrailAmount),OrderTakeProfit(),0,CLR_NONE);
     }
   for(int s=OrdersTotal()-1;s>=0;s--)
     {
      if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
        if(OrderMagicNumber()==InpMagicNumber)
         if(OrderSymbol()==Symbol())
          if(OrderType()==OP_SELL)
           if(OrderOpenPrice()-Ask>WhenToTrail*pips)
            if(OrderStopLoss()>Ask+TrailAmount*pips)
             OrderModify(OrderTicket(),OrderOpenPrice(),Ask+(pips*TrailAmount),OrderTakeProfit(),0,CLR_NONE);
     }     
  }

The logic of your code seems right.

Be sure to check the return value of OrderModify.

Returned value

If the function succeeds, it returns true, otherwise false. To get the detailed error information, call the GetLastError() function.

It's also recommended that your Normalize the price of the stoploss since you performed arithmetic on it.

Side notes:

I also recommend you refactor (clean up and optimize) your code.

For example, you have two for-loops to distinguish between Buy orders and Sell orders, when you only need one for-loop and then run a check on OrderType to distinguish between OP_BUY and OP_SELL.

Another thing you can do is store the boolean values from the if-statements into variables with descriptive names so it's easier to read, debug, and maintain your code.

OrderModify - Trade Functions - MQL4 Reference
OrderModify - Trade Functions - MQL4 Reference
  • docs.mql4.com
OrderModify - Trade Functions - MQL4 Reference
 
Why do you try it yourself? There are dozens solutions. you have to search for them. Top right is a lens copy in the field trailing stop automated and select articles and codebase.
Reason: