Time interval

Author: Copyright © 2021, Vladimir Karputov
Miscellaneous
It issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites
Time interval
ÿþ//+------------------------------------------------------------------+

//|                                                Time interval.mq5 |

//|                              Copyright © 2021, Vladimir Karputov |

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

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

#property copyright "Copyright © 2021, Vladimir Karputov"

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

#property version   "1.000"

#property description "High price of 'Timeframe' on the 'Start Hour' bar"

#property indicator_chart_window

#property indicator_buffers 0

#property indicator_plots   0

//--- input parameters

input group             "Main Parameters"

input ENUM_TIMEFRAMES      Inp_period              = PERIOD_M30;     // Timeframe

input uchar                InpStartHour            = 06;             // Start Hour

input uchar                InpEndHour              = 10;             // End Hour

input group             "Trans lines Parameters"

input color                InpColor                = clrRed;         // Line color

input ENUM_LINE_STYLE      InpStyle                = STYLE_DASH;     // Line style

input int                  InpWidth                = 2;              // Line width

input bool                 InpBack                 = false;          // Background line

input bool                 InpSelection            = false;          // Highlight to move

input bool                 InpRayLeft              = false;          // Line's continuation to the left

input bool                 InpRayRight             = false;          // Line's continuation to the right

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

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

//---

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

double   m_high                     = 0.0;      // High price of 'Timeframe' on the 'Start Hour' bar

string   m_prefix                   = "Time interval ";

bool     m_init_error               = false;    // error on InInit

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

//---

   if(Inp_period!=PERIOD_CURRENT && Period()>Inp_period)

     {

      string inp_period=StringSubstr(EnumToString(Inp_period),7,-1);

      string curr_period=StringSubstr(EnumToString(Period()),7,-1);

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

                      ""09<D@59< 3@0D8:0 ("+curr_period+") =5 <>65B 1KBL > 'Timeframe' ("+inp_period+")!":

                      "The chart timeframe ("+curr_period+") cannot be > 'Timeframe' ("+inp_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);

     }

   if(Period()>=PERIOD_D1)

     {

      string curr_period=StringSubstr(EnumToString(Period()),7,-1);

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

                      ""09<D@59< 3@0D8:0 =5 <>65B 1KBL >= "+curr_period+"!":

                      "The chart timeframe cannot be >= "+curr_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);

     }

//---

   return(INIT_SUCCEEDED);

  }

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

//| Indicator deinitialization function                              |

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

void OnDeinit(const int reason)

  {

//---

   ObjectsDeleteAll(ChartID(),m_prefix,0,OBJ_TREND);

  }

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

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

   int limit=prev_calculated-1;

   if(prev_calculated==0)

     {

      limit=0;

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

      m_high                     = 0.0;      // High price of 'Timeframe' on the 'Start Hour' bar

     }

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

     {

      //--- what day?

      int bar_shift_d1=iBarShift(Symbol(),PERIOD_D1,time[i]);

      if(bar_shift_d1<0)

        {

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

         m_high                     = 0.0;      // High price of 'Timeframe' on the 'Start Hour' bar

         return(0);

        }

      datetime time_d1=iTime(Symbol(),PERIOD_D1,bar_shift_d1);

      if(time_d1==D'1970.01.01 00:00')

        {

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

         m_high                     = 0.0;      // High price of 'Timeframe' on the 'Start Hour' bar

         return(0);

        }

      if(time_d1>m_current_day)

        {

         m_current_day=time_d1;

         m_high=0.0;

        }

      //---

      MqlDateTime STime;

      if(Inp_period==PERIOD_CURRENT)

        {

         TimeToStruct(time[i],STime);

         int int_time=STime.hour*60*60+STime.min*60+STime.sec;

         if(int_time==InpStartHour*60*60)

            if(high[i]>m_high)

               m_high=high[i];

        }

      else

        {

         int bar_shift_period=iBarShift(Symbol(),Inp_period,time[i]);

         if(bar_shift_period<0)

           {

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

            m_high                     = 0.0;      // High price of 'Timeframe' on the 'Start Hour' bar

            return(0);

           }

         MqlRates rates_period[];

         if(CopyRates(Symbol(),Inp_period,bar_shift_period,1,rates_period)!=1)

           {

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

            m_high                     = 0.0;      // High price of 'Timeframe' on the 'Start Hour' bar

            return(0);

           }

         //---

         TimeToStruct(rates_period[0].time,STime);

         int int_time=STime.hour*60*60+STime.min*60+STime.sec;

         if(int_time==InpStartHour*60*60)

            if(rates_period[0].high>m_high)

               m_high=rates_period[0].high;

        }

      //---

      datetime time_start=0,time_end=0;

      STime.hour=InpStartHour;

      STime.min=0;

      STime.sec=0;

      time_start=StructToTime(STime);

      STime.hour=InpEndHour;

      time_end=StructToTime(STime);

      //---

      if(m_high>0.0)

        {

         long chart_id=ChartID();

         string name=m_prefix+TimeToString(m_current_day,TIME_DATE|TIME_SECONDS);

         if(ObjectFind(chart_id,name)<0)

           {

            TrendCreate(chart_id,name,0,time_start,m_high,time_end,m_high,

                        InpColor,

                        InpStyle,

                        InpWidth,

                        InpBack,

                        InpSelection,

                        InpRayLeft,

                        InpRayRight,

                        InpHidden,

                        InpZOrder);

           }

         else

           {

            TrendPointChange(chart_id,name,0,time_start,m_high);

            TrendPointChange(chart_id,name,1,time_end,m_high);

           }

        }

     }

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

   return(rates_total);

  }



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

//| Create a trend line by the given coordinates                     |

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

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

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

                 const int             sub_window=0,      // subwindow index

                 datetime              time1=0,           // first point time

                 double                price1=0,          // first point price

                 datetime              time2=0,           // second point time

                 double                price2=0,          // second point price

                 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_left=false,    // line's continuation to the left

                 const bool            ray_right=false,   // line's continuation to the right

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

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

  {

//--- set anchor points' coordinates if they are not set

   ChangeTrendEmptyPoints(time1,price1,time2,price2);

//--- reset the error value

   ResetLastError();

//--- create a trend line by the given coordinates

   if(!ObjectCreate(chart_ID,name,OBJ_TREND,sub_window,time1,price1,time2,price2))

     {

      Print(__FUNCTION__,

            ": failed to create a trend 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 continuation of the line's display to the left

   ObjectSetInteger(chart_ID,name,OBJPROP_RAY_LEFT,ray_left);

//--- enable (true) or disable (false) the mode of continuation of the line's display to the right

   ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);

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

//--- successful execution

   return(true);

  }

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

//| Move trend line anchor point                                     |

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

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

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

                      const int    point_index=0,    // anchor point index

                      datetime     time=0,           // anchor point time coordinate

                      double       price=0)          // anchor point price coordinate

  {

//--- if point position is not set, move it to the current bar having Bid price

   if(!time)

      time=TimeCurrent();

   if(!price)

      price=SymbolInfoDouble(Symbol(),SYMBOL_BID);

//--- reset the error value

   ResetLastError();

//--- move trend line's anchor point

   if(!ObjectMove(chart_ID,name,point_index,time,price))

     {

      Print(__FUNCTION__,

            ": failed to move the anchor point! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Check the values of trend line's anchor points and set default   |

//| values for empty ones                                            |

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

void ChangeTrendEmptyPoints(datetime &time1,double &price1,

                            datetime &time2,double &price2)

  {

//--- if the first point's time is not set, it will be on the current bar

   if(!time1)

      time1=TimeCurrent();

//--- if the first point's price is not set, it will have Bid value

   if(!price1)

      price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);

//--- if the second point's time is not set, it is located 9 bars left from the second one

   if(!time2)

     {

      //--- array for receiving the open time of the last 10 bars

      datetime temp[10];

      CopyTime(Symbol(),Period(),time1,10,temp);

      //--- set the second point 9 bars left from the first one

      time2=temp[0];

     }

//--- if the second point's price is not set, it is equal to the first point's one

   if(!price2)

      price2=price1;

  }

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

Comments