DEV Community

Omais Ali
Omais Ali

Posted on

Stop your MQL5 EA from firing orders into a closed market

If your EA has ever filled its log with retcode 10018 (TRADE_RETCODE_MARKET_CLOSED), you know the pattern. A signal appears during the daily break, on a holiday, or a few seconds before the weekend close, and the EA tries again on every tick. Nothing is lost on that request, but retry logic, counters and alerts all get confused, and on a busy account it can look like the EA is broken.

MT5 already knows the trading sessions for each symbol. You only have to ask.

Reading the trade sessions

SymbolInfoSessionTrade returns the start and end of each trading session for a given weekday. The times come back as seconds from midnight in server time.

bool IsInTradeSession(const string symbol)
{
   datetime serverNow = TimeTradeServer();
   MqlDateTime now;
   TimeToStruct(serverNow, now);
   ENUM_DAY_OF_WEEK day = (ENUM_DAY_OF_WEEK)now.day_of_week;
   int secondsNow = (int)(serverNow % 86400);   // seconds since midnight

   datetime from, to;
   for(uint i = 0; SymbolInfoSessionTrade(symbol, day, i, from, to); i++)
   {
      int f = (int)from;
      int t = (int)to;          // 24:00 comes back as 86400
      if(secondsNow >= f && secondsNow < t)
         return true;
   }
   return false;
}
Enter fullscreen mode Exit fullscreen mode

A symbol can have several sessions per day, which is why the loop keeps asking for the next index until the call returns false.

Check the trade mode too

Sessions say when the market is open. They do not say whether you are allowed to open a position. Check SYMBOL_TRADE_MODE as well:

bool CanOpen(const string symbol)
{
   long mode = SymbolInfoInteger(symbol, SYMBOL_TRADE_MODE);
   if(mode == SYMBOL_TRADE_MODE_DISABLED || mode == SYMBOL_TRADE_MODE_CLOSEONLY)
      return false;
   if(!TerminalInfoInteger(TERMINAL_CONNECTED))
      return false;
   return IsInTradeSession(symbol);
}
Enter fullscreen mode Exit fullscreen mode

Close only mode shows up more often than people expect, for example on expiring contracts or symbols a broker is retiring.

Leave a margin near the edges

Quotes often stop a little before the session officially ends, and the first seconds after the open can have wide spreads. A simple rule is to refuse new entries in the last five minutes before a session end and the first two minutes after a start. Exits should still be allowed whenever the market accepts them.

Still handle 10018

The session table comes from the broker and holidays are not always reflected in it. So keep a handler for TRADE_RETCODE_MARKET_CLOSED anyway: do not retry on every tick, pause new entries for that symbol for a few minutes, and write one log line instead of hundreds.

Test note

The strategy tester uses the session settings of the symbol, so you can confirm the filter by running a week that includes a holiday and checking that no orders are attempted while the market is shut.

Top comments (0)