Tiki en tiempo real - página 14

 
Roman:

No utilizo el dealing forex.
Usted, en el ejemplo deCopyTick, sólo obtiene un último elemento de la estructura, de hecho sólo los mejores precios.

¿Qué te hace pensar que es sólo un artículo?

Esa es la cuestión, me salen absolutamente todos los ticks (y no sólo los ticks, sino también los cambios en la taza)

Consulte

//+------------------------------------------------------------------+
//|                                                   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[], s_tick;
ulong last_time, mem_cnt, tot_cnt;
bool is_first;
int t_cnt, result;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
  tot_cnt = 0;
  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(is_book == true) MarketBookRelease(Symbol());
}
//+------------------------------------------------------------------+
//| BookEvent function                                               |
//+------------------------------------------------------------------+
void OnBookEvent(const string &symbol)
{
  if(symbol != Symbol()) return;
  tot_cnt++;
  if(SymbolInfoTick(Symbol(), s_tick) == true)
  {
    Print("SymbolInfoTick: ",GetTickDescription(s_tick));
  }
  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
  {
    if(SymbolInfoTick(Symbol(), s_tick) == true)
    {
      Print("SymbolInfoTick: ",GetTickDescription(s_tick));
    }
    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!");                          //Изменения стакана (добавлен/удален отложенный ордер)
      }
    }
    else
    {
      Print(__FUNCTION__, ": Pending order!");                          //Изменения стакана (добавлен/удален отложенный ордер)
    }
  }
}
//+------------------------------------------------------------------+
 

Ahí lo tienes, eso es bueno.

Prometí hablarle de otra ventaja de OnTick, en comparación con OnBook. Si tiene cálculos un poco pesados (o, Dios no lo quiera, operaciones), puede acumular una cola bastante grande de eventos que no tienen sentido(no contienen información relacionada con el evento). Aquí es donde la ventaja se convierte en desventaja, como suele ocurrir.

En este caso, OnTick simplemente omitirá los eventos que entraron en el momento del cálculo, y se activará en el primer evento nuevo y relevante. En la variante OnBook, para liberar la cola (omitir los eventos inútiles), tiene que hacer sus propias muletas.

 
Andrey Khatimlianskii:

Ahí lo tienes, eso es bueno.

Prometí hablarle de otra ventaja de OnTick, en comparación con OnBook. Si tiene cálculos un poco pesados (o, Dios no lo quiera, operaciones), puede acumular una cola bastante grande de eventos que no tienen sentido(no contienen información relacionada con el evento). Aquí es donde la ventaja se convierte en desventaja, como suele ocurrir.

En este caso, OnTick simplemente omitirá los eventos que entraron en el momento del cálculo, y se activará en el primer evento nuevo y relevante. En la variante de OnBook, para liberar la cola (omitir los eventos inútiles), hay que hacer sus propias muletillas.

Personalmente, utilizo las órdenes asíncronas en las operaciones comerciales.

La cuestión es que (si operas en serio en la Bolsa), necesitas todos los cambios del mercado,

y cuanto antes llegue este acontecimiento, mejor.

Además, necesita volúmenes de compra y venta...

Yo, por mi parte, no veo ninguna alternativa a OnBook

 
Roman:

No utilizo el dealing forex.
En el ejemplo deCopyTick sólo se obtiene un último elemento de la estructura, de hecho sólo los mejores precios.

Al ejecutar el código anterior, resulta que

 if(SymbolInfoTick(Symbol(), s_tick) == true)
  {
    Print("SymbolInfoTick: ",GetTickDescription(s_tick));
  }
s_tick.flags = 0

:)

2020.02.03 19:28:14.656 Ticks_test (GOLD-3.20,M1)       OnTick: 2020.02.03 19:28:13.160 Bid=1581.9 
2020.02.03 19:28:14.656 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 19:28:13.160
2020.02.03 19:28:14.656 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 19:28:13.160
2020.02.03 19:28:14.656 Ticks_test (GOLD-3.20,M1)       OnBookEvent: 2020.02.03 19:28:13.160 Bid=1581.9 

El mismo tick y al llamar aSymbolInfoTick- no hay bandera :)

Añadido

if(tick.flags == 0)
   {
     res = res + " ask = " + string(tick.ask) + "; bid = " + string(tick.bid);
   }

Recibimos una garrapata pero no sabemos quién la ha "creado".

2020.02.03 19:36:56.576 Ticks_test (GOLD-3.20,M1)       OnTick: 2020.02.03 19:36:54.735 Bid=1583 
2020.02.03 19:36:56.576 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 19:36:55.61 ask = 1583.3; bid = 1583.0
2020.02.03 19:36:56.576 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 19:36:55.61 ask = 1583.3; bid = 1583.0
2020.02.03 19:36:56.576 Ticks_test (GOLD-3.20,M1)       OnBookEvent: 2020.02.03 19:36:54.735 Bid=1583 

¿Qué pasa con los tiempos de las garrapatas?

Parece absurdo. Recibimos los ticks del nuevo paquete con la hora19:36:54.735, peroSymbolInfoTick se adelantó en 900 ms.

De la ayuda deSymbolInfoTick

[out]  Ссылка на структуру типа MqlTick, в которую будут помещены текущие цены и время последнего обновления цен.
 

Bonito tema, muchas cosas interesantes, gracias chicos.

Sin bromas y sin chanzas...

