Errores, fallos, preguntas - página 3147

 
Buenos días a todos. ¿Puede indicar si la función Sleep() se ejecuta en el modo de prueba de EA (probando en ticks reales, por supuesto)?
 
SuhanovDM94 #:
Buenos días a todos. ¿Podría indicar si Sleep() se ejecuta en el modo de prueba del Asesor Experto (probando en ticks reales, por supuesto)?

En progreso - el tiempo del Probador se modifica en una cantidad apropiada.

 
fxsaber #:

Ejecutado - el tiempo del Probador se modifica en una cantidad apropiada.

¡Muchas gracias!

 
Wizard #:
¿Es posible encontrar el tamaño del propio tick en mql5, tras el cual se abrió una posición?

Resulta que sí se puede. El bucle for se inserta en una función separada, en la función OnTick() o a su propia discreción. Me interesa la opinión de los demás. Por ejemplo, lo necesito para crear un sistema ultrapreciso. Por lo tanto, estoy escribiendo sin bibliotecas, incluyendo funciones para abrir y cerrar posiciones. Quien dice que, las bibliotecas mqh ralentizan el trabajo, por ejemplo la compilación tarda 1,5 veces más. Es mejor escribir todo en un solo archivo. El estilo, OOP o procedimental, no importa. MQL5 nunca se convertirá en un lenguaje al nivel de C++, es limitado. El punto está en las 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);
      }
   }
}

 

Estoy harto de este error - hay un indicador, hay un experto trabajando en ello. Cambié el indicador y lo recompilé. Los cambios del indicador se ven claramente en el gráfico - el Asesor Experto se ejecuta en el probador - pero es como si no cambiara nada. El mismo resultado.

Si reinicio el terminal y paso el probador después se genera un nuevo código.

Qué es este hack, no lo entiendo.

He eliminado el indicador ex5. El probador sigue funcionando como si no pasara nada. ¿De dónde saca el archivo para ejecutar????

 
Roman #:

3184
Comportamiento extraño en el indicador.
El bucle for entra en el cuerpo, no en cada tick, sino sólo una vez en una nueva vela.

Pero i == 0 y la condición dada permite i>=0

en el tick de la misma barra límite = 0
por lo que el primer valor de i = -1 y la condición i>=0
por eso no entra en el bucle.

 
Nikolai Semko #:

en el tick de la misma barra límite = 0
por lo que el primer valor i = -1 y la condición i>=0
por eso no entra en el bucle.

Gracias, se me escapó.

Pero ahora el búfer indicador IndBuff[i] se está haciendo la cabeza, array fuera de rango.
¿Qué necesita? ¿Por qué no se asigna a la inicial i=límite?


//+------------------------------------------------------------------+
//|                                                       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 #:

Gracias, me perdí el uno.

Pero ahora el buffer indicador IndBuff[i] está haciendo el cerebro, array fuera de rango.
¿Qué necesita? ¿Por qué no se asigna a la inicial i=limit?

   //Проверка и расчёт количества просчитываемых баров
   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 #:

Así que en cada barra entra en un bucle, mientras que necesita entrar en un bucle en cada tick.

Solía funcionar así

para los ticks i>=0,

para las barras i>0

Ahora no sé cómo trabajar con el buffer.

 

Eso es porque IndBuff no está asignado a rates_total + 1
Y ArrayResize no es aplicable a él.
Rompieron el para construir. ¿Ahora tenemos que usar if-arses para hacer todo?

//+------------------------------------------------------------------+
//| 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)
Razón de la queja: