How to check Market Open/Closed in MT5 ? - page 3

 
Alain Verleyen:

The only conclusion for everyone is try it yourself according to your needs, there is no universal solution by using a single function call.

Alain is correct—brokers have all sorts of wonky settings! I found one broker who specifies forex hours between two separate sessions.

As this thread is the top one to show up in Google, I will place this code here. It seems to work for two separate brokers for forex and odd symbols like an index fund that takes a 15 minute break on weekdays.

Caveat emptor.

// Checks if market is currently open for specified symbol
bool IsMarketOpen(const string symbol, const bool debug = false)
{
    datetime from = NULL;
    datetime to = NULL;
    datetime serverTime = TimeTradeServer();

    // Get the day of the week
    MqlDateTime dt;
    TimeToStruct(serverTime,dt);
    const ENUM_DAY_OF_WEEK day_of_week = (ENUM_DAY_OF_WEEK) dt.day_of_week;

    // Get the time component of the current datetime
    const int time = (int) MathMod(serverTime,HR2400);

    if ( debug ) PrintFormat("%s(%s): Checking %s", __FUNCTION__, symbol, EnumToString(day_of_week));

    // Brokers split some symbols between multiple sessions.
    // One broker splits forex between two sessions (Tues thru Thurs on different session).
    // 2 sessions (0,1,2) should cover most cases.
    int session=2;
    while(session > -1)
    {
        if(SymbolInfoSessionTrade(symbol,day_of_week,session,from,to ))
        {
            if ( debug ) PrintFormat(    "%s(%s): Checking %d>=%d && %d<=%d",
                                        __FUNCTION__,
                                        symbol,
                                        time,
                                        from,
                                        time,
                                        to );
            if(time >=from && time <= to )
            {
                if ( debug ) PrintFormat("%s Market is open", __FUNCTION__);
                return true;
            }
        }
        session--;
    }
    if ( debug ) PrintFormat("%s Market not open", __FUNCTION__);
    return false;
}
 
Anthony Garot:

Alain is correct—brokers have all sorts of wonky settings! I found one broker who specifies forex hours between two separate sessions.

As this thread is the top one to show up in Google, I will place this code here. It seems to work for two separate brokers for forex and odd symbols like an index fund that takes a 15 minute break on weekdays.

Caveat emptor.

hello Anthony, what is HR2400?

thanks

 
FXreedom: hello Anthony, what is HR2400?
#define  HR2400 (PERIOD_D1 * 60) // 86400 = 24 * 3600 = 1440 * 60
 
William Roeder:

thanks for your answer William.

In MT5, PERIOD_D1=16408, so I think in MT5 the code should be HR2400=PeriodSeconds(PERIOD_D1)

regards

 

The method I use:

        bool Status()
        {
                trade.OrderDelete(0);
                switch(trade.ResultRetcode())
                {
                        case 10017: return false; // Trade Disabled
                        case 10018: return false; // Market Closed
                        case 10027: return false; // Auto-Trading disabled
                        case 10031: return false; // No Connection
                        case 10032: return false; // Only Live Accounts
                        case 10033: return false; // Max Number of Limit Orders

                                // ADD OTHER RELEVANT ResultCodes HERE

                        default: return true;
                }
        }
 
leoa451:

The method I use:

Should be noted that this won't work in indicators.
 
Alain Verleyen #:

Not at all.

Why do you want to know when market is closed ? On Forex the open/close hours are well known, you can just check broker time, session time (I mean asian, europa, us sessions) and you will know if the market is open/close.

For metals or CFDS, you have sometimes a market close for 15 minutes or 1 hour, to know that the most reliable way is MarketInfo(symbol,MODE_TRADEALLOWED) (MT4).

For MT5 you can always use SymbolInfoSessionTrade().

Using last tick time is not really useful, as you can't make the difference between a closed market and a "slow" market.

I am working with a lot of customers and a lot of brokers, so I am talking in general, but of course I didn't check all brokers. Also it's probably always possible to find a broker who will provide data that contradicts the above.

Not sure why you are being condescending, but checking if market is closed or open is important for many trading strategies. The OP's question is clearly a concern for many developers.
 
HoagieT #:
Not sure why you are being condescending, but checking if market is closed or open is important for many trading strategies. The OP's question is clearly a concern for many developers.

I never said it's not important. I asked "why...?" in a given context. I also provided the solution.

How is your comment useful ?

 
Petr Nosek #:

MarketInfo(Symbol(),MODE_TRADEALLOWED) in MT4 isn't reliable.

If you want to check Opened/Closed market you should use these functions together (both in MT4 and MT5):

SymbolInfoSessionTrade() => to find the last session start/end time

SymbolInfoInteger(_Symbol,SYMBOL_TIME) => to find out the last known tick time for the symbol

TimeCurrent() and TerminalInfoInteger(TERMINAL_CONNECTED) => to find out if the server is "ON"

Hello Petr

Thank you very much for your input on how to check opened/closed markets. Very helpful.

I assume you subtract TimeCurrent() with SymbolinfoInteger(_Symbol, SYMBOL_TIME) and find out how long ago the last tick appeared.

May I ask how much time you let pass since the last tick before defining the market as closed?

I'm not very experienced, but I'm very curious on how experienced programmers do.

 

Having experimented with all this in MT5, I have several questions. First though, I want to do this to ensure that no matter where on the globe my EA is used, I can always give an accurate answer to the question "Is the market for this symbol with this broker still active/open or not?" That applies to any symbol, any broker, any exchange, any global timezone in which a trader is trading. This includes Forex. I recognise that different brokers may have different times for the same symbol. That's fine, and all the more reason for this to be able to provide a reliably accurate determination of open/closed.

So, my questions:

  1. The recommended way to determine this seems to be to use SymbolInfoSessionTrade and SymbolInfoSessionQuote. Is that correct? If not, what is preferred?
  2. Using SymbolInfoSessionTrade/Quote, what timezone is used for the Day of Week specified, and in what timezone are the retrieved session times specified?
  3. In 2 above, it is reasonable to assume that for exchange-based symbols (e.g. futures), this would be the timezone of the exchange. Is that correct? If not, what timezone must be used?
  4. If 3 above is correct, can one determine the exchange timezone for these types of symbols in MT5? If not, what is recommended to find this?
  5. For non-exchange-based symbols (e.g. Forex), what timezone is required for the Day of Week specified, and in what timezone are the retrieved session times specified?

    Assume that the questions above are able to be answered fully and accurately, and for any symbol with any broker, and that the relevant session times and dates are correctly determined and specified in a known timezone.

  6. To determine active/closed requires a datetime comparison. It seems that using TimeTradeServer is the required reference time for comparison with retrieved session times. Is that correct? If not, what is required?
  7. Is it safe to assume that 6 above works for all exchange-based symbols?
  8. What reference time is required for non-exchange-based symbols?

I appreciate answers to the questions. Any code that is comprehensive for any symbol, any broker, any timezone used by a trader, would be most welcome.

Thanks.