Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1217

 
Pineapple88:

Good afternoon!

I'm trying to understand arrays and have the following question.

Why useArraySetAsSeries in this example and set flag true, if inCopyRates counting is made from present to the past?

I understand, that theArraySetAsSeries function is necessary to search the array from the present to the past.

I want to understand the purpose of this function in this example.

After

ArraySetAsSeries(rates,true); 

rates[0] will correspond to the RIGHT BAR in the chart. This is the simplest explanation, without the confusing terms "present" and "future".

 
Vladimir Karputov:

After

rates[0] will correspond to the RIGHT BAR on the graph. This is the simplest explanation, without the confusing terms "present" and "future".

Thanks for the answer!

But if we don't useArraySetAsSeries, thenCopyRates will also assign rates[0] to the rightmost bar on the chart.

Just trying to understand what isArraySetAsSeriesfunction for when it works the same without it?

Or it's just an accepted form of writing code?

 
Pineapple88:

Thanks for the answer!

But if we don't useArraySetAsSeries, thenCopyRates will also assign rates[0] to the rightmost bar on the chart.

Just trying to understand whyArraySetAsSeriesfunction is needed when it works the same without it?

Or it's just an accepted form of writing code?

you are wrong, CopyRates assigns rate[0] to the oldest value due to the size of rate[] array.
 
Anatolii Zainchkovskii:
you're wrong, CopyRates assign rate[0] to the oldest value due to the size of rate[] array.

Thank you!

Now I get it, I was wrong)

 

Good afternoon!

Once again I am asking for help!

I have written a code with the condition "buy" when MA(20) crosses MA(50) from bottom to top

input int SmallMovingAverage = 20;
input int BigMovingAverage   = 50;


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {

   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

   string signal = "";

   double SmallMovingAverageArray[], BigMovingAverageArray[];

   int SmallMovingAverageDefinition = iMA(_Symbol,_Period,SmallMovingAverage,0,MODE_SMA,PRICE_CLOSE);
   int BigMovingAverageDefinition   = iMA(_Symbol,_Period,BigMovingAverage,0,MODE_SMA,PRICE_CLOSE);

   CopyBuffer(SmallMovingAverageDefinition,0,0,3,SmallMovingAverageArray);
   CopyBuffer(BigMovingAverageDefinition,0,0,3,BigMovingAverageArray);

   if(BigMovingAverageArray[1] < SmallMovingAverageArray[1])
   if(BigMovingAverageArray[2] > SmallMovingAverageArray[2])
        {
         Print("buy");
        }
  }

But in fact it executes like this

Files:
n2b3h1.png  140 kb
 
Pineapple88:

Good afternoon!

Once again I am asking for help!

I have written a code with the condition "buy" when MA(20) crosses MA(50) from bottom to top

But in fact it is done like this

Gross error: You create two indicator handles on every tick. The correct way to do it is to

   int SmallMovingAverageDefinition = iMA(_Symbol,_Period,SmallMovingAverage,0,MODE_SMA,PRICE_CLOSE);
   int BigMovingAverageDefinition   = iMA(_Symbol,_Period,BigMovingAverage,0,MODE_SMA,PRICE_CLOSE);

move to OnInit, add a check of the handle correctness.


Also arrays that take values from IMA must be made

ArraySetAsSeries(SmallMovingAverageArray,true);  
ArraySetAsSeries(BigMovingAverage,true)
Основы тестирования в MetaTrader 5
Основы тестирования в MetaTrader 5
  • www.mql5.com
Идея автоматической торговли привлекательна тем, что торговый робот может без устали работать 24 часа в сутки и семь дней в неделю. Робот не знает усталости, сомнений и страха,  ему не ведомы психологические проблемы. Достаточно четко формализовать торговые правила и реализовать их в виде алгоритмов, и робот готов неустанно трудиться. Но прежде...
 

Thank you very much for your prompt reply!

I understand aboutArraySetAsSeries.

I will try to figure out how to move indicator to OnInit, and check the handle.

***

 
Pineapple88:

Thank you very much for your prompt reply!

I understand aboutArraySetAsSeries.

I will try to figure out how to move indicator to OnInit, and check the handle.

***

Everything is there from the beginning

  • in documentation:iMA
  • MetaEditor - Expert Advisor [data folder]MQL5\Experts\Examples\Moving Average\Moving Average.mq5
Документация по MQL5: Технические индикаторы / iMA
Документация по MQL5: Технические индикаторы / iMA
  • www.mql5.com
//|                                                     Demo_iMA.mq5 | //|                        Copyright 2011, MetaQuotes Software Corp. | //|                                             https://www.mql5.com | //| Перечисление способов создания хэндла                            |  Creation             type=Call_iMA;                ...
 
Vladimir Karputov:

It's all there from the beginning.

  • in the documentation:iMA
  • in MetaEditor - EA [data folder]MQL5\Experts\Examples\Moving Average\Moving Average.mq5

Thanks, I will study

 

Fixed it, everything seems to be working!)

I transferred two MA indicators to the OnInit function.

I understand that we create only the indicator handle in the OnInit function and perform all other manipulations with the arrays in the OnTick function and check it on every tick?

int SmallMovingAverageDefinition = 0;
int BigMovingAverageDefinition   = 0;
input int SmallMovingAverage = 20;
input int BigMovingAverage   = 50;


int OnInit()
  {
//---
   SmallMovingAverageDefinition = iMA(_Symbol,_Period,SmallMovingAverage,0,MODE_SMA,PRICE_CLOSE);
   BigMovingAverageDefinition   = iMA(_Symbol,_Period,BigMovingAverage,0,MODE_SMA,PRICE_CLOSE);

   if(SmallMovingAverageDefinition==INVALID_HANDLE  || BigMovingAverageDefinition==INVALID_HANDLE)
     {
      Print("Ошибка создания хендла");
     }
//---
   return(INIT_SUCCEEDED);
  }


void OnDeinit(const int reason)
  {
//---

  }


void OnTick()
  {

   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);

   string signal = "";

   double SmallMovingAverageArray[], BigMovingAverageArray[];

   ArraySetAsSeries(SmallMovingAverageArray,true);
   ArraySetAsSeries(BigMovingAverageArray, true);

   CopyBuffer(SmallMovingAverageDefinition,0,0,3,SmallMovingAverageArray);
   CopyBuffer(BigMovingAverageDefinition,0,0,3,BigMovingAverageArray);

   if(SmallMovingAverageArray[1] > BigMovingAverageArray[1])
      if(SmallMovingAverageArray[2] < BigMovingAverageArray[2])
        {
         Print("buy");
        }
  }
Документация по MQL5: Основы языка / Функции / Функции обработки событий
Документация по MQL5: Основы языка / Функции / Функции обработки событий
  • www.mql5.com
В языке MQL5 предусмотрена обработка некоторых предопределенных событий. Функции для обработки этих событий должны быть определены в программе MQL5: имя функции, тип возвращаемого значения, состав параметров (если они есть) и их типы должны строго соответствовать описанию функции-обработчика события. Именно по типу возвращаемого значения и по...
Reason: