c++arraysloopsmqlmql5

Array out of range MQL5 loop


I am trying to loop through an array of close prices to get the rate of return of each asset. The code that I wrote is:

´´´

void Returns(MqlRates &rt[], int a_size)

{

  double rtacao[];
  ArraySetAsSeries(rtacao, true);
  ArrayResize(rtacao,(a_size-1));

  for(int i=1;i<=a_size;i++)
  {
    rtacao[i]=MathLog(rt[i].close/rt[i-1].close); 
  }
 return;

}

void OnStart()

{

 int nacoes=144; 
 string acao[];

 count_instr("ativos.txt",nacoes);
 ArrayResize(acao,nacoes);
 load_instr("ativos.txt",nacoes,acao,100);

 MqlRates rates[];
 ArraySetAsSeries(rates,true);
 ArrayResize (rates,100);


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

     SymbolSelect(acao[i],true);
     if(CopyRates(acao[i],APeriod,0,100,rates)!=100)
     {
        Print("CopyRates of ",acao[i]," failed, no history");
        //Erase(acao, i);
        //nacoes=nacoes-1;
     } else
     {
        Returns(rates, 100);
     }
  }     

}

´´´

I am getting the following error message:

2019.12.30 08:11:57.983 OnStart (IBOV,D1) array out of range in 'OnStart.mq5' (39,15)

That refers to the array - rtacao[] - in the calculation of the return. I couldn't see what I am doing wrong in the loop. Can someone help me?


Solution

  • Arrays are start counting from 0. That means the last index of an array is (array_size - 1). According to that you should use "i < a_size" instead of "i <= a_size" in your loop:

    for(int i=0;i<a_size;i++)
    {
      rtacao[i]=MathLog(rt[i].close/rt[i-1].close); 
    }
    

    But you have to consider your term rt[i-1] which would be -1 in your first run of the loop. That means you need a specification for your first run of the loop. Something like:

    for(int i=0;i<a_size;i++)
    {
      if(i==0)
         // something that happens when i is 0
      else
         rtacao[i]=MathLog(rt[i].close/rt[i-1].close); 
    }
    

    Or:

    // something that happens when i is 0
    for(int i=1;i<a_size;i++)
    {
      rtacao[i]=MathLog(rt[i].close/rt[i-1].close); 
    }