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

 

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.

Example with three variables (in fact there are more variables, it's cumbersome):

//+------------------------------------------------------------------+
//|                                                            1.mq4 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

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;";

//Надо: Вместо rsLevels[] задать двухмерный массив

string rsLevels[]; 

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{

//Надо: Перебрать в цикле переменные L1, L2, L3 и записать в двухмерный массив 

 L1 = StringTrimLeft(StringTrimRight(L1));
 
 if(StringSubstr(L1, StringLen(L1)-1, 1) != ";")
  L1 = StringConcatenate(L1, ";");

 int s = 0,i = StringFind(L1, ";", s);
 string current;
 
 while(i>0)
 
 {
 
  current=StringSubstr(L1, s, i - s);
  
  ArrayResize(rsLevels, ArraySize(rsLevels) + 1);
  
  rsLevels[ArraySize(rsLevels) - 1] = current;
  
  s = i + 1;
  
  i = StringFind(L1,";",s);
  
 }
 
//---------------------------------------------------------

 for(int x=0; x<ArraySize(rsLevels); x++)
  
 {

  Print(rsLevels[x]); 
   
 }
 
 return(INIT_SUCCEEDED);
}
 
kopeyka2:

THANK YOU for the reply. Full code. Increased static array size. Removed zero control entry 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 with static arrays in mql5 yet.....

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

here are errors when compiling your code


 
stepystr:

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.

Example with three variables (in fact, there are more variables, it's cumbersome):

Of course, the topic is "crooked" (in MQL4 and MQL5), so it would be good to specify the platform to which the question is addressed ))))

 
stepystr:

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.

Example with three variables (in fact there are more variables, it's cumbersome):

First, we need to decide on the number of values in the second dimension of the future array. Already now we can see that the number of elements is not equal. Probably, we should take maximal one, and where there are redundant ones we should fill with zeros or -1, for example. And it wouldn't hurt to define the first dimension beforehand if it is known. And then in the nested loop take L1 and write everything you need into the array, then the second iteration of the outer loop writes into the next index everything in L2 and so on.


And quite correctly, it's better to stick it in a structure.

 struct name
   {
    double L1[];
    double L2[];
    double Ln[];
   }arr[];
Then the array will be able to change dimension in the first and in the second dimension. That is, it will be a one-dimensional array in a one-dimensional array.
 
Alexandr Sokolov:

here are errors when compiling your code


It was me who shortened the code and Tf - I just didn't notice it. The question is fundamental, why elements from static array are not processed for calculation?

Here I have checked, compilation without errors))) Calculation result is the same - NULL !!! arrays open[], close[] etc - not so important....

//+------------------------------------------------------------------+
//|                                                          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;
input double    CorrectorHL = 1.0;           //Корректор HL фильтрации размера свечи
input double    CorrectorOC = 1.0;           //Корректор OC фильтрации размера свечи
input color     ColorLines = clrLime;        //Цвет линий
input bool      Tf = false;
//----
int    limit=0,br=0,to_copy=0;
double corrHL,corrOC;
double averpips,averpipsHL,coeff;
double filterOC,filterHL,candle,candleHL;
double opn,hgh,lw,cls;
double Open[65],High[65],Low[65],Close[65];
double level_1,level_2,level_3;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0,"UP Period ");
   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(CorrectorHL<=0)
      corrHL=1;
   else
      corrHL=CorrectorHL;
   if(CorrectorOC<=0)
      corrOC=1;
   else
      corrOC=CorrectorOC;
//----
   if(nBars<0)
      to_copy=6;
   else
      to_copy=nBars;
      //+------------------------------------------------------------------+
//| Поиск события и установка меток  на графике                      |
//+------------------------------------------------------------------+
   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=0; 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);
         filterOC=averpips;
         filterHL=averpipsHL;
        }
     
     }
   Comment("indexmass  ",indexmass,"  Open ",Open[10],"  candle  ",candle,"  averpips ",averpips);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
It's even.
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
  • www.mql5.com
Допускается объявление не более чем 4-мерного массива. При объявлении динамического массива (массива с неуказанным значением в первой паре квадратных скобок) компилятор автоматически создает переменную указанной выше структуры (объект динамического массива) и обеспечивает код для правильной инициализации.   Статические массивы При явном...
 
kopeyka2:

I was shortening the code and Tf - I just didn't notice it. The question is fundamental, why elements from static array are not processed for calculation?

Here I checked, compilation without errors))) Calculation result is the same - NULL !!! arrays open[], close[] etc - not so important....

Compilation does not check for logical errors of the programmer himself - this is left to the conscience of the programmer, because the compiler is not yet able to read minds.

 
Сергей Таболин:

Of course, the topic is "crooked" (in MQL4 and MQL5), so it would be good to specify the platform to which the question is addressed)))

MQL4.

 
Artyom Trishkin:

The compilation does not check for logical errors of the programmer himself - this is left to the conscience of the programmer, because the compiler is not yet able to read minds.

I am fundamentally looking for the reason where? in writing the existing code or is there something else in the code to process the static array?

I can't know what I don't know... So I ask an outside observer, with experience, to point out where I don't know)))
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
Документация по MQL5: Основы языка / Типы данных / Объект динамического массива
  • www.mql5.com
Допускается объявление не более чем 4-мерного массива. При объявлении динамического массива (массива с неуказанным значением в первой паре квадратных скобок) компилятор автоматически создает переменную указанной выше структуры (объект динамического массива) и обеспечивает код для правильной инициализации.   Статические массивы При явном...
 
kopeyka2:

am i principally looking for the reason where? in writing existing code or is there something else in the code to process the static array?

I can't know what I don't know... So I'm asking an outside observer with experience to point out where I don't know)))

it doesn't get to the calculations.


here's an initialization

input bool      Tf = false;


and here's a test condition

if(Tf==true)
 
Are SQLite database operations available from the tester ? I mean adding and changing data.