title: Writing an SMA custom indicator in MQL4 without iMA()
body: <p>As an exercise to learn <strong><code>MQL4</code></strong>, I'm writing a custom indicator which just replicates the Simple Moving Average, but without using the builtin <code>iMA()</code> function. The code below paints the indicator onto the chart, but every part of the line except the ending is showing extremely low values. For instance, on the <strong><code>AUD/CAD</code></strong> chart, which is usually, in 0.80-0.90 range, the SMA line is around 0.20-0.30.</p>
  
  <p>The line moves up and down in-sync with the price, and the very last bar seems to have an accurate reading ( as the SMA spikes towards the current price at that point ), but everything else is way low. I've exhausted every possible reason for why this may be happening, and nothing is changing it. Can somebody help me to figure out what is going wrong?</p>
  
  <pre><code>/*
     SELF-CODED 5-DAY SMA
     Set up buffer with style, indexbegin, and color
     for each bar:
         calculate closing price of last 4 bars and current price
         use to find SMA value at that bar
     update last value after every tick
     lock each bar's SMA value once the bar has close
  */
  #property strict
  #property indicator_chart_window
  #property indicator_buffers 1
  
  double buffer[];
  
  int OnInit() 
     {
     IndicatorBuffers(1);
     SetIndexBuffer(0, buffer);
     SetIndexStyle(0, DRAW_LINE);
  
     return(INIT_SUCCEEDED);
     }
  
  int OnCalculate( const int       rates_total,
                   const int       prev_calculated,
                   const datetime &amp;time[],
                   const double   &amp;open[],
                   const double   &amp;high[],
                   const double   &amp;low[],
                   const double   &amp;close[],
                   const long     &amp;tick_volume[],
                   const long     &amp;volume[],
                   const int      &amp;spread[]
                   )
     {
     int limit = rates_total - prev_calculated;
  
     buffer[0] = iClose(NULL, 0, 0); 
  
     for(int b = 1; b&lt;5; b++)
        {
        buffer[0] = buffer[0] + iClose(NULL, 0, b);
        }
     buffer[0] = buffer[0]/5;   
  
     for(int i = 1; i&lt;limit; i++)
        {
        buffer[i] = iClose(NULL, 0, i); // Placeholder in first for loop interation
        for(int a = 1; a&lt;4; a++) {
           {
           buffer[i] = buffer[i] + iClose(NULL, 0, i+a);
           }
        buffer[i] = buffer[i]/5.0;
        }
     }
  return(rates_total);   
  }
  </code></pre>