Sólo que no desarmes el código, lo tendré en cuenta...

 
prostotrader:

De todas formas, ¿qué pasa con el tiempo de tic-tac?

Es absurdo. Obtenemos los ticks del nuevo paquete con la hora19:36:54.735, pero al llamar aSymbolInfoTick obtenemos el tick "adelantado" en 900 ms??

De referencia

Realmente extraño, el valor de la oferta es el mismo para todos, pero el tiempo de SymbolInfoTick es diferente.

 
Roman:

Realmente extraño, el valor de la Oferta es el mismo para todos, pero el tiempo de SymbolInfoTick es diferente.

Parece que el terminal organiza el tiempo "como quiere" :)

2020.02.03 21:56:44.409 Ticks_test (GOLD-3.20,M1)       OnTick: 2020.02.03 21:56:42.776 Sell Tick: Last=1582.9 Volume=2 
2020.02.03 21:56:48.122 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 21:56:42.780 ask = 1583.1; bid = 1582.9
2020.02.03 21:56:48.122 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 21:56:42.780 ask = 1583.1; bid = 1582.9
2020.02.03 21:56:48.122 Ticks_test (GOLD-3.20,M1)       OnBookEvent: 2020.02.03 21:56:42.776 Sell Tick: Last=1582.9 Volume=2 

¡Casi 4 segundos pasaron por la hora local!

¡Eso no puede ser!

Y aquí todo es normal.

2020.02.03 21:57:02.294 Ticks_test (GOLD-3.20,M1)       OnTick: 2020.02.03 21:57:00.671 Sell Tick: Last=1582.9 Volume=5 
2020.02.03 21:57:02.294 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 21:57:00.671 Sell Tick: Last=1582.9 Volume=5 
2020.02.03 21:57:02.294 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick: 2020.02.03 21:57:00.671 Sell Tick: Last=1582.9 Volume=5 
2020.02.03 21:57:02.294 Ticks_test (GOLD-3.20,M1)       OnBookEvent: 2020.02.03 21:57:00.671 Sell Tick: Last=1582.9 Volume=5 
 
prostotrader:

Parece que el terminal organiza el tiempo "como quiere" :)

¡Casi 4 segundos han pasado por la hora local!

¡No puede ser!


El registro muestra que OnTick capturó el mismo tick 4 segundos más rápido que OnBookEvent

1  2020.02.03 21:56:44.409 Ticks_test (GOLD-3.20,M1)       OnTick:            2020.02.03 21:56:42.776 Sell Tick: Last=1582.9 Volume=2 
   2020.02.03 21:56:48.122 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick:    2020.02.03 21:56:42.780 ask = 1583.1; bid = 1582.9
   2020.02.03 21:56:48.122 Ticks_test (GOLD-3.20,M1)       SymbolInfoTick:    2020.02.03 21:56:42.780 ask = 1583.1; bid = 1582.9
2  2020.02.03 21:56:48.122 Ticks_test (GOLD-3.20,M1)       OnBookEvent:       2020.02.03 21:56:42.776 Sell Tick: Last=1582.9 Volume=2 
 
Yuriy Zaytsev:

Según el registro resulta que OnTick capturó el mismo tick más rápido por 4 segundos que OnBookEvent

Definitivamente, esto no puede ser el caso en la realidad,

porque los ticks ya están en el terminal (es decir, ya ha llegado un nuevo paquete de ticks)

 
prostotrader:

Definitivamente, esto no puede ser el caso en la realidad,

porque los ticks ya están en el terminal (es decir, ya ha llegado un nuevo paquete de ticks)

Pero miro el registro, y el registro uno y el mismo tick con una diferencia de 4 segundos vino.

p.d.

Realmente no me gusta la frase "no puede ser", me acostumbré a que todo puede pasar.

Por cierto, tal vez es lejos del tema, pero una vez en la afirmación de que la tierra es redonda, también, dijo algo como esto - "no puede ser.

En general, siempre tengo dudas hasta que lo compruebo y lo vuelvo a comprobar, y preferiblemente alguien más lo vuelve a comprobar unas cuantas veces.


¿Estás seguro de que tu código no se está estropeando, que forma el registro, procesa los datos?


este código produjo milagros con una diferencia de 4 segundos?


//+------------------------------------------------------------------+
//|                                                   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[], s_tick;
ulong last_time, mem_cnt, tot_cnt;
bool is_first;
int t_cnt, result;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
  tot_cnt = 0;
  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(is_book == true) MarketBookRelease(Symbol());
}
//+------------------------------------------------------------------+
//| BookEvent function                                               |
//+------------------------------------------------------------------+
void OnBookEvent(const string &symbol)
{
  if(symbol != Symbol()) return;
  tot_cnt++;
  if(SymbolInfoTick(Symbol(), s_tick) == true)
  {
    Print("SymbolInfoTick: ",GetTickDescription(s_tick));
  }
  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
  {
    if(SymbolInfoTick(Symbol(), s_tick) == true)
    {
      Print("SymbolInfoTick: ",GetTickDescription(s_tick));
    }
    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!");                          //Изменения стакана (добавлен/удален отложенный ордер)
      }
    }
    else
    {
      Print(__FUNCTION__, ": Pending order!");                          //Изменения стакана (добавлен/удален отложенный ордер)
    }
  }
}
//+------------------------------------------------------------------+
Razón de la queja: