Array out of range

 

There is some explanation on this error here and here. But still I can not figure it out.. So please check out this code on an indicator called RMO, "Rahul Mohindar Oscillator". Coded not by me, but a great coder on another forum.. But after all the updates and changes to MT4 this does not work any more: I get the error "array out of range in 'rmo.mq4' (85,14)" which is the third line in this code fragment; the full code is attached.

 

   for(i=limit,r=Bars-limit-1; i>=0; i--,r++)
     {
      buffer4[i]=iMA(NULL,0,1,0,MODE_SMA,Price,i);
      double high   = buffer4[ArrayMaximum(buffer4,Depth,i)];
      double low    = buffer4[ArrayMinimum(buffer4,Depth,i)];
      double iprice = buffer4[i];
      double price  = iprice;
      double sum    = 0;

      for(int k=1; k<=Depth; k++)
        {
         pBuffer[r][k-1] = price;
         price           = (pBuffer[r][k-1]+pBuffer[r-1][k-1])/2.0;
         sum            += price;
        }


      if((high-low)!=0)
         buffer3[i] = 100*(iprice-sum/(Depth*1.0))/(high-low);
      else  buffer3[i] = 0;
      buffer2[i] = buffer2[i+1]+alpha*(buffer3[i]-buffer2[i+1]);
      buffer1[i] = buffer2[i];
     }
   return(0);
  }
Files:
rmo.mq4  3 kb
 
"the correct way should be for(int i=Bars-1; i>=0; i--) - 
that way you shall avoid errors in a lot of cases"-mladen on tsd forum
limit=Bars-1-counted_bars;
you know you could email him by emailing admin right?
 
Your maximum look back is Depth.
      double high   = buffer4[ArrayMaximum(buffer4,Depth,i)];
:
      for(int k=1; k<=Depth; k++)
Handle lookback.
   int    counted_bars=IndicatorCounted();
   int    i,r,limit;

   if(counted_bars<0) return(-1);
// if(counted_bars>0) counted_bars--;
// limit=Bars-counted_bars;
limit=Bars-1-MathMax(Depth, counted_bars);
No need for the decrement.
 

Once again thank you WHRoeder. And thanks Subgenius. I will do something nice for a stranger tomorrow to even out the cosmic balance ;)