Вопрос MQL5 init handle ERR_INDICATOR_WRONG_HANDLE 4807 Ошибочный хэндл индикатора

 

Приветствую!

Вопрос похоже к разработчикам о правильности работы, но может я что то не так понимаю... Набросал пример кода инициализации handle в двух вариантах:

1) все прописал в int OnInit(); и это работает!

2) вынес все тоже самое отдельно, ошибок не выдает, но вот при попытке получить данные: ERROR 4807 Ошибочный хэндл индикатора

Вопрос: Что я делаю не так? или ошибка не во мне?:))) подскажите плиз...

//+------------------------------------------------------------------+
//|                                                         test.mq5 |
//|                                Copyright 07.05.2024, LeonSi Ltd. |
//|                             https://www.mql5.com/ru/users/leonsi |
//+------------------------------------------------------------------+
#property copyright "Copyright 07.05.2024, LeonSi Ltd."
#property link      "https://www.mql5.com/ru/users/leonsi"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots   2
//--- plot ATR1
#property indicator_label1  "ATR1"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- plot ATR2
#property indicator_label2  "ATR2"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrFuchsia
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1
//--- input parameters
input int      ATR_Period1=14;
input int      ATR_Period2=21;
//--- indicator buffers
double         ATR1Buffer[];
double         ATR2Buffer[];
int            handle_ATR1;
int            handle_ATR2;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,ATR1Buffer,INDICATOR_DATA);
   SetIndexBuffer(1,ATR2Buffer,INDICATOR_DATA);
//+------------------------------------
//--- Variable 1!!!!!! Good Work
//+------------------------------------
   ResetLastError();
   if(!ArraySetAsSeries(ATR1Buffer,true))
     {
      Print("Failed to ArraySetAsSeries of the buffer 1 for the symbol "+
            Symbol()+EnumToString(Period())+" error code "+ IntegerToString(GetLastError()));
      return(INIT_FAILED);
     }
//--- create handle of the indicator iATR
   ResetLastError();
   handle_ATR1=iATR(Symbol(),Period(),ATR_Period1);
//--- if the handle is not created
   if(handle_ATR1==INVALID_HANDLE)
     {
      Print("Failed to create handle of the iATR indicator 1 for the symbol "+
            Symbol()+EnumToString(Period())+ " error code "+IntegerToString(GetLastError()));
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//+------------------------------------
//--- Variable 2!!!!!! Not work - Not ERROR!!!!
//+------------------------------------
   if(!atr2_init(ATR2Buffer,handle_ATR2))
      return(INIT_FAILED);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
   if(!FillArrayFromBuffer(ATR1Buffer,handle_ATR1,100))
      return(0);
   if(!FillArrayFromBuffer(ATR2Buffer,handle_ATR2,50))
      return(0);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
bool atr2_init(double &values[],    // buffer
               int handle           // handle
              )
  {
//---
   ResetLastError();
   if(!ArraySetAsSeries(values,true))
     {
      Print("Failed to ArraySetAsSeries of the buffer 2 for the symbol "+
            Symbol()+EnumToString(Period())+" error code "+ IntegerToString(GetLastError()));
      return(false);
     }
//--- create handle of the indicator iATR
   ResetLastError();
   handle=iATR(Symbol(),Period(),ATR_Period2);
//--- if the handle is not created
   if(handle==INVALID_HANDLE)
     {
      Print("Failed to create handle of the iATR indicator 2 for the symbol "+
            Symbol()+EnumToString(Period())+ " error code "+IntegerToString(GetLastError()));
      //--- the indicator is stopped early
      return(false);
     }
   return(true);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Filling indicator buffers from the iATR indicator                |
//+------------------------------------------------------------------+
bool FillArrayFromBuffer(double &values[],   // indicator buffer of ATR values
                         int handle,         // handle of the iATR indicator
                         int amount          // number of copied values
                        )
  {
//--- reset error code
   ResetLastError();
//--- fill a part of the ATR array with values from the indicator buffer that has 0 index
   if(CopyBuffer(handle,0,0,amount,values)<0)
     {
      //--- if the copying fails, tell the error code
      PrintFormat(" Failed to copy data from the iATR indicator %s%s, error code %d, amout %d",
                  Symbol(),EnumToString(Period()),GetLastError(), amount);
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
//--- everything is fine
   return(true);
  }
//+------------------------------------------------------------------+
 
SERGEI NAIDENOV:

Приветствую!

Вопрос похоже к разработчикам о правильности работы, но может я что то не так понимаю... Набросал пример кода инициализации handle в двух вариантах:

1) все прописал в int OnInit(); и это работает!

2) вынес все тоже самое отдельно, ошибок не выдает, но вот при попытке получить данные: ERROR 4807 Ошибочный хэндл индикатора

Вопрос: Что я делаю не так? или ошибка не во мне?:))) подскажите плиз...

по логике, в atr2_init параметр handle должен быть ссылкой..вы же его инициализируете и его значение должно сохраниться

bool atr2_init(double &arr[], int &handle);

 
Maxim Kuznetsov #:

по логике, в atr2_init параметр handle должен быть ссылкой..вы же его инициализируете и его значение должно сохраниться

bool atr2_init(double &arr[], int &handle);

Огромное спасибо! помогло... просто сделал по аналогии... а тут оказалось все в деталях:))...

bool FillArrayFromBuffer(double &values[],   // indicator buffer of ATR values
                         int handle,         // handle of the iATR indicator
                         int amount          // number of copied values
                        )
Причина обращения: