Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1231

 

I am trying to make a simple entry. As I wanted - if open price is less than close price by the number of points (on the previous bar), then buy at the beginning of a new bar, taking into account take profit and stop loss. But something seems to be working in a different way than I wanted. Help me to understand


   MqlRates rt[1];

   if(CopyRates(_Symbol,_Period,0,1,rt)!=1)
     {
      Print("CopyRates of ",_Symbol," failed, no history");
      return;
     }
   
   ENUM_ORDER_TYPE signal=WRONG_VALUE;

      if(rt[1].open - rt[1].close >= padenie) 
	 {
         signal=ORDER_TYPE_BUY;
         printf(rt[1].open+"____"+rt[1].close);
         }
         
      if(signal !=WRONG_VALUE && TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) && Bars(_Symbol,_Period)>100)
         ExtTrade.PositionOpen(_Symbol,signal,1,SYMBOL_ASK,SymbolInfoDouble(_Symbol,SYMBOL_BID)-sl,SymbolInfoDouble(_Symbol,SYMBOL_ASK)+tp);
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Ценовые константы
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Ценовые константы
  • www.mql5.com
Технические индикаторы требуют для своих расчетов указания значений цен и/или значений объемов, на которых они будут считаться. Существуют 7 предопределенных идентификаторов перечисления ENUM_APPLIED_PRICE, для указания нужной ценовой базы расчетов. Если технический индикатор для своих расчетов использует ценовые данные, тип которых задается...
 
BorisD:

I am trying to make a simple entry. As I wanted - if open price is less than close price by the number of points (on the previous bar), then buy at the beginning of a new bar, taking into account take profit and stop loss. But something seems to be working in a different way than I wanted. Please help me to understand


Error 1: You are copying ONE item. Therefore, item index will be [0].

Open 100, Close 105 - bull bar. Open - Close = 100 - 105 = - 5. '-5' will always be lower than your set value, as the result is a negative number.

Open 110, Close 103 - bearish bar. Open - Close = 110 - 103 = 7. '7' is a positive number and this will already work correctly.


To sum it up: correct the reference to the index (instead of [1] we should refer to index [0]. Before calculating, consider the type of candle: whether it is bullish or bearish.

 

A continuation of the issue of DRAW_HISTOGRAM2 constructions.

Example:

// Индикатор Проба DRAW_HISTOGRAM2.mq5
//+------------------------------------------------------------------+
#property indicator_chart_window                   
#property indicator_buffers   20                    
#property indicator_plots     20                  

#property indicator_color1    clrOrange                
#property indicator_color2    clrOrange               
#property indicator_color3    clrLimeGreen        
#property indicator_color4    clrLimeGreen        

#property indicator_type5     DRAW_HISTOGRAM2
#property indicator_color5    clrOrange               
#property indicator_type6     DRAW_HISTOGRAM2
#property indicator_color6    clrLimeGreen        

//#property indicator_color9    clrRed                

double
   Line_High_Up[], Line_High_Dn[], Hist_High_Up[], Hist_High_Dn[],
   Line_Low_Up[],  Line_Low_Dn[],  Hist_Low_Up[],  Hist_Low_Dn[],  Line_Red[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void OnInit() 
   { 
   SetIndexBuffer     (0, Line_High_Up,      INDICATOR_DATA); 
   PlotIndexSetInteger(0, PLOT_DRAW_TYPE,    DRAW_LINE);      
   SetIndexBuffer     (1, Line_High_Dn,      INDICATOR_DATA); 
   PlotIndexSetInteger(1, PLOT_DRAW_TYPE,    DRAW_LINE);      

   SetIndexBuffer     (2, Line_Low_Up,       INDICATOR_DATA);
   PlotIndexSetInteger(2, PLOT_DRAW_TYPE,    DRAW_LINE);     
   SetIndexBuffer     (3, Line_Low_Dn,       INDICATOR_DATA);
   PlotIndexSetInteger(3, PLOT_DRAW_TYPE,    DRAW_LINE);     

   SetIndexBuffer     (4, Hist_High_Up,      INDICATOR_DATA); 
   SetIndexBuffer     (5, Hist_High_Dn,      INDICATOR_DATA);

   SetIndexBuffer     (6, Hist_Low_Up,       INDICATOR_DATA);
   SetIndexBuffer     (7, Hist_Low_Dn,       INDICATOR_DATA);

   //SetIndexBuffer     (8, Line_Red,          INDICATOR_DATA);
   //PlotIndexSetInteger(8, PLOT_DRAW_TYPE,    DRAW_LINE);     
   }
//+------------------------------------------------------------------+
//| 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[]   )                   
   {  
   int i;
   for(i=prev_calculated; i<=rates_total-1; i++)      
      {
      Line_High_Up[i] = high[i] + 50*_Point;
      Line_High_Dn[i] = high[i] + 30*_Point;
      Line_Low_Up[i]  = low[i]  - 30*_Point;
      Line_Low_Dn[i]  = low[i]  - 50*_Point;

      Hist_High_Up[i] = Line_High_Up[i];
      Hist_High_Dn[i] = Line_High_Dn[i];
      Hist_Low_Up[i]  = Line_Low_Up[i];
      Hist_Low_Dn[i]  = Line_Low_Dn[i];
      
      //Line_Red[i]     = low[i]  - 70*_Point;
      }
   return(i-1);
   }           
//+------------------------------------------------------------------+

In the presented indicator it was possible to build both histograms. An unexpected peculiarity was the following:

For normal lines in entries #property indicator_colorn, #property indicator_typen etc. the value of n is 1 more than the buffer index.
Moreover, this requirement remains even if buffer indices are not specified in a row, and there is free space between adjacent ones.
For example, if indexes 0, 1, 2, 3, 8 are used, all five lines will be displayed.

A different requirement is for DRAW_HISTOGRAM2 type constructions, namely:
If histograms are specified in a row, the entries #property indicator_colorn, #property indicator_typen etc.
n value is calculated from a count and not from a buffer index. In the example, indices 5 and 6 are specified, although logically 5 and 7 are expected.

All this nonsense makes it impossible to understand what the value of n should be for the regular line (red) following the two histograms at all.
In this example the value of n=9 is specified, but it doesn't work, so all lines relating to buffer 8 are commented out. It didn't work for other values of n either.

Conclusion: all histograms must be specified in a row at the end of buffer list. Moreover, their values should be calculated just in a row by quantitative count (despite their buffer indices).
It is impossible to understand this, but it is possible to live with it.

By the way: no effect of the order of INDICATOR_CALCULATIONS and INDICATOR_DATA buffers was detected.

Thanks to Vladimir Karputov and Artem Trishkin for their participation in solving the issue.

Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Стили рисования
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Стили рисования
  • www.mql5.com
При создании пользовательского индикатора можно указать один из 18 типов графического построения (способа отображения на главном окне графика или в подокне графика), значения которых указаны в перечислении ENUM_DRAW_TYPE. В зависимости от стиля рисования, может потребоваться от одного до четырех буферов значений (отмеченных как INDICATOR_DATA...
 
User_mt5:

A continuation of the issue of DRAW_HISTOGRAM2 constructions.

Example:

In the presented indicator it was possible to build both histograms. An unexpected peculiarity was the following:

For normal lines in entries #property indicator_colorn, #property indicator_typen etc. the value of n is 1 more than the buffer index.
Moreover, this requirement remains even if buffer indices are not specified in a row, and there is free space between adjacent ones.
For example, if indexes 0, 1, 2, 3, 8 are used, all five lines will be displayed.

A different requirement is for DRAW_HISTOGRAM2 type constructions, namely:
If histograms are specified in a row, the entries #property indicator_colorn, #property indicator_typen etc.
n value is calculated from a count and not from a buffer index. In the example, indices 5 and 6 are specified, although logically 5 and 7 are expected.

All this nonsense makes it impossible to understand what the index for the regular line (red) following the two histograms should be at all.
In this example the value n=9 is specified, but it doesn't work, so all lines relating to buffer 8 are commented out. It didn't work for other values of n either.

Conclusion: all histograms must be specified in a row at the end of buffer list. Moreover, their values should be calculated just in a row by quantitative count (despite their buffer indices).
It is impossible to understand this, but it is possible to live with it.

By the way: no effect of the order of INDICATOR_CALCULATIONS and INDICATOR_DATA buffers was detected.

Thanks to Vladimir Karputov and Artem Trishkin for their participation in the solution of the problem.

You are welcome. But you have not solved the problem.

There is no dependence on the order of the different buffer types in the indicators. Only the calculated ones should be after the ones being drawn.

 
Artyom Trishkin:

You're welcome. But you haven't solved the issue.

The indicators do not depend on the order of the different buffer types. Only the calculated ones have to be after the ones being drawn.

Without much certainty, but I still believe that both of these statements are wrong.

As for "no dependency". I didn't get any way to map the 8th buffer in the last example . What should be the order... Maybe you can do it?

About "calculated ... after drawn". My indicator uses more than 200 buffers, the first 100 of which are calculated buffers.
In my case, they are all simple lines, therefore n for #property is calculated from the buffer index value : n=b+1. And simple lines are displayed. The confusion begins with the appearance of histograms.

Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Стили рисования
Документация по MQL5: Константы, перечисления и структуры / Константы индикаторов / Стили рисования
  • www.mql5.com
При создании пользовательского индикатора можно указать один из 18 типов графического построения (способа отображения на главном окне графика или в подокне графика), значения которых указаны в перечислении ENUM_DRAW_TYPE. В зависимости от стиля рисования, может потребоваться от одного до четырех буферов значений (отмеченных как INDICATOR_DATA...
 
User_mt5:

Without much certainty, but I still believe that both of these statements are wrong.

As for "no dependency". I didn't get any way to map the 8th buffer in the last example . What should be the order... Maybe you can do it?

About "calculated ... after drawn". My indicator uses more than 200 buffers, the first 100 of which are calculated buffers.
In my case, they are all simple lines, therefore n for #property is calculated from the buffer index value : n=b+1. And simple lines are displayed. Misunderstandings start with the appearance of histograms.

I am not going to argue. I create the buffers to be drawn in absolutely any sequence. But as soon as I add a calculation buffer between them, the graphic plotting of the indicators to be drawn will not be shown on the chart. Their values remain in the data window. I have conducted many tests to describe the creation of indicators and their buffers in the articles. I came to a conclusion that only the calculated buffers (their location in the order of declaring the indicator buffers) somehow affect the displaying/not displaying of the drawn ones.

 
Artyom Trishkin:

I'm not going to argue. I create drawing buffers in absolutely any sequence. But as soon as I add a calculation buffer between them, the graphical constructions of the indicators to be drawn will not be displayed on the chart. Their values remain in the data window. I have conducted many tests to describe the creation of indicators and their buffers in the articles. I came to a conclusion that only the calculated buffers (their location in the order of declaring of indicator buffers) somehow affect the displaying/not displaying of drawn ones.

I'm not sure either.

For some time now (last 3-4 months) there have been some incomprehensible and alarming phenomena going on in the symbol window in general.

First of all, I have noticed that the drawing of the indicator can simply shift to any direction, for example down or to the right, for no apparent reason. Just at a new tick the whole indicator suddenly slides down. The same sometimes happens when the PC is first turned on.

Secondly, if some buffers are deleted and then compiled, the "traces" of these deleted constructions remain until some unexplained events (TF back and forth, new recompilation, update of settings, etc.). ) Probably, there are "traces" in data window, which are memory of long gone days (technically arrays are cleaned only forcibly, and in MT 5 if array is not needed, it is simply "unregistered", but data remains; of course, all this is MT5 glitches)
--

There's a joke: the history of our homeland is not predictable. The same can be said about MT5: too mysterious:)
--

By the way, I made some changes in my real indicator, according to my last statement. It's not working. I added DRAW_HISTOGRAM2 and INDICATOR_CALCULATIONS for reflection arrays - it works.

Просмотр и настройка графиков - Графики котировок, технический и фундаментальный анализ - Справка по MetaTrader 5
Просмотр и настройка графиков - Графики котировок, технический и фундаментальный анализ - Справка по MetaTrader 5
  • www.metatrader5.com
Графики в торговой платформе отображают изменение котировок финансовых инструментов во времени. Они необходимы для проведения технического анализа и работы советников. Они позволяют трейдерам наглядно следить за котировками валют и акций в режиме реального времени и моментально реагировать на любое изменение ситуации на финансовых рынках...
 
User_mt5:


No need to be amateurish - create the Expert Advisor blank using MQL5 Wizard - this way you will make as few errors as possible when declaring graphical constructions and indicator arrays.

 
User_mt5:

I'm not sure either.

For some time now (last 3-4 months) there are some incomprehensible and alarming phenomena happening in the symbol window in general.

First, I have noticed that the indicator construction can simply shift in any direction, e.g. down or to the right, for no apparent reason. Just at a new tick the whole indicator suddenly slides down. The same sometimes happens when the PC is first turned on.

Secondly, if some buffers are deleted and then compiled, the "traces" of these deleted constructions remain until some unexplained events (TF back and forth, new recompilation, update of settings, etc.). ) Probably, there are "traces" in data window, which are memory of long gone days (technically arrays are cleaned only forcibly, and in MT 5 if array is not needed, it is simply "unregistered", but data remains; of course, all this is MT5 glitches)
--

There's a joke: the history of our homeland is not predictable. The same can be said about MT5: too mysterious:)
--

By the way, I made some changes in my real indicator according to my last statement. It's not working. I added DRAW_HISTOGRAM2 and INDICATOR_CALCULATIONS for reflection arrays - it works.

Not about me.

The rest - your bugs and inattention (except for indicator line shift, but I think it was fixed, if memory serves me correctly).

What build do you have?

 
Vladimir Karputov:

No need to be amateurish - create an Expert Advisor blank using MQL5 Wizard - that way you will make as few errors as possible when declaring graphical constructions and indicator arrays.

Can you tell me how to correctly reflect the 8th buffer in my last example? Without any amateurism?
Can you tell me the rules?

Artyom Trishkin:

Not about me.

The rest are your mistakes and inattention (except indicator line shift, but I think it was fixed, if memory serves me correctly).

What is your build?

Can you tell me how to correctly reflect the 8th buffer in my last example? With all due care?
And give reasons?
Build 2530.

--
I'm still just learning, so I'd be extremely grateful if you gentlemen could point out where to read about all of this in the documentation.

Reason: