Características da linguagem mql5, subtilezas e técnicas - página 103

 
Nikolai Semko:

Só queria dizer que talvez usar o user32.dll em vez do kernel32.dll possa ser mais rápido em ligar dois terminais usando o WinAPI, porque todas as implementações que eu vi usam o kernel32.dll.

Bem, não vejo nenhuma razão para ser mais rápido importar de uma biblioteca do que de outra.

Talvez não seja relevante nas versões atuais do MQL, mas até onde me lembro do antigo MQL4, esses custos eram bastante significativos e às vezes até comparáveis com a velocidade de execução das funções.

 
fxsaber:

Sim.

Ahh... bem, pensem nisso como um capricho meu.

Eu só gosto de velocidade, porque quem é mais rápido vem primeiro, e também há menos carga na CPU, o que significa mais recursos e tempo para tomar uma decisão.

 
fxsaber:
Implementação rápida do OnTick com múltiplos símbolos

Ao executar um Expert Advisor vazio utilizando um espião em 50 símbolos, as mensagens começam a acumular-se no registo:

2018.10.09 22:49:24.730 Spy (AUDNZD,W1) indicator is too slow, 4281 ms. rewrite the indicator, please

Se eu adicionar um filtro ao indicador para a frequência de envio de eventos castum de 500ms, os erros tornam-se menos frequentes, mas eles não desaparecem.

É só eu?


Código EA:

#define  ForEach(index,array)   for(int index=0, max_##index=ArraySize(array);  index<max_##index;  index++)

string Symbols[];

int OnInit()
{
   ArrayResize( Symbols, SymbolsTotal(true) );

   ForEach( i, Symbols )
   {
      Symbols[i] = SymbolName(i,true);

      if( Symbols[i] != _Symbol )
         iCustom( Symbols[i], PERIOD_W1, "Spy.ex5", ChartID(), i );
   }
   return(INIT_SUCCEEDED);
}

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   if( id == CHARTEVENT_CUSTOM )
      OnTickMS( Symbols[ (int)lparam ] );
}

void OnTick()
{
   CheckSignal( _Symbol );
}

void OnTickMS(const string &Symb)
{
   CheckSignal( Symb );
}

void CheckSignal(const string symbol)
{
   //Comment( symbol, ": ",
   //                   DoubleToString( SymbolInfoDouble( symbol, SYMBOL_BID ), 5 ), " / ",
   //                   DoubleToString( SymbolInfoDouble( symbol, SYMBOL_ASK ), 5 ) );
   return;
}


OProfiler mostra 95% de tempo iCustom, o OnChartEvent não leva quase nada. O processador (i5-3570) está carregado a 75%.

 
Andrey Khatimlianskii:

Ao executar um EA vazio usando um espião em 50 instrumentos, as mensagens começam a derramar no registro:

É impressão minha?

Eu apanhei vários destes erros no início. Eu não os levei mais longe.

O profiler mostra 95% do tempo do iCustom, OnChartEvent não leva quase nada. A carga da CPU (i5-3570) é de 75%.

Em CPU Release-version é de ~3%.

 
fxsaber:

Apanhei alguns destes erros no início. Não há mais colisões.

A versão de liberação tem CPU ~3%.

Eu construí indicador e Expert Advisor com "Optimize=1", ainda ocorrem erros.

 

Acrescentei uma segunda pausa ao indicador:

int OnCalculate( const int rates_total, const int prev_calculated, const int, const double &[] )
{
   static datetime prev = 0;
   if ( TimeCurrent() <= prev ) return(rates_total);
   prev = TimeCurrent();

Os erros permanecem.

 

Indicador

#property indicator_chart_window
#property indicator_plots 0

input long Chart = 0; // идентификатор графика-получателя события
input int  Index = 0;

ulong timer = GetMicrosecondCount();
//===================================================================
//| 
//+------------------------------------------------------------------
int OnCalculate( const int rates_total, const int prev_calculated, const int, const double &[] )
{
   if( GetMicrosecondCount() - timer < 1 e6 ) return( rates_total );
   
   timer = GetMicrosecondCount();
   
   if( prev_calculated )
   {
      ResetLastError();
      
      if( EventChartCustom( Chart, 0, Index, 0, NULL ))
         Print( GetMicrosecondCount() - timer );
      else
         Print( (string)_LastError +" "+ (string)(GetMicrosecondCount() - timer) );
   }
   
   return( rates_total );
}
//+------------------------------------------------------------------

EA

#property strict
//+------------------------------------------------------------------
#define  ForEach(index,array)               for(int index=0, max_##index=ArraySize(array);  index<max_##index;  index++)
//+------------------------------------------------------------------
string Symbols[];

//===================================================================
//| Expert initialization function
//+------------------------------------------------------------------
int OnInit()
{
   ArrayResize( Symbols, SymbolsTotal(true) );
   
   ForEach( i, Symbols )
   {
      Symbols[i] = SymbolName(i,true);
      
      if( Symbols[i] != _Symbol )
         iCustom( Symbols[i], PERIOD_W1, "Spy.ex5", ChartID(), i ); // MQL5\Indicators\Spy.ex5
   }
   
   return(INIT_SUCCEEDED);
}
//===================================================================
//| Expert deinitialization function
//+------------------------------------------------------------------
void OnDeinit(const int reason)
{
   ArrayFree( Symbols );
}
//===================================================================
//| ChartEvent function
//+------------------------------------------------------------------
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
}
//===================================================================
//| Expert tick function
//+------------------------------------------------------------------
void OnTick()
{
}
//+------------------------------------------------------------------


Aumentar a pausa não ajuda muito. Começa a desmoronar mesmo aos 3 segundos.

Por razões desconhecidas, em certo momento, o EventChartCustom deixa de funcionar. Empata por cerca de 3 segundos e gera erro 4001.

Arquivos anexados:
20181010.log  276 kb
 
Oleksii Chepurnyi:

Indicador

EA


Aumentar a pausa não ajuda muito. Começou a desmoronar mesmo aos 3 segundos.

Por alguma razão desconhecida, em algum momento, o EventChartCustom deixa de funcionar. Empata por cerca de 3 segundos e dá erro 4001.

Sim, parece ser esse o problema.

Alguém mais o tem a tocar?

 
Andrey Khatimlianskii:

Ainda está a tocar?

Não é.

#define  ForEach(index,array)   for(int index=0, max_##index=ArraySize(array);  index<max_##index;  index++)

string Symbols[];
int Counter[];

int OnInit()
{
   ArrayResize(Counter, ArrayResize( Symbols, SymbolsTotal(true) ));   
   ArrayInitialize(Counter, 0);

   ForEach( i, Symbols )
   {
      Symbols[i] = SymbolName(i,true);

      if( Symbols[i] != _Symbol )
         if (iCustom( Symbols[i], PERIOD_W1, "Spy.ex5", ChartID(), i ) == INVALID_HANDLE)
          Alert(Symbols[i]);
   }
   return(INIT_SUCCEEDED);
}

void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
   static int Count = 0;
   
   if( id == CHARTEVENT_CUSTOM )
   {
     Counter[(int)lparam]++;
     
     string Str = (string)Count++ + "\nMarketWatch:";
     
     for (int i = 0; i < ArraySize(Counter); i++)
      Str += "\n" + (string)i + ": " + Symbols[i] + " " + (string)Counter[i];
      
     Comment(Str);
   }
}


Uma hora de trabalho - o voo é normal.

 
fxsaber:

Sem reprodução


Uma hora de trabalho - voo normal.

Quantos instrumentos na análise do mercado?