A minute and a half difference between local time and fresh tick time. What to do. - page 2

 
prostotrader:

There is source code with comments.

Feel lazy to have a look at it? Or is there something I don't understand?

I did. I got the idea without the code. I don't understand why you're advising me:

prostotrader:

You need to add the most liquid instruments to Market Watch.

Then, add layers of these instruments.

And, when OnBookEvent() triggers, copy 1 tick (last) there will be a time and immediately take the local time and compare.

How is your method better ?

 
pivomoe:

I've had a look. I got the idea without the code. I don't understand why you're advising me:

Why is your method better?

Because it's the right one!

I made a mistake, not the local time, but the server time.

1. Ticks come to the terminal in packets.

2. Each subsequent packet may contain ticks which were not "stacked" in the previous packet, but have the same time as the previous one.

3. OnBookEvent() is triggered on arrival of any tick (change of price, volume ) i.e. each tick. (you trigger a timer - already bad).

4. You use local computer time, which is not needed at all!

 

Here is actually everything you need to trade (check trading session times)

//+------------------------------------------------------------------+
//|                                                         Time.mq5 |
//|                                                   Copyright 2019 |
//|                                                                  |
//+------------------------------------------------------------------+
int is_book;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
  is_book = MarketBookAdd(Symbol());
  if(is_book == false) return(INIT_FAILED);
  return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
  if(is_book == true) MarketBookRelease(Symbol()); 
}
//+------------------------------------------------------------------+
// Expert Book event function                                        |
//+------------------------------------------------------------------+  
void OnBookEvent(const string &symbol)
{
  if(symbol == Symbol())
  {
    if(CheckMarketTime() == true)
    {
     //Торговое время
     //Наш код
    }
  }
}
//+------------------------------------------------------------------+
//| Expert Check Market Time function                                |
//+------------------------------------------------------------------+
bool CheckMarketTime()
{
  MqlDateTime cur_time, sv_time;
  MqlTick ticks[];
  cur_time.year = 0;
  TimeTradeServer(cur_time); //Возвращает расчетное текущее время торгового сервера.
  if(cur_time.year > 0)
  {
    int result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, 0, 1);
    if(result > 0)
    {
      if(TimeToStruct(ticks[0].time, sv_time) == true)
      {
        if(sv_time.day_of_year == cur_time.day_of_year)      //Проверка, что это сегодняшний тик
        {
          ulong tr_time = sv_time.hour * 3600 + sv_time.min * 60 + sv_time.sec;
          if(((tr_time >= 3600) && (tr_time < 50370)) ||   //10:00:00 - 13:59:30
             ((tr_time >= 50700) && (tr_time < 67470)) ||  //14:05:00 - 19:44:30 
             ((tr_time >= 68700) && (tr_time < 85770)))    //19:05:00 - 23:49:30
          {
            return(true);
          }
        }
      }
    }
  }   
  return(false);
} 

Added by

If you need millisecond accuracy, then this

double t_msc = double(ticks[0].time_msc - ulong(ticks[0].time) * 1000)/1000; //Получаем в секундах
double tr_time = sv_time.hour * 3600 + sv_time.min * 60 + sv_time.sec + t_msc;

Added

But all this will not give the desired result (the boundaries of trading time) because

there may be no ticks in a trading session, and time does not stop.

Suppose someone has removed their pending order, the ticker has changed,

there is a signal but there is an "old" correlation (time is not the current time).

The terminal does not broadcast the exact server time.

 

You don't understand me. Let's start at the beginning.

1) In your program, you call TimeCurrent() and get the arrival time of the last quote for one of the selected symbols in Market Watch.

Let it be 18:00:00.

2) With the next command, you get the time of the last SBER tick.

Let it be 17:58:00

3) A little time passes and you again request the time of the last tick by SBER.

Let it be 17:59:00


Note the question: Do you think it's ok at 18:00:00 by TimeCurrent() to not know about a tick with a time of 17:59:00 ?

 
pivomoe:

You don't understand me. Let's start at the beginning.

1) In your program, you call TimeCurrent() and get the arrival time of the last quote for one of the selected symbols in Market Watch.

Let it be 18:00:00.

2) With the next command, you get the time of the last SBER tick.

Let it be 17:58:00

3) A little time passes and you again request the time of the last tick by SBER.

Let it be 17:59:00


Attention question: Do you think it's OK to be unaware at 18:00:00 by TimeCurrent() of a tick with the time 17:59:00 ?

In the code I cited you can account for all ticks (no problem)

The last code does not use TineCurrent() butTimeTradeServer() - this time is only needed

to check the tick with an accuracy of one day and that's it!

Let's start from the beginning.

In general, what do you want to do, to find out?

Why did you start comparing tick time with local time?

What is the original purpose?

 

I will now show you how this problem looks in practice. I have completely redesigned the Expert Advisor. I made it possible to catch new ticks in OnTimer as well as in OnBookEvent.

There are 45 symbols in Market Watch. Most of them are not liquid.

Here is the result of catching new ticks in OnBookEvent:

РЕКОРДная  Разница между временем последенго тика по ВСЕМ символам Минус только, что полученный новый тик по символу 494013 милесекундa.

CR      0       18:51:47.334    ProverkaAktyalnostiTikov (ALRS,H1)       Получен НОВЫЙ тик по символу                     SNGR-3.19 time_msc= 2019.03.18 18:41:47.988

HN      0       18:51:47.335    ProverkaAktyalnostiTikov (ALRS,H1)       ХОТЯ до этого был получeн тик                        ARMD time_msc 2019.03.18 18:50:02.001

I.e. a new tick was caught at 18:50 on TimeCurrent for the symbolSNGR-3.19 with a time of 18:41.


Then there are measurements of local computer time at the moment:


1) getting a new tick, i.e. at the moment of last call of CopyTick (or SymbolInfo depending on settings).

2) The moment of last call.

18:51:47.335    ProverkaAktyalnostiTikov (ALRS,H1)       Локальное время получения нового тика по символу.                      2019.03.18 18:51:47.334

18:51:47.335    ProverkaAktyalnostiTikov (ALRS,H1)       Предпоследние Локальное время попытки получить новый тик по символу    2019.03.18 18:41:47.204


So in this case the problem occurred because the get new function just wasn't called for 10 minutes.... That's because the OnBookEvent event forSNGR-3.19 was not generated for 10 minutes.

Maybe terminal placed it in events queue and it somehow disappeared from this queue. There are no such errors with OnTimer. Yes, there may be a tick with 20 seconds delay.


 
pivomoe:


What is your original purpose?

Why do you need to compare tee times with local time?

 
prostotrader:

What is your original purpose?

Why do you need to compare tick times with local time?

I want to know the maximum delay between when the tick occurs on the server and when it arrives in the terminal. And I want to know how to minimize this time.

This knowledge can be used in writing my own tester. You may even ask the developers to make the delay longer.

TimeCurrent() - time of the last tick by a symbol will be less than the delay time, so it can be used. Using local time in the first version was not a good idea.

 
pivomoe:

I want to know the maximum delay between when a tick occurs on the server and when it reaches the terminal. And how to minimise this time.

This knowledge can be used when writing my own tester. And maybe I will even be able to baffle developers with longer delays.

I see. Go on... Without me.

And for the rest of the forum

//+------------------------------------------------------------------+
//|                                                         Time.mq5 |
//|                                                   Copyright 2019 |
//|                                                                  |
//+------------------------------------------------------------------+
enum FRESH_TICK
{
  UNKNOWN_TICK,
  NEW_TICK,
  CUR_TICK
};
//
int is_book;
ulong last_tick_time; //Время последнего тика
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
  last_tick_time = 0;
  is_book = MarketBookAdd(Symbol());
  if(is_book == false) return(INIT_FAILED);
  return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
  if(is_book == true) MarketBookRelease(Symbol()); 
}
//+------------------------------------------------------------------+
// Expert Book event function                                        |
//+------------------------------------------------------------------+  
void OnBookEvent(const string &symbol)
{
  if(symbol == Symbol())
  {
    MqlTick a_ticks[];
    int result = CopyTicks(symbol, a_ticks, COPY_TICKS_ALL, 0, 1);
    if(result > 0)
    {
      FRESH_TICK tick_state = CheckTickTime(a_ticks[0]);
      switch(tick_state)
      {
       case UNKNOWN_TICK:; //Тик не определен
       break;
       case NEW_TICK:;     //Торговое время, можно отсылать ордера;
       break;
       case CUR_TICK:;     //По усмотрению разработчика;
       break;
      }
    }  
  }
}
//+------------------------------------------------------------------+
//| Expert Check Market Time function                                |
//+------------------------------------------------------------------+
FRESH_TICK CheckTickTime(MqlTick &a_tick)
{
  MqlDateTime cur_time, tick_time;
  cur_time.year = 0;
  TimeTradeServer(cur_time); //Возвращает расчетное текущее время торгового сервера.
  if(cur_time.year > 0)
  {
    if(TimeToStruct(a_tick.time, tick_time) == true)
    {
      if(tick_time.day_of_year == cur_time.day_of_year)      //Проверка, что это сегодняшний тик
      {
        double t_msc = double(a_tick.time_msc - ulong(a_tick.time) * 1000)/1000;
        double tr_time = double(tick_time.hour * 3600 + tick_time.min * 60 + tick_time.sec) + t_msc;
        if(((tr_time >= 36000) && (tr_time < 50370)) ||   //10:00:00 - 13:59:30
           ((tr_time >= 50700) && (tr_time < 67470)) ||   //14:05:00 - 19:44:30 
           ((tr_time >= 68700) && (tr_time < 85770)))     //19:05:00 - 23:49:30
        {
          if(ulong(a_tick.time_msc) > last_tick_time)
          {
            last_tick_time = ulong(a_tick.time_msc);
            return(NEW_TICK);
          } else return(CUR_TICK);  
        }
      }
    }
  }   
  return(UNKNOWN_TICK);
} 
      
 
pivomoe:

Attention question: Do you think it is normal to be unaware of a tick at 18:00:00 by TimeCurrent() with a time of 17:59:00 ?

I think the question is moot. We want the tick sequence to meet at least the following criteria:

1. it must be sequential, i.e. the time of each subsequent tick >= the time of the previous tick;

2. actuality. I.e. the time of the last arriving tick is as close to the current moment as possible;

It seems that the problem is with the second point.

Argumentativeness of point 2 is as follows: I want the time from the tick generation on the server till I receive it (lag) to be minimum, so I can process it faster than others and make a trading decision. But! If the lag is the same for all bidders - then there is no problem (as far as I understand it). I.e. the broker's server has the problem, but everyone is on an equal footing. If somebody got the information about the tick at 17:59:01, and I did not got it even at 18:00 - this is the big problem.

And here is the question. What is the problem (and is there one)? In the broker's server, which doesn't give the tick (to everyone) for a long time, or in MT5, which doesn't receive it for a long time.

Reason: