Bug, or can anyone explain this please (iMaOnArrray)

 
I have an array of 20 items. Index [0 ... 10] filled with a value of 9, the rest empty (zero).

Now, when I do an iMAOnArray with Shift 0 (Period 5) I would expect to get a result of 9 (average of items with index [0 ... 4]), same as if I did an iMA of shift 0 where I would get the average of indicator bars [0 ... 4].

However, what I'm getting is a value of 0.2341 ...

From the code below I'd expect a couple of 9's ( average of bh[5...9], bh[4...8], etc. which all have a value of 9) but I'm getting odd numbers.

Is this a bug or am I completely misinterpreting the iMAOnArray function?




   
   double bh[];
   int smooth= 5;
      
   ArrayResize(bh, 20);
   ArrayInitialize(bh, 0);
   
   for (int shift= 10; shift>= 0; shift--) {
      bh[shift]= 9;
   }


   Print("Size: ", ArraySize(bh));
   
   for ( shift= smooth; shift>= 0; shift--) {
      double ma=  iMAOnArray(bh, 0, smooth, 0, MODE_EMA, shift);
      Print("idx ", shift, " should be 9: ", ma);
   }     
   
 
no it is not a bug. it is just how this formula works. If you make a little chage in code you understand why. but first things first. if you make a array, lets say 5 members, and fill first 9 with 9 then you have something like this
array 1 2 3 4 5
value 9 9 9 0 0

now if you make iMAOnArray(array, 0, 2, MODE_EMA, 3) -- period of 2; place 3 then you expect to get 9 but you get 3
this is turn around way Moving average works. It takes start at the end... this means that place 5 with a value 0 is for this function first avialble dataset.

change in for smooth to 19 and you see what I'm talking about. 19 is because first is 0 (not 1)

for ( shift=19; shift>= 0; shift--) {
      double ma=  iMAOnArray(bh, 0, smooth, 0, MODE_EMA, shift);
      Print("idx ", shift, " should be 9: ", ma);
   }     



and then happens something funny. If value of array is zero it takes last value and calculates with that... so the moving average moves "smoothly" to the zero. at this point as values ends... then the calculation will be 0*(2/6)+9*(1-2/6)=6
after that it should be 0*(2/6)+0*(1-2/6)=0 but it is 0*(2/6)+6*(1-2/6)=4 etc.

so to get your first 5 numbers you should use the code (it is from Moving Average index which comes with Metatrader).

double pr=2.0/(smooth+1);
   for ( shift=smooth; shift>=0; shift--) {
      ma=bh[shift]*pr+bh[shift+1]*(1-pr);
      Print("idx ", shift, " should be 9: ", ma);
   }     



or just do not forget that if the dataset ends before array does the Exponent Moving Average goes smoothly to zero.

Had sometimes ago problems with that function...