how do i call ema sma and other moving averages ?

 

i try to create my own macd but i dont know how to call the moving averages , how do i use those cidema , some sample codes would be appreciate.

 

ok now i got the moving average to work but it only appear 1 flat line. 


 

#property copyright "dk"
#property link      "http://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
//---- plot ma
#property indicator_label1  "ma"
#property indicator_type1   DRAW_LINE
#property indicator_color1  Red
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- input parameters
input int      ma1=20;
//--- indicator buffers
double         maBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,maBuffer,INDICATOR_DATA);
   PlotIndexSetString(ma1,PLOT_LABEL,"moving average");
   PlotIndexSetInteger(0,PLOT_LINE_STYLE,ma1,Red);
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[])
  {
//---

for (int i = 1; i < rates_total; i++)
{
maBuffer[i] = iMA(0,PERIOD_CURRENT,ma1,0,MODE_EMA,PRICE_CLOSE);
}

//--- return value of prev_calculated for next call
   return(rates_total);
  }
 
ddock:

ok now i got the moving average to work but it only appear 1 flat line. 


 

Try looking at the MetaQuotes MACD indicator code.  iMA returns a handle to the MA, not its value, see https://www.mql5.com/en/docs/indicators/ima - this is a complete change from the MQL4 approach.

Paul

http://paulsfxrandomwalk.blogspot.com/ 

Documentation on MQL5: Technical Indicators / iMA
  • www.mql5.com
Technical Indicators / iMA - Documentation on MQL5
 
ddock:

ok now i got the moving average to work but it only appear 1 flat line.

Here is your code that works (I have outlined some code modifications with bold font):

#property copyright "dk"
#property link      "http://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
//---- plot ma
#property indicator_label1  "ma"
#property indicator_type1   DRAW_LINE
#property indicator_color1  Red
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- input parameters
input int      ma1=20;
//--- indicator buffers
double         maBuffer[];
int            MAHandle;       // Handle of MA indicator
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,maBuffer,INDICATOR_DATA);
   PlotIndexSetString(ma1,PLOT_LABEL,"moving average");
   PlotIndexSetInteger(0,PLOT_LINE_STYLE,ma1,Red);
   MAHandle=iMA(NULL,0,ma1,0,MODE_EMA,PRICE_CLOSE);
//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[])
  {
//---

//---  Reset the value of the last error
   ResetLastError();
//--- Copy Moving average indicator data to our indictor buffer maBuffer []
   int copied=CopyBuffer(MAHandle,0,0,rates_total,maBuffer);
   if(copied<=0)
     {
      Print("Unable to copy the values Moving Average indicator. Error =",
            GetLastError(),",  copied =",copied);
      return(0);
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

1) The first you get the handle of an indicator in OnInit using the function iMA().

2) In OnCalculate you should copy the values to the indicator buffer using CopyBuffer with reference to the handle.

So the handle is the key, there are several ways to implement moving averages using iMA, IndicatorCreate, and iCustom.

 

Here is an example of Moving Averages (the notation of the input parameters is the same as Custom Moving Average.mq5)

//+------------------------------------------------------------------+
//|                                                   MA_Example.mq5 |
//|      A simple example of Moving Averages by 3 different methods: |
//|                              1)iMA, 2)IndicatorCreate, 3)iCustom |
//|                        Copyright 2010, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2010, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  Red
//--- enumeration for indicator call methods
enum ENUM_CallMethod
  {
   Method_1_iMA,                 // using iMA
   Method_2_IndicatorCreate,     // using IndicatorCreate with IND_MA
   Method_3_CustomMovingAverage  // using iCustom (Custom Moving Average.ex5)
  };

//--- input parameters
input int                InpMAPeriod=13;                 // Period
input int                InpMAShift=0;                   // Shift
input ENUM_MA_METHOD     InpMAMethod=MODE_SMA;           // Method
input ENUM_APPLIED_PRICE InpMAAppliedPrice=PRICE_CLOSE;  // Applied price
input ENUM_CallMethod    InpCallMethod=Method_1_iMA;     // Default method-can be changed manually in options

//--- indicator buffers
double         MABuffer[];     // Here we store the values of MA
int            MAHandle;       // Handle of MA indicator
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- indicator buffers mapping
   SetIndexBuffer(0,MABuffer,INDICATOR_DATA);
//--- set accuracy
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits+1);
//--- sets first bar from what index will be drawn
   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,InpMAPeriod);
//---- line shifts when drawing
   PlotIndexSetInteger(0,PLOT_SHIFT,InpMAShift);
//--- name for DataWindow
   string short_name="unknown ma";
   switch(InpMAMethod)
     {
      case MODE_SMA :  short_name="SMA";  break;
      case MODE_EMA :  short_name="EMA";  break;
      case MODE_SMMA : short_name="SMMA"; break;
      case MODE_LWMA : short_name="LWMA"; break;
     }
   IndicatorSetString(INDICATOR_SHORTNAME,short_name+"("+string(InpMAPeriod)+")");
//---- sets drawing line empty value--
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);
   string sMethod="";
   ResetLastError();

   switch(InpCallMethod)
     {
      case Method_1_iMA :
        {
         sMethod="1st method - built-in iMA:";
         //--- create MA
         //--- MA handle using built-in iMA
         MAHandle=iMA(Symbol(),Period(),InpMAPeriod,InpMAShift,InpMAMethod,InpMAAppliedPrice);
         break;
        }
      case Method_2_IndicatorCreate :
        {
         sMethod="2nd method - function IndicatorCreate with IND_MA:";
         MqlParam params[];
         ArrayResize(params,4);
         //--- set ma_period
         params[0].type         =TYPE_INT;
         params[0].integer_value=InpMAPeriod;
         //--- set ma_shift
         params[1].type         =TYPE_INT;
         params[1].integer_value=InpMAShift;
         //--- set ma_method
         params[2].type         =TYPE_INT;
         params[2].integer_value=InpMAMethod;
         //--- set applied_price
         params[3].type         =TYPE_INT;
         params[3].integer_value=InpMAAppliedPrice;
         //--- create MA
         //--- MA handle using IndicatorCreate
         MAHandle=IndicatorCreate(Symbol(),Period(),IND_MA,4,params);
         break;
        }

      case Method_3_CustomMovingAverage :
        {
         sMethod="3rd method - iCustom using Custom Moving Average.mq5:";
         //--- create MA
         //MA handle using iCustom
         MAHandle=iCustom(NULL,0,"Custom Moving Average",InpMAPeriod,InpMAShift,InpMAMethod,InpMAAppliedPrice);

         if(MAHandle<0)
           {
            Print("Custom Moving Average.ex5 not found there - trying to look it in Examples");
            MAHandle=iCustom(NULL,0,"Examples\Custom Moving Average",InpMAPeriod,InpMAShift,InpMAMethod,InpMAAppliedPrice);

            if(MAHandle<0)
              {
               Print("ERROR! not found in \Examples\ - if it exists please compile Custom Moving Average.mq5");
               return(-1); // terminate indicator because we haven't found compiled Custom Moving Average.ex5
              }
           }
         break;
        }
     }

   if(MAHandle<0)
     {
      Print(sMethod,"ERROR in indicator creation (IndicatorCreate). Error=",GetLastError());
      return(-1); // terminate indicator because we have problems with handle
     }
   else
     {
      Print(sMethod,"Indicator created, handle=",MAHandle);
     }

//---
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
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[])
  {

//---  Reset the value of the last error
   ResetLastError();
//--- Copy Moving average indicator data to our indictor buffer MABuffer []
   int copied=CopyBuffer(MAHandle,0,0,rates_total,MABuffer);
   if(copied<=0)
     {
      Print("Unable to copy the values Moving Average indicator. Error =",
            GetLastError(),",  copied =",copied);
      return(0);
     }
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+