# Obtaining the average high value of previous bars

131

Hello

I want to obtain the high price of the previous candles and calculate the average price.

double average1()
{//average1 start
double highfirst[];
CopyHigh(FirstSymbol,timeframe,0,50,highfirst);
sum=0;
for(int k=0;k<=noofbars;k++)
sum=sum+highfirst[k];

double ave=sum/noofbars;
return (ave);

}//average1 end

but the function returns no value.

17050

 Morteza Khorasani:  but the function returns no value. Of course it return a value. Print out your variables, and find out why it doesn't return the value you think it should.
3951

Morteza Khorasani: I want to obtain the high price of the previous candles and calculate the average price but the function returns no value.

WHRoeder is correct, see the documentation on the function CopyHigh().

However why complicate things? Just use the iMA()!

AverageOfHighs = iMA( FirstSymbol, timeframe, noofbars, 0, MODE_SMA, PRICE_HIGH, 0 );

Also, please note that in your code your average calculation is incorrect because you are summing "noofbars + 1" and dividing the sum by "noofbars". The loop should probably be as follows:

for( int k = 0; k < noofbars; k++ ) // using "<" instead of "<="
CopyHigh - Timeseries and Indicators Access - MQL4 Reference
• docs.mql4.com
CopyHigh - Timeseries and Indicators Access - MQL4 Reference
131

whroeder1:
 Of course it return a value. Print out your variables, and find out why it doesn't return the value you think it should.

This message:

2016.12.30 00:10:52.270 DMCS1 GBPJPY,H1: array out of range in 'DMCS1.mq4' (225,18)

3951

Morteza Khorasani: 2016.12.30 00:10:52.270 DMCS1 GBPJPY,H1: array out of range in 'DMCS1.mq4' (225,18)
That is because you are only collecting "50" bars but then testing "noofbars" which is probably more than 50. Also, please take note of the "for" loop using "k < noofbars" instead of the "<=" which adds one more iteration.
131

Fernando Carreiro:
That is because you are only collecting "50" bars but then testing "noofbars" which is probably more than 50. Also, please take note of the "for" loop using "k < noofbars" instead of the "<=" which adds one more iteration.
Thank you dear Fernando. I am editing the code to see the results.
3951

Morteza Khorasani: Thank you dear Fernando. I am editing the code to see the results.
// Untested! Alternatively use the iMA solution (previously posted)
double HighAverage( string strSymbol, int intTimeFrame, int intBars )
{
double dblHighs[], dblAverage = 0.0;
int intCount = CopyHigh( strSymbol, intTimeFrame, 0, intBars, dblHighs );

if( intCount > 0 )
{
for( int i = 0; i < intCount; i++ ) dblAverage += dblHighs[ i ];
dblAverage /= double( intCount ); // Explicit typecasting just for good code practice
}

return( dblAverage );
}