Alert Crossing Two MA

Author: Copyright © 2021, Vladimir Karputov
Indicators Used
Moving average indicator
Miscellaneous
It plays sound alertsIt issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Alert Crossing Two MA
ÿþ//+------------------------------------------------------------------+

//|                                        Alert Crossing Two MA.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 indicator_chart_window

#property indicator_buffers 2

#property indicator_plots   0

//--- input parameters

input group             "MA Fast"

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

input int                  Inp_MA_Fast_ma_shift      = 0;            // MA Fast: horizontal shift

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 group             "MA Slow"

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

input int                  Inp_MA_Slow_ma_shift      = 0;            // MA Slow: horizontal shift

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

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

input uchar                InpSoundRepetitions        = 3;           // Repetitions

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

//--- indicator buffers

double   FastBuffer[];

double   SlowBuffer[];

//---

int      handle_iMA_Fast;                    // variable for storing the handle of the iMA indicator

int      handle_iMA_Slow;                    // variable for storing the handle of the iMA indicato

//---

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

bool     m_init_error               = false;    // error on InInit

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,FastBuffer,INDICATOR_CALCULATIONS);

   SetIndexBuffer(1,SlowBuffer,INDICATOR_CALCULATIONS);

//--- create handle of the indicator iMA

   handle_iMA_Fast=iMA(Symbol(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift,

                       Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price);

//--- if the handle is not created

   if(handle_iMA_Fast==INVALID_HANDLE)

     {

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

      PrintFormat("Failed to create handle of the iMA indicator ('Fast') for the symbol %s/%s, error code %d",

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early

      m_init_error=true;

      return(INIT_SUCCEEDED);

     }

//--- create handle of the indicator iMA

   handle_iMA_Slow=iMA(Symbol(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift,

                       Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price);

//--- if the handle is not created

   if(handle_iMA_Slow==INVALID_HANDLE)

     {

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

      PrintFormat("Failed to create handle of the iMA indicator ('Slow') for the symbol %s/%s, error code %d",

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early

      m_init_error=true;

      return(INIT_SUCCEEDED);

     }

//---

   int fast=Inp_MA_Fast_ma_period+Inp_MA_Fast_ma_shift;

   int slow=Inp_MA_Slow_ma_period+Inp_MA_Slow_ma_shift;

   start=(fast<slow)?fast:slow;

//---

   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(m_init_error)

      return(0);

   if(rates_total<start+1)

      return(0);

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

   int values_to_copy;

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

   int calculated_fast=BarsCalculated(handle_iMA_Fast);

   if(calculated_fast<=0)

     {

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

      return(0);

     }

   int calculated_slow=BarsCalculated(handle_iMA_Slow);

   if(calculated_slow<=0)

     {

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

      return(0);

     }

   if(calculated_fast!=calculated_slow)

     {

      PrintFormat("BarsCalculated(handle_iMA_Fast) returned %d, BarsCalculated(handle_iMA_Slow) returned %d",calculated_fast,calculated_slow);

      return(0);

     }

   int calculated=calculated_fast;

//--- if it is the first start of calculation of the indicator or if the number of values in the iMA 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 iMABuffer array is greater than the number of values in the iMA 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 FastBuffer array with values of the Moving Average indicator

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

   if(!FillArrayFromBuffer(FastBuffer,Inp_MA_Fast_ma_shift,handle_iMA_Fast,values_to_copy))

      return(0);

//--- fill the SlowBuffer array with values of the Moving Average indicator

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

   if(!FillArrayFromBuffer(SlowBuffer,Inp_MA_Slow_ma_shift,handle_iMA_Slow,values_to_copy))

      return(0);

//--- memorize the number of values in the Moving Average indicator

   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((FastBuffer[i-1]<SlowBuffer[i-1] && FastBuffer[i]>SlowBuffer[i]) || (FastBuffer[i-1]>SlowBuffer[i-1] && FastBuffer[i]<SlowBuffer[i]) ||

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

     {

      if(m_repetitions>=InpSoundRepetitions)

         return(rates_total);

      //---

      datetime time_current=TimeCurrent();

      if(time_current-m_last_sound>InpSoundPause)

        {

         if(FastBuffer[i-1]<SlowBuffer[i-1] && FastBuffer[i]>SlowBuffer[i])

           {

            PlaySound(InpSoundName);

            Alert("Fast and Slow Intersection UP, ",TimeToString(time[i]));

            m_last_sound=time_current;

            m_repetitions++;

            return(rates_total);

           }

         if(FastBuffer[i-1]>SlowBuffer[i-1] && FastBuffer[i]<SlowBuffer[i])

           {

            PlaySound(InpSoundName);

            Alert("Fast and Slow 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);

  }

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

//| Filling indicator buffers from the MA indicator                  |

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

bool FillArrayFromBuffer(double &values[],   // indicator buffer of Moving Average values

                         int shift,          // shift

                         int ind_handle,     // handle of the iMA indicator

                         int amount          // number of copied values

                        )

  {

//--- reset error code

   ResetLastError();

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

   if(CopyBuffer(ind_handle,0,-shift,amount,values)<0)

     {

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

      PrintFormat("Failed to copy data from the iMA 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);

  }

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

//| Indicator deinitialization function                              |

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

void OnDeinit(const int reason)

  {

   if(handle_iMA_Fast!=INVALID_HANDLE)

      IndicatorRelease(handle_iMA_Fast);

   if(handle_iMA_Slow!=INVALID_HANDLE)

      IndicatorRelease(handle_iMA_Slow);

  }

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

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