# Moving average starting at daily open

26

Hello All,

I am have very basic programming skills in mql4 and I'd appreciate some help with the following code.

I'm trying to code a simple moving average that starts at daily open that has a period equal to the number of candles present on chart since the beginning of the current day (timeframe independent).

Ex. assuming we are on M1, at midnight my moving average is equal to the close (I'm computing my MA on close price), at 00:01 MA = (Close 00:00 + Close 00:01)/2, etc.

The code is fairly unsofisticated but it works fine until the last candle, when as soon as a new tick arrives "j" and "mean" are reset to zero (I saw that from Experts tab) and so my average suddenly drops to current Close/2. Indeed, if in my while

loop I put i>1 everything works ok. What am I doing wrong?

```int start()

{

int    i,j,nCountedBars;

double mean,av,close;

//---- insufficient data

if(Bars<=0) return(0);

//---- bars count that does not changed after last indicator launch.

nCountedBars=IndicatorCounted();

//----calculation

i=Bars-1;

if(nCountedBars>1)

i=Bars-nCountedBars;

while(i>=0)

{

if (TimeDay(Time[i]) != TimeDay(Time[i+1])) {ExtStdDevBuffer[i]=close;mean=0;j=0;}

close=Close[i];

j=j+1;

mean= (mean+close);

av = mean/j;

ExtStdDevBuffer[i]=av;

i--;

}

//----

return(0);

}```

Thanks for any help.

Moderator
20339

Please use the code button (Alt + S) when posting code. I have done it for you this time.

It makes it easier for others to read your code if you avoid the huge gaps between lines.

26

Keith Watford:

Please use the code button (Alt + S) when posting code. I have done it for you this time.

It makes it easier for others to read your code if you avoid the huge gaps between lines.

Ok thanks. It's my first post.