MACD Intersection Chart

Download script
Author: Copyright © 2021, Vladimir Karputov

This script is designed to function as a visual trading tool for the MetaTrader 5 platform. It simplifies technical analysis by automatically identifying and marking specific trend shifts on your chart using arrows, rather than requiring you to constantly monitor complex moving averages manually.

Core Functionality

The primary purpose of this tool is to detect "crossovers" and "zero-line breaks" within the MACD (Moving Average Convergence Divergence) indicator. It translates these mathematical movements into clear visual signals:

  • Trend Crosses: The script monitors the interaction between the "Main" line and the "Signal" line of the MACD. When these two lines cross each other, the script identifies a potential shift in momentum.
  • Zero-Line Breaks: The script also tracks when the "Main" line crosses the center zero mark, which often signifies a change from bearish to bullish sentiment (or vice versa).

Visual Signals

Instead of cluttering your screen with extra lines or windows, the script places specific symbols (arrows) directly on the price chart:

  1. Buy Signals: Represented by Blue arrows. These appear when the Main and Signal lines cross in an upward direction while remaining below the zero line, or when the Main line crosses from below to above the zero mark.
  2. Sell Signals: Represented by Red arrows. These appear when the Main and Signal lines cross in a downward direction while remaining above the zero line, or when the Main line crosses from above to below the zero mark.

Customization Options

The script is highly flexible, allowing you to choose between two different calculation styles:

  • MACD Original: Uses standard moving average calculations.
  • MACD Custom Averaging: Allows for more specialized smoothing of the data using different moving average types and periods.

Key Technical Features

  • Dynamic Updates: The script is designed to update in real-time as new price data arrives, ensuring the arrows appear as soon as a condition is met.
  • Adjustable Sensitivity: Users can modify the "Fast," "Slow," and "Signal" periods to make the indicator more responsive to quick price changes or more stable by ignoring minor fluctuations.
  • Visual Offsets: There is an option to shift the arrows vertically so they do not overlap with the actual price candles, keeping your chart clean and readable.

In summary, this tool acts as a "translator" that watches the complex math of the MACD indicator for you and highlights the most important momentum shifts with simple colored arrows on your trading screen.

Indicators Used
MACD Histogram
12 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