Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1290

 
Vitaly Muzichenko:

---

P.S. In general, there's a lot wrong with the same array, for example.

Thanks for the help and for the tip!!! This is how it compiles

//+------------------------------------------------------------------+
//|                                                        Funct.mq5 |
//|                        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"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
int UP; //Глобальная переменная

//_____________________________________Массивы для Handleлов____________________________________
double HandleFractalDown_W1[],HandleFractalUP_W1[];    // одномерный динамический массив

//_____________________________________Массивы для фракталов____________________________________
double FractalDown_W1[],FractalUP_W1[];    // одномерный динамический массив

//-----------------------------------------------------------------------------------------------
int  Fractal_W1=iFractals(Symbol(),PERIOD_W1); //Хендл индикатора

//----------------------------------------------------------------------
void OnStart()
  {
   CopyBuffer(Fractal_W1,0,TimeCurrent(),Bars(Symbol(),PERIOD_W1),HandleFractalUP_W1);   // заполнение масива FractalUp[] верхними фракталами на дневном графике
   CopyBuffer(Fractal_W1,1,TimeCurrent(),Bars(Symbol(),PERIOD_W1),HandleFractalDown_W1); // заполнение масива FractalUp[] нижними фракталами на дневном графике
//--- индексация как в таймсериях
   ArraySetAsSeries(FractalUP_W1,true);  //Заполнение массива FractalUp[],FractalDown, нулевым баром в первом окне массива и далее по порядку убывания от нулевого в тайм-серии
   ArraySetAsSeries(FractalDown_W1,true);//Второй параметр -true- функции ArraySetAsSeries Устанавливает флаг индексации как в таймсериях.

  Search_Fractal(PERIOD_W1, HandleFractalUP_W1, FractalUP_W1); //Пользовательская функция заполнения массива FractalUP_W1 значениями
                                                               //верхних фракталов  

  }
//+------------------------------------------------------------------+

//+-----------------------Функция заполнения массива-------------------------------------------+
void Search_Fractal(ENUM_TIMEFRAMES period, double &handle[], double &fract_mass[])
  {
   UP = 0;                      //Глобальная переменная
   int i=Bars(Symbol(),period); //Колличество баров на W1 графике
   
   for(int n=0; n< i; n++)
     {
      //--- если непустое значение, пишем в массив fract_mass[UP] цену фрактала
      if(handle[n]!=EMPTY_VALUE)
        {
         UP++;
         fract_mass[UP] = handle[n];
        }
     }
  }
//+------------------------------------------------------------------+
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
  • 2021.02.13
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
 
Tweaked a bit, almost works as needed, before 51.20 it crashes there with an error

Funct array (BRN, W1) out of range

//+------------------------------------------------------------------+
//|                                                        Funct.mq5 |
//|                        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"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
int UP; //Глобальная переменная

//_____________________________________Массивы для Handleлов____________________________________
double HandleFractalDown_W1[],HandleFractalUP_W1[];    // одномерный динамический массив

//_____________________________________Массивы для фракталов____________________________________
double FractalDown_W1[],FractalUP_W1[];    // одномерный динамический массив

//-----------------------------------------------------------------------------------------------
int  Fractal_W1=iFractals(Symbol(),PERIOD_W1); //Хендл индикатора

//----------------------------------------------------------------------
void OnStart()
  {
   CopyBuffer(Fractal_W1,0,TimeCurrent(),Bars(Symbol(),PERIOD_W1),HandleFractalUP_W1);   // заполнение масива FractalUp[] верхними фракталами на дневном графике
   CopyBuffer(Fractal_W1,1,TimeCurrent(),Bars(Symbol(),PERIOD_W1),HandleFractalDown_W1); // заполнение масива FractalUp[] нижними фракталами на дневном графике
//--- индексация как в таймсериях
   ArraySetAsSeries(HandleFractalUP_W1,true);  //Заполнение массива FractalUp[],FractalDown, нулевым баром в первом окне массива и далее по порядку убывания от нулевого в тайм-серии
   ArraySetAsSeries(HandleFractalDown_W1,true);//Второй параметр -true- функции ArraySetAsSeries Устанавливает флаг индексации как в таймсериях.

  Search_Fractal(PERIOD_W1, HandleFractalUP_W1, FractalUP_W1); //Пользовательская функция заполнения массива FractalUP_W1 значениями
                                                               //верхних фракталов  
  }
//+------------------------------------------------------------------+



//+-----------------------Функция заполнения массива-------------------------------------------+
void Search_Fractal(ENUM_TIMEFRAMES period, double &handle[], double &fract_mass[])
  {
   UP = 0;                      //Глобальная переменная
   int i=Bars(Symbol(),period); //Колличество баров на W1 графике

   for(int n=0; n< i; n++)
     {
      //--- если непустое значение, пишем в массив fract_mass[UP] цену фрактала
      if(handle[n]!=EMPTY_VALUE)
        {
         UP++;
         fract_mass[UP] = handle[n];
         Alert("Frakt= ",fract_mass[UP]);
        }
     }
  }
//+------------------------------------------------------------------+
What can it be?
 
Kira27:
I just tweaked it a bit and it works just fine, before 51.20 it crashes with an error

Funct array (BRN, W1) outside allowed range

What can it be?

Try it this way, you have not set the dimensionality of the array

void Search_Fractal(ENUM_TIMEFRAMES period, double &handle[], double &fract_mass[])
  {
   UP = 0;                      //Глобальная переменная
   int i=Bars(Symbol(),period); //Колличество баров на W1 графике
   ArrayResize(fract_mass,i+1);
   for(int n=0; n< i; n++)
     {
      //--- если непустое значение, пишем в массив fract_mass[UP] цену фрактала
      if(handle[n]!=EMPTY_VALUE)
        {
         UP++;
         fract_mass[UP] = handle[n];
         Alert("Frakt= ",fract_mass[UP]);
        }
     }
  }

In general, this is not a good solution

 
Kira27:
Tweaked it a bit, almost works as needed, before 51.20 there crashes with an error

Funct array (BRN, W1) out of range

What can it be?

The line that solved the crash.

 ArrayResize(handle,i,0);//*------Строчка решившая проблему
//+-----------------------Функция заполнения массива-------------------------------------------+
void Search_Fractal(ENUM_TIMEFRAMES period, double &handle[], double &fract_mass[])
  {
   UP = 0;                      //Глобальная переменная
   int i=Bars(Symbol(),period); //Колличество баров на W1 графике

//***************************
   ArrayResize(handle,i,0);//*------Строчка решившая проблему
//***************************

   for(int n=0; n< i; n++)
     {
      //--- если непустое значение, пишем в массив fract_mass[UP] цену фрактала
      if(handle[n]!=EMPTY_VALUE)
        {
         UP++;
         fract_mass[UP] = handle[n];
         Alert("Frakt= ",fract_mass[UP]);
        }
     }
  }
//+------------------------------------------------------------------+

Correct now? Correct if you don't mind.

 
Kira27:
Tweaked it a little bit, it's almost working as it should, up to 51.20 there it crashes with an error.

Funct array (BRN, W1) outside allowed range

What can it be?

At the same time, you copy a certain number of elements into the HandleFractalUP_W1 array, but you don't control exactly how many.

Then loop through int i=Bars(Symbol(),period); //Number of bars on W1 chart

As the result, you will again get an exit outside the array, but inhandle[n]

Work out some of the filling logic, take your time.

----

Kira27:

The line that solved the crash.

Is it correct now? Correct it if you don't mind.

It's so complicated, but you'll get it right.

 
Kira27:

The line that solved the crash problem

Is that right now? Correct it if you don't mind.

The only thing is that there are fewer fractals than bars in the weekly chart window, and when filling the array with price values of fractals, only 90 cells are filled, and the rest of the memory layout is redundant So, you should first calculate the number of fractals, and only then apply ArrayResize for memory reservation?

 
Vitaly Muzichenko:

At the same time, you copy a certain number of elements into the HandleFractalUP_W1 array, but you don't control exactly how many.

Then loop through int i=Bars(Symbol(),period); //Number of bars on W1 chart

As the result, you will again get an exit outside the array, but inhandle[n]

Work out some of the filling logic, take your time.

----

It's so complicated, but you'll get it right.

Thank you!!!

 

Good afternoon, all. Please help me understand why I can't get the volume history. Tried to do it in 2 ways.

First way:

MqlRates mrate5[];

if(CopyRates(_Symbol,PERIOD_M5,1,bars_used,mrate5)<0)

{

Alert("Error in copying historical data for M5 - error:",GetLastError(),"!!");

return;

}

for (int i=0;i<bars_used;i++) {

Print(mrate5[i].real_volume)

}

Second way:

long volumes5[];

if(CopyRealVolume(_Symbol,PERIOD_M5,1,bars_used,volumes5)<0)

{

Alert("Copy volumes error for M5 - error:",GetLastError(),"!");

return;

}

for (int i=0;i<bars_used;i++) {

Print(volumes5[i])

}

In both cases, the array of volumes always contains only zeros. You just cannot get any meaningful information...


 
seleand:

Good afternoon, all. Please help me understand why I can't get the volume history. Tried to do it in 2 ways.

First way:

MqlRates mrate5[];
      if(CopyRates(_Symbol,PERIOD_M5,1,bars_used,mrate5)<0)
        {
            Alert("Ошибка копирования исторических данных для М5 - ошибка:",GetLastError(),"!!");
            return;
        }
for (int i=0;i<bars_used;i++) {
Print(mrate5[i].real_volume)
}

The second way:

long volumes5[];
      if(CopyRealVolume(_Symbol,PERIOD_M5,1,bars_used,volumes5)<0)
        {
            Alert("Ошибка копирования объемов для М5 - ошибка:",GetLastError(),"!!");
            return;
        }
for (int i=0;i<bars_used;i++) {
Print(volumes5[i])
}

In both cases, the volume array always contains only zeros. I just can't get any meaningful information...


  1. Learn how to insert code.
  2. In forex, there are no real volumes at all.
 

Thank you. Do I understand correctly that there is a tick volume?

When I downloaded the quote history for forex from finam site, there was vol in addition to open, high, low, close. You didn't say exactly what volume it was. This is a tick volume?

Reason: