Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1465

 
Dzmitry Zaitsau:
Hi, could you please tell me why ChartGetInteger is preceded by (int) in parentheses?

int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);

ChartGetInteger возвращает значение формата long или bool. Через (int) происходит перевод ChartGetInteger в значение int. 
если int bars, значит и значение должно быть int при присваивании.

1. Непосредственно возвращает значение свойства.
long  ChartGetInteger( 
   long  chart_id,          // идентификатор графика 
   int   prop_id,           // идентификатор свойства 
   int   sub_window=0       // номер подокна, если требуется 
   );
 
2. Возвращает true или false в зависимости от успешности выполнения функции.  В случае успеха значение свойства помещается в приемную переменную, передаваемую по ссылке последним параметром
bool  ChartGetInteger( 
   long    chart_id,        // идентификатор графика 
   int     prop_id,         // идентификатор свойства 
   int     sub_window,      // номер подокна 
   long&   long_var         // сюда примем значение свойства 
   );
 
 

Hello. Please advise.

I have an indicator that is supposed to draw the High and Low lines of the day on each bar of a smaller timeframe.

When I put it on the chart, it just draws the lines at the current high and low of the day (in the picture, as it should be).

#property indicator_chart_window 
#property indicator_buffers 2       
#property indicator_color1 Blue     
#property indicator_color2 Red      

//datetime time=D'2021.03.30 00:00';

string strTime = "0:00";
 
double Buf_0[],Buf_1[];                   
double Sum_H=0;                    
double Sum_L=0;
//--------------------------------------------------------------------
int init()                         
  {
   SetIndexBuffer(0,Buf_0);        
   SetIndexStyle (0,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(1,Buf_1);        
   SetIndexStyle (1,DRAW_LINE,STYLE_SOLID,1);
   return(0);                        
  }
//--------------------------------------------------------------------
int start()                        
  {
   int i, Counted_bars;                    
//--------------------------------------------------------------------
   Counted_bars=IndicatorCounted(); 
   datetime time=StringToTime(strTime);
   int bar_index=iBarShift(Symbol(),PERIOD_CURRENT,time,false); 
   i=Bars-Counted_bars;          
   if (i>bar_index) i=bar_index-1;  
   while(i>=0)                      
     {
      Sum_H=iHigh(Symbol(),PERIOD_D1,0);
      Sum_L=iLow(Symbol(),PERIOD_D1,0);
      Buf_0[i]=Sum_H;
      Buf_1[i]=Sum_L;
      i--;                          
     }
//--------------------------------------------------------------------
   return(0);                        
  }
//--------------------------------------------------------------------
Files:
2.png  31 kb
 
ifitstrue:

Hello. Please advise.

I have an indicator that is supposed to draw the High and Low lines of the day on each bar of a smaller timeframe.

When I put it on a chart, it just draws lines at the current high and low of the day (in the picture, as it should be).

Here is the answer

 
Thank you.
 
Hello, could you tell me please what is the chart ID?

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

For example, when attaching the script to eur/usd, what is the chart ID? Where can I find it to find out.




 
Dzmitry Zaitsau:
Hello, could you please tell me what is the chart ID?

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

For example, when attaching the script to eur/usd, what is the chart ID? Where do I dig, in order to understand it.

I usually go to the help.

Документация по MQL5: Операции с графиками
Документация по MQL5: Операции с графиками
  • www.mql5.com
Операции с графиками - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 

Can you please give me a code for MT4 and MT5 Expert Advisor to puta stop loss 2-3 points above the maximum/minimum of just closed candle.

Or where can i see the tutorial on this subject. Thanks in advance :-)

Files:
izilo2.jpeg  270 kb
 
WindUP:

Please give me a code for MT4 and MT5 Expert Advisor to puta stop loss 2-3 points above the maximum/minimum of just closed candle.

Or where can i see the tutorial on this subject. Thanks in advance :-)

You declare an array of type MqlRates. You copy the OHLC and other parameters of a closed candlestick

int  CopyRates(
   string           symbol_name,       // имя символа
   ENUM_TIMEFRAMES  timeframe,         // период
   int              start_pos,         // откуда начнем (начнём с 1)
   int              count,             // сколько копируем (надо всего 1)
   MqlRates         rates_array[]      // массив, куда будут скопированы данные
   );

and then take the High or Low values from which you are offset by 2-3 points and put stops there.

You may also use

double  iHigh(
   string           symbol,          // символ
   int              timeframe,       // период
   int              shift            // сдвиг
   );

и

double  iLow(
   string           symbol,          // символ
   int              timeframe,       // период
   int              shift            // сдвиг
   );
CopyRates - Доступ к таймсериям и индикаторам - Справочник MQL4
CopyRates - Доступ к таймсериям и индикаторам - Справочник MQL4
  • docs.mql4.com
CopyRates - Доступ к таймсериям и индикаторам - Справочник MQL4
 
Alexey Viktorov:

Declare an array of MqlRates type. Copy OHLC and other parameters of closed candlestick

and then take values High or Low from which you are 2 or 3 points away and put stops there.

You may also use

и

Thank you, but could we have at least one objective example? A view from above, so to speak. I'm a complete novice and I've been on the subject for two days :-)
 
WindUP:
Thank you, but could you give me at least one objective example? A view from above, so to speak. I'm a complete novice and I've been on the subject for two days :-)

I'm trying to learn too - I think I'm getting somewhere

//+------------------------------------------------------------------+
//|                                                    CopyRates.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property script_show_inputs
//---
sinput int    Inpcopiedrates = 2;    // какой бар
sinput double Inphigh        = 100;  // отступить от high
//---
datetime m_right_time = 0,m_left_Ctime = 0;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int copied=CopyRates(Symbol(),0,0,Inpcopiedrates,rates);
   if(copied>0)
     {
      Print("Скопировано баров: "+copied);
      string format="open = %G, high = %G, low = %G, close = %G, volume = %d";
      string out;
      int size=fmin(copied,10);
      for(int i=0; i<size; i++)
        {
         out=i+":"+TimeToString(rates[i].time);
         out=out+" "+StringFormat(format,
                                  rates[i].open,
                                  rates[i].high,
                                  rates[i].low,
                                  rates[i].close,
                                  rates[i].tick_volume);
         Print(out);
         ObjectDelete(0,"CopyRateshigh");
         m_left_Ctime=rates[i].time;
         m_right_time=TimeCurrent();
         TrendCreate(0,"CopyRateshigh",clrBlue,STYLE_DASHDOTDOT,1);
         TrendPointChange(0,"CopyRateshigh",0,m_left_Ctime,rates[i].high+Inphigh/100);
         TrendPointChange(0,"CopyRateshigh",1,m_right_time,rates[i].high+Inphigh/100);
        }
     }
   else
      Print("Не удалось получить исторические данные по символу ",Symbol());
  }
//+------------------------------------------------------------------+
//| 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 color           clr=clrRed,        // line color
                 const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
                 const int             width=1,           // line width
                 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 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);
//--- set the text
   ObjectSetString(chart_ID,name,OBJPROP_TEXT,name);
//--- 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;
  }
//+------------------------------------------------------------------+

CopyRates

Reason: