Erros, bugs, perguntas - página 3147

 
Bom dia a todos. Pode por favor informar se a função Sleep() é executada no modo de teste do Expert Advisor (teste em carraças reais, claro)?
 
SuhanovDM94 #:
Bom dia para todos. Pode informar se o Sleep() é executado no modo de teste do Expert Advisor (teste em carraças reais, claro)?

Em curso - o tempo do Testador é alterado por um montante apropriado.

 
fxsaber #:

Executado - o tempo do Testador é alterado por um montante apropriado.

Muito obrigado!

 
Wizard #:
É possível encontrar o tamanho do próprio tick em mql5, após o qual foi aberta uma posição?

Acontece que pode. O laço para é inserido numa função separada, na função OnTick() ou à sua própria discrição. Estou interessado na opinião de outros. Por exemplo, preciso dele para criar um sistema ultra-preciso. Por conseguinte, estou a escrever sem bibliotecas, incluindo funções de abertura e encerramento de posições. Quem diz o quê, as bibliotecas mqh atrasam o trabalho, por exemplo a compilação leva 1,5 vezes mais tempo. É melhor escrever tudo num só ficheiro. O estilo, OOP ou procedimento, não importa. MQL5 nunca se tornará uma linguagem ao nível de C++, é limitado. A questão está nas bibliotecas.

#define  EXPERT_MAGIC 261              // MagicNumber эксперта
input string Symbol_T  = "XAUUSD";    // глобальная переменная для задаваемого символа

..............

for(int i = PositionsTotal()-1; i >= 0; i--)
{
   if(PositionGetTicket(i) > 0 && PositionGetString(POSITION_SYMBOL) == Symbol_T && PositionGetInteger(POSITION_MAGIC) == EXPERT_MAGIC)
   {
      int attempts = 0;       // счетчик попыток
      bool success = false;   // флаг успешного выполнения копирования тиков
      MqlTick tick_array[];   // массив для приема тиков
         
      //--- сделаем 3 попытки получить тики
      while(attempts < 3)
      {
         //--- замерим время старта перед получением тиков
         uint start = GetTickCount();
         //--- дата, по которую запрашиваются тики (время открытия позиции)
         datetime Time_Open = (datetime)PositionGetInteger(POSITION_TIME);
         //--- дата, с которой запрашиваются тики (достаточно взять на 30 секунд раньше открытия позиции)
         datetime Time_Start = (datetime)(Time_Open-30);
         //--- запросим тиковую историю с момента Time_Start до момента Time_Open
         int received = CopyTicksRange(Symbol_T, tick_array, COPY_TICKS_ALL, Time_Start*1000, Time_Open*1000);
         if(received != -1)
         { 
            //--- выведем информацию о количестве тиков и затраченном времени
            PrintFormat("%s: received %d ticks in %d ms", Symbol_T, received, GetTickCount()-start);  
            //--- если тиковая история синхронизирована, то код ошибки равен нулю
            if(GetLastError()==0)
            {
               success = true;
               break;
            }
            else
               PrintFormat("%s: Ticks are not synchronized yet, %d ticks received for %d ms. Error=%d", Symbol_T, received, GetTickCount()-start, _LastError);
         }
         //--- считаем попытки
         attempts++;
         //--- пауза в 1 секунду в ожидании завершения синхронизации тиковой базы
         Sleep(1000);
      }
      //--- не удалось получить запрошенные тики от самого начала истории с трех попыток 
      if(!success)
      {
         PrintFormat("Ошибка! Не удалось получить %d тиков по %s с трех попыток", Symbol_T);
	 //return; (вставить, если цикл находится внутри функции типа void)
      }

      //--- узнаем количесто элементов в массиве
      int ticks = ArraySize(tick_array);

      //--- выведем bid последнего тика в массиве перед самым открытием позиции
      double last_bid_before_priceopen = tick_array[ticks-1].bid;
      Print("BID последнего тика: ", tick_array[ticks-1].bid);
      //--- выведем ask последнего тика в массиве перед самым открытием позиции
      double last_ask_before_priceopen = tick_array[ticks-1].ask;
      Print("ASK последнего тика: ", tick_array[ticks-1].ask);

      //--- узнаем цену, по которой была открыта позиция
      double Position_PriceOpen = PositionGetDouble(POSITION_PRICE_OPEN);

      if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
      {
         //--- вычислим размер последнего тика, на котором была открыта позиция (для BUY позиции открытие было по цене ASK)
         double size_last_tick_ASK = NormalizeDouble(fabs(Position_PriceOpen - last_ask_before_priceopen), _Digits);
      }
      else if((ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
      {
         //--- вычислим размер последнего тика, на котором была открыта позиция (для SELL позиции открытие было по цене BID)
         double size_last_tick_BID = NormalizeDouble(fabs(last_bid_before_priceopen - Position_PriceOpen), _Digits);
      }
   }
}

 

Estou farto deste insecto - há um indicador, há um perito a trabalhar nele. Mudo o indicador e recompilo-o. As mudanças do indicador podem ser claramente vistas no gráfico - o Expert Advisor é executado no testador - mas é como se não tivesse mudado nada. O mesmo resultado.

Se eu reiniciar o terminal e passar o testador depois disso, gerará um novo código.

O que é este hack, eu não compreendo.

Retirei o indicador ex5. O testador continua a funcionar como se nada tivesse acontecido. Onde obtém o ficheiro para correr????

 
Roman #:

3184
Estranho comportamento no indicador.
O for loop vai para o corpo, não em cada carrapato, mas apenas uma vez numa vela nova.

Mas i === 0 e a condição dada permite i>=0

no tick no mesmo limite de barras = 0
então o primeiro valor de i = -1 e condição i>=0
é por isso que não entra no laço.

 
Nikolai Semko #:

no mesmo limite de barras = 0
então o primeiro valor i = -1 e a condição i>=0
é por isso que não entra no laço.

Obrigada, perdi a tal.

Mas agora o IndBuff[i] está a fazer a sua cabeça dentro, matriz fora de alcance.
Do que é que precisa? Porque é que não atribui ao i=limite inicial ?


//+------------------------------------------------------------------+
//|                                                       Simple.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window

#property indicator_buffers      1
#property indicator_plots        1


//indicator buffers
double IndBuff[];

double c = 0;

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
{
   SetIndexBuffer(0, IndBuff, INDICATOR_DATA);
   PlotIndexSetInteger(0, PLOT_DRAW_TYPE,  DRAW_LINE);   //тип отрисовки
   PlotIndexSetInteger(0, PLOT_LINE_STYLE, STYLE_SOLID); //стиль отрисовки
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, clrAqua);     //цвет отрисовки
   PlotIndexSetInteger(0, PLOT_LINE_WIDTH, 1);           //толщина отрисовки
   PlotIndexSetString(0,  PLOT_LABEL,"K");               //метка
   PlotIndexSetDouble(0,  PLOT_EMPTY_VALUE, 0.0);        //нулевые значения считать пустыми
   
   return(INIT_SUCCEEDED);
}


//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate (const int rates_total,       
                 const int prev_calculated,   
                 const int begin,             
                 const double& price[])      
{

   ArraySetAsSeries(IndBuff, true);
   
   //-------------------------------------------------------------------------
   //Проверка и расчёт количества просчитываемых баров
   int limit = rates_total-prev_calculated;

   
   //-------------------------------------------------------------------------
   //Расчёт индикатора
   for(int i=limit; i>=0; i--)
   {
      c = iClose(_Symbol,PERIOD_CURRENT,i);      
      
      IndBuff[i] = c;  //на этой строке array out of range

   }
   

   return(rates_total);
}


 
Roman #:

