ATR Dual Alert

Author: Copyright © 2022, Vladimir Karputov
Price Data Components
Indicators Used
Indicator of the average true range
Miscellaneous
It issuies visual alerts to the screenIt plays sound alertsIt sends emails
0 Views
0 Downloads
0 Favorites
ATR Dual Alert
ÿþ//+------------------------------------------------------------------+

//|                                               ATR Dual Alert.mq5 |

//|                              Copyright © 2022, Vladimir Karputov |

//|                      https://www.mql5.com/en/users/barabashkakvn |

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

#property copyright "Copyright © 2022, Vladimir Karputov"

#property link      "https://www.mql5.com/en/users/barabashkakvn"

#property version   "1.000"

#property indicator_separate_window

#property indicator_buffers 2

#property indicator_plots   2

//--- plot ATR Master

#property indicator_label1  "ATR Master"

#property indicator_type1   DRAW_LINE

#property indicator_style1  STYLE_DOT

#property indicator_color1  clrDarkTurquoise

#property indicator_width1  1

//--- plot ATR Slave

#property indicator_label2  "ATR Slave"

#property indicator_type2   DRAW_HISTOGRAM

#property indicator_style2  STYLE_SOLID

#property indicator_color2  clrDarkOrange

#property indicator_width2  2

//--- input parameters

input group             "ATR Dual"

input int                  Inp_ATR_Master_ma_period   = 14;          // ATR "Master" averaging period

input int                  Inp_ATR_Slave_ma_period    = 1;           // ATR "Slave" averaging period

input group             "Alerts"

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

input uchar                InpSoundRepetitions        = 3;           // Repetitions

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

input bool                 InpAlert                   = true;        // Alert

input bool                 InpMail                    = true;        // Send mail

input bool                 InpNotification            = true;        // Send notification

//--- indicator buffers

double   ATR_Master_Buffer[];

double   ATR_Slave_Buffer[];

//---

int      handle_iATR_Master;           // variable for storing the handle of the iATR indicator

int      handle_iATR_Slave;            // variable for storing the handle of the iATR indicator

int      m_start;

int      bars_calculated   = 0;        // we will keep the number of values in the Average True Range indicator

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,ATR_Master_Buffer,INDICATOR_DATA);

   SetIndexBuffer(1,ATR_Slave_Buffer,INDICATOR_DATA);

