MACD Intersection Chart

Author: Copyright © 2021, Vladimir Karputov
Indicators Used
MACD Histogram
0 Views
0 Downloads
0 Favorites
MACD Intersection Chart
ÿþ//+------------------------------------------------------------------+

//|                                      MACD Intersection Chart.mq5 |

//|                              Copyright © 2021, Vladimir Karputov |

//|                     https://www.mql5.com/ru/market/product/43516 |

//+------------------------------------------------------------------+

#property copyright "Copyright © 2021, Vladimir Karputov"

#property link      "https://www.mql5.com/ru/market/product/43516"

#property version   "1.000"

#property description "When the 'Main' and 'Signal' lines cross, the indicator draws an Arrow"

#property description "When the 'Main' line cross zero, the indicator draws an Arrow."

#property indicator_chart_window

#property indicator_buffers 6

#property indicator_plots   4

//+------------------------------------------------------------------+

//| Enum MACD                                                        |

//+------------------------------------------------------------------+

enum ENUM_MACD

  {

   macd=0,     // MACD Original

   custom=1,   // MACD Custom Averaging

  };

//--- plot Main and Signal Buy

#property indicator_label1  "Main and Signal Buy"

#property indicator_type1   DRAW_ARROW

#property indicator_color1  clrBlue

#property indicator_style1  STYLE_SOLID

#property indicator_width1  1

//--- plot Main and Signal Sell

#property indicator_label2  "Main and Signal Sell"

#property indicator_type2   DRAW_ARROW

#property indicator_color2  clrRed

#property indicator_style2  STYLE_SOLID

#property indicator_width2  1

//--- plot Main cross zero Buy

#property indicator_label3  "Main cross zero Buy"

#property indicator_type3   DRAW_ARROW

#property indicator_color3  C'175,175,255'

#property indicator_style3  STYLE_DASH

#property indicator_width3  1

//--- plot Main cross zero Sell

#property indicator_label4  "Main cross zero Sell"

#property indicator_type4   DRAW_ARROW

#property indicator_color4  C'255,175,175'

#property indicator_style4  STYLE_DASH

#property indicator_width4  1

//--- input parameters

input ENUM_MACD            InpMACD                    = macd;           // MACD type:

input group             "MACD Original"

input int                  Inp_MACD_fast_ema_period   = 12;             // MACD: period for Fast average calculation

input int                  Inp_MACD_slow_ema_period   = 26;             // MACD: period for Slow average calculation

input int                  Inp_MACD_signal_period     = 9;              // MACD: period for their difference averaging

input ENUM_APPLIED_PRICE   Inp_MACD_applied_price     = PRICE_CLOSE;    // MACD: type of price

input group             "MACD Custom Averaging"

input int                  Inp_MA_Fast_ma_period      = 12;             // MA Fast: averaging period

input ENUM_MA_METHOD       Inp_MA_Fast_ma_method      = MODE_SMA;       // MA Fast: smoothing type

input ENUM_APPLIED_PRICE   Inp_MA_Fast_applied_price  = PRICE_CLOSE;    // MA Fast: type of price

input int                  Inp_MA_Slow_ma_period      = 26;             // MA Slow: averaging period

input ENUM_MA_METHOD       Inp_MA_Slow_ma_method      = MODE_SMA;       // MA Slow: smoothing type

input ENUM_APPLIED_PRICE   Inp_MA_Slow_applied_price  = PRICE_CLOSE;    // MA Slow: type of price

input int                  InpSignalSMA               = 9;              // Signal SMA period

input group             "Arrow"

input uchar                InpCode                    = 159;            // Arrow code (font Wingdings)

input int                  InpShift                   = 10;             // Vertical shift of arrows in pixels

//--- indicator buffers

double   MainSignalBuyBuffer[];

double   MainSignalSellBuffer[];

double   MainZeroBuyBuffer[];

double   MainZeroSellBuffer[];

double   iMACDBuffer[];

double   iSignalBuffer[];

//---

int      handle_iMACD;                       // variable for storing the handle of the iMACD indicator

int      bars_calculated   = 0;              // we will keep the number of values in the Moving Averages Convergence/Divergence indicator

int      start             = 0;

bool     m_init_error      = false;          // error on InInit

//+------------------------------------------------------------------+

//| Custom indicator initialization function                         |

//+------------------------------------------------------------------+

int OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,MainSignalBuyBuffer,INDICATOR_DATA);

   SetIndexBuffer(1,MainSignalSellBuffer,INDICATOR_DATA);

   SetIndexBuffer(2,MainZeroBuyBuffer,INDICATOR_DATA);

   SetIndexBuffer(3,MainZeroSellBuffer,INDICATOR_DATA);

   SetIndexBuffer(4,iMACDBuffer,INDICATOR_CALCULATIONS);

   SetIndexBuffer(5,iSignalBuffer,INDICATOR_CALCULATIONS);

//--- setting a code from the Wingdings charset as the property of PLOT_ARROW

   PlotIndexSetInteger(0,PLOT_ARROW,InpCode);

   PlotIndexSetInteger(1,PLOT_ARROW,InpCode);

   PlotIndexSetInteger(2,PLOT_ARROW,InpCode);

   PlotIndexSetInteger(3,PLOT_ARROW,InpCode);

//--- set the vertical shift of arrows in pixels

   PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,InpShift);

   PlotIndexSetInteger(1,PLOT_ARROW_SHIFT,-InpShift);

   PlotIndexSetInteger(2,PLOT_ARROW_SHIFT,InpShift);

   PlotIndexSetInteger(3,PLOT_ARROW_SHIFT,-InpShift);

//--- set as an empty value 0.0

   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);

   PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0.0);

   PlotIndexSetDouble(2,PLOT_EMPTY_VALUE,0.0);

   PlotIndexSetDouble(3,PLOT_EMPTY_VALUE,0.0);

   string macd_type="unknown type";

   if(InpMACD==macd)

     {

      //--- create handle of the indicator iMACD

      handle_iMACD=iMACD(Symbol(),Period(),Inp_MACD_fast_ema_period,Inp_MACD_slow_ema_period,

                         Inp_MACD_signal_period,Inp_MACD_applied_price);

      //--- if the handle is not created

      if(handle_iMACD==INVALID_HANDLE)

        {

         //--- tell about the failure and output the error code

         PrintFormat("Failed to create handle of the iMACD indicator for the symbol %s/%s, error code %d",

                     Symbol(),

                     EnumToString(Period()),

                     GetLastError());

         //--- the indicator is stopped early

         m_init_error=true;

        }

      macd_type="MACD Original";

     }

   else

     {

      //--- create handle of the indicator iCustom

      handle_iMACD=iCustom(Symbol(),Period(),"MACD Custom Averaging",

                           "MA Fast",

                           Inp_MA_Fast_ma_period,

                           Inp_MA_Fast_ma_method,

                           Inp_MA_Fast_applied_price,

                           "MA Slow",

                           Inp_MA_Slow_ma_period,

                           Inp_MA_Slow_ma_method,

                           Inp_MA_Slow_applied_price,

                           "MACD",

                           InpSignalSMA);

      //--- if the handle is not created

      if(handle_iMACD==INVALID_HANDLE)

        {

         //--- tell about the failure and output the error code

         PrintFormat("Failed to create handle of the iCustom indicator for the symbol %s/%s, error code %d",

                     Symbol(),

                     EnumToString(Period()),

                     GetLastError());

         //--- the indicator is stopped early

         m_init_error=true;

         return(INIT_SUCCEEDED);

        }

      macd_type="MACD Custom Averaging";

     }

   start=Inp_MACD_fast_ema_period+Inp_MACD_slow_ema_period+Inp_MACD_signal_period;

