N last bars OBJ_CHART

Author: Copyright © 2020-2022, Vladimir Karputov
Price Data Components
0 Views
0 Downloads
0 Favorites
N last bars OBJ_CHART
ÿþ//+------------------------------------------------------------------+

//|                                        N last bars OBJ_CHART.mq5 |

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

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

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

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

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

#property version   "1.003"

#property indicator_chart_window //indicator_separate_window

#property indicator_buffers 5

#property indicator_plots   0

//--- plot Label1

#property indicator_label1  "N last bars"

#property indicator_type1   DRAW_COLOR_CANDLES

#property indicator_color1  clrLavender,clrLimeGreen

#property indicator_style1  STYLE_SOLID

#property indicator_width1  1

//--- input parameters

input group "Indicator"

input uchar             InpLastBars    = 3;                 // N last bars

input color             InpBullColor   = clrLavender;       // Bull Color

input color             InpBearColor   = clrLimeGreen;      // Bear Color

//--- input parameters of the OBJ_CHART

input group "Chart"

input string            InpName        = "Chart";           // Object name

input string            InpSymbol      = "EURUSD";          // Symbol

input ENUM_TIMEFRAMES   InpPeriod      = PERIOD_H1;         // Period

input ENUM_BASE_CORNER  InpCorner      = CORNER_LEFT_UPPER; // Anchoring corner

input int               InpScale       = 4;                 // Scale

input bool              InpDateScale   = true;              // Time scale display

input bool              InpPriceScale  = true;              // Price scale display

input color             InpColor       = clrRed;            // Border color when highlighted

input ENUM_LINE_STYLE   InpStyle       = STYLE_DASHDOTDOT;  // Line style when highlighted

input int               InpPointWidth  = 1;                 // Point size to move

input bool              InpBack        = false;             // Background object

input bool              InpSelection   = true;              // Highlight to move

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

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

//--- indicator buffers

double         Label1Buffer1[];

double         Label1Buffer2[];

double         Label1Buffer3[];

double         Label1Buffer4[];

double         Label1Colors[];

//---

int            handle_iCustom;                     // variable for storing the handle of the iCustom indicat

bool           m_chart_indicator_add=false;

string         m_chart_name="";

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

//| Indicator deinitialization function                                 |

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

void OnDeinit(const int reason)

  {

//---

   ObjectChartDelete(0,m_chart_name);

  }

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

//| Custom indicator initialization function                         |

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

int OnInit()

  {

//--- indicator buffers mapping

   SetIndexBuffer(0,Label1Buffer1,INDICATOR_DATA);

   SetIndexBuffer(1,Label1Buffer2,INDICATOR_DATA);

   SetIndexBuffer(2,Label1Buffer3,INDICATOR_DATA);

   SetIndexBuffer(3,Label1Buffer4,INDICATOR_DATA);

   SetIndexBuffer(4,Label1Colors,INDICATOR_COLOR_INDEX);

//--- set accuracy

   IndicatorSetInteger(INDICATOR_DIGITS,Digits());

//--- an empty value

   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0.0);

//--- the name of the symbol, for which the bars are drawn

   string symbol=Symbol();

//--- set the display of the symbol

   PlotIndexSetString(0,PLOT_LABEL,"Open;"+"High;"+"Low;"+"Close");

   IndicatorSetString(INDICATOR_SHORTNAME,"N last bars("+symbol+","+IntegerToString(InpLastBars)+")");

//--- chart window size

   long x_distance;

   long y_distance;

//--- set window size

   if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))

     {

      Print("Failed to get the chart width! Error code = ",GetLastError());

      return(INIT_FAILED);

     }

   if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))

     {

      Print("Failed to get the chart height! Error code = ",GetLastError());

      return(INIT_FAILED);

     }

//--- set Chart object coordinates and its size

   int x=(int)(x_distance-x_distance/2);

   int y=(int)(y_distance-y_distance/2);

   int x_size=(int)x_distance*4/16;

   int y_size=(int)y_distance*7/16;

//--- Initialize the generator of random numbers

   MathSrand(GetTickCount());

   m_chart_name=InpName+IntegerToString(rand(),5,'0');

//--- create Chart object

   if(!ObjectChartCreate(0,m_chart_name,0,InpSymbol,InpPeriod,x,y,x_size,y_size,InpCorner,InpScale,InpDateScale,

                         InpPriceScale,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,InpZOrder))

     {

      return(INIT_FAILED);

     }

//---

   long chart_id=ObjectChartGetID(0,m_chart_name);

   color back_color=ChartBackColorGet(0);

   ChartShowPeriodSepapatorSet(false,chart_id); // disables displaying of vertical separators between adjacent periods

   ChartShowGridSet(false,chart_id);            // disables displaying of grid on chart

   ChartShowVolumesSet(false,chart_id);         // sets mode of displaying volumes on chart

   ChartBackColorSet(back_color,chart_id);      // chart background color

   ChartUpColorSet(back_color,chart_id);        // sets the color of up bar, shadow and border of a bullish candlestick's body

   ChartDownColorSet(back_color,chart_id);      // sets the color of down bar, shadow and border of a bearish candlestick's body

   ChartLineColorSet(back_color,chart_id);      // sets the color of chart line and Doji candlesticks

   ChartBullColorSet(back_color,chart_id);      // sets the color of bullish candlestick's body

   ChartBearColorSet(back_color,chart_id);      // sets the color of bearish candlestick's body

//--- create handle of the indicator iCustom

   handle_iCustom=iCustom(InpSymbol,InpPeriod,"N last bars",InpLastBars,InpBullColor,InpBearColor);

//--- if the handle is not created

   if(handle_iCustom==INVALID_HANDLE)

     {

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

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

                  InpSymbol,

                  EnumToString(InpPeriod),

                  GetLastError());

      //--- the indicator is stopped early

      ObjectChartDelete(0,m_chart_name);

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

  {

   if(!m_chart_indicator_add)

     {

      long chart_id=ObjectChartGetID(0,m_chart_name);

      //--- set the scale

      if(!ObjectSetInteger(chart_id,m_chart_name,OBJPROP_CHART_SCALE,InpScale))

         return(rates_total);

      //---

      m_chart_indicator_add=ChartIndicatorAdd(chart_id,0,handle_iCustom);

      if(!m_chart_indicator_add)

        {

         PrintFormat("Failed to add \"N last bars\" indicator on %d chart window. Error code  %d",0,GetLastError());

         return(rates_total);

         m_chart_indicator_add=true;

        }

      //---

      ChartRedraw(chart_id);

     }

   return(rates_total);

   if(rates_total<=InpLastBars)

      return(0);

   int limit=prev_calculated-1;

//--- first calculation -> (prev_calculated==0)

//--- number of bars was changed OR new bar (or several new bars) -> (prev_calculated>0 && rates_total-limit>1)

   if((prev_calculated==0) || (prev_calculated>0 && rates_total-limit>1))

     {

      //--- initialize buffers with empty values

      ArrayInitialize(Label1Buffer1,0.0);

      ArrayInitialize(Label1Buffer2,0.0);

      ArrayInitialize(Label1Buffer3,0.0);

      ArrayInitialize(Label1Buffer4,0.0);

      //---

      limit=rates_total-InpLastBars;

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

        {

         Label1Buffer1[i]=open[i];

         Label1Buffer2[i]=high[i];

         Label1Buffer3[i]=low[i];

         Label1Buffer4[i]=close[i];

         if(close[i]>open[i])

            Label1Colors[i]=0.0;

         else

            Label1Colors[i]=1.0;

        }

      //---

      return(rates_total);

     }

//--- main loop

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

     {

      Label1Buffer1[i]=open[i];

      Label1Buffer2[i]=high[i];

      Label1Buffer3[i]=low[i];

      Label1Buffer4[i]=close[i];

      if(close[i]>open[i])

         Label1Colors[i]=0.0;

      else

         Label1Colors[i]=1.0;

     }

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

   return(rates_total);

  }

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

//| Creating Chart object                                            |

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

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

                       const string            name="Chart",             // object name

                       const int               sub_window=0,             // subwindow index

                       const string            symbol="EURUSD",          // symbol

                       const ENUM_TIMEFRAMES   period=PERIOD_H1,         // period

                       const int               x=0,                      // X coordinate

                       const int               y=0,                      // Y coordinate

                       const int               width=300,                // width

                       const int               height=200,               // height

                       const ENUM_BASE_CORNER  corner=CORNER_LEFT_UPPER, // anchoring corner

                       const int               scale=2,                  // scale

                       const bool              date_scale=true,          // time scale display

                       const bool              price_scale=true,         // price scale display

                       const color             clr=clrRed,               // border color when highlighted

                       const ENUM_LINE_STYLE   style=STYLE_SOLID,        // line style when highlighted

                       const int               point_width=1,            // move point size

                       const bool              back=false,               // in the background

                       const bool              selection=false,          // highlight to move

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

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

  {

//--- reset the error value

   ResetLastError();

//--- create Chart object

   if(!ObjectCreate(chart_ID,name,OBJ_CHART,sub_window,0,0))

     {

      Print(__FUNCTION__,

            ": failed to create \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

//--- set object coordinates

   ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);

   ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);

//--- set object size

   ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);

   ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);

//--- set the chart's corner, relative to which point coordinates are defined

   ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);

//--- set the symbol

   ObjectSetString(chart_ID,name,OBJPROP_SYMBOL,symbol);

//--- set the period

   ObjectSetInteger(chart_ID,name,OBJPROP_PERIOD,period);

//--- set the scale

   ObjectSetInteger(chart_ID,name,OBJPROP_CHART_SCALE,scale);

//--- display (true) or hide (false) the time scale

   ObjectSetInteger(chart_ID,name,OBJPROP_DATE_SCALE,date_scale);

//--- display (true) or hide (false) the price scale

   ObjectSetInteger(chart_ID,name,OBJPROP_PRICE_SCALE,price_scale);

//--- set the border color when object highlighting mode is enabled

   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);

//--- set the border line style when object highlighting mode is enabled

   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);

//--- set a size of the anchor point for moving an object

   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_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 label by mouse

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);

   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);

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

  }

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

