Writing an SMA indicator from scratch

Back to topics list To post a new topic, please log in or register
avatar
2
grafs50 2016.07.27 19:43
 
/*
   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 &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])   
   {
   int limit = rates_total - prev_calculated;
   
   buffer[0] = iClose(NULL, 0, 0); //Placeholder: the current SMA value is updated on each tick
   
   for(int b = 1; b<5; b++)
      {
      buffer[0] = buffer[0] + iClose(NULL, 0, b);
      }
   buffer[0] = buffer[0]/5;   
   
   for(int i = 1; i<limit; i++)
      {
      buffer[i] = iClose(NULL, 0, i); //Placeholder in first for loop interation

      for(int a = 1; a<4; a++) {
         {
         buffer[i] = buffer[i] + iClose(NULL, 0, i+a);
         }       
       buffer[i] = buffer[i]/5.0;
       
       }
   }

return(rates_total);   
}

As an exercise to learn MQL4, I'm writing a custom indicator which just replicates the Simple Moving Average, but without using the builtin iMA() 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 AUD/CAD chart, which is usually, 0.80-0.90, the SMA line is around 0.20-0.30.

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 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?

 

 

avatar
Moderator
3404
GumRai 2016.07.28 10:58 #
 
   for(int i = 1; i<limit; i++)
      {
      buffer[i] = iClose(NULL, 0, i); //Placeholder in first for loop interation

      for(int a = 1; a<4; a++) {
         {
         buffer[i] = buffer[i] + iClose(NULL, 0, i+a);
         }       
       buffer[i] = buffer[i]/5.0;
       
       }

your for loop will only have 3 iterations. This means that you are adding 4 values and then dividing by 5


Back to topics list  

To add comments, please log in or register