Fractals Fibo

Author: Copyright © 2020-2021, Vladimir Karputov
Price Data Components
Indicators Used
Fractals
0 Views
0 Downloads
0 Favorites
Fractals Fibo
ÿþ//+------------------------------------------------------------------+

//|                                                Fractals Fibo.mq5 |

//|                         Copyright © 2020-2021, Vladimir Karputov |

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

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

#property copyright "Copyright © 2020-2021, Vladimir Karputov"

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

#property version   "1.003"

#property indicator_chart_window

#property indicator_buffers 2

#property indicator_plots   2

//--- plot Fractal_Up

#property indicator_label1  "Fractal Up"

#property indicator_type1   DRAW_ARROW

#property indicator_color1  clrDeepSkyBlue

#property indicator_style1  STYLE_SOLID

#property indicator_width1  1

//--- plot Fractal_Down

#property indicator_label2  "Fractal Down"

#property indicator_type2   DRAW_ARROW

#property indicator_color2  clrDeepSkyBlue

#property indicator_style2  STYLE_SOLID

#property indicator_width2  1

//--- input parameters

input group             "Fibo"

input color             InpColor       = clrSpringGreen;       // Fibo color

input ENUM_LINE_STYLE   InpStyles      = STYLE_SOLID;          // Style of Fibo

input int               InpWidth       = 3;                    // Fibo line width

input group             "Levels"

input color             InpLevelsColor = clrMediumSlateBlue;   // Color of level lines

input ENUM_LINE_STYLE   InpLevelsStyles= STYLE_DOT;            // Style of level lines

input int               InpLevelsWidth = 3;                    // Fibo line width

//--- indicator buffers

double   FractalUpBuffer[];

double   FractalDownBuffer[];

//--- 10 pixels upper from high price

int      m_arrow_shift=-10;

//---

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

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

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

string   m_fibo="fibo";

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

//| Structurt Fractals                                               |

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

struct STRUCT_FRACTALS

  {

   int               fractal_type;           // fractal type ('-1' -> down, '1' -> up)

   double            fractal_price;          // fractal price

   datetime          fractal_time;           // fractal time

   //--- Constructor

                     STRUCT_FRACTALS()

     {

      fractal_type               = 0;

      fractal_price              = 0.0;

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

     }

  };

STRUCT_FRACTALS SFractals[];

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,FractalUpBuffer,INDICATOR_DATA);

   SetIndexBuffer(1,FractalDownBuffer,INDICATOR_DATA);

   IndicatorSetInteger(INDICATOR_DIGITS,Digits());

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

   PlotIndexSetInteger(0,PLOT_ARROW,217);

   PlotIndexSetInteger(1,PLOT_ARROW,218);

//--- arrow shifts when drawing

   PlotIndexSetInteger(0,PLOT_ARROW_SHIFT,m_arrow_shift);

   PlotIndexSetInteger(1,PLOT_ARROW_SHIFT,-m_arrow_shift);

//--- sets drawing line empty value--

   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE);

   PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,EMPTY_VALUE);

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

     }

//---

   ArrayFree(SFractals);

   ArrayResize(SFractals,3);

   ArraySetAsSeries(SFractals,true);

//---

   return(INIT_SUCCEEDED);

  }

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

//| Indicator deinitialization function                              |

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

void OnDeinit(const int reason)

  {

   ObjectDelete(ChartID(),m_fibo);

   if(handle_iFractals!=INVALID_HANDLE)

      IndicatorRelease(handle_iFractals);

  }

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

//| 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(rates_total<10)

      return(0);

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

   int values_to_copy;

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

     }

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

   int limit=prev_calculated-4;

   if(prev_calculated==0)

      limit=3;

//---

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

     {

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

      datetime time_0=time[i];

      if(time_0==m_prev_bars)

         return(rates_total);

      m_prev_bars=time_0;

      //---

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

        {

         STRUCT_FRACTALS SFractals_temp[];

         //---

         ArrayResize(SFractals_temp,3);

         ArraySetAsSeries(SFractals_temp,true);

         ArrayCopy(SFractals_temp,SFractals,1,0,2);

         //---

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

           {

            if(SFractals_temp[1].fractal_type==1)

               continue;

            SFractals_temp[0].fractal_type=1;

            SFractals_temp[0].fractal_price=FractalUpBuffer[i];

           }

         else

           {

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

              {

               /*arr_temp_fractals[0]=FractalDownBuffer[i];*/

               if(SFractals_temp[1].fractal_type==-1)

                  continue;

               SFractals_temp[0].fractal_type=-1;

               SFractals_temp[0].fractal_price=FractalDownBuffer[i];

              }

           }

         SFractals_temp[0].fractal_time=time[i];

         ArrayCopy(SFractals,SFractals_temp,0,0,WHOLE_ARRAY);

         //---

         if(SFractals[1].fractal_price!=0.0 && SFractals[0].fractal_price!=0.0)

           {

            datetime time1=0;    // first point time

            double   price1=0;   // first point price

            datetime time2=0;    // second point time

            double   price2=0;   // second point price

            if(SFractals[1].fractal_price<SFractals[0].fractal_price)

              {

               time1=SFractals_temp[0].fractal_time;

               price1=SFractals_temp[0].fractal_price;

               time2=SFractals_temp[1].fractal_time;

               price2=SFractals_temp[1].fractal_price;

              }

            else

              {

               time1=SFractals_temp[1].fractal_time;

               price1=SFractals_temp[1].fractal_price;

               time2=SFractals_temp[0].fractal_time;

               price2=SFractals_temp[0].fractal_price;

              }

            if(ObjectFind(ChartID(),m_fibo)<0)

              {

               FiboLevelsCreate(ChartID(),m_fibo,0,time1,price1,time2,price2,InpColor,InpStyles,InpWidth);

               /*

               0 0.0

               0.236 23.6

               0.382 38.2

               0.5 50.0

               0.618 61.8

               1 100.0

               1.618 161.8

               2.618 261.8

               4.236 423.6

               */

               int               levels   = 7;                                                                    // number of level lines

               double            values[7]= {0.0,0.236,0.382,0.5,0.618,1.0,1.618};                                // values of level lines

               color             colors[7];                                                                       // color of level lines

               for(int j=0; j<7; j++)

                  colors[j]=InpLevelsColor;

               ENUM_LINE_STYLE   styles[7];                                                                       // style of level lines

               for(int j=0; j<7; j++)

                  styles[j]=InpLevelsStyles;

               int               widths[7];                                                                       // width of level lines

               for(int j=0; j<7; j++)

                  widths[j]=InpLevelsWidth;

               string            texts[7] = {"0.0","23.6","38.2","50.0","61.8","100.0","161.8"};                  // text of level lines

               //---

               FiboLevelsSet(levels,values,colors,styles,widths,texts,ChartID(),m_fibo);

              }

            else

              {

               FiboLevelsPointChange(ChartID(),m_fibo,1,time1,price1);

               FiboLevelsPointChange(ChartID(),m_fibo,0,time2,price2);

              }

           }

         //---

        }

     }

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

  }

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

//| Create Fibonacci Retracement by the given coordinates            |

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

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

                      const string          name="FiboLevels", // object 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,        // object color

                      const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style

                      const int             width=1,           // object line width

                      const bool            back=false,        // in the background

                      const bool            selection=false,   // highlight to move

                      const bool            ray_left=false,    // object's continuation to the left

                      const bool            ray_right=true,    // object's continuation to the right

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

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

  {

//--- reset the error value

   ResetLastError();

//--- Create Fibonacci Retracement by the given coordinates

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

     {

      Print(__FUNCTION__,

            ": failed to create \"Fibonacci Retracement\"! Error code = ",GetLastError());

      return(false);

     }

//--- set color

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- set line 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 highlighting the channel for moving

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

  }

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

//| Set number of levels and their parameters                        |

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

bool FiboLevelsSet(int             levels,            // number of level lines

                   double          &values[],         // values of level lines

                   color           &colors[],         // color of level lines

                   ENUM_LINE_STYLE &styles[],         // style of level lines

                   int             &widths[],         // width of level lines

                   string          &texts[],          // text of level lines

                   const long      chart_ID=0,        // chart's ID

                   const string    name="FiboLevels") // object name

  {

//--- check array sizes

   if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||

      levels!=ArraySize(widths) || levels!=ArraySize(widths) ||

      levels!=ArraySize(texts))

     {

      Print(__FUNCTION__,": array length does not correspond to the number of levels, error!");

      return(false);

     }

//--- set the number of levels

   ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);

//--- set the properties of levels in the loop

   for(int i=0; i<levels; i++)

     {

      //--- level value

      ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);

      //--- level color

      ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);

      //--- level style

      ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);

      //--- level width

      ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);

      //--- level description

      ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,texts[i]);

     }

//--- successful execution

   return(true);

  }

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

//| Move Fibonacci Retracement anchor point                          |

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

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

                           const string name="FiboLevels", // object 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 the 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);

  }

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

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