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

 
mwwm:

how to do it properly?

How do you do it?
 
Artyom Trishkin:
How do you do it?
int OnCalculate(const int rates_total, 
                const int prev_calculated, 
                const datetime &time[], 
                const double &Op[], 
                const double &Hi[], 
                const double &Lo[], 
                const double &Cl[], 
                const long &tick_volume[], 
                const long &volume[], 
                const int &spread[]) 
  { 
   ArraySetAsSeries(time,true); 
   ArraySetAsSeries(Op,true); 
   ArraySetAsSeries(Hi,true); 
   ArraySetAsSeries(Lo,true); 
   ArraySetAsSeries(Cl,true); 
//--- 
double mas[];
   if(prev_calculated==0) 
     { 
      int prices1=CopyOpen(Symbol(),0,0,Bars(_Symbol,_Period),Op);
      int prices2=CopyHigh(Symbol(),0,0,Bars(_Symbol,_Period),Hi); 
      int prices3=CopyLow(Symbol(),0,0,Bars(_Symbol,_Period),Lo); 
      int prices4=CopyClose(Symbol(),0,0,Bars(_Symbol,_Period),Cl); 
      int prices5=CopyTime(Symbol(),0,0,Bars(_Symbol,_Period),time); 

     } 
   else 
     { 

      int prices1=CopyOpen(Symbol(),0,0,1,Op);
      int prices2=CopyHigh(Symbol(),0,0,1,Hi); 
      int prices3=CopyLow(Symbol(),0,0,1,Lo); 
      int prices4=CopyClose(Symbol(),0,0,1,Cl);     
      int prices5=CopyTime(Symbol(),0,0,1,time);     
       }   
      for(int i=rates_total-1;i>=0 && !IsStopped();) {
      mas[i]=Op[i]/Cl[i];
      i--;
      }
   
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+-------------------------------

Simplified so, CopyOpen I understand is superfluous for OnCalculate, but so it only sees the history from the terminal window?

 
mwwm:

Simplified, CopyOpen is unnecessary for OnCalculate, but so it sees only the history from the terminal window?

Array mas is created with zero size on every tick and doesn't change its size anywhere else. So any access to it will cause array overrun.

To solve the problem, we should either resize it to the size, that will contain readings of all history bars, or bind it to the indicator buffer (declared as a global variable of the program). If I understand correctly, these values should be displayed using the indicator.

 
mwwm:

Simplified, CopyOpen I understand is superfluous for OnCalculate, but so it only sees the history from the terminal window?

Example:

//+------------------------------------------------------------------+
//|                                                         Test.mq5 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                             https://mql5.com/ru/users/artmedia70 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018, MetaQuotes Software Corp."
#property link      "https://mql5.com/ru/users/artmedia70"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
//--- plot OC
#property indicator_label1  "Open/Close"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- indicator buffers
double         BufferOC[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- Задаём массив BufferOC как буфер индикатора
   SetIndexBuffer(0,BufferOC,INDICATOR_DATA);
//--- Устанавливаем ему направление индексации как у таймсерии
   ArraySetAsSeries(BufferOC,true);
//---
   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(rates_total<1) return 0;
//--- Установка массивов буферов как таймсерий
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(close,true);
//--- Проверка и расчёт количества просчитываемых баров
   int limit=rates_total-prev_calculated;
   if(limit>1) // если это первый запуск, или изменение истории, или открытие нового бара
     {
      limit=rates_total-1;                   // установим начало цикла на начало исторических данных
      ArrayInitialize(BufferOC,EMPTY_VALUE); // инициализируем массив
     }
//--- Расчёт индикатора
   for(int i=limit; i>=0 && !IsStopped(); i--)
     {
      if(close[i]==0) continue;
      BufferOC[i]=open[i]/close[i];
     }

//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
Ihor Herasko:

The mas array is created with a zero size on every tick and does not change its size anywhere else. Therefore, any reference to it will cause exit from the array.

To solve the problem, you should either resize it to the size that will contain readings of all history bars, or bind it to the indicator buffer (declared as a global variable of the program). If I understand correctly, it is these values that must be displayed using the indicator.

My mistake, mas[] should really be a global array, but the indicator buffer is not suitable either, it will rather be an intermediate multidimensional array. What is the best way to determine the optimal array size for M5, not through indicator buffer?

 
mwwm:

My inaccuracy, mas[] is really a global array, but indicator buffer is not suitable either, rather it would be an intermediate multidimensional array. What's the best way to determine optimal array size for M5, not through indicator buffer?

I don't understand what I mean by multidimensional. We are speaking of a one-dimensional array. In addition, in MQL4 the maximum dimension of an array is 4.

To make the array the same size as the timeseries, we should resize it according to the number of bars available on the chart for the needed symbol and period:

double fArray[];
int nBarsCnt = iBars(<символ>, <таймфрейм>);
if (ArrayResize(fArray, nBarsCnt) != nBarsCnt)
{
   // Не удалось изменить размер массива
   return;
}

ArraySetAsSeries(fArray, true);
 
mwwm:

My inaccuracy, mas[] is really a global array, but indicator buffer is not suitable either, rather it would be an intermediate multidimensional array. What's the best way to determine the optimal array size for M5, not through an indicator buffer?

Why don't you want to use arrays as indicator buffers? They are monitored by the subsystem, which makes your job easier.

And the intermediate indicator buffer array is easy to do:

SetIndexBuffer(1,BufferMA,INDICATOR_CALCULATIONS);
 

Hello.

The volumes on the platform are tick volumes, will there be real volumes?

 
Олег Литинский:

Hello.

On the platform the volumes are ticking, will there be any real volumes?

It won't. Use MT5, some brokers provide real volumes there.

 

Good afternoon!

Please help with the following problem:

1) After some conditions are met, a pending order opens:

{
price=High[1]+OrderPoint*Point;
stoploss=Low[1]-Point;
takeprofit=price+price-stoploss;
OrderSend(Symbol(),OP_BUYSTOP,1,price,3,stoploss,takeprofit);
}

Please tell me what to add and where to delete a pending order if price has already passed stop loss (of this pending order).

Sorry for the stupid question, I got lost in the forums while searching for an answer.

Thanks in advance!

Reason: