iFractals Trend Line

Author: Copyright © 2019, Vladimir Karputov
Indicators Used
Fractals
0 Views
0 Downloads
0 Favorites
iFractals Trend Line
ÿþ//+------------------------------------------------------------------+

//|                                         iFractals Trend Line.mq5 |

//|                              Copyright © 2019, Vladimir Karputov |

//|                                           http://wmua.ru/slesar/ |

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

#property copyright "Copyright © 2019, Vladimir Karputov"

#property link      "http://wmua.ru/slesar/"

#property version   "1.000"

#property indicator_chart_window

#property indicator_buffers 2

#property indicator_plots 0

//--- indicator buffers

double   FractalUpBuffer[];

double   FractalDownBuffer[];

//---

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

string   m_prefix             = "FTL ";   //

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

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

     }

   TrendCreate(0,m_prefix+"up left",0,0,0,0,0,clrDarkOrchid);

   TrendCreate(0,m_prefix+"up right",0,0,0,0,0,clrYellowGreen);

   TrendCreate(0,m_prefix+"down left",0,0,0,0,0,clrDarkOrchid);

   TrendCreate(0,m_prefix+"down right",0,0,0,0,0,clrYellowGreen);

//---

   return(INIT_SUCCEEDED);

  }

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

//| Indicator deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

   ObjectsDeleteAll(0,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(rates_total<330)

      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;

//---

   int limit=rates_total-4;

   double up[],down[];

   datetime dt_up[],dt_down[];

   int size_up=0,size_down=0;

   for(int i=limit; i>rates_total-300; i--)

     {

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

        {

         size_up=ArraySize(up);

         if(size_up<3)

           {

            ArrayResize(up,size_up+1);

            ArrayResize(dt_up,size_up+1);

            up[size_up]=FractalUpBuffer[i];

            dt_up[size_up]=time[i];

           }



        }

      //---

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

        {

         size_down=ArraySize(down);

         if(size_down<3)

           {

            ArrayResize(down,size_down+1);

            ArrayResize(dt_down,size_down+1);

            down[size_down]=FractalDownBuffer[i];

            dt_down[size_down]=time[i];

           }

        }

      //---

      if(size_up==3 && size_down==3)

         break;

     }

   if(size_up!=3 || size_down!=3)

      return(0);

//---

   TrendPointChange(0,m_prefix+"up left",0,dt_up[2],up[2]);

   TrendPointChange(0,m_prefix+"up left",1,dt_up[1],up[1]);



   TrendPointChange(0,m_prefix+"up right",0,dt_up[1],up[1]);

   TrendPointChange(0,m_prefix+"up right",1,dt_up[0],up[0]);



   TrendPointChange(0,m_prefix+"down left",0,dt_down[2],down[2]);

   TrendPointChange(0,m_prefix+"down left",1,dt_down[1],down[1]);



   TrendPointChange(0,m_prefix+"down right",0,dt_down[1],down[1]);

   TrendPointChange(0,m_prefix+"down right",1,dt_down[0],down[0]);

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

  }

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

//| ChartEvent function                                              |

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

void OnChartEvent(const int id,

                  const long &lparam,

                  const double &dparam,

                  const string &sparam)

  {

//---



  }

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

//| 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_DASHDOTDOT, // line style

                 const int             width=1,             // line width

                 const bool            back=false,          // in the background

                 const bool            selection=false,     // highlight to move

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

                 const bool            ray_right=true,      // 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

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