MACD Intersection Main and Signal

Author: Copyright © 2020, Vladimir Karputov
Indicators Used
MACD Histogram
0 Views
0 Downloads
0 Favorites
MACD Intersection Main and Signal
ÿþ//+------------------------------------------------------------------+

//|                            MACD Intersection Main and Signal.mq5 |

//|                              Copyright © 2020, Vladimir Karputov |

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

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

#property copyright "Copyright © 2020, Vladimir Karputov"

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

#property version   "1.001"

#property description "When the 'Main' and 'Signal' lines cross, the indicator draws a vertical line"

#property indicator_separate_window

#property indicator_buffers 2

#property indicator_plots   2

//--- plot MACD_Last_!rossing

#property indicator_label1  "MACD"

#property indicator_type1   DRAW_LINE

#property indicator_color1  clrSilver

#property indicator_style1  STYLE_SOLID

#property indicator_width1  2

#property indicator_label2  "Signal"

#property indicator_type2   DRAW_LINE

#property indicator_color2  clrRed

#property indicator_style2  STYLE_DASH

#property indicator_width2  2

//--- input parameters

input group             "MACD"

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             "VLine"

input string               InpPrefix               = "MACD Vline ";  // VLines: prefix

input color                InpColor                = clrBlue;        // VLines: color

input ENUM_LINE_STYLE      InpStyle                = STYLE_SOLID;    // VLines: style

input int                  InpWidth                = 2;              // VLines: width

input bool                 InpBack                 = false;          // VLines: Background line

input bool                 InpSelection            = false;          // VLines: Highlight to move

input bool                 InpRay                  = true;           // VLines: Line's continuation down

input bool                 InpHidden               = true;           // VLines: Hidden in the object list

input long                 InpZOrder               = 0;              // VLines: Priority for mouse click

input bool                 InpDescription          = true;           // VLines: Description

//--- indicator buffers

double   MACDBuffer[];

double   SignalBuffer[];

//---

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;

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

   ObjectsDeleteAll(ChartID(),InpPrefix,0,OBJ_VLINE);

//--- indicator buffers mapping

   SetIndexBuffer(0,MACDBuffer,INDICATOR_DATA);

   SetIndexBuffer(1,SignalBuffer,INDICATOR_DATA);

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

      return(INIT_FAILED);

     }

   start=Inp_MACD_fast_ema_period+Inp_MACD_slow_ema_period+Inp_MACD_signal_period;

//---

   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);

//--- 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(MACDBuffer,SignalBuffer,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++)

     {

      if((MACDBuffer[i-1]<SignalBuffer[i-1] && MACDBuffer[i]>SignalBuffer[i]) || (MACDBuffer[i-1]>SignalBuffer[i-1] && MACDBuffer[i]<SignalBuffer[i]))

        {

         string time_to_string=TimeToString(time[i],TIME_DATE|TIME_MINUTES);

         string vline_name=InpPrefix+time_to_string;

         long chart_id=ChartID();

         if(ObjectFind(chart_id,vline_name)<0)

            VLineCreate(chart_id,vline_name,0,time[i],InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRay,InpHidden,InpZOrder,

                        (InpDescription)?vline_name:"");

        }

     }

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

   return(rates_total);

  }

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

//| Indicator deinitialization function                              |

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

void OnDeinit(const int reason)

  {

   ObjectsDeleteAll(ChartID(),InpPrefix,0,OBJ_VLINE);

  }

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

//| 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);

  }

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

//| Create the vertical line                                         |

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

bool VLineCreate(const long            chart_ID=0,        // chart's ID

                 const string          name="VLine",      // line name

                 const int             sub_window=0,      // subwindow index

                 datetime              time=0,            // line time

                 const color           clr=clrRed,        // line color

                 const ENUM_LINE_STYLE style=STYLE_SOLID, // line style

                 const int             width=1,           // line width

                 const bool            back=false,        // in the background

                 const bool            selection=true,    // highlight to move

                 const bool            ray=true,          // line's continuation down

                 const bool            hidden=true,       // hidden in the object list

                 const long            z_order=0,         // priority for mouse click

                 const string          text="")           // test

  {

//--- if the line time is not set, draw it via the last bar

   if(!time)

      time=TimeCurrent();

//--- reset the error value

   ResetLastError();

//--- create a vertical line

   if(!ObjectCreate(chart_ID,name,OBJ_VLINE,sub_window,time,0))

     {

      Print(__FUNCTION__,

            ": failed to create a vertical line! Error code = ",GetLastError());

      return(false);

     }

//--- set line color

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- set line display style

   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);

//--- set line width

   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);

//--- display in the foreground (false) or background (true)

   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);

//--- enable (true) or disable (false) the mode of moving the line by mouse

//--- when creating a graphical object using ObjectCreate function, the object cannot be

//--- highlighted and moved by default. Inside this method, selection parameter

//--- is true by default making it possible to highlight and move the object

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);

//--- enable (true) or disable (false) the mode of displaying the line in the chart subwindows

   ObjectSetInteger(chart_ID,name,OBJPROP_RAY,ray);

//--- hide (true) or display (false) graphical object name in the object list

   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);

//--- set the priority for receiving the event of a mouse click in the chart

   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);

   if(text!="")

     {

      //--- set description of the object

      ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);

     }

//--- successful execution

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