Indicator return EMPTY_VALUE in EA

 

Hello and sorry for my bad english.

I made this very simple indicator that draws a SMA using iMA (totally useless but consider it like an exercice for me). It works fine when I use it manually on the terminal but always returns EMPTY_VALUE in an EA. Could you please help me understand what's wrong ?


Here's the indicator:

#property strict
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 White

double SMA[];

int OnInit()
{
  IndicatorBuffers(1);
  SetIndexBuffer(0, SMA);
  SetIndexLabel(0, "SMA");
  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(rates_total<=20+1) return(0);
  int limit=rates_total-prev_calculated;
  for(int i=limit-2; i>=0; i--)
  {
    SMA[i]=iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE, i);
    //Print("SMA[", i, "]=", SMA[i]);
  }
  return(rates_total);
}


And the EA:

int start()
{
  static datetime NewBar;
  if(NewBar==Time[0]) return(0);
  else NewBar=Time[0];
  
  double SMA=iCustom(NULL, 0, "SMA indicator", 0, 0);
  //if(SMA!=EMPTY_VALUE)
    Print(TimeToStr(Time[0], TIME_DATE|TIME_SECONDS), " SMA=", SMA); // always displays SMA=2147483647

  return(0);
}
 
  int limit=rates_total-prev_calculated;
  for(int i=limit-2; i>=0; i--)

Why are you subtracting 2?
 
Thank you for your help, you pointed the problem :)

I was using [i+1] earlier in the 'for' loop and limit-1 would produce an array out of range. Then I found a bug. After several hours (!!) of unsuccessful attempts I tried to isolate the bug by reducing the code but didn't realize that limit-2 made a big difference with limit-1. And it's still not clear for me.

With limit-1, or limit-2, limit-3, etc... there are enough bars in the past to calculate the MA, so why does iMA returns EMPTY_VALUE in the EA? Maybe because of the case limit=1 which cause an infinite loop?
 
BGen:


With limit-1, or limit-2, limit-3, etc... there are enough bars in the past to calculate the MA, so why does iMA returns EMPTY_VALUE in the EA? Maybe because of the case limit=1 which cause an infinite loop?

There may be when prev_calculated==0

but what about when

 int limit=rates_total-prev_calculated;

calculates at 0 or 1?

for(int i=limit-2; i>=0; i--)

will not be executed as i will equal either -1 or -2

 
Ok now I understand why the problem does not appear when I run the indicator on the terminal.

whroeder1, your solution seems efficient in all cases. I will keep it for future projects.

Problem solved. Thank you very much to both of you for taking the time to help me. And others :)