Timecurrent issue with my EA

 

Hi, need your help on my timeccurent code in my EA, basically what I want my EA to do is only trade during specific market hours, but it just ended up not taking any trades during back testing:

here's a PORTION of my code:


   datetime time_to_trade =  TimeCurrent();
   datetime open_time = "15:00:00";
   datetime close_time = "22:00:00";
      
   if(!CheckIfOpenOrdersByMagicNB(magicNB))//if no open orders try to enter new position
   {


       && (time_to_trade <= (open_time)) && time_to_trade >= (close_time))
      


any suggestions would help, thanks in advance

 
  1.    datetime time_to_trade =  TimeCurrent();

    That is not an assignment; it's initialization of a common (globally declared), or static variable with a constant. They work exactly the same way in MT4/MT5/C/C++.

    1. They are initialized once on program load.

    2. They don't update unless you assign to them.

    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use).

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

    4. Unlike indicators, EAs are not reloaded on chart change, so you must reinitialize them, if necessary.
                external static variable - MQL4 programming forum #2 (2013)

  2.    datetime open_time = "15:00:00";
       datetime close_time = "22:00:00";
  3. A string is not a datetime. Garbage.
  4. 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)