Obrigada, falhei esta.

Mas agora o indicador IndBuff[i] está a fazer o cérebro, matriz fora de alcance.
Do que é que precisa? Porque não atribui ao i=limite inicial ?

   //Проверка и расчёт количества просчитываемых баров
   int limit = rates_total-prev_calculated;

   if(limit==1)
     limit=2;
   //-------------------------------------------------------------------------
   //Расчёт индикатора
   for(int i=limit-1; i>=0; i--)
   {
      c = iClose(_Symbol,PERIOD_CURRENT,i);      
      
      IndBuff[i] = c;  //на этой строке array out of range

   }
 
Vitaly Muzichenko #:

Assim, em cada barra entra num laço, enquanto precisa de entrar num laço em cada carraça.

Costumava funcionar desta forma

para as carraças i>=0,

para barras i>0

Agora não sei como trabalhar com o tampão.

 

Isto porque o IndBuff não é atribuído a taxas_total + 1
e o ArrayResize não é aplicável a ele.
Partiram o para construção. Agora temos de usar o if-arses para fazer tudo?

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate (const int rates_total,       
                 const int prev_calculated,   
                 const int begin,             
                 const double& price[])      
{

   ArraySetAsSeries(IndBuff, true);
   
   //-------------------------------------------------------------------------
   //Проверка и расчёт количества просчитываемых баров
   int limit = rates_total-prev_calculated;
   
   if(limit > 1)
   {
      
      Print(rates_total,": rates_total");
      Print(limit,": limit");   
      Print(ArraySize(IndBuff),": IndBuff");
   }   
   
   //-------------------------------------------------------------------------
   //Расчёт индикатора
   for(int i=limit; i>=0; i--)
   {
      c = iClose(_Symbol,PERIOD_CURRENT,i);    

      IndBuff[i] = c;  //array out of range

   }
   

   return(rates_total);
}
100686: rates_total
100686: limit
100686: IndBuff
array out of range in 'Simple.mq5' (82,15)