Tiki in real time - page 11

 

Andrey Khatimlianskii,fxsaber

Let's do the following

Find a bug (if there is one) in my code

//+------------------------------------------------------------------+
//|                                                   Ticks_test.mq5 |
//|                                      Copyright 2019 prostotrader |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019 prostotrader"
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
bool is_book;
MqlTick ticks[];
ulong last_time, mem_cnt;
bool is_first;
int t_cnt, result;
enum ENUM_BOOK_OR_TICK
{
        USE_BOOK,       // Use OnBookEvent
        USE_TICK        // Use OnTick
};

input ENUM_BOOK_OR_TICK Mode = USE_BOOK;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
  is_book = MarketBookAdd(Symbol());
  result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, 0, 1);
  if(result > 0)
  {
    last_time = ulong(ticks[0].time_msc);
    is_first = true;
  }
  else
  {
    is_first = false;
    Alert("No start time!");
    return(INIT_FAILED);
  }   
  return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+ 
//| возвращает строковое описание тика                               | 
//+------------------------------------------------------------------+ 
string GetTickDescription(MqlTick &tick) 
  { 
   string res = string(tick.time) + "." +  string(tick.time_msc%1000); 
// 
   bool buy_tick = ((tick.flags&TICK_FLAG_BUY)==TICK_FLAG_BUY); 
   bool sell_tick = ((tick.flags&TICK_FLAG_SELL)==TICK_FLAG_SELL); 
   bool ask_tick = ((tick.flags&TICK_FLAG_ASK)==TICK_FLAG_ASK); 
   bool bid_tick = ((tick.flags&TICK_FLAG_BID)==TICK_FLAG_BID); 
   bool last_tick = ((tick.flags&TICK_FLAG_LAST)==TICK_FLAG_LAST); 
   bool volume_tick = ((tick.flags&TICK_FLAG_VOLUME)==TICK_FLAG_VOLUME); 
// 
   if((buy_tick== true) || (sell_tick == true)) 
   { 
     res = res + (buy_tick?StringFormat(" Buy Tick: Last=%G Volume=%d ",tick.last,tick.volume):""); 
     res = res + (sell_tick?StringFormat(" Sell Tick: Last=%G Volume=%d ",tick.last,tick.volume):""); 
     res = res + (ask_tick?StringFormat(" Ask=%G ",tick.ask):""); 
     res = res + (bid_tick?StringFormat(" Bid=%G ",tick.ask):""); 
   } 
   else 
   { 
     res = res + (ask_tick?StringFormat(" Ask=%G ",tick.ask):""); 
     res = res + (bid_tick?StringFormat(" Bid=%G ",tick.ask):""); 
     res = res + (last_tick?StringFormat(" Last=%G ",tick.last):""); 
     res = res + (volume_tick?StringFormat(" Volume=%d ",tick.volume):""); 
   } 
   return res; 
  } 
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
  if(is_book == true) MarketBookRelease(Symbol());
}
//+------------------------------------------------------------------+
//| BookEvent function                                               |
//+------------------------------------------------------------------+
//void OnTick()
void OnBookEvent(const string &symbol)
{
  if ( Mode != USE_BOOK || symbol != Symbol() ) return;
  //if(Symbol() == symbol)
 // {
    if(is_first == true)
    {
      result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0);
      if(result > 0)
      {
      //  Print("First packet of ticks:");
        t_cnt = 0;
        for(int i= 0; i<result; i++)
        {
          if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;
          Print(__FUNCTION__, ": ",GetTickDescription(ticks[i]));
        }
        is_first = false;
        last_time = ulong(ticks[0].time_msc);
      } 
    }
    else
    {
      result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0);
      if(result > 0)
      {
        if(result > t_cnt)
        {
          mem_cnt = t_cnt;
          t_cnt = 0;
          for(int i= 0; i<(result - int(mem_cnt)); i++)
          {
            if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;
            Print(__FUNCTION__, ": ",GetTickDescription(ticks[i]));
          } 
          if(last_time == ulong(ticks[0].time_msc))
          {
            t_cnt += int(mem_cnt);
          }
          else last_time = ulong(ticks[0].time_msc + 1);
        }
        else
        {
          t_cnt = 0;
          last_time++;
        }
      }
      else
      {
        t_cnt = 0;
        last_time++;
        Print(__FUNCTION__, ": Pending order!");
      }
    }
 // }
}

void OnTick()
{
   if ( Mode != USE_TICK ) return;
   if(is_first == true)
    {
      result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0);
      if(result > 0)
      {
    //    Print("First packet of ticks:");
        t_cnt = 0;
        for(int i= 0; i<result; i++)
        {
          if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;
          Print(__FUNCTION__, ": ", GetTickDescription(ticks[i]));
        }
        is_first = false;
        last_time = ulong(ticks[0].time_msc);
      } 
    }
    else
    {
      result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0);
      if(result > 0)
      {
        if(result > t_cnt)
        {
          mem_cnt = t_cnt;
          t_cnt = 0;
          for(int i= 0; i<(result - int(mem_cnt)); i++)
          {
            if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;
            Print(__FUNCTION__, ": ", GetTickDescription(ticks[i]));
          } 
          if(last_time == ulong(ticks[0].time_msc))
          {
            t_cnt += int(mem_cnt);
          }
          else last_time = ulong(ticks[0].time_msc + 1);
        }
        else
        {
          t_cnt = 0;
          last_time++;
        }
      }
      else
      {
        t_cnt = 0;
        last_time++;
        Print(__FUNCTION__, ": Pending order!");
      }
    }
  
}
//+------------------------------------------------------------------+
Andrey Khatimlianskii
Andrey Khatimlianskii
  • www.mql5.com
Добавил тему Быстрый TimeHour/TimeMinute? Попытался ускорить TimeHour/TimeMinute, ни фига не получилось: void OnStart() {         ulong s1 = GetMicrosecondCount();         for ( datetime t = D'1990.01.01'; t Добавил тему Больше агентов — меньше скорость! WTF!? Наткнулся на интересного советника, использующего кастумный индикатор, подключенный...
 
prostotrader:

Find a bug (if there is one) in my code

I won't even look at this sheet without comments. I made the conclusion through my own code. I think it's unreasonable to settle an argument on the Internet. Everyone stays at his own place.

 
fxsaber:

I won't even look at the sheet without comments. I've made the conclusion through my own code. I don't think it's wise to settle things on the internet. Everyone stays with what he/she has.

So, you don't care about the result of functions?

Oh, yes, you are not a trader, but a writer, sorry, I forgot.

 
prostotrader:

So you don't care about the results of the functions?

Yes, I do. That's why I' ve written the Expert Advisor and made conclusions for myself.

Oh, yes, you're not a trader, but a writer, I'm sorry, I forgot.

Yes, I'm not a trader, but a writer.

 

Well, there's only one opponent left (if there is one left :) ) ...

Waiting for the result...

 
prostotrader:

Well, there's only one opponent left (if there is one left :) ) ...

Waiting for the result...

Opponents leave not because they are wrong, but because you reek of hubris.
 
Artyom Trishkin:
Opponents leave not because they are wrong, but because you reek of hubris.

Artem(no offence)!

The FOREX people come to the Exchange topic, "put their foot up", then get off without proof!

What has pride got to do with it, if I'm wrong - I'm ready to admit it!

But from logical reasoning and my own experience

OnBookEvent() is faster and doesn't miss a single tick, not a single change in the glass!

Find a bug (if there is one) in my code.

From the logs of my code - everything is very clearly visible!

2020.01.31 17:01:58.293 Ticks_test (GOLD-3.20,H1)       OnTick: 2020.01.31 17:01:47.889 Ask=1585.4 
2020.01.31 17:01:58.294 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:50.159 Bid=1585.4 
2020.01.31 17:01:58.519 Ticks_test (GOLD-3.20,H1)       OnTick: 2020.01.31 17:01:47.889 Ask=1585.4 
2020.01.31 17:01:58.519 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:51.444 Bid=1585.4 
2020.01.31 17:01:58.519 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:51.444 Bid=1585.4 
2020.01.31 17:01:58.519 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:51.536 Bid=1585.4 
2020.01.31 17:01:58.519 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:52.107 Ask=1585.5 
2020.01.31 17:01:58.519 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:52.326 Ask=1585.4 
2020.01.31 17:01:59.674 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:51.536 Bid=1585.4 
2020.01.31 17:01:59.861 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:52.107 Ask=1585.5 
2020.01.31 17:02:00.530 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:52.326 Ask=1585.4 
2020.01.31 17:02:01.189 Ticks_test (GOLD-3.20,H1)       OnTick: 2020.01.31 17:01:47.889 Ask=1585.4 
2020.01.31 17:02:01.216 Ticks_test (GOLD-3.20,H1)       OnBookEvent: 2020.01.31 17:01:55.7 Ask=1585.5 
2020.01.31 17:02:01.492 Ticks_test (GOLD-3.20,H1)       OnBookEvent: Pending order!

Marked in yellow is the same tick!

Added

Is it really hard for you praised programmers to make sense of 15 lines of uncomplicated code?

Added

Maybe the comments will help?

//+------------------------------------------------------------------+
//|                                                   Ticks_test.mq5 |
//|                                      Copyright 2019 prostotrader |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019 prostotrader"
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
bool is_book;
MqlTick ticks[], l_tick;
ulong last_time, mem_cnt, tot_cnt;
bool is_first;
int t_cnt, result;
enum ENUM_BOOK_OR_TICK
{
        USE_BOOK,       // Use OnBookEvent
        USE_TICK        // Use OnTick
};

input ENUM_BOOK_OR_TICK Mode = USE_BOOK;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
  tot_cnt = 0;
  if(Mode == USE_BOOK) is_book = MarketBookAdd(Symbol());
  result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, 0, 1);
  if(result > 0)
  {
    last_time = ulong(ticks[0].time_msc); //запоминаем время последнего известного тика
    is_first = true;
  }
  else
  {
    is_first = false;
    Alert("No start time!");
    return(INIT_FAILED);
  } 
  ArraySetAsSeries(ticks, true);  
  return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+ 
//| возвращает строковое описание тика                               | 
//+------------------------------------------------------------------+ 
string GetTickDescription(MqlTick &tick) 
  { 
   string res = string(tick.time) + "." +  string(tick.time_msc%1000); 
// 
   bool buy_tick = ((tick.flags&TICK_FLAG_BUY)==TICK_FLAG_BUY); 
   bool sell_tick = ((tick.flags&TICK_FLAG_SELL)==TICK_FLAG_SELL); 
   bool ask_tick = ((tick.flags&TICK_FLAG_ASK)==TICK_FLAG_ASK); 
   bool bid_tick = ((tick.flags&TICK_FLAG_BID)==TICK_FLAG_BID); 
   bool last_tick = ((tick.flags&TICK_FLAG_LAST)==TICK_FLAG_LAST); 
   bool volume_tick = ((tick.flags&TICK_FLAG_VOLUME)==TICK_FLAG_VOLUME); 
// 
   if((buy_tick== true) || (sell_tick == true)) 
   { 
     res = res + (buy_tick?StringFormat(" Buy Tick: Last=%G Volume=%d ",tick.last,tick.volume):""); 
     res = res + (sell_tick?StringFormat(" Sell Tick: Last=%G Volume=%d ",tick.last,tick.volume):""); 
     res = res + (ask_tick?StringFormat(" Ask=%G ",tick.ask):""); 
     res = res + (bid_tick?StringFormat(" Bid=%G ",tick.bid):""); 
   } 
   else 
   { 
     res = res + (ask_tick?StringFormat(" Ask=%G ",tick.ask):""); 
     res = res + (bid_tick?StringFormat(" Bid=%G ",tick.bid):""); 
     res = res + (last_tick?StringFormat(" Last=%G ",tick.last):""); 
     res = res + (volume_tick?StringFormat(" Volume=%d ",tick.volume):""); 
   } 
   return res; 
  } 
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
  if(Mode == USE_BOOK)
  {
    Print("USE_BOOK ticks received: ", tot_cnt);
    if(is_book == true) MarketBookRelease(Symbol());
  }
  else
  {
    Print("USE_TICK ticks received: ", tot_cnt);
  }  
}
//+------------------------------------------------------------------+
//| BookEvent function                                               |
//+------------------------------------------------------------------+
void OnBookEvent(const string &symbol)
{
  if ( Mode != USE_BOOK || symbol != Symbol() ) return;
  tot_cnt++;
  if(is_first == true)
  {
    result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0); //копируем все вновь пришедшие тики от последнего известного времени
    if(result > 0)
    {
      t_cnt = 0;
      for(int i= 0; i<result; i++)
      {
        if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;             //Считаем кол-во тиков с одинаковым временем
        Print(__FUNCTION__, ": ",GetTickDescription(ticks[i]));
      }
      l_tick = ticks[0];
      is_first = false;
      last_time = ulong(ticks[0].time_msc);                             //Запоминаем время последнего тика
    } 
  }
  else
  {
    result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0); //забираем тики из последнего (посчитанного пакета тикив и считываем тики из нового пакета)
    if(result > 0)
    {
      l_tick = ticks[0];
      if(result > t_cnt)
      {
        mem_cnt = t_cnt;
        t_cnt = 0;
        for(int i= 0; i<(result - int(mem_cnt)); i++)
        {
          if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;           //Считаем кол-во тиков с одинаковым временем
          Print(__FUNCTION__, ": ",GetTickDescription(ticks[i]));
        } 
        if(last_time == ulong(ticks[0].time_msc))
        {
          t_cnt += int(mem_cnt);
        }
        else last_time = ulong(ticks[0].time_msc);
      }
    }
    else
    {
      Print(__FUNCTION__, ": Pending order!");                          //Изменения стакана (добавлен/удален отложенный ордер)
    }
  }
}
//+------------------------------------------------------------------+
//| OnTick function                                                  |
//+------------------------------------------------------------------+
void OnTick()
{
  if ( Mode != USE_TICK ) return;
  tot_cnt++;
  if(is_first == true)
  {
    result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0); //копируем все вновь пришедшие тики от последнего известного времени
    if(result > 0)
    {
      t_cnt = 0;
      for(int i= 0; i<result; i++)
      {
        if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;             //Считаем кол-во тиков с одинаковым временем
        Print(__FUNCTION__, ": ",GetTickDescription(ticks[i]));
      }
      is_first = false;
      last_time = ulong(ticks[0].time_msc);                             //Запоминаем время последнего тика
    } 
  }
  else
  {
    result = CopyTicks(Symbol(), ticks, COPY_TICKS_ALL, last_time, 0); //забираем тики из последнего (посчитанного пакета тикив и считываем тики из нового пакета)
    if(result > 0)
    {
      if(result > t_cnt)
      {
        mem_cnt = t_cnt;
        t_cnt = 0;
        for(int i= 0; i<(result - int(mem_cnt)); i++)
        {
          if(ticks[i].time_msc == ticks[0].time_msc) t_cnt++;           //Считаем кол-во тиков с одинаковым временем
          Print(__FUNCTION__, ": ",GetTickDescription(ticks[i]));
        } 
        if(last_time == ulong(ticks[0].time_msc))
        {
          t_cnt += int(mem_cnt);
        }
        else last_time = ulong(ticks[0].time_msc);
      }
    }
    else
    {
      Print(__FUNCTION__, ": Pending order!");                          //Изменения стакана (добавлен/удален отложенный ордер)
    }
  }
}
//+------------------------------------------------------------------+
 
prostotrader:

Artem(no offence)!

The FOREX people come to the Exchange topic, "put their foot up", then get off without proof!

What has pride got to do with it, if I'm wrong - I'm ready to admit it!

But from logical reasoning and my own experience

OnBookEvent() is faster and doesn't miss a single tick, not a single change in the glass!

Find a bug (if there is one) in my code.

From my code logs - you can see everything very clearly!

Added

Is it really hard for you praised programmers to make sense of 15 lines of uncomplicated code?

Added

Maybe the comments will help?

I'm not interested. I can see that there is no difference. But Andrei promised to show you how to do it better. But he made a condition to show you that is impossible for you to fulfil.
 
Artyom Trishkin:
I don't care. I see that there is no difference. But Andrey has promised to show you the best way. However, he put an impossible condition to show you.

Okay.

But I'll say just a small remark.

The fact that OnTick() doesn't handle pending orders

2020.01.31 17:02:01.492 Ticks_test (GOLD-3.20,H1)       OnBookEvent: Pending order!

is a good reason to dump this function in the trash for stock trading.

Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства ордеров
Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства ордеров
  • www.mql5.com
Приказы на проведение торговых операций оформляются ордерами. Каждый ордер имеет множество свойств для чтения, информацию по ним можно получать с помощью функций Идентификатор позиции, который ставится на ордере при его исполнении. Каждый исполненный ордер порождает сделку, которая открывает новую или изменяет уже существующую позицию...
 

I would like to remind you that OnTick receives two independent threads, information and trade,COPY_TICKS_INFO and COPY_TICKS_ALL and undergoes preprocessing .

These threads are not synchronized with each other, so if you compare OnBookEvent with OnTick, you should takeTICKS_INFO.

By definition, OnBookEvent should be faster since it doesn't go through pre-processing.

The tests do not reliably determine who is faster, because we do not know the stock time of the tick.

Although, we have many times asked developers to ADD STOCK TIME! ! !


p.s. besides speed, tumblr also has advantages over OnTick,

as already stated, it is not possible to get better Bid and Ask prices in OnTick,

andOnTick doesn't get data from other symbols, it's useless for Expert Advisors analysing multiple symbols.