Download MetaTrader 5

Does iMAOnArray give the true result ?

To add comments, please log in or register
bertrand
9
bertrand  
I try to compute MA to check if the fuction iMAOnArray gives the true result. I find the same result for SMA, but not for EMA, can someone check my code ?
double iMAOnArray2(double       array[],          // array with data
                   int          total,            // number of elements
                   int          ma_period,        // MA averaging period
                   int          ma_shift,         // MA shift
                   int          ma_method,        // MA averaging method
                   int          shift             // shift)
                  ) {

  int n = ArraySize(array) - ma_shift;
  int i,j;
  double sum = 0;
  double priceprec,price;
  
  switch(ma_method) {

  case MODE_SMA:
    for(i = n-1-shift; i >= n-ma_period-1; i--) {
      if(i >= 0) sum+=array[i];
      else return 0;
    }
    return sum / (ma_period - j);
  break;
  
  case MODE_EMA:
    price = 0;
    double pr = 2.0/(ma_period+1);
    for(i = n-ma_period-1; i <= n-1-shift; i++) {
      if(i == n-ma_period-1) price = array[i];
      else {
        price = array[i]*pr+priceprec*(1-pr);
      }
      priceprec = price;
    }
    return price;
  break;
  
  case MODE_SMMA:
  
  break;
  
  case MODE_LWMA:
  
  break;
  }   
   
}
whroeder1
16071
whroeder1  
bertrand125: I try to compute MA to check if the fuction iMAOnArray gives the true result. I find the same result for SMA, but not for EMA, can someone check my code ?
    for(i = n-ma_period-1; i <= n-1-shift; i++) {
      if(i == n-ma_period-1) price = array[i];
      else {
        price = array[i]*pr+priceprec*(1-pr);
      }
      priceprec = price;
    }
  1. I assume your array is timeseries (a buffer,) so you need to loop from [n-1 .. shift] so your i <= n-1-shift means no loop. bogus
  2. There is no need to not use the first ma_period values.
  3. a[]*pr + prev*(1-pr) magnifies round off error. Use the form below which fades round off errors. Moving average - Wikipedia, the free encyclopedia
i = n - 1; price = array[i];
while(--i >= shift) price += ( array[i] - price )*pr;
bertrand
9
bertrand  
Thank you. Your code works, but i have to use ArraySetAsSeries(array,true). I will try to rewrite it in order to not use this function.
whroeder1
16071
whroeder1  
If you create your array with newer elements having higher indexes, you have to undo it with ASAS. Create your array with newest @ zero.
Cristiano Konrad
256
Cristiano Konrad  
.
To add comments, please log in or register