//| Sets the symbol and time frame of the Chart object               |

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

bool ObjectChartSetSymbolAndPeriod(const long            chart_ID=0,       // chart's ID (not Chart object's one)

                                   const string          name="Chart",     // object name

                                   const string          symbol="EURUSD",  // symbol

                                   const ENUM_TIMEFRAMES period=PERIOD_H1) // time frame

  {

//--- reset the error value

   ResetLastError();

//--- set Chart object's symbol and time frame

   if(!ObjectSetString(chart_ID,name,OBJPROP_SYMBOL,symbol))

     {

      Print(__FUNCTION__,

            ": failed to set a symbol for \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

   if(!ObjectSetInteger(chart_ID,name,OBJPROP_PERIOD,period))

     {

      Print(__FUNCTION__,

            ": failed to set a period for \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Move Chart object                                                |

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

bool ObjectChartMove(const long   chart_ID=0,   // chart's ID (not Chart object's one)

                     const string name="Chart", // object name

                     const int    x=0,          // X coordinate

                     const int    y=0)          // Y coordinate

  {

//--- reset the error value

   ResetLastError();

//--- move the object

   if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))

     {

      Print(__FUNCTION__,

            ": failed to move X coordinate of \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

   if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))

     {

      Print(__FUNCTION__,

            ": failed to move Y coordinate of \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Change Chart object size                                         |

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

bool ObjectChartChangeSize(const long   chart_ID=0,   // chart's ID (not Chart object's one)

                           const string name="Chart", // object name

                           const int    width=300,    // width

                           const int    height=200)   // height

  {

//--- reset the error value

   ResetLastError();

//--- change the object size

   if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))

     {

      Print(__FUNCTION__,

            ": failed to change the width of \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

   if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))

     {

      Print(__FUNCTION__,

            ": failed to change the height of \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Return Chart object's ID                                         |

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

long ObjectChartGetID(const long   chart_ID=0,   // chart's ID (not Chart object's one)

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

  {

//--- prepare the variable to get Chart object's ID

   long id=-1;

//--- reset the error value

   ResetLastError();

//--- get ID

   if(!ObjectGetInteger(chart_ID,name,OBJPROP_CHART_ID,0,id))

     {

      Print(__FUNCTION__,

            ": failed to get \"Chart\" object's ID! Error code = ",GetLastError());

     }

//--- return the result

   return(id);

  }

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

//| Delete Chart object                                              |

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

bool ObjectChartDelete(const long   chart_ID=0,   // chart's ID (not Chart object's one)

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

  {

//--- reset the error value

   ResetLastError();

//--- delete the button

   if(!ObjectDelete(chart_ID,name))

     {

      Print(__FUNCTION__,

            ": failed to delete \"Chart\" object! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Enables/disables displaying of vertical separators between adjacent periods |

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

bool ChartShowPeriodSepapatorSet(const bool value,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set property value

   if(!ChartSetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,0,value))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Enables/disables displaying of grid on chart                     |

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

bool ChartShowGridSet(const bool value,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the property value

   if(!ChartSetInteger(chart_ID,CHART_SHOW_GRID,0,value))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets mode of displaying volumes on chart                         |

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

bool ChartShowVolumesSet(const long value,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set property value

   if(!ChartSetInteger(chart_ID,CHART_SHOW_VOLUMES,value))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Gets the background color of chart                               |

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

color ChartBackColorGet(const long chart_ID=0)

  {

//--- prepare the variable to receive the color

   long result=clrNONE;

//--- reset the error value

   ResetLastError();

//--- receive chart background color

   if(!ChartGetInteger(chart_ID,CHART_COLOR_BACKGROUND,0,result))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

     }

//--- return the value of the chart property

   return((color)result);

  }

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

//| Sets the background color of chart                               |

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

bool ChartBackColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the chart background color

   if(!ChartSetInteger(chart_ID,CHART_COLOR_BACKGROUND,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets the color of axes, scale and OHLC line                      |

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

bool ChartForeColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the color of axes, scale and OHLC line

   if(!ChartSetInteger(chart_ID,CHART_COLOR_FOREGROUND,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets the color of up bar, shadow and border of a bullish candlestick's body |

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

bool ChartUpColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the color of up bar, its shadow and border of body of a bullish candlestick

   if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_UP,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets the color of down bar, shadow and border of a bearish candlestick's body |

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

bool ChartDownColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the color of down bar, its shadow and border of bearish candlestick's body

   if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_DOWN,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets the color of chart line and Doji candlesticks               |

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

bool ChartLineColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set color of the chart line and Doji candlesticks

   if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_LINE,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets the color of bullish candlestick's body                     |

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

bool ChartBullColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the color of bullish candlestick's body

   if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", Error Code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

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

//| Sets the color of bearish candlestick's body                     |

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

bool ChartBearColorSet(const color clr,const long chart_ID=0)

  {

//--- reset the error value

   ResetLastError();

//--- set the color of bearish candlestick's body

   if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,clr))

     {

      //--- display the error message in Experts journal

      Print(__FUNCTION__+", 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 ---