How to find out if the market is closed? (mql4)

 

Switched the Expert Advisor to OnTimer() mode and now when the market is closed it does not understand this and tries to trade, in general it contacts the server and of course receives errors and clogs logs. GetLastError() = Market is closed. What other conditions may be used to check if the market is closed or on a weekend?

   if (DayOfWeek()==0 || DayOfWeek()==6) // Не помогает, последнее время сервера 21:54 ПЯТНИЦА хотя реально сейчас суббота!
      {
         TradeEnabled = 0;
      }
   else
      {
         TradeEnabled = 1;
      } 
MarketInfo(symbol,MODE_TRADEALLOWED) // не помогает, всегда возвращает True
 
add a pause or ban on trade orders at certain times
 
I need it under mql4, and yes the expert sees that today is Friday, although in fact it is Saturday.
 

If correct, none of the above, as it is inconvenient to make a code for each broker (each has its own regulations) for different characters.

It is unambiguously defined as follows:

1. Anytrading operation is carried out.

2. In reply to the operation, we get error code 132 (ERR_MARKET_CLOSED).

Further on, in order not to miss the opening of the market, you can repeat trading operations with some periodicity.

For example, I made this in one Expert Advisor that works with a lot of symbols:

bool DoTrade(ENUM_TRADE_TYPE tradeType, TradeParam &tradeParam)
{
   // Проверка возможности проведения торговой операции по символу
   if (!IsSymbolTradeAllowed(tradeParam.symbol))
      return false;
   
   bool res = true;
   int ticket = 0;
   switch (tradeType)
   {
      case TRADE_TYPE_DELETE:    res = OrderDelete(tradeParam.orderTicket);                                                                  break;
      case TRADE_TYPE_CLOSE:     res = OrderClose(tradeParam.orderTicket, tradeParam.orderVolume, tradeParam.orderCP, i_slippage);           break;
      case TRADE_TYPE_CLOSEBY:   res = OrderCloseBy(tradeParam.orderTicket, tradeParam.orderTicketCounter);                                  break;
      case TRADE_TYPE_MODIFY:    res = OrderModify(tradeParam.orderTicket, tradeParam.orderOP, tradeParam.orderSL, tradeParam.orderTP, 0);   break;
      case TRADE_TYPE_OPEN:      {
                                    tradeParam.orderTicket = OrderSend(tradeParam.symbol, tradeParam.orderType, 
                                                                       tradeParam.orderVolume, tradeParam.orderOP, 
                                                                       i_slippage, tradeParam.orderSL, tradeParam.orderTP, 
                                                                       "", tradeParam.orderMN);  
                                    res = (tradeParam.orderTicket > 0);
                                    break;
                                 }
   }
   
   int error = GetLastError();
   if (!res)
   {
      ... // обработка других ошибок
      if (error == ERR_MARKET_CLOSED || error == ERR_OFF_QUOTES)
         AddSymbolToMarketClosedList(tradeParam.symbol);
   }
      
   return res;
}

A function to check if it is possible to trade on a symbol:

bool IsSymbolTradeAllowed(string symbol)
{
   if (SymbolInfoInteger(symbol, SYMBOL_TRADE_MODE) != SYMBOL_TRADE_MODE_FULL)
   {
      Alert(WindowExpertName(), ": невозможно совершить торговую операцию по символу ", symbol, ", т. к. по нему торговля запрещена!");
      AddSymbolToMarketClosedList(symbol, true);
      return false;
   }

   for (int i = g_marketSymbolsCnt - 1; i >= 0; i--)
      if (g_marketClosedSymbols[i].symbol == symbol)
         return (TimeCurrent() - g_marketClosedSymbols[i].lastRequest) > 60;
      
   return true;
}

A function for recording a symbol that cannot be traded:

void AddSymbolToMarketClosedList(string symbol, bool isStopTrade = false)
{
   datetime time = TimeCurrent();
   if (isStopTrade)
      time = StringToTime("3000.01.01");

   for (int i = g_marketSymbolsCnt - 1; i >= 0; i--)
      if (g_marketClosedSymbols[i].symbol == symbol)
      {
         g_marketClosedSymbols[i].lastRequest = time;
         return;
      }
      
   if (g_marketSymbolsCnt >= MAX_SYMBOLS_AMOUNT)
      return;
      
   g_marketClosedSymbols[g_marketSymbolsCnt].symbol = symbol;
   g_marketClosedSymbols[g_marketSymbolsCnt].lastRequest = time;
   g_marketSymbolsCnt++;
}

As you can easily guess, array g_marketClosedSymbols is an array of structures.

 
Kino:

Switched the Expert Advisor to OnTimer() mode and now when the market is closed it does not understand this and tries to trade, in general it contacts the server and of course receives errors and clogs logs. GetLastError() = Market is closed. What other conditions to check for a day off or a closed market can be implemented?

ticks are not coming

server time does not change

if (DayOfWeek()==0 || DayOfWeek()==6) by the comp time +/- server time

If there is an error, it must be the weekend

Scriptong

2. in response to operation we get error code 132 (ERR_MARKET_CLOSED).

 
input int       Timer_Sleep_After = 3600; // Если тиков нет уже час, знач рынок закрыт

datetime gt_Last_Tick_Time = 0;


void OnTimer() {
        if(TimeLocal() - gt_Last_Tick_Time > Timer_Sleep_After) return;
}


void OnTick() {
        gt_Last_Tick_Time = TimeLocal();
}
 
Scriptong:

If correct, none of the above, as it is inconvenient to make a code for each broker (each has its own regulations) for different characters.

It is unambiguously defined as follows:

1. Anytrading operation is carried out.

2. In reply to the operation, we get error code 132 (ERR_MARKET_CLOSED).

Further on, in order not to miss the opening of the market, you can repeat trading operations with some periodicity.

For example, I made this in one Expert Advisor that works with a lot of symbols:

A function to check if it is possible to trade on a symbol:

A function for recording a symbol that cannot be traded:

As you can easily guess, array g_marketClosedSymbols is an array of structures.

Thank you for the tip, but when the market is open it is still not correct to try to detect the possibility to work with orders but it will work.
 
f2011:
Thanks too, interesting solution.
 

Now a question to MK developers, why make an event that will never work ? https://docs.mql4.com/ru/dateandtime/dayofweek

if(DayOfWeek()==0 ||DayOfWeek()==6)return(0);

If I am working with ticks, there is no ticks and the event will not happen; if I am working with timer, the server gives me the arrival time of the last nick to it, i.e. the last Friday minutes and the event will also never happen. It turns out I have an EA on timer and server is working on ticks as before, but server is online because when I send a request it gives me error 132. Please fix it or the server will change time on timer too or I can check if the market is closed without sending a trade order. This is a fierce bug, hope for understanding and solutions to the problem.

DayOfWeek - Документация на MQL4
  • docs.mql4.com
DayOfWeek - Документация на MQL4
 

int Weekday = TimeDayOfWeek(TimeLocal());                                                          //Локальное время  |
int Weekdays = TimeDayOfWeek(TimeCurrent());                                                       //Серверное время  |

while(IsExpertEnabled())                                                                 //До тех пор пока запушенно  |

     {
     if(Weekday!=0||Weekday!=6){Exp=true;if(Weekday==1){Info(4,Weekday,0);}}       //Если не Сбб. Воск. то разрешено  |
     if(Weekdays==0||Weekdays==6)                                                  //Если Сбб. Воск. то не разрешено  |
       {
       Exp=false;Info(5,Weekdays,0);
       if(Weekdays==6){Sleep(86400000);}                                                //Если суббота пауза 24 часа  |
       if(Weekdays==0){Sleep(3600000);}                                               //Если воскресение пауза 1 час  |
       }

This is roughly how I solved it, through pauses and loops, but it's old code, before the terminal version was updated. There are simpler ways now, you just have to read the literature a bit.
 
Back to MK! If the server knows that the market is closed and gives error 132, in other words give a request to check if the market is open or not without referring to order handling, this is important because defining Saturday and Sunday is not quite correct, there are holidays and early trading session closes and each DC has a different one.
Reason: