mql4mt4

Why is iCustom() returning default empty value (2147483647) for my indicator?


I built my own custom indicator that calculates the approximate slope and acceleration of a chart using the previous X number of bars.

When I attach the indicator to a chart it works as expected, but when I try to retrieve the latest value within an EA using iCustom() it only returns 2147483647.

I've already tried using different values for the iCustom() shift parameter without success.

double         SlopeBuffer[];
double         AccelerationBuffer[];

extern int delta;

int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,SlopeBuffer);
   SetIndexBuffer(1,AccelerationBuffer);

//---
   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[])
  {
//---
   int i, counted_bars;
   counted_bars = IndicatorCounted();
   i = Bars - counted_bars - delta; // Here I offset the initial bar by the delta(period)
                                    // so that the first bar has delta previous bars on the chart.

   while(i>=0){                     
      double Ex = 0; //intermediate calculation variables...
      double Ey = 0;
      double Exy = 0;
      double Exx = 0;
      for(int n=0;n<delta;n++){     // This for loop iterates over the previous delta bars
         Ex += n;                   // to calculate various sigma variables used to find the
         Ey += Close[i+delta-n-1];  // slope.
         Exy += n*Close[i+delta-n-1];
         Exx += n*n;
         }
      double slope = 100*(delta*Exy - Ex*Ey)/(delta*Exx - Ex*Ex); // final slope calculation.
      SlopeBuffer[i] = slope;                                     // add to the buffer.
      AccelerationBuffer[i] = (slope - SlopeBuffer[i+1]);         // calculate acceleration
   i--;                                                           // and adding to buffer.
   }

//--- return value of prev_calculated for next call
   return(rates_total);
  }

Solution

  • I figured out the issue.

    This line was the culprit.

    i = Bars - counted_bars - delta;

    Once the indicator had "caught up" with all of the completed bars on the chart that would leave i equal to 1 - delta which would be negative. The result was that the while loop would never run.