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

 

Good internet and good health to all.


Question, what am I doing wrong? The arrays (STATIC) are filled in, but the calculation gives 0 (zero). Can you tell me what I don't have in my code? Why the array elements are not being compared and added...? Thanks


 double Open[60],High[60],Lo[60,Close[60]; int to_copy=60;
if(CopyOpen(NULL,PERIOD_H4,1,to_copy,Open)<to_copy)return(0);
   if(CopyHigh(NULL,PERIOD_H4,1,to_copy,High)<to_copy)return(0);
   if(CopyLow(NULL,PERIOD_H4,1,to_copy,Low)<to_copy)return(0);
   if(CopyClose(NULL,PERIOD_H4,1,to_copy,Close)<to_copy)return(0);
//----   
   //int start=to_copy*PeriodSeconds(PERIOD_H4)/PeriodSeconds(_Period);
   int start=to_copy;
   
   if(Tf==true)
     {
      if(prev_calculated==0)
         for(int j=1; j<=start; j++)
           {
            if(Open[j]>Close[j])
               candle+=Open[j]-Close[j];
            if(Close[j]>Open[j])
               candle+=Close[j]-Open[j];
            candleHL+=High[j]-Low[j];
            br+=1;
           } //for 
Comment(High[10],". ",candle);
candle дает результат 0 ноль
 
kopeyka2:

Good internet and good health to all.


Question, what am I doing wrong? The arrays (STATIC) are filled in, but the calculation gives 0 (zero). Can you tell me what I don't have in my code? Why the array elements are not being compared and added...? Thanks


1) The loop goes beyond the array - if the buffer size is 60, the last index is 59, because the first index is 0

2) The code is not complete - e.g. how is Tf defined and what was candle initialised with?


* when copying prices the indexing is shifted by one, because you copy 60 elements starting from the first index, i.e. prices of the first closed bar will already be under index 0

 

How the function works

IsStopped();

... and what list of tasks does it perform?


In help it is written - "Checks forced termination of mql5-program". That is, it sort of "looks" at some number of lines of code ahead and checks if anything is correct? How is its area of responsibility set (e.g. per line or 10 lines)?


I thought it only prevents the loop from going beyond the array, but I saw it back in the FAMA code before copying High and Low prices

 
Alexandr Sokolov:

How the function works

... and what list of tasks does it perform?


In help it is written - "Checks forced termination of mql5-program". That is, it sort of "looks" at some number of lines of code ahead and checks if anything is correct? How is its area of responsibility set (e.g. per line or 10 lines)?


I thought it only prevents the loop from going beyond the array, but I saw it still in the FAMA code before copying prices High and Low

It doesn't look anywhere... It's clearly written there. It checks the flag... Reread it.

Документация по MQL5: Проверка состояния / IsStopped
Документация по MQL5: Проверка состояния / IsStopped
  • www.mql5.com
Возвращает true, если в системной переменной _StopFlag содержится значение, отличное от 0. Ненулевое значение записывается в переменную _StopFlag, если поступила команда завершить...
 
Alexandr Sokolov:

How the function works

... and what list of tasks does it perform?


In help it is written - "Checks forced termination of mql5-program". That is, it sort of "looks" at some number of lines of code ahead and checks if anything is correct? How is its area of responsibility set (e.g. per line or 10 lines)?


I thought it only prevents the loop from going beyond the array, but I saw it in the FAMA code before copying the High and Low prices

if a stop of an MQL-program takes place, the _StopFlag will be set, and it can be checked either using a predefined variable or the IsStopped() function - whatever is convenient, use it that way.

after setting _StopFlag , MQL-program has a little time to stop, and then the terminal forcibly unloads it

the most widespread use - looped scripts, you should not

while(true)
{
...
}

it is better to write it this way:

while(!IsStopped())
{
...
}

well, sometimes in cost calculations or in large cycles they use

for(int i=0; i<1 e6 && !IsStopped(); i++)
{

}
 

Hi all.

Can you tell me if it's possible to loop through variables with names: L1, L2, L3 ... Ln to write to a two-dimensional array

extern string L1       = "1.15110;1.14105;1.13240;1.12370;1.11640;1.11170;1.10655;1.09895;1.08850;1.07850;1.06475;";
extern string L2       = "1.32130;1.31030;1.29860;1.29042;1.27985;1.25605;1.24725;1.23565;1.22505;1.20815;1.20115;1.18850;1.16690;1.14465;"; 
extern string L3       = "0.94947;0.93222;0.91472;0.90077;0.89075;0.88658;0.86814;0.84687;0.82795;0.81132;0.79022;0.75976;"; 

...

extern string Ln      = " ... ";    
 
Alexandr Sokolov:

1) The loop has an array overrun - if the buffer size is 60, then the last index will be 59, as the first index is 0

2) The code is not complete - e.g. how is Tf defined and what was candle initialised with?


* when copying prices the indexing is shifted by one, as you copy 60 elements starting from the first index, i.e. the prices of the first closed bar will already be under index 0

THANK YOU for your reply. Full code. Increased the static size of the array. Removed zero control entry in operators. Common "dummy". I'm still trying to figure out WHY it's not adding. What's not in my code now? Thanks for the tips. I haven't worked with static arrays in mql5 yet.....

I UPDATED THE CODE. The question is the same...

//+------------------------------------------------------------------+
//|                                                          123.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, "
//---- номер версии индикатора
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 0
#property indicator_plots   0
//----
input int       nBars = 20;
//----
int    limit=0,br=0,to_copy=nBars;
double corrHL,corrOC;
double averpips,averpipsH;
double candle,candleHL;
double opn,hgh,lw,cls;
double Open[65],High[65],Low[65],Close[65];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   
   Comment("");
  }
//+------------------------------------------------------------------+
//| 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(CopyOpen(NULL,PERIOD_H4,0,to_copy,Open)<to_copy)
      return(0);
   if(CopyHigh(NULL,PERIOD_H4,0,to_copy,High)<to_copy)
      return(0);
   if(CopyLow(NULL,PERIOD_H4,0,to_copy,Low)<to_copy)
      return(0);
   if(CopyClose(NULL,PERIOD_H4,0,to_copy,Close)<to_copy)
      return(0);
     int indexmass=ArraySize(Open);
//----
   if(Tf==true)
     {
      if(prev_calculated==0)
         for(int j=1; j<=to_copy; j++) // поменять на ноль?????
           {
            opn=Open[j];
            hgh=High[j];
            lw=Low[j];
            cls=Close[j];
            if(opn>cls)
               candle+=opn-cls;
            if(cls>opn)
               candle+=cls-opn;
            candleHL+=hgh-lw;
            br+=1;
           } //for j
      if(br>0)
        {
         averpips=candle/br;
         averpips=NormalizeDouble(averpips,_Digits);
         averpipsHL=candleHL/br;
         averpipsHL=NormalizeDouble(averpipsHL,_Digits);
        }
      }
   Comment("indexmass  ",indexmass,"  Open ",Open[10],"  candle  ",candle,"  averpipsHL ",averpipsHL);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
Comment("indexmass  ",indexmass,"  Open ",Open[10],"  candle  ",candle,"  averpips ",averpips);
The values of the array elements are greater than zero. In calculations, zero
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
  • www.mql5.com
Допускается объявление не более чем 4-мерного массива. При объявлении динамического массива (массива с неуказанным значением в первой паре квадратных скобок) компилятор автоматически создает переменную указанной выше структуры (объект динамического массива) и обеспечивает код для правильной инициализации.   Статические массивы При явном...
 
stepystr:

Hi all.

Can you tell me if it's possible to loop through variables with names: L1, L2, L3 ... Ln to write into a two-dimensional array

deleted the post - you know about arrays

but still not possible

as an option to write a macro substitution, write a specific example - maybe someone will write a macro to your task, I'm bad at writing macros.

 

People!!! (Hint ... )))

Full code. Increased static array size. Removed write zero control in operators... Common "dummy". Still want to understand WHY it doesn't count addition. What is missing in my code now? Thanks for the tips. I haven't worked withstatic arrays in mql5 yet.....

I UPDATED THE CODE. The question is the same...

The values of the array elements are greater than zero. In calculations, zero
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
  • www.mql5.com
Допускается объявление не более чем 4-мерного массива. При объявлении динамического массива (массива с неуказанным значением в первой паре квадратных скобок) компилятор автоматически создает переменную указанной выше структуры (объект динамического массива) и обеспечивает код для правильной инициализации.   Статические массивы При явном...
 
kopeyka2:

THANK YOU for the reply. Full code. Increased static array size. Removed zero control entry in operators... Common "dummy". I'm still trying to figure out WHY it's not adding. What is missing in my code now? Thanks for the tips. I haven't worked with static arrays in mql5 yet.....

I UPDATED THE CODE. The question is the same...

I am not familiar with indicators, but it's just unnecessary. I already have it ))))

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(CopyOpen(NULL,PERIOD_H4,0,to_copy,Open)<to_copy)
      return(0);
   if(CopyHigh(NULL,PERIOD_H4,0,to_copy,High)<to_copy)
      return(0);
   if(CopyLow(NULL,PERIOD_H4,0,to_copy,Low)<to_copy)
      return(0);
   if(CopyClose(NULL,PERIOD_H4,0,to_copy,Close)<to_copy)
      return(0);
     int indexmass=ArraySize(Open);