Error text "2018.07.05 15:21:32.080 StBB0 (EURUSD,M5) array out of range in 'StBB0.mq5' (139,33)"
I don't understand why values for the whole array are calculated, though I've explicitly specified only the first 5 candlesticks (replacement with values_to_copy doesn't help).
//+------------------------------------------------------------------+//| StBB0.mq5 |//| Copyright 2018, MetaQuotes Software Corp. |//| https://www.mql5.com |//+------------------------------------------------------------------+#property copyright"Copyright 2018, MetaQuotes Software Corp."#property link"https://www.mql5.com"#property version"1.00"#property indicator_separate_window//#property indicator_chart_window //#property indicator_minimum 1//#property indicator_maximum 100#property indicator_buffers4#property indicator_plots1//--- построение Middle #property indicator_label1"Middle"#property indicator_type1DRAW_LINE#property indicator_color1clrMediumSeaGreen#property indicator_style1STYLE_SOLID#property indicator_width11//--- построение Upper #property indicator_label3"Upper"#property indicator_type3DRAW_LINE#property indicator_color3clrMediumSeaGreen#property indicator_style3STYLE_SOLID#property indicator_width31//--- построение Lower #property indicator_label2"Lower"#property indicator_type2DRAW_LINE#property indicator_color2clrMediumSeaGreen#property indicator_style2STYLE_SOLID#property indicator_width21//--- индикаторные буферы double UpperBuffer[];
double LowerBuffer[];
double MiddleBuffer[];
double Buffer[];
inputint bands_period=20; // период скользящей средней inputint bands_shift=0; // сдвиг inputdouble deviation=2.0; // кол-во стандартных отклонений inputENUM_APPLIED_PRICE applied_price=PRICE_CLOSE; // тип цены //--- переменная для хранения хэндла индикатора iBands int handle;
//--- будем хранить количество значений в индикаторе Bollinger Bands int bars_calculated=0;
//+------------------------------------------------------------------+//| Custom indicator initialization function |//+------------------------------------------------------------------+intOnInit()
{
//--- indicator buffers mapping//--- привязка массивов к индикаторным буферам SetIndexBuffer(0,Buffer,INDICATOR_DATA);
SetIndexBuffer(2,UpperBuffer,INDICATOR_CALCULATIONS);
SetIndexBuffer(1,LowerBuffer,INDICATOR_CALCULATIONS);
SetIndexBuffer(3,MiddleBuffer,INDICATOR_CALCULATIONS);
//--- зададим смещение для каждой линии PlotIndexSetInteger(0,PLOT_SHIFT,bands_shift);
//PlotIndexSetInteger(1,PLOT_SHIFT,bands_shift);//PlotIndexSetInteger(2,PLOT_SHIFT,bands_shift);//---- индексация элементов в буферах как в таймсериях ArraySetAsSeries(UpperBuffer,true);
ArraySetAsSeries(LowerBuffer,true);
ArraySetAsSeries(MiddleBuffer,true);
ArraySetAsSeries(Buffer,true);
//--- создадим хэндл индикатора
handle=iBands(_Symbol,PERIOD_CURRENT,bands_period,bands_shift,deviation,applied_price);
//--- если не удалось создать хэндл if(handle==INVALID_HANDLE)
{
//--- сообщим о неудаче и выведем номер ошибки PrintFormat("Не удалось создать хэндл индикатора iBands для пары %s/%s, код ошибки %d",_Symbol,EnumToString(PERIOD_CURRENT),GetLastError()); //--- работа индикатора завершается досрочно return(INIT_FAILED);
}
//---return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+//| Custom indicator iteration function |//+------------------------------------------------------------------+intOnCalculate(constint rates_total,
constint prev_calculated,
constdatetime &time[],
constdouble &open[],
constdouble &high[],
constdouble &low[],
constdouble &close[],
constlong &tick_volume[],
constlong &volume[],
constint &spread[])
{
//--- количество копируемых значений из индикатора iBands int values_to_copy;
//--- узнаем количество рассчитанных значений в индикаторе int calculated=BarsCalculated(handle);
if(calculated<=0)
{
PrintFormat("BarsCalculated() вернул %d, код ошибки %d",calculated,GetLastError());
return(0);
}
//--- если это первый запуск вычислений нашего индикатора или изменилось количество значений в индикаторе iBands //--- или если необходимо рассчитать индикатор для двух или более баров (значит что-то изменилось в истории) if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)
{
//--- если размер индикаторных массивов больше, чем значений в индикаторе iBands на паре symbol/period, то копируем не все //--- в противном случае копировать будем меньше, чем размер индикаторных буферов if(calculated>rates_total) values_to_copy=rates_total;
else values_to_copy=calculated;
}
else
{
//--- значит наш индикатор рассчитывается не в первый раз и с момента последнего вызова OnCalculate()) //--- для расчета добавилось не более одного бара
values_to_copy=(rates_total-prev_calculated)+1;
}
//--- заполняем массив значениями из индикатора Bollinger Bands //--- если FillArraysFromBuffer вернула false, значит данные не готовы - завершаем работу if(!FillArraysFromBuffers(MiddleBuffer,UpperBuffer,LowerBuffer,bands_shift,handle,values_to_copy)) return(0);
//--- сформируем сообщение string comm=StringFormat("%s ==> Обновлено значений в индикаторе %s: %d",
TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),values_to_copy);
//--- выведем на график служебное сообщение //Comment(comm); if(ArraySize(UpperBuffer)>0)
{
for(int bar=0; 0<5 && !IsStopped(); bar++)
{
double _max=UpperBuffer[bar];double _min=LowerBuffer[bar];
double _Close=iClose(_Symbol,PERIOD_CURRENT,bar);
Buffer[bar]=MathAbs((((_max+_min)/2)-_Close));
};
};//Print(bars_calculated);//--- запомним количество значений в индикаторе Bollinger Bands
bars_calculated=calculated;
//--- вернем значение prev_calculated для следующего вызова return(rates_total);
}
//+------------------------------------------------------------------+ //| Заполняем индикаторные буферы из индикатора iBands | //+------------------------------------------------------------------+ bool FillArraysFromBuffers(double &base_values[], // индикаторный буфер средней линии Bollinger Bands double &upper_values[], // индикаторный буфер верхней границы double &lower_values[], // индикаторный буфер нижней границы int shift, // смещение int ind_handle, // хэндл индикатора iBands int amount // количество копируемых значений
)
{
//--- сбросим код ошибки ResetLastError();
//--- заполняем часть массива MiddleBuffer значениями из индикаторного буфера под индексом 0 if(CopyBuffer(ind_handle,0,-shift,amount,base_values)<0)
{
//--- если копирование не удалось, сообщим код ошибки PrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
//--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитанным return(false);
}
//--- заполняем часть массива UpperBuffer значениями из индикаторного буфера под индексом 1 if(CopyBuffer(ind_handle,1,-shift,amount,upper_values)<0)
{
//--- если копирование не удалось, сообщим код ошибки PrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
//--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитанным return(false);
}
//--- заполняем часть массива LowerBuffer значениями из индикаторного буфера под индексом 2 if(CopyBuffer(ind_handle,2,-shift,amount,lower_values)<0)
{
//--- если копирование не удалось, сообщим код ошибки PrintFormat("Не удалось скопировать данные из индикатора iBands, код ошибки %d",GetLastError());
//--- завершим с нулевым результатом - это означает, что индикатор будет считаться нерассчитанным return(false);
}
//--- все получилось return(true);
}
//+------------------------------------------------------------------+ //| Indicator deinitialization function | //+------------------------------------------------------------------+ voidOnDeinit(constint reason)
{
//--- почистим график при удалении индикатора Comment("");
}
//+------------------------------------------------------------------+
Error text "2018.07.05 15:21:32.080 StBB0 (EURUSD,M5) array out of range in 'StBB0.mq5' (139,33)"
It's unclear why the values are calculated for the entire array, even though I've explicitly selected only the first 5 candlesticks (replacement with values_to_copy doesn't help).
Where is it wrong? Please mark the line with the colour.
Vladimir, thank you for the code - everything works! The only question that remains is why my enum cannot be declared directly in the signals module, but only in the main Expert Advisor's code.
Vladimir, thanks for the code - everything works! Only one question remains - why can't I declare my enum directly in the signal module, but only in the main EA code?
I don't know. I would only assume that at the time when signal modules were invented, no one thought that enum could be used as a variable type. That is, it wasn't provided for.
Yes, I guess so. And it takes enumerations from the MAs of the standard library - you can put them directly into the description of your signal module.
Allow the use of cookies to log in to the MQL5.com website.
Please enable the necessary setting in your browser, otherwise you will not be able to log in.
You are signed in. Two-factor authentication has been disabled. Set it up again and scan a new QR code, or continue with two-factor authentication disabled.
Please help with the error.
Error text "2018.07.05 15:21:32.080 StBB0 (EURUSD,M5) array out of range in 'StBB0.mq5' (139,33)"
I don't understand why values for the whole array are calculated, though I've explicitly specified only the first 5 candlesticks (replacement with values_to_copy doesn't help).
Please help with the error.
Error text "2018.07.05 15:21:32.080 StBB0 (EURUSD,M5) array out of range in 'StBB0.mq5' (139,33)"
It's unclear why the values are calculated for the entire array, even though I've explicitly selected only the first 5 candlesticks (replacement with values_to_copy doesn't help).
Where is it wrong? Please mark the line with the colour.
О!
Why is the DIGITAL "0" compared to the number "5"?
О!
And why is the DIGITAL "0" compared to the number "5"?
I got confused, replaced it with "bar<values_to_copy ", everything works)
Thank you!
The solution is as follows: in the signals module
In the Expert Advisor that was generated by the MQL5 Wizard:
Bottom Line:
Vladimir, thank you for the code - everything works! The only question that remains is why my enum cannot be declared directly in the signals module, but only in the main Expert Advisor's code.
Vladimir, thanks for the code - everything works! Only one question remains - why can't I declare my enum directly in the signal module, but only in the main EA code?
I don't know. I would only assume that at the time when signal modules were invented, no one thought that enum could be used as a variable type. That is, it wasn't provided for.
Yeah, I guess so. And it takes enums from the MAs of the standard library and you can put them right into the description of your signal module.
I meant that the custom enum was not provided.
Yes, but the built-in enums from MA are!
Forum on Trading, Automated Trading Systems and Strategy Tests
FAQ from Beginners MQL5 MT5 MetaTrader 5
Vladimir Karputov, 2018.07.05 15:44
I meant that custom enum were not provided.