ATR Two TimeFrames

Author: Copyright © 2020, Vladimir Karputov
Indicators Used
Indicator of the average true range
1 Views
0 Downloads
0 Favorites
ATR Two TimeFrames
ÿþ//+------------------------------------------------------------------+

//|                                           ATR Two TimeFrames.mq5 |

//|                              Copyright © 2020, Vladimir Karputov |

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

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

#property copyright "Copyright © 2020, Vladimir Karputov"

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

#property version   "1.000"

#property indicator_separate_window

#property indicator_buffers 2

#property indicator_plots   2

//--- plot ATR

#property indicator_label1  "ATR"

#property indicator_type1   DRAW_LINE

#property indicator_color1  clrDeepSkyBlue

#property indicator_style1  STYLE_SOLID

#property indicator_width1  2

//--- plot ATR_

#property indicator_label2  "ATR_"

#property indicator_type2   DRAW_LINE

#property indicator_color2  clrBlue

#property indicator_style2  STYLE_SOLID

#property indicator_width2  2

//--- input parameters

input int               Inp_ATR_Current_ma_period  = 14;          // ATR Current: averaging period

input ENUM_TIMEFRAMES   Inp_ATR_Two_period         = PERIOD_D1;   // ATR Two: timeframe

input int               Inp_ATR_Two_ma_period      = 14;          // ATR Two: averaging period

//--- indicator buffers

double   ATRCurrentBuffer[];

double   ATRTwoBuffer[];

//---

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

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

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

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

   if(Inp_ATR_Two_period<Period())

      return(INIT_PARAMETERS_INCORRECT);

//--- indicator buffers mapping

   SetIndexBuffer(0,ATRCurrentBuffer,INDICATOR_DATA);

   SetIndexBuffer(1,ATRTwoBuffer,INDICATOR_DATA);

//--- set the display of the symbol

   PlotIndexSetString(1,PLOT_LABEL,"ATR,"+StringSubstr(EnumToString(Inp_ATR_Two_period),7));

//--- create handle of the indicator iATR

   handle_iATR=iATR(Symbol(),Period(),Inp_ATR_Current_ma_period);

//--- if the handle is not created

   if(handle_iATR==INVALID_HANDLE)

     {

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

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

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early

      return(INIT_FAILED);

     }

//--- create handle of the indicator iATR

   handle_iATR_Two=iATR(Symbol(),Inp_ATR_Two_period,Inp_ATR_Two_ma_period);

//--- if the handle is not created

   if(handle_iATR_Two==INVALID_HANDLE)

     {

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

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

                  Symbol(),

                  EnumToString(Inp_ATR_Two_period),

                  GetLastError());

      //--- the indicator is stopped early

      return(INIT_FAILED);

     }

//---

   int bar_shift        = iBarShift(Symbol(),Inp_ATR_Two_period,TimeCurrent(),false);

   datetime time_two_0  = iTime(Symbol(),Inp_ATR_Two_period,0);

//---

   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[])

  {

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

   int values_to_copy;

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

   int calculated=BarsCalculated(handle_iATR);

   if(calculated<=0)

     {

      PrintFormat("BarsCalculated(ATR Current) returned %d, error code %d",calculated,GetLastError());

      return(0);

     }

   int calculated_two=BarsCalculated(handle_iATR_Two);

   if(calculated_two<=0)

     {

      PrintFormat("BarsCalculated(ATR Two) returned %d, error code %d",calculated_two,GetLastError());

      return(0);

     }

//--- 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(ATRCurrentBuffer,handle_iATR,values_to_copy))

      return(0);

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

   bars_calculated=calculated;

//--- main loop

   if(Inp_ATR_Two_period>Period())

     {

      int limit=prev_calculated-1;

      if(prev_calculated==0)

         limit=0;

      for(int i=limit; i<rates_total; i++)

        {

         int bar_shift        = iBarShift(Symbol(),Inp_ATR_Two_period,time[i],false);

         if(bar_shift<0)

            return(0);

         datetime time_two    = iTime(Symbol(),Inp_ATR_Two_period,bar_shift);

         double atr_two[];

         if(!iGetArray(handle_iATR_Two,0,time_two,1,atr_two))

            return(0);

         ATRTwoBuffer[i]=atr_two[0];

        }

     }

   if(Inp_ATR_Two_period==Period())

     {

      //--- 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(ATRTwoBuffer,handle_iATR_Two,values_to_copy))

         return(0);

     }

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

  }

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

//| Get value of buffers                                             |

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

bool iGetArray(const int handle,const int buffer,const datetime start_time,

               const int count,double &arr_buffer[])

  {

   bool result=true;

   if(!ArrayIsDynamic(arr_buffer))

     {

      PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);

      return(false);

     }

   ArrayFree(arr_buffer);

//--- reset error code

   ResetLastError();

//--- fill a part of the iBands array with values from the indicator buffer

   int copied=CopyBuffer(handle,buffer,start_time,count,arr_buffer);

   if(copied!=count)

     {

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

      PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",

                  __FILE__,__FUNCTION__,count,copied,GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated

      return(false);

     }

   return(result);

  }

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

//| Indicator deinitialization function                              |

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

void OnDeinit(const int reason)

  {

   if(handle_iATR!=INVALID_HANDLE)

      IndicatorRelease(handle_iATR);

   if(handle_iATR_Two!=INVALID_HANDLE)

      IndicatorRelease(handle_iATR_Two);

  }

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



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

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