//--- set the accuracy of values to be displayed in the Data Window

   IndicatorSetInteger(INDICATOR_DIGITS,Digits());

   if(Inp_ATR_Master_ma_period<=0 && Inp_ATR_Slave_ma_period<=0)

     {

      string err_text=(TerminalInfoString(TERMINAL_LANGUAGE)=="Russian")?

                      "Parameter '... averaging period' cannot be <= '0'!":

                      "0@0<5B@ '... averaging period' =5 <>65B 1KBL <= '0'!";

      if(MQLInfoInteger(MQL_TESTER)) // when testing, we will only output to the log about incorrect input parameters

         Print(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

      else // if the Expert Advisor is run on the chart, tell the user about the error

         Alert(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

      //---

      m_init_error=true;

      return(INIT_SUCCEEDED);

     }

   if(Inp_ATR_Master_ma_period<=Inp_ATR_Slave_ma_period)

     {

      string err_text=(TerminalInfoString(TERMINAL_LANGUAGE)=="Russian")?

                      "'Master averaging period' cannot be <= 'Slave averaging period'!":

                      "'Master averaging period' =5 <>65B 1KBL <= 'Slave averaging period'!";

      if(MQLInfoInteger(MQL_TESTER)) // when testing, we will only output to the log about incorrect input parameters

         Print(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

      else // if the Expert Advisor is run on the chart, tell the user about the error

         Alert(__FILE__," ",__FUNCTION__,", ERROR: ",err_text);

      //---

      m_init_error=true;

      return(INIT_SUCCEEDED);

     }

//--- sets first bar from what index will be drawn

   m_start=(Inp_ATR_Master_ma_period>Inp_ATR_Slave_ma_period)?Inp_ATR_Master_ma_period:Inp_ATR_Slave_ma_period;

   PlotIndexSetInteger(0,PLOT_DRAW_BEGIN,m_start);

//--- create handle of the indicator iATR

   handle_iATR_Master=iATR(Symbol(),Period(),Inp_ATR_Master_ma_period);

//--- if the handle is not created

   if(handle_iATR_Master==INVALID_HANDLE)

     {

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

      PrintFormat("Failed to create handle of the iATR indicator (\"Master\") 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 iATR

   handle_iATR_Slave=iATR(Symbol(),Period(),Inp_ATR_Slave_ma_period);

//--- if the handle is not created

   if(handle_iATR_Slave==INVALID_HANDLE)

     {

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

      PrintFormat("Failed to create handle of the iATR indicator (\"Slave\") for the symbol %s/%s, error code %d",

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early

      m_init_error=true;

      return(INIT_SUCCEEDED);

     }

//--- show the symbol/timeframe the Average True Range indicator is calculated_master for

   string short_name=StringFormat("ATR Dual Alert(%d,%d)",Inp_ATR_Master_ma_period,Inp_ATR_Slave_ma_period);

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

      return(0);

//---

   if(rates_total<m_start+1)

      return(0);

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

   int values_to_copy;

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

   int calculated_master=BarsCalculated(handle_iATR_Master);

   if(calculated_master<=0)

     {

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

      return(0);

     }

   int calculated_slave=BarsCalculated(handle_iATR_Slave);

   if(calculated_slave<=0)

     {

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

      return(0);

     }

   if(calculated_master!=calculated_slave)

     {

      PrintFormat("BarsCalculated(Master) returned %d, BarsCalculated(Slave) returned %d",calculated_master,calculated_slave);

      return(0);

     }

   int calculated=calculated_master;

//--- if it is the first start of calculation of the indicator or if the number of values in the iATR 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 iATRBuffer array is greater than the number of values in the iATR 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 iATRBuffer array with values of the Average True Range indicator

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

   if(!FillArrayFromBuffer(ATR_Master_Buffer,handle_iATR_Master,values_to_copy))

      return(0);

   if(!FillArrayFromBuffer(ATR_Slave_Buffer,handle_iATR_Slave,values_to_copy))

      return(0);

//--- memorize the number of values in the Average True Range indicator

   bars_calculated=calculated;

//--- alert

   if(time[rates_total-1]>m_prev_bars)

     {

      m_last_sound=0;

      m_prev_bars=time[rates_total-1];

      m_repetitions=0;

     }

   if(m_repetitions>=InpSoundRepetitions)

      return(rates_total);

   datetime time_current=TimeCurrent();

   if(time_current-m_last_sound>InpSoundPause)

     {

      int i=rates_total-1;

      if(ATR_Slave_Buffer[i-1]<ATR_Master_Buffer[i-1] && ATR_Slave_Buffer[i]>ATR_Master_Buffer[i])

        {

         PlaySound(InpSoundName);

         m_text=Symbol()+","+StringSubstr(EnumToString(Period()),7,-1)+" ATR Dual Alert, "+TimeToString(time[i]);

         if(InpAlert)

            Alert(m_text);

         m_last_sound=time_current;

         m_repetitions++;

         //---

         if(InpMail)

           {

            SendMail(Symbol()+","+StringSubstr(EnumToString(Period()),7,-1),m_text);

           }

         if(InpNotification)

           {

            SendNotification(Symbol()+","+StringSubstr(EnumToString(Period()),7,-1)+" "+m_text);

           }

        }

     }

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

   return(rates_total);

  }

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

//| Filling indicator buffers from the iATR indicator                |

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

bool FillArrayFromBuffer(double &values[],  // indicator buffer for ATR values

                         int ind_handle,    // handle of the iATR indicator

                         int amount         // number of copied values

                        )

  {

//--- reset error code

   ResetLastError();

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

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

     {

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

      PrintFormat("Failed to copy data from the iATR 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_iATR_Master!=INVALID_HANDLE)

      IndicatorRelease(handle_iATR_Master);

   if(handle_iATR_Slave!=INVALID_HANDLE)

      IndicatorRelease(handle_iATR_Slave);

  }

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

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