limiting EA to trade of given hours and days

 

Hi,

I'd like to confirm my logic to limiting my trading EA to given hours (start to finish) and days.

//setting up trading session
input  string  SectionLabel         = "Trading Session";
extern string  StartTime            = "01.00";     //EA starts hour
extern string  EndTime              = "23:00";     //EA stops hour
input  bool    Sunday               = false;
input  bool    Monday               = true;
input  bool    Tuesday              = true;
input  bool    Wednesday            = true;
input  bool    Thursday             = true;
input  bool    Friday               = true;
input  bool    Saturday             = false;

//function to working with day time
bool DayOfWeek(){
   MqlDateTime dt;
   TimeToStruct(TimeCurrent(),dt);
   
   if((dt.day_of_week ==0 && Sunday)    ||
      (dt.day_of_week ==1 && Monday)    ||
      (dt.day_of_week ==2 && Tuesday)   ||
      (dt.day_of_week ==3 && Wednesday) ||
      (dt.day_of_week ==4 && Tuesday)   ||
      (dt.day_of_week ==5 && Friday)    ||
      (dt.day_of_week ==6 && Saturday)) return true;
   
   return false;
}

Void OnTick()
{
      //--stop trade outside broker's trades allowed time
      _currentServerTime = TimeCurrent();
      datetime serverTimeOfDay = _currentServerTime % 86400;

      if((serverTimeOfDay >= _finish || serverTimeOfDay <= _start) && DayOfWeek() == false) //time an days when broker doesn't allow trading
        {
         if(ObjectFind(0,"OutOfHours_Label")<0)
            OutOfHours();
         return;
        }
      ObjectDelete(0,"OutOfHours_Label"); //broker allowed time to trade
      //--

      //Logic to open trade below


}

I'm grateful if someone can confirm it or correct it if there's any problem with the code above.

Thanks.

 
  1. extern string  StartTime            = "01.00";     //EA starts hour
    extern string  EndTime              = "23:00";     //EA stops hour

    When dealing with time, a lot of people use strings; they can not be optimized. Using (int) seconds or (double) hours and fraction can be inputs.

    See also Dealing with Time (Part 1): The Basics - MQL5 Articles (2021.10.01)
    Dealing with Time (Part 2): The Functions - MQL5 Articles (2021.10.08)
    MQL5 Programming Basics: Time - MQL5 Articles (2013.04.26)


  2. Your code
       if((dt.day_of_week ==0 && Sunday)    ||
          ⋮
          (dt.day_of_week ==6 && Saturday)) return true;
       
       return false;
    Simplified
    return (dt.day_of_week ==0 && Sunday)    ||
           ⋮
           (dt.day_of_week ==6 && Saturday);