MACD Intersection Alert

Author: Copyright © 2021, Vladimir Karputov
Indicators Used
MACD Histogram
Miscellaneous
It plays sound alertsIt issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
MACD Intersection Alert
ÿþ//+------------------------------------------------------------------+

//|                                      MACD Intersection Alert.mq5 |

//|                              Copyright © 2021, Vladimir Karputov |

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

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

#property copyright "Copyright © 2021, Vladimir Karputov"

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

#property version   "1.000"

#property description "When the 'Main' and 'Signal' lines cross, the indicator signals ..."

#property indicator_separate_window

#property indicator_buffers 2

#property indicator_plots   2

//--- plot MACD_Last_!rossing

#property indicator_label1  "MACD"

#property indicator_type1   DRAW_HISTOGRAM

#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             "Alerts"

input string               InpSoundName            = "alert.wav";    // Sound Name

input uchar                InpSoundRepetitions     = 3;              // Repetitions

input uchar                InpSoundPause           = 3;              // Pause, in seconds

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

datetime m_last_sound            = 0;        // "0" -> D'1970.01.01 00:00';

uchar    m_repetitions           = 0;        //

string   m_text                  = "";       //

datetime m_prev_bars             = 0;        // "0" -> D'1970.01.01 00:00';

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

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

//--- we work only at the time of the birth of new bar

   datetime time_0=time[rates_total-1];

   if(time_0!=m_prev_bars)

     {

      m_last_sound   = 0;  // "0" -> D'1970.01.01 00:00';

      m_repetitions  = 0;  //

      m_text         = "";

      m_prev_bars    = time_0;

     }

//---

   int i=rates_total-1;

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

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

     {

      if(m_repetitions>=InpSoundRepetitions)

         return(rates_total);

      //---

      datetime time_current=TimeCurrent();

      if(time_current-m_last_sound>InpSoundPause)

        {

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

           {

            PlaySound(InpSoundName);

            Alert("MACD and Signal Intersection UP, ",TimeToString(time[i]));

            m_last_sound=time_current;

            m_repetitions++;

            return(rates_total);

           }

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

           {

            PlaySound(InpSoundName);

            Alert("MACD and Signal Intersection DOWN, ",TimeToString(time[i]));

            m_last_sound=time_current;

            m_repetitions++;

            return(rates_total);

           }

         //--- zero

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

           {

            PlaySound(InpSoundName);

            Alert("MACD and Zero Intersection UP, ",TimeToString(time[i]));

            m_last_sound=time_current;

            m_repetitions++;

            return(rates_total);

           }

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

           {

            PlaySound(InpSoundName);

            Alert("MACD and Zero Intersection DOWN, ",TimeToString(time[i]));

            m_last_sound=time_current;

            m_repetitions++;

            return(rates_total);

           }

        }

     }

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

   return(rates_total);

  }

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

//| Indicator deinitialization function                              |

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

void OnDeinit(const int reason)

  {

//---

  }

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

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