Question on MA Shift

 

I am trying to flag the condition of MA crssover in my EA. For this the code I have written is

min15ma14now=iMA(Symbol(),PERIOD_M15,14,0,MODE_EMA,PRICE_CLOSE,0);
min15ma7now=iMA(Symbol(),PERIOD_M15,7,0,MODE_EMA, PRICE_CLOSE, 0);
min15ma14prev=iMA(Symbol(),PERIOD_M15,14,0,MODE_EMA, PRICE_CLOSE, 1);
min15ma7prev=iMA(Symbol(),PERIOD_M15,7,0,MODE_EMA, PRICE_CLOSE, 1);

cross=0;
if (min15ma7now>min15ma14now && min15ma7prev<min15ma14prev)cross=1;
if (min15ma7now<min15ma14now && min15ma7prev>min15ma14prev)cross=-1;

The above code executes at the start of a new bar and identifies if MA crossover has happened. In the above code shift=1 and shift is MA calculated 1 bar ago in the case above.

However when I look at the result min15ma14prev is not always equal to min15ma14now as calculated at the start of the previous bar. Can someone explain why this would be the case?

 

I think I got the answer. When I calculate min15ma14now at the start of Bar X, it takes into account the current tick which would be considered the close of the bar X and calculate the MA accordingly. However when I calculate min15ma14prev at the start of Bar X+1, it takes into account the actual close price of Bar X to calculate the MA. The Close price of Bar X will be different at the end of Bar X as compared to the begining of Bar X, hence the difference in the MA's.


Can someone let me know if the explanation is incorrect?

 

If bar 0 is included in your calculation, then the result is unstable.

I'm not sure what you are saying "exactly", but it seems you are seeing the problem.

 
Because I use close of Bar 0 it is a problem. If I use open of Bar 0 for the calculations, there should not be a problem..right?
 

The open price will not change.

Now, will you use the open or close of the bar you are comparing with?

Reason: