[SERVICE DESK] Error in getting the time of the senior TF in the timer! - page 2

 
Alexey Kozitsyn:

Once again. It doesn't say that anywhere. That's first of all. Secondly, why is it then misleading by first showing an error code 4066 and then not?

The data are pumped in batches and then processed by the terminal, and since you're working on a timer, you are paused. I don't see it explicitly anywhere but many programmers writing MTF applications usually know about it and I've told you about it at once.

https://docs.mql4.com/ru/series/timeseries_access read it thoroughly.

Well, above you already gave us a variant of checking history accessibility. It is not perfect but it is simple and obvious.

If this variant does not work, check as follows.

if(iBarShift(Symbol(),PERIOD_H1,TimeCurrent(),true)==-1){Print("Данные истории по последнему часу отсутствуют!");}
Организация доступа к данным - Доступ к таймсериям и индикаторам - Справочник MQL4
Организация доступа к данным - Доступ к таймсериям и индикаторам - Справочник MQL4
  • docs.mql4.com
Прежде чем ценовые данные будут доступны в терминале MetaTrader 4, их необходимо получить и обработать. Для получения данных требуется подключение к торговому серверу MetaTrader 4. Данные поступают с сервера по запросу терминала в виде экономно упакованных блоков минутных баров. Механизм обращения к серверу за данными не зависит от того, каким...
 
Vitaly Gorbunov:

The data is pumped in portions and then processed by the terminal, and since you are on a timer, you get paused. Yes, it's not explicitly mentioned anywhere, but many programmers who write MTF applications usually know about it and I told you about it right away.

https://docs.mql4.com/ru/series/timeseries_access read it thoroughly.

Well, above you already gave us a variant of checking history accessibility. It is not perfect but it is simple and obvious.

About getting "into a pause", where are the proofs?

I read it carefully (and have read it before). I am aware that data (especially older TFs) is not always immediately available. No problem. But why then does the SeriesInfoInteger() function return no error!? Here is the question!

Assuming that the request falls on some pause/swap/update/break etc., then let it return error code != 0. And there won't be any problems!

 
Vitaly Gorbunov:

And above you have already given the option of checking the accessibility of the story. It's not perfect, but it's simple and straightforward.

Answered above @Ihor Herasko on this point.

 
Alexey Kozitsyn:

Answered @Ihor Herasko above on this point already.

Above gave his version of the test. Why so question to the developers but this point has been known for a very long time!
 
Vitaly Gorbunov:
I gave my version of the test above. Why so question to the developers but this point has been known for a long time!

I will certainly try your version of the test and report the results.

 
Alexey Kozitsyn:

I will certainly try your version of the test and report back with the results.

Will definitely report back! It works for me! But there may be all sorts of pitfalls if it doesn't work and we'll think about what else we can do.
 

First a reply from @Ihor Herasko. Code for playback:

#property version   "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//--- Время открытия текущего часа, дня и недели
datetime _m15OpenTime=0;
//--- Вести лог журнала
const bool inpFileLog=true;
//--- Количество секунд в одном дне
const int SEC_PER_DAY=86400;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Запускаем таймер
   if(!EventSetMillisecondTimer(20))
     {
      Print(__FUNCTION__,": ОШИБКА #",GetLastError(),": таймер с частотой 20 ms не установлен!");
      return( INIT_FAILED );
     }
//--- Сбрасываем время открытия текущего бара м15, часа, дня
   _m15OpenTime = 0;
//---
   return( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {

   return( rates_total );
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//--- Проверяем, записано ли время открытия текущего бара М15
   if(!CheckCurrentM15OpenTime())                        // Если время не записано
      return;                                                // Выходим                                                                                                                         // Выходим
  }
//+------------------------------------------------------------------+
//| Проверяем, записано ли время открытия текущего бара М15             |
//+------------------------------------------------------------------+
bool CheckCurrentM15OpenTime()
  {
//--- Проверяем, записано ли время
   if(_m15OpenTime==0) // Если время не записано
     {
      //---
      ResetLastError();
      iTime(NULL,PERIOD_M15,1);
      //---
      if(GetLastError()==ERR_NO_ERROR)
        {
         ResetLastError();
         //--- Запоминаем время открытия бара
         _m15OpenTime=iTime(NULL,PERIOD_M15,0);
         //---
         Print(__FILE__,": Актуальное время открытия бара М15 = "+TimeToString(_m15OpenTime)+". Ошибка #",GetLastError());
         //--- Возвращаем истину
         return( true );
        }
      else
         return( false );
     }
//--- Время открытия М15 ранее записано. Возвращаем истину
   return( true );
  }

Result:

2018.09.21 14:25:02.793 Custom indicator test_isNewDayInTimer_iTime() EURGBP.e,M1: removed
2018.09.21 14:30:44.120 Custom indicator test_isNewDayInTimer_iTime() EURGBP.e,M1: loaded successfully
2018.09.21 14:30:44.149 test_isNewDayInTimer_iTime() EURGBP.e,M1: initialized
2018.09.21 14:30:44.262 test_isNewDayInTimer_iTime() EURGBP.e,M1: test_isNewDayInTimer_iTime().mq4: Актуальное время открытия бара М15 = 2018.09.21 12:15. Ошибка #0

According to the log entries. The terminal was switched off at 14:25. Next, switched on at 14:30. We check the time of bar M15. We started with TF M1. The indicator (code above) showed actual open time 12:15 (terminal time, lagged behind my local time by 2 hours). The result should have been 12:30! Conclusion - the error is present. And this method suggested by @Ihor Herasko does not work.

 
Vitaly Gorbunov:
Make sure to report back! It works for me! But there may be all sorts of pitfalls if it does not work we will think what else we can do.

I'll sign off. Code:

#property version   "1.00"
#property strict
#property indicator_chart_window
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//--- Время открытия текущего часа, дня и недели
datetime _m15OpenTime=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Запускаем таймер
   if(!EventSetMillisecondTimer(20))
     {
      Print(__FUNCTION__,": ОШИБКА #",GetLastError(),": таймер с частотой 20 ms не установлен!");
      return( INIT_FAILED );
     }
//--- Сбрасываем время открытия текущего бара м15
   _m15OpenTime=0;
//---
   return( INIT_SUCCEEDED );
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {

   return( rates_total );
  }
//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
  {
//--- Проверяем, записано ли время открытия текущего бара М15
   if(!CheckCurrentM15OpenTime())                        // Если время не записано
      return;                                                // Выходим
  }
//+------------------------------------------------------------------+
//| Проверяем, записано ли время открытия текущего бара М15             |
//+------------------------------------------------------------------+
bool CheckCurrentM15OpenTime()
  {
//--- Проверяем, записано ли время
   if(_m15OpenTime==0) // Если время не записано
     {
      //---
      ResetLastError();
      if(iBarShift(Symbol(),PERIOD_M15,TimeCurrent(),true)==-1)
        {
         Print(__FILE__+": Данные истории по последнему часу отсутствуют! Ошибка #",GetLastError());
         return( false );
        }
      //---
      if(GetLastError()==ERR_NO_ERROR)
        {
         ResetLastError();
         //--- Запоминаем время открытия бара
         _m15OpenTime=iTime(NULL,PERIOD_M15,0);
         //---
         Print(__FILE__,": Актуальное время открытия бара М15 = "+TimeToString(_m15OpenTime)+". Ошибка #",GetLastError());
         //--- Возвращаем истину
         return( true );
        }
      else
         return( false );
     }
//--- Время открытия недели ранее записано. Возвращаем истину
   return( true );
  }
//+------------------------------------------------------------------+

Result:

2018.09.21 14:48:46.485 Custom indicator test_isNewDayInTimer_iBarShirt() EURGBP.e,M1: removed
2018.09.21 15:01:23.158 Custom indicator test_isNewDayInTimer_iBarShirt() EURGBP.e,M1: loaded successfully
2018.09.21 15:01:23.175 test_isNewDayInTimer_iBarShirt() EURGBP.e,M1: initialized
2018.09.21 15:01:23.295 test_isNewDayInTimer_iBarShirt() EURGBP.e,M1: test_isNewDayInTimer_iBarShirt().mq4: Актуальное время открытия бара М15 = 2018.09.21 12:45. Ошибка #0

Turned the terminal off at 2:48pm, turned it back on at 3:01pm. Should have gotten the time at 1:00 p.m. I got 12:45. Any other questions?

I changed TF from M1 to M5 and got correct result:

2018.09.21 15:01:23.295 test_isNewDayInTimer_iBarShirt() EURGBP.e,M1: test_isNewDayInTimer_iBarShirt().mq4: Актуальное время открытия бара М15 = 2018.09.21 12:45. Ошибка #0
2018.09.21 15:05:50.057 test_isNewDayInTimer_iBarShirt() EURGBP.e,M1: uninit reason 3
2018.09.21 15:05:50.058 test_isNewDayInTimer_iBarShirt() EURGBP.e,M5: initialized
2018.09.21 15:05:50.094 test_isNewDayInTimer_iBarShirt() EURGBP.e,M5: test_isNewDayInTimer_iBarShirt().mq4: Актуальное время открытия бара М15 = 2018.09.21 13:00. Ошибка #0
 
Once again I ask developers(@Slava, @Alexander, @Renat Fatkhullin) to pay attention to this problem.
 

I think I've got it! Is the indicator started immediately with the terminal? If so, before checking wait for a connection to the server IsConnected() you have a very fast timer it does not have time to synchronize!

Or do this

if(iBarShift(Symbol(),PERIOD_M15,TimeLocal(),true)==-1)
        {
         Print(__FILE__+": Данные истории по последнему часу отсутствуют! Ошибка #",GetLastError());
         return( false );
        }
But you have to take into account the difference between server time and local time. Write back with the results!
Reason: