Checking myself on MAs

 

I've been looking at the Custom Moving Average.mq5 code that is in the Indicators\Examples folder.

My understanding of the calculation of a simple moving average is as follows:

Simple Moving Average (SMA): This is the most common type. The formula for calculating an SMA is:
SMA = (X1 + X2 + X3 + ... + Xn) / N
Where:

X1, X2, X3, ..., Xn are the data points you want to average (e.g., closing prices)

N is the number of data points to include in the average

Let's say the MA period = 5. That means go 5 bars back, sum the values of those 5 bars plus the current bar and divide by the MA period plus 1, doesn't it? So the divisor would be 6. Am I wrong?

This code from the CalculateSimpleMA function in Custom Moving Average.mq5isn't what I expected.

Is the line repeatedly executed in the for loop below actually the equivalent of the formula  above? Previous bar price + (current price + the price MA-period bars back) /  MA-period?

//--- main loop
   for(i=start; i<rates_total && !IsStopped(); i++)
      ExtLineBuffer[i]=ExtLineBuffer[i-1]+(price[i]-price[i-InpMAPeriod])/InpMAPeriod;
  }
 

Look at MovingAverages.mqh in the Include directory.


I think the code in MovingAverages.mqh is easier to understand than the code you showed

//+------------------------------------------------------------------+
//| Simple Moving Average                                            |
//+------------------------------------------------------------------+
double SimpleMA(const int position,const int period,const double &price[])
  {
   double result=0.0;
//--- check period
   if(period>0 && period<=(position+1))
     {
      for(int i=0; i<period; i++)
         result+=price[position-i];

      result/=period;
     }

   return(result);
  }
 
Vladislav Boyko #: I think the code in MovingAverages.mqh is easier to understand than the code you showed

Or Sum multiple elements of a large array - MQL4 programming forum #2.2 (2023)

 
No answers to my question yet, but I guess that's OK. I overlaid the stock Moving Average indicator from the menu with the Custom Moving Average indicator from the Examples folder and, yup, they match perfectly. So, I have the answer to my question. I'll have to ask my son the mathematician to explain why it works.