Respecting broker trading sessions in MQL5 with SymbolInfoSessionTrade

2026-11-27来源 dev.toEnglish

A lot of Expert Advisors carry a hand typed session filter: trade from 08 to 20, server time. That works until the broker changes its hours for a holiday, a symbol has a daily break, or the EA moves to a broker on a different server time zone. Then the EA sends orders into a closed market and collects TRADE_RETCODE_MARKET_CLOSED errors.

MQL5 already knows the real sessions. SymbolInfoSessionTrade returns the trading windows the broker publishes for each symbol and weekday, so the EA can ask the terminal instead of guessing.

Reading the sessions

Each weekday can have several sessions, indexed from 0. The function returns false when there are no more.

bool InTradeSession(const string sym) { datetime t = TimeTradeServer(); MqlDateTime now; TimeToStruct(t, now); ENUM_DAY_OF_WEEK day = (ENUM_DAY_OF_WEEK)now.day_of_week; int secNow = (int)(t % 86400); // seconds since midnight datetime from, to; for(uint i = 0; SymbolInfoSessionTrade(sym, day, i, from, to); i++) { int a = (int)(from % 86400); int b = (int)(to % 86400); if(b == 0) b = 86400; // session ending at 24:00 if(secNow >= a && secNow < b) return true; } return false; } 

The from and to values are times of day stored as datetime, so taking them modulo 86400 gives seconds since midnight. A session that ends at midnight comes back as 0, which is why the code turns 0 into 86400.

Add a margin at both ends

Spreads are often wide right after the open and right before a break. I usually skip the first and last few minutes of every session. The input is in seconds to keep the math simple:

input int EdgeSeconds = 300; // 5 minutes bool InSafeSession(const string sym) { int edge = EdgeSeconds; datetime t = TimeTradeServer(); MqlDateTime now; TimeToStruct(t, now); ENUM_DAY_OF_WEEK day = (ENUM_DAY_OF_WEEK)now.day_of_week; int secNow = (int)(t % 86400); // seconds since midnight datetime from, to; for(uint i = 0; SymbolInfoSessionTrade(sym, day, i, from, to); i++) { int a = (int)(from % 86400) + edge; int b = (int)(to % 86400); if(b == 0) b = 86400; b = b - edge; if(secNow >= a && secNow < b) return true; } return false; } 

Things to know

  1. Use TimeTradeServer, not TimeLocal. Sessions are in server time.
  2. Sessions describe when trading is allowed, not when liquidity is good. Keep your own strategy hours on top if the logic needs them.
  3. Holidays are not always reflected in the published sessions, so still handle TRADE_RETCODE_MARKET_CLOSED gracefully and do not retry in a tight loop.
  4. In the Strategy Tester the sessions come from the symbol settings of the account you test on, so test on the broker you will trade.

With this in place the EA follows the broker's calendar instead of a pair of numbers someone typed years ago.

原文:https://www.a8q9.cn/en/article/respecting-broker-trading-sessions-in-mql5-with-symbolinfosessiontrade-0ef326.html

相关文章