Line through two fractals

Author: Copyright © 2020, Vladimir Karputov
Price Data Components
Indicators Used
Fractals
0 Views
0 Downloads
0 Favorites
Line through two fractals
ÿþ//+------------------------------------------------------------------+

//|                                    Line through two fractals.mq5 |

//|                              Copyright © 2020, Vladimir Karputov |

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

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

#property copyright "Copyright © 2020, Vladimir Karputov"

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

#property version   "1.000"

#property indicator_chart_window

#property indicator_buffers 2

#property indicator_plots   0

//--- input parameters

input    string         InpUpperName      = "Trend line upper";   // "Trend line upper": name

input    string         InpLowerName      = "Trend line lower";   // "Trend line lower": name



input    color          InpUpperColor     = clrBlue;              // "Trend line upper": color

input    color          InpLowerColor     = clrRed;               // "Trend line lower": color



input ENUM_LINE_STYLE   InpUpperStyle     = STYLE_DASH;           // "Trend line upper": style

input ENUM_LINE_STYLE   InpLowerStyle     = STYLE_DASH;           // "Trend line lower": style



input int               InpUpperWidth     = 2;                    // "Trend line upper": width

input int               InpLowerWidth     = 2;                    // "Trend line lower": width



input bool              InpUpperBack      = false;                // "Trend line upper": background line

input bool              InpLowerBack      = false;                // "Trend line lower": background line



input bool              InpUpperSelection = true;                 // "Trend line upper": highlight to move

input bool              InpLowerSelection = true;                 // "Trend line lower": highlight to move



input bool              InpUpperRayLeft   = false;                // "Trend line upper": continuation to the left

input bool              InpLowerRayLeft   = false;                // "Trend line lower": continuation to the left



input bool              InpUpperRayRight  = true;                 // "Trend line upper": continuation to the right

input bool              InpLowerRayRight  = true;                 // "Trend line lower": continuation to the right



input bool              InpUpperHidden    = true;                 // "Trend line upper": hidden in the object list

input bool              InpLowerHidden    = true;                 // "Trend line lower": hidden in the object list



input long              InpUpperZOrder    = 0;                    // "Trend line upper": priority for mouse click

input long              InpLowerZOrder    = 0;                    // "Trend line lower": priority for mouse click

//--- indicator buffers

double   FractalUpBuffer[];

double   FractalDownBuffer[];

int      bars_calculated=0;                              // we will keep the number of values in the Fractals indicator

//---

int      handle_iFractals;                               // variable for storing the handle of the iFractals indicator

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

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

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,FractalUpBuffer,INDICATOR_CALCULATIONS);

   SetIndexBuffer(1,FractalDownBuffer,INDICATOR_CALCULATIONS);

//--- create handle of the indicator iFractals

   handle_iFractals=iFractals(Symbol(),Period());