//--- show the symbol/timeframe the Moving Average Convergence/Divergence indicator is calculated for

   string short_name=StringFormat("%s(%d,%d,%d,%s)",macd_type,Inp_MACD_fast_ema_period,

                                  Inp_MACD_slow_ema_period,Inp_MACD_signal_period,EnumToString(Inp_MACD_applied_price));

   IndicatorSetString(INDICATOR_SHORTNAME,short_name);

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| 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[])

  {

   if(rates_total<start)

      return(0);

   if(m_init_error)

      return(0);

//--- number of values copied from the iMACD indicator

   int values_to_copy;

//--- determine the number of values calculated in the indicator

   int calculated=BarsCalculated(handle_iMACD);

   if(calculated<=0)

     {

      PrintFormat("BarsCalculated() returned %d, error code %d",calculated,GetLastError());

      return(0);

     }

//--- if it is the first start of calculation of the indicator or if the number of values in the iMACD indicator changed

//---or if it is necessary to calculated the indicator for two or more bars (it means something has changed in the price history)

   if(prev_calculated==0 || calculated!=bars_calculated || rates_total>prev_calculated+1)

     {

      //--- if the MACDBuffer array is greater than the number of values in the iMACD indicator for symbol/period, then we don't copy everything

      //--- otherwise, we copy less than the size of indicator buffers

      if(calculated>rates_total)

         values_to_copy=rates_total;

      else

         values_to_copy=calculated;

     }

   else

     {

      //--- it means that it's not the first time of the indicator calculation, and since the last call of OnCalculate()

      //--- for calculation not more than one bar is added

      values_to_copy=(rates_total-prev_calculated)+1;

     }

//--- fill the arrays with values of the iMACD indicator

//--- if FillArraysFromBuffer returns false, it means the information is nor ready yet, quit operation

   if(!FillArraysFromBuffers(iMACDBuffer,iSignalBuffer,handle_iMACD,values_to_copy))

      return(0);

//--- memorize the number of values in the Moving Averages indicator Convergence/Divergence

   bars_calculated=calculated;

//--- main loop

   int limit=prev_calculated-1;

   if(prev_calculated==0)

      limit=start;

   for(int i=limit; i<rates_total-1; i++)

     {

      MainSignalBuyBuffer[i]=0.0;

      MainSignalSellBuffer[i]=0.0;

      MainZeroBuyBuffer[i]=0.0;

      MainZeroSellBuffer[i]=0.0;

      //---

      if(iMACDBuffer[i-1]<iSignalBuffer[i-1] && iMACDBuffer[i]>iSignalBuffer[i])

        {

         if(iMACDBuffer[i-1]<0.0 && iSignalBuffer[i-1]<0.0 && iMACDBuffer[i]<0.0 && iSignalBuffer[i]<0.0)

            MainSignalBuyBuffer[i]=low[i];

         continue;

        }

      else

        {

         if(iMACDBuffer[i-1]>iSignalBuffer[i-1] && iMACDBuffer[i]<iSignalBuffer[i])

           {

            if(iMACDBuffer[i-1]>0.0 && iSignalBuffer[i-1]>0.0 && iMACDBuffer[i]>0.0 && iSignalBuffer[i]>0.0)

               MainSignalSellBuffer[i]=high[i];

            continue;

           }

        }

      //---

      if(iMACDBuffer[i-1]<0.0 && iMACDBuffer[i]>0.0)

        {

         MainZeroBuyBuffer[i]=low[i];

         continue;

        }

      else

        {

         if(iMACDBuffer[i-1]>0.0 && iMACDBuffer[i]<0.0)

           {

            MainZeroSellBuffer[i]=high[i];

            continue;

           }

        }

     }

//--- return value of prev_calculated for next call

   return(rates_total);

  }

//+------------------------------------------------------------------+

//| Filling indicator buffers from the iMACD indicator               |

//+------------------------------------------------------------------+

bool FillArraysFromBuffers(double &macd_buffer[],    // indicator buffer of MACD values

                           double &signal_buffer[],  // indicator buffer of the signal line of MACD

                           int ind_handle,           // handle of the iMACD indicator

                           int amount                // number of copied values

                          )

  {

//--- reset error code

   ResetLastError();

//--- fill a part of the iMACDBuffer array with values from the indicator buffer that has 0 index

   if(CopyBuffer(ind_handle,0,0,amount,macd_buffer)<0)

     {

      //--- if the copying fails, tell the error code

      PrintFormat("Failed to copy data from the iMACD indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated

      return(false);

     }

//--- fill a part of the SignalBuffer array with values from the indicator buffer that has index 1

   if(CopyBuffer(ind_handle,1,0,amount,signal_buffer)<0)

     {

      //--- if the copying fails, tell the error code

      PrintFormat("Failed to copy data from the iMACD indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated

      return(false);

     }

//--- everything is fine

   return(true);

  }

//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---