Indicator cannot call in OnCalculate()

 

"[MQL5 bug]" removed from topic title by moderator.

Indicator call function like iMA(), iRSI(), iCustom() .... etc. It's strict must call only in OnInit() ?

If call in other event like OnCalculate(), Buffer value will be distorted. (From code the red line buffer should be equal as moving average period 1)

Below is code. You can compare between call in OnInit() and call on OnCalculate() with input.

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_color1 clrRed
#property indicator_type1 DRAW_LINE

enum enum_Mode
{
Initial=0 //OnInit()
,Calculate=1 //OnCalculate()
};

input enum_Mode Mode=Calculate;

double buffer[];
int handle=-1;

int OnInit()
{
SetIndexBuffer(0,buffer);

   if(Mode==Initial)
   handle=iMA(_Symbol,PERIOD_CURRENT,1,0,0,PRICE_CLOSE);

return(INIT_SUCCEEDED);
}

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(prev_calculated==0)
   {
      for(int i=0;i<rates_total;i++)
      {
         if(Mode==Calculate)
         handle=iMA(_Symbol,PERIOD_CURRENT,1,0,0,PRICE_CLOSE);
         
      CopyBuffer(handle,0,i,1,buffer);
      }
   }
   
return(rates_total);
}
Moving Average - Trend Indicators - Technical Indicators - Price Charts, Technical and Fundamental Analysis - MetaTrader 5 Help
  • www.metatrader5.com
The Moving Average Technical Indicator shows the mean instrument price value for a certain period of time. When one calculates the moving average...
 
Your topic has been moved to the section: Technical Indicators
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
momocoong:Indicator call function like iMA(), iRSI(), iCustom() .... etc. It's strict must call only in OnInit() ? If call in other event like OnCalculate(), Buffer value will be distorted. (From code the red line buffer should be equal as moving average period 1) Below is code. You can compare between call in OnInit() and call on OnCalculate() with input.

There is no MQL5 bug. You need to fix your code. Read the documentation on CopyBuffer and on iMA.

Here is an example for beginners ...

Code Base

Moving average code for beginners by William210

Gerard Willia G J B M Dinh Sy, 2023.08.24 16:40

Moving average beginner tutorial to learn how to code in MQL5