How to fix loop to create average high from last bars

 

Hi i know about iMA function but my indicator isnt finished like that yet and iMa does not work for my purpose. 

int inpPeriod = 5;
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[])
  {

for(int i=1;i<rates_total && !IsStopped();i++)

   {          

         double dblhigh[], dblAverageHigh = 0.0;

         int intCountHigh = CopyHigh( _Symbol, _Period, i, inpPeriod, dblhigh );

         if( intCountHigh  > 0){

            for( int i2 = 0; i2 < intCountHigh  ; i2++ ){            

              dblAverageHigh  += dblhigh[ i2 ] ;

            }

              dblAverageHigh  = dblAverageHigh  / inpPeriod; 

          }            

         Buffer[i] = dblAverageHigh;

      }
}

What i want is that it takes the last 5 bars and calculate the average, and so on for all 5 bars before like "5 bars -1", "5 bars -2".

The problem is that the indicator is working but not correctly taking the last 5 bars from his position. So i recieve kind of random results.


If i change my start position to 0

int intCountHigh = CopyHigh( _Symbol, _Period, 0, inpPeriod, dblhigh );

Then it works for the current last 5 bars, but the whole buffer is filled with just this value and not calculates last 5 bars -1 ...

Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
Documentation on MQL5: Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
  • www.mql5.com
Predefined Macro Substitutions - Named Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

You don't need to use "CopyHigh". There is array of "high".

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[])

You are to sum the values of the 5 bars from position i.

for( int i2 = i ; i2 > i - inpPeriod; i2-- )

You need to consider the starting position of the calculation. However, "prev_calculated" should be applied.

for(int i = inpPeriod;i<rates_total && !IsStopped();i++)
 

Oh your right, thank you very much for help. 

Its working fine now.

Reason: