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

 
Alexey:

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.
Thanks of course, but it's like they say, climb through the eye of one place) I also can put a pause on the euro at 5.0 server lets me do it and then with every timer cycle try to change pause, if error 132 then market is closed, if normal then trade is there, but at trading time this server is flooding, I want to solve the problem humanly, not through "loops", but this is to MK developers.
 

IsTradeAllowed

Returns information about the ability to trade with Expert Advisors.

boolIsTradeAllowed();

The second form of this call returns information on ability to trade for a specified symbol at a specified time.

boolIsTradeAllowed(
const string symbol// symbol
datetimetested_time// time
);

Parameters

symbol

[in] symbol.

tested_time

[in] Time.

Returned value

Returns true if the EA is allowed to trade and the thread is free, otherwise returns false.

 
if(SymbolInfoInteger(NULL,SYMBOL_TIME)>60) return(0);
 
Kino:
Thanks of course, but it's like they say to get in through the eye of one place) I can also put a pause on the euro at 5.0 server will allow it, and then with each timer cycle try to change the pause, if the error 132 then the market is closed, if normal then trade is there, but at trading time is server flooding, I would like to solve the problem humanly, not through "loops", but this is the developers MK.
Request for permission to trade needed. I don't have this request in my example because there is a three hour time difference between market closes and 3 hours before market closes, it is mostly flat. That's why I did it differently there, but also with pauses, but with a much smaller interval.
 
offfline:

IsTradeAllowed

Returns information about the ability to trade with Expert Advisors.

boolIsTradeAllowed();

The second form of this call returns information on ability to trade for a specified symbol at a specified time.

boolIsTradeAllowed(
const string symbol// symbol
datetimetested_time// time
);

Parameters

symbol

[in] symbol.

tested_time

[in] Time.

Returned value

Returns true if the EA is allowed to trade and the thread for trading operations is free, otherwise returns false.

Alexander, you are wrong)


//+------------------------------------------------------------------+
//|                                                         test.mq4 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2015, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetTimer(1);
      
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();
      
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
  if (IsTradeAllowed() == True) Print("---- Ура торгуем -----");
   {
      int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,0,0,"My order",16384,0,clrGreen);
      {
         if (ticket <0) Print("---- Уже не торгуем -----",GetLastError());
      }
   }

  }
//+------------------------------------------------------------------+
 

this one works quite well

//+------------------------------------------------------------------+
//|                                                         тест.mq4 |
//|                                                   Sergey Gritcay |
//|                                               sergey1294@list.ru |
//+------------------------------------------------------------------+
#property copyright "Sergey Gritcay"
#property link      "sergey1294@list.ru"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create timer
   EventSetTimer(1);

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//--- destroy timer
   EventKillTimer();

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//---
   if(isNewTime())
     {
      Print("---- Ура торгуем -----");
      int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,0,0,"My order",16384,0,clrGreen);
        {
         if(ticket<0) Print("---- Уже не торгуем -----",GetLastError());
        }
     }
     else Print("---- функция isNewTime() = false, возможно торговля закрыта ");

  }
//+------------------------------------------------------------------+
bool isNewTime()
  {
//--- в статической переменной будем помнить время 
   static datetime last_time=0;
//--- текущее время
   datetime time=TimeCurrent();

//--- если это первый вызов функции
   if(last_time==0)
     {
      //--- установим время и выйдем 
      last_time=time;
      return(false);
     }

//--- если время отличается
   if(last_time!=time)
     {
      //--- запомним время и вернем true
      last_time=time;
      return(true);
     }
//--- дошли до этого места - значит время сервера не обновилось, вернем false
   return(false);
  }
 
sergey1294:

this one works quite well

Thanks, I'll give it a try.
 
Kino:
Thanks for the tip, but when the market is open it is not correct to try to determine the possibility to work with orders but it will work.

For my part, my reasoning is as follows.

If it is necessary to trade on the current symbol, an indirect sign that the market is open is the arrival of new ticks. Thus, the OnTick event is enough and the issue is closed.

If we need to work with symbols other than the current one, the fact of opening of trades on the current symbol does not guarantee that trades are executed on some other symbol. For example, the Expert Advisor has been run on EURUSD, the time is 09:00 UTC, and we want to trade US stocks, the market of which will only open at 13:00 UTC. So, OnTick will not help. We will need to determine whether the market opens by other symbols through attempts to send orders to the server at certain intervals. Sending an order once per minute is by no means a server bombardment, but quite a normal approach. What's wrong with that?

 

no ticks no trade as I was once told by servicedesk about this day of the week problem,

they suggested a solution like.

TimeDayOfWeek(TimeLocal());

although it's not entirely correct, because the day of the week may not be the same as the terminal day.

 
In one of the recent projects we had the task to detect the fact that trade with an arbitrary symbol was open and available.
An important condition was not to try to open orders although I had resorted to it many times in other projects. To be honest, it seems to me that this is the easiest and most reliable method so far.

So far I have found the best way to do this (but I'm still searching, see below):
1) Determine whether trading is allowed "face-to-face" - second form of IsTradeAllowed() function (I mentioned it above). If not, then it is not allowed :)
2) Compare the time of last quote using SymbolInfoInteger(<symbol>, SYMBOL_TIME) with the time of one of the trading sessions(SymbolInfoSessionTrade()), if the time of the quote falls into one of the session range, then trade is allowed.
3) Check if the time of the quote is not too "outdated": if it is more than xx minutes ago (compare SymbolInfoInteger(<symbol>, SYMBOL_TIME) and TimeCurrent(), then we think that the quote is outdated and, therefore, we cannot trade by it (if I'm right, it was about three minutes)

The disadvantage of this approach is the following: there may be conditions when trades in the symbol are impossible, while the ticks pass.
I did not get into the mechanism; the development was made for a broker and during the testing they have switched on such a mode - ticks go, but trading is impossible. I have not managed to overcome this variant yet.

It is fair to say that I have not encountered this in real trading. So under "normal" conditions the solution seems tolerable. But I am still searching for it :)

P.S. Steps 1 and 2 can be combined (to transfer SymbolInfoInteger(<symbol>, SYMBOL_TIME) into function IsTradeAllowed), but I haven't made tests of such variant yet and will not say so.

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