//--- if the handle is not created

   if(handle_iFractals==INVALID_HANDLE)

     {

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

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

                  Symbol(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early

      return(INIT_FAILED);

     }

//---

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

  {

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

   int calculated=BarsCalculated(handle_iFractals);

   if(calculated<=0)

     {

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

      return(0);

     }

//---

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

   int values_to_copy;

//--- if it is the first start of calculation of the indicator or if the number of values in the iFractals 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 FractalUpBuffer array is greater than the number of values in the iFractals 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 FractalUpBuffer and FractalDownBuffer arrays with values from the Fractals indicator

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

   if(!FillArraysFromBuffers(FractalUpBuffer,FractalDownBuffer,handle_iFractals,values_to_copy))

      return(0);

//--- memorize the number of values in the Fractals indicator

   bars_calculated=calculated;

//--- main loop

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

   datetime time_0=iTime(Symbol(),Period(),0);

   if(time_0==m_prev_bars)

      return(rates_total);

   m_prev_bars=time_0;



   double upper_left=0.0,upper_right=0.0,lower_left=0.0,lower_right=0.0;

   datetime upper_left_date=0,upper_right_date=0,lower_left_date=0,lower_right_date=0;

   for(int i=rates_total-4; i>=10; i--)

     {

      if(FractalUpBuffer[i]!=0.0 && FractalUpBuffer[i]!=EMPTY_VALUE)

        {

         if(upper_left==0.0)

           {

            upper_left=FractalUpBuffer[i];

            upper_left_date=time[i];

           }

         else

            if(upper_right==0.0)

              {

               upper_right=FractalUpBuffer[i];

               upper_right_date=time[i];

              }

        }

      if(FractalDownBuffer[i]!=0.0 && FractalDownBuffer[i]!=EMPTY_VALUE)

        {

         if(lower_left==0.0)

           {

            lower_left=FractalDownBuffer[i];

            lower_left_date=time[i];

           }

         else

            if(lower_right==0.0)

              {

               lower_right=FractalDownBuffer[i];

               lower_right_date=time[i];

              }

        }

      if(upper_left!=0.0 && upper_right!=0.0 && lower_left!=0.0 && lower_right!=0.0)

         break;

     }

   if(upper_left==0.0 || upper_right==0.0 || lower_left==0.0 || lower_right==0.0)

      return(rates_total);



   if(ObjectFind(0,InpUpperName)<0)

     {

      if(!TrendCreate(0,InpUpperName,0,upper_right_date,upper_right,upper_left_date,upper_left,

                      InpUpperColor,InpUpperStyle,InpUpperWidth,InpUpperBack,InpUpperSelection,

                      InpUpperRayLeft,InpUpperRayRight,InpUpperHidden,InpUpperZOrder))

         return(rates_total);

     }

   else

     {

      TrendPointChange(0,InpUpperName,0,upper_right_date,upper_right);

      TrendPointChange(0,InpUpperName,1,upper_left_date,upper_left);

     }





   if(ObjectFind(0,InpLowerName)<0)

     {

      if(!TrendCreate(0,InpLowerName,0,lower_right_date,lower_right,lower_left_date,lower_left,

                      InpLowerColor,InpLowerStyle,InpLowerWidth,InpLowerBack,InpLowerSelection,

                      InpLowerRayLeft,InpLowerRayRight,InpLowerHidden,InpLowerZOrder))

         return(rates_total);

     }

   else

     {

      TrendPointChange(0,InpLowerName,0,lower_right_date,lower_right);

      TrendPointChange(0,InpLowerName,1,lower_left_date,lower_left);

     }

   /*string text="UPPER | LOWER";

   for(int i=rates_total-9; i<rates_total; i++)

     {



      text=text+"\n"+IntegerToString(i)+"# "+

           ((FractalUpBuffer[i]==EMPTY_VALUE)?"0.0":DoubleToString(FractalUpBuffer[i],Digits()))+" | "+

           ((FractalDownBuffer[i]==EMPTY_VALUE)?"0.0":DoubleToString(FractalDownBuffer[i],Digits()));

     }

   Comment(text);*/

//int limit=prev_calculated

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

   return(rates_total);

  }

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

//| Filling indicator buffers from the iFractals indicator           |

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

bool FillArraysFromBuffers(double &up_arrows[],        // indicator buffer for up arrows

                           double &down_arrows[],      // indicator buffer for down arrows

                           int ind_handle,             // handle of the iFractals indicator

                           int amount                  // number of copied values

                          )

  {

//--- reset error code

   ResetLastError();

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

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

     {

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

      PrintFormat("Failed to copy data from the iFractals indicator to the FractalUpBuffer array, 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 FractalDownBuffer array with values from the indicator buffer that has index 1

   if(CopyBuffer(ind_handle,1,0,amount,down_arrows)<0)

     {

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

      PrintFormat("Failed to copy data from the iFractals indicator to the FractalDownBuffer array, 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_iFractals!=INVALID_HANDLE)

      IndicatorRelease(handle_iFractals);

   TrendDelete(0,InpUpperName);

   TrendDelete(0,InpLowerName);

  }

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

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

  }

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

//| The function deletes the trend line from the chart.              |

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

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

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

  {

//--- reset the error value

   ResetLastError();

//--- delete a trend line

   if(!ObjectDelete(chart_ID,name))

     {

      Print(__FUNCTION__,

            ": failed to delete a trend line! 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

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