Issue in assigning values to buffers

 

Hello all!

I open this topic because I have a problem in assigning values to buffers and I didn't find a solution. 

Here is a summary of the code

#property indicator_buffers 2


double buf_1[], buf_2[];

int OnInit()
{
  if(!IndicatorBuffers(2)){Print("Error allocating memory");return INIT_FAILED;}
  
  SetIndexBuffer(0,buf_1);
  SetIndexBuffer(1,buf_2);

  SetIndexStyle(0,DRAW_ARROW,EMPTY,EMPTY,clrRed);
  SetIndexStyle(1,DRAW_ARROW,EMPTY,EMPTY,clrGreen);

  ...
  
  for(int i=Bars-2; i>=0; i--){
    if(/* some prices conditions */){
      buf_1[i]=Close[i];
      buf_2[i]=High[i];
    }
  }
  
  ...
  
  return INIT_SUCCEEDED
}

It gives me no compiling error, but if I attach the indicator on a chart, the terminal gives me an array out of range error and inside the brackets it writes the line and the column of this point (red highlighted):

...
buf_1 [i] = Close[i];
...

I tried to search in this forum other similar issues, but I didn't find anything.

I tried also to make some attempts using ArraySize(buf_1) to verify the size of the buffer (I'm not sure if it can be used ArraySize for this purpose) and it gives me always 0.

 
  1. #property indicator_buffers 2
    
      if(!IndicatorBuffers(2)){Print("Error allocating memory");return INIT_FAILED;}
    First you specify that you have two visible buffers. Then you specify that you have a total of two buffers. That second line is only necessary when you have extra buffers.

  2. int OnInit(){
      :
          buf_1[i]=Close[i];
          buf_2[i]=High[i];
    Don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:
    1. Terminal starts.
    2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
    3. OnInit is called.
    4. For indicators OnCalculate is called with any existing history.
    5. Human may have to enter password, connection to server begins.
    6. New history is received, OnCalculate called again.
    7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent and prices are valid.

  3.  for(int i=Bars-2; i>=0; i--){
    Don't recalculate all bars every tick.
              Detailed explanation of iCustom - MQL4 and MetaTrader 4 - MQL4 programming forum
 

Great! Thank you very much. Now it works properly.

 
Algosupremacy:

Great! Thank you very much. Now it works properly.

can you show the correct working script