Simple enough, but Array Out of Range?

 

Really new to coding. MQL4 is the only thing I'm learning. Someone wrote me a code so that I could play with and experiment with some ideas I have. They did the hard stuff and created variables that represented the swing highs and swing lows on the price chart (H_Price would be a swing high price and H_Price_T would be the candle number) This way I can simply use those variables to find divergence or wave sizes and simple things like that. Well I'm trying to write a small part (excuse the inefficient coding) to simply calculate the average size of the last 5 waves. If I remove the section of code that I'm sharing here, then everything works fine. These variables have been used in other parts of the code and worked. I don't understand what I've done differently. The divergence example is the part that works fine. When I add the code underneath it to calculate the average wave size then I get the error. I would appreciate any help. Please speak to me in layman's terms - I'm practically a baby when it comes to this stuff.


Thank you in advance!

      //Divergence example:
      if(H_Price[0]>H_Price[1])
      if(H_Macd[0]<H_Macd[1])   
      {
         Line(H_Price_T[1],H_Price[1],H_Price_T[0],H_Price[0],clrBlue);                      
      }
      double wave1, wave2, wave3, wave4, wave5;  
      double currentWave;
//      bool bValidWave = FALSE;   
      double avgWave;
//      bool bBullWave = FALSE;
      
         if(H_Price_T[1] < L_Price_T[1]){       // When the variable has the _T it represents the candle number.
            wave1 = H_Price[1] - L_Price[1];    // Without the _T it represents the price.
            wave2 = H_Price[2] - L_Price[1]; 	
            wave3 = H_Price[2] - L_Price[2];
            wave4 = H_Price[3] - L_Price[2];
            wave5 = H_Price[3] - L_Price[3];            
            avgWave = ((wave1 + wave2 + wave3 + wave4 + wave5)/5)*pipValue; //pipValue = 100 or 10,000 depending on the pair
            Comment("Average Wave: " + avgWave + " pips");
            }
         else{
            wave1 = H_Price[1] - L_Price[1]; 
            wave2 = H_Price[1] - L_Price[2]; 
            wave3 = H_Price[2] - L_Price[2];
            wave4 = H_Price[2] - L_Price[3];
            wave5 = H_Price[3] - L_Price[3];
            avgWave = ((wave1 + wave2 + wave3 + wave4 + wave5)/5)*pipValue;
            Comment("Average Wave: " + avgWave + " pips");
            }  //Arrau out of range (155,41) <- not sure what the numbers mean.
 
dasilvja When I add the code underneath it to calculate the average wave size then I get the error. 

Do you really expect an answer? There are no mind readers here and our crystal balls are cracked.

  1. Always post all relevant code (using Code button). We have no idea what H_Price or L_Price is, where it is declared, or its size.
  2. You don't state what error (other than in your title). State the error and indicate what line of code.
 
William Roeder:

Do you really expect an answer? There are no mind readers here and our crystal balls are cracked.

  1. Always post all relevant code (using Code button). We have no idea what H_Price or L_Price is, where it is declared, or its size.
  2. You don't state what error (other than in your title). State the error and indicate what line of code.
The error just says Array Out of Range (155,41). That's written on the last line of the posted code (which is line 155). 

Sorry. I can post more when I get home. I've seen people only post segments of code so thought the etiquette was not to post too much. Just what is relevant. Obviously I'm struggling to know what that is. The values from the variables you mentioned are from a separate indicator. I'll post the entire code for that as well as the entire code for the EA that's written so far. 
 
William Roeder:

Do you really expect an answer? There are no mind readers here and our crystal balls are cracked.

  1. Always post all relevant code (using Code button). We have no idea what H_Price or L_Price is, where it is declared, or its size.
  2. You don't state what error (other than in your title). State the error and indicate what line of code.
#property indicator_chart_window  // I'm not sure what this is for.  Does this just open the MACD window? Does that window have to be open?
//This is just for the indicator to be drawn on the chart window; otherwise, you need to use #property indicator_separate_window
//with separate window, you are just going to have indicators drawn like RSI, oscilators or similar
#property indicator_buffers 3
#property indicator_color1  Red

extern string ____________________________________________________________ms="++++++++++ MACD Settings ++++++++++";
extern int fast_ema_period=12;//Fast EMA Period  
extern int slow_ema_period=26;//Slow EMA Period
extern int signal_period=9;//Signal Period

double Peak[];
double up[],dn[];

int init(){
   IndicatorBuffers(3);  // A buffer is an array for each line used in an indicator?  Could you explain the SetIndex area below?
   //Buffer are the values used for the indicator to be shown in the DATA (you may use less, more or none, that's depending on the DATA you need.
   
   SetIndexBuffer(0,Peak); //Naming the buffer array
   SetIndexStyle (0, DRAW_SECTION);//Type of drawn, this case we need "zig zag" type
   SetIndexEmptyValue(0,0.0);//Just setting the empty
   
   
   SetIndexBuffer(1,up); 
   SetIndexStyle (1, DRAW_NONE);
   SetIndexEmptyValue(1,0.0);
   
   SetIndexBuffer(2,dn); 
   SetIndexStyle (2, DRAW_NONE);
   SetIndexEmptyValue(2,0.0);

   return(0);
}

// Remove the lines that were drawn with the indicator when the indicator is removed.

int deinit(){
for(int i=ObjectsTotal()-1;i>=0;i--)
   if(StringFind(ObjectName(i),"Line",0)!=-1) ObjectDelete(ObjectName(i));
   return(0);
}

// Create the global variables
datetime PrevBullish=0;
datetime PrevBearish=0;

// Run the Indicator
int start(){
   int counted_bars=IndicatorCounted(); // IndicatorCounted counts how many bars the indicator has gone over so far?
   //Yes, to avoid extra calculations. Sometimes you need to go over previous bars, sometimes no. This entry just indicates 0 if the indicator
   //has started, or the number of new bars the indicator has not calculated. For example, if you have the indicator running and you lose internet connection
   //after X bars you gain the connection, then this value will say the indicator than there are new X bars than has not been calculated yet
   if(counted_bars < 0) return(-1);
   int limit = Bars - counted_bars;  // This determines how many bars back the indicator will cover?
   //Yeah; the line bellow it's just something I add because that way, I avoid posible bugs you can have near the firsts bars of the chart. 
   //if you have indicators with periods 200 for example, I recommend you to remplace 10 by 200, because that way, the first 200 bars, when 
   //starting, won't be calculated.
   if(limit>Bars-10) limit=Bars-10;

   for(int i=limit;i>0;i--){
      double MacdMain=iMACD(NULL,0,fast_ema_period,slow_ema_period,signal_period,PRICE_CLOSE,MODE_MAIN,i);
      double MacdMain_1=iMACD(NULL,0,fast_ema_period,slow_ema_period,signal_period,PRICE_CLOSE,MODE_MAIN,i+1);
      double MacdSignal=iMACD(NULL,0,fast_ema_period,slow_ema_period,signal_period,PRICE_CLOSE,MODE_SIGNAL,i);
      double MacdSignal_1=iMACD(NULL,0,fast_ema_period,slow_ema_period,signal_period,PRICE_CLOSE,MODE_SIGNAL,i+1);
      
      bool NewZone=false;
      
      // MACD crosses up
      if(MacdMain>MacdSignal && MacdMain_1<MacdSignal_1){
         PrevBullish=Time[i];    //PrevBullish/PrevBearish are global variables so they can be used in different IF loops.
         NewZone=true;
      }
      
      // MACD crosses down
      if(MacdMain<MacdSignal && MacdMain_1>MacdSignal_1){
         PrevBearish=Time[i];
         NewZone=true;
      }
      
      // Findind peaks
      if(NewZone){   // Every time NewZone is true, PrevBullish & PrevBearish have a new value. Between each new value the HH or LL are located.
         int Peak_Bar=0;
         
         if(PrevBullish<PrevBearish){
            int j=iBarShift(NULL,0,PrevBearish,false);
            int k=iBarShift(NULL,0,PrevBullish,false);
            Peak_Bar=iHighest(NULL,0,MODE_HIGH,k-j,j);
            Peak[Peak_Bar]=High[Peak_Bar];
            up[Peak_Bar]=Peak[Peak_Bar];
         }
         
         if(PrevBullish>PrevBearish){
            int j=iBarShift(NULL,0,PrevBullish,false);
            int k=iBarShift(NULL,0,PrevBearish,false);
            Peak_Bar=iLowest(NULL,0,MODE_LOW,k-j,j);
            Peak[Peak_Bar]=Low[Peak_Bar];
            dn[Peak_Bar]=Peak[Peak_Bar];
         }
         
      }
   }

 return(0);  
}

Above is the code for the indicator that he created for me. Don't mind the comments. I'm just asking questions about it to him. Below is the code for the EA. Again, there are some comments and questions for him. Some things are just notes so I know what's going on. You can tell by the nature of the comments how new I am.

#include <CustomFunctions01.mqh>

extern string _________________________or="Order Settings";
extern int Magic=123456;
extern double Stop_Loss=20;
extern double Take_Profit=20;
extern double Lot=0.1;
extern string ____________________________________________________________is="++++++++++ Indicator Settings ++++++++++";
extern int fast_ema_period=12;//Fast EMA Period  
extern int slow_ema_period=26;//Slow EMA Period
extern int signal_period=9;//Signal Period
extern bool Use_Signal=true;


//Not using initialization instructions
int init()
{
return(0);
}

//Not using deinitializaion instructions
int deinit()
{
return(0);
}

//EA Starts here
//----------------------------------------------------------------

int start()
{
double lot, SL=0, TP=0;
int i, k;
bool BUY=false;
bool SELL=false;

//Create multiplyer to convert price to pips
double pipValue;
if(GetPipValue()>0.001){
pipValue = 100;
}
else{
pipValue = 10000;
}
   

   if(Volume[0]==1){    //If the Volume at the current bar is equal to 1... ? I don't understand the purpose this serves.
   
      //The Price value at swing points.
      double H_Price[3];
      double L_Price[3];
      double H_Macd[3];
      double L_Macd[3];
      
      //The time value at swing points.
      datetime H_Price_T[3];
      datetime L_Price_T[3];
      datetime H_Macd_T[3];
      datetime L_Macd_T[3];
      
      //Looking for Highs on the Zig zag Price! (Creating the H_Price and H_Price_T values)
      int c=0;
      double aux=0;
      for(i=1;i<Bars;i++){
         aux=iCustom(NULL,0,"ZigZag_JayDasilva","",fast_ema_period,slow_ema_period,signal_period,1,i);
            if(aux!=0){
            H_Price[c]=aux;
            H_Price_T[c]=Time[i];
            c++;
            }
         if(c==2) break;
      }  
      
      //Looking for Lows on the Zig zag Price! (Creating the L_Price and L_Price_T values)
      c=0;
      aux=0;
      for(i=1;i<Bars;i++){
         aux=iCustom(NULL,0,"ZigZag_JayDasilva","",fast_ema_period,slow_ema_period,signal_period,2,i);
            if(aux!=0){
            L_Price[c]=aux;
            L_Price_T[c]=Time[i];
            c++;
            }
         if(c==2) break;
      }
      
      //Looking for Highs on the Zig zag MACD!(Creating the H_Macd and H_Macd_T values)
      c=0;
      aux=0;
      for(i=1;i<Bars;i++){
         aux=iCustom(NULL,0,"ZigZag_MACD_JayDasilva","",fast_ema_period,slow_ema_period,signal_period,Use_Signal,3,i);
            if(aux!=0){
            H_Macd[c]=aux;
            H_Macd_T[c]=Time[i];
            c++;
            }
         if(c==2) break;
      }
      
      //Looking for Lows on the Zig zag MACD! (Creating the L_Macd and L_Macd_T values)
      c=0;
      aux=0;
      for(i=1;i<Bars;i++){
         aux=iCustom(NULL,0,"ZigZag_MACD_JayDasilva","",fast_ema_period,slow_ema_period,signal_period,Use_Signal,4,i);
            if(aux!=0){
            L_Macd[c]=aux;
            L_Macd_T[c]=Time[i];
            c++;
            }
         if(c==2) break;
   }
   
// Insert Your Rules Here
//-----------------------------------------------------------------------------------
   
      //Divergence example:
      if(H_Price[0]>H_Price[1])
      if(H_Macd[0]<H_Macd[1])   
      {
         Line(H_Price_T[1],H_Price[1],H_Price_T[0],H_Price[0],clrBlue);                      
      }
      
      // My Additional Conditions
      //-----------------------------------------------------------------------------
      double wave1, wave2, wave3, wave4, wave5;  
      double currentWave;
//      bool bValidWave = FALSE;   
      double avgWave;
//      bool bBullWave = FALSE;
      
         if(H_Price_T[1] < L_Price_T[1]){       // When the variable has the _T it represents the candle number.
            wave1 = H_Price[1] - L_Price[1];    // Without the _T it represents the price.
            wave2 = H_Price[2] - L_Price[1]; 
            wave3 = H_Price[2] - L_Price[2];
            wave4 = H_Price[3] - L_Price[2];
            wave5 = H_Price[3] - L_Price[3];            
            avgWave = ((wave1 + wave2 + wave3 + wave4 + wave5)/5)*pipValue; //pipValue = 100 or 10,000 depending on the pair
            Comment("Average Wave: " + avgWave + " pips");
            }
         else{
            wave1 = H_Price[1] - L_Price[1]; 
            wave2 = H_Price[1] - L_Price[2]; 
            wave3 = H_Price[2] - L_Price[2];
            wave4 = H_Price[2] - L_Price[3];
            wave5 = H_Price[3] - L_Price[3];
            avgWave = ((wave1 + wave2 + wave3 + wave4 + wave5)/5)*pipValue;
            Comment("Average Wave: " + avgWave + " pips");
            }  //Arrau out of range (155,41) <- not sure what the numbers mean.           *** This is line 151 ***
            
      if(BUY){
        lot=Lot;
        if(Stop_Loss!=0) SL=Bid-Stop_Loss*10*Point;
        if(Take_Profit!=0) TP=Bid+Take_Profit*10*Point;
        k=OrderSend(Symbol(),OP_BUY,lot,Ask,MarketInfo(Symbol(),MODE_SPREAD),SL,TP,lot,Magic);
      }
      
      if(SELL){
        lot=Lot;
        if(Stop_Loss!=0) SL=Bid+Stop_Loss*10*Point;
        if(Take_Profit!=0) TP=Bid-Take_Profit*10*Point;
        k=OrderSend(Symbol(),OP_SELL,lot,Bid,MarketInfo(Symbol(),MODE_SPREAD),SL,TP,lot,Magic);
      }
      
   }


//}               <---Why is this here?
return(0);  //    <---I don't understand what this is for.

}
// ************* EA End *************

// Functions ----------------------------------------------------

// A function called "Line" to easily draw lines with the new values.
string name="Jay";
void Line(datetime ax, double a, datetime bx, double b, color cl){
  string n=name+(string)ax+(string)a+(string)b;
  ObjectDelete(n);
  ObjectCreate(0,n,OBJ_GANNLINE,0,ax,a,bx,b);
  ObjectSetInteger(0,n,OBJPROP_RAY_RIGHT,FALSE);
  ObjectSetInteger(0,n,OBJPROP_COLOR,cl);
  ObjectSetInteger(0,n,OBJPROP_SELECTABLE,true);
  ObjectSetInteger(0,n,OBJPROP_BACK,False);
  ObjectSetInteger(0,n,OBJPROP_HIDDEN,true);
   return;
}

The error I found in the journal was:

2021.04.26 20:03:18.946 2019.05.01 00:00:00  Jay_Divergences_EA GBPUSD,H1: array out of range in 'Jay_Divergences_EA.mq4' (151,41)

I'm not sure but does the error mean that the indicator doesn't have the array values passed [1] ?  So, when I try to look up [2] or [3] etc, they were never created? I haven't been able to get in touch with the guy who wrote it for me so I don't know whether or not it goes farther than just candle 1. I assumed it did but maybe he didn't know that's what I meant. I can't tell by looking at the code. Sorry to post so much. I just don't know what is relevant and what isn't. I thought I put all the relevant code in the first post. 


 
dasilvja:

Above is the code for the indicator that he created for me. Don't mind the comments. I'm just asking questions about it to him. Below is the code for the EA. Again, there are some comments and questions for him. Some things are just notes so I know what's going on. You can tell by the nature of the comments how new I am.

The error I found in the journal was:

2021.04.26 20:03:18.946 2019.05.01 00:00:00  Jay_Divergences_EA GBPUSD,H1: array out of range in 'Jay_Divergences_EA.mq4' (151,41)

I'm not sure but does the error mean that the indicator doesn't have the array values passed [1] ?  So, when I try to look up [2] or [3] etc, they were never created? I haven't been able to get in touch with the guy who wrote it for me so I don't know whether or not it goes farther than just candle 1. I assumed it did but maybe he didn't know that's what I meant. I can't tell by looking at the code. Sorry to post so much. I just don't know what is relevant and what isn't. I thought I put all the relevant code in the first post. 


The number "(151,41) " in the error message, means the error is at line 151, at character position 41. So you will have to tell us where exactly is line 151 in your code.

Alternatively, which I believe will be easier and better for those helping you, is for you to instead of pasting your files as text, is to add them to a post as a true file attachments with their original names so the user can download and compile and test themselves to be able to see what is happening.

 
Fernando Carreiro:

The number "(151,41) " in the error message, means the error is at line 151, at character position 41. So you will have to tell use where exactly is line 151 in your code.

Alternatively, which I believe will be easier and better for those helping you, is for you to instead of pasting your files as text, is to add them to a post as a true file attachments with their original names so the user can download and compile and test themselves to be able to see what is happening.

Sorry. That makes sense. I'll attach them here.

I thought I figured it out for a minute. Nope. lol I'm lost. I'd appreciate any help from anyone.

 
dasilvja: Sorry. That makes sense. I'll attach them here. I thought I figured it out for a minute. Nope. lol I'm lost. I'd appreciate any help from anyone.

Unable to compile "Jay_Divergences_EA.mq4", given that there is at least one file missing; namely "CustomFunctions01.mqh".

 

I have found at least one location that will generate an Array out of Range error:

You are declaring arrays of size 3, but then in the loop you are incrementing variable "c" up to 5 (0 to 4) which is beyond the range of the arrays size of 3 (0 to 2).

EDIT: Please note that the following code was lifted from your "Jay_Divergences_EA.mq4" file you attached in a previous post and not the code text in previous posts.

//The Price value at swing points.
double H_Price[3];
double L_Price[3];
double H_Macd[3];
double L_Macd[3];

//The time value at swing points.
datetime H_Price_T[3];
datetime L_Price_T[3];
datetime H_Macd_T[3];
datetime L_Macd_T[3];

//Looking for Highs on the Zig zag Price! (Creating the H_Price and H_Price_T values)
int c=0;
double aux=0;
for(i=1; i<Bars; i++)
{
   aux=iCustom(NULL, 0, "ZigZag_JayDasilva", "", fast_ema_period, slow_ema_period, signal_period, 1, i);
   if(aux!=0)
   {
      H_Price[c]=aux;
      H_Price_T[c]=Time[i];
      c++;
   }
   if(c==5) break;
}
 
dasilvja: Sorry. That makes sense. I'll attach them here. I thought I figured it out for a minute. Nope. lol I'm lost. I'd appreciate any help from anyone.

Please note that the files you provided do not match in content to the code text that you have shown in previous posts!

So, we are left not knowing which ones you are actually using in your tests.

Please be consistent and provide the correct information, or else we will be unable to help!

 
dasilvja: Really new to coding. MQL4 is the only thing I'm learning. Someone wrote me a code so that I could play with and experiment with some ideas I have. They did the hard stuff and created variables that represented the swing highs and swing lows on the price chart (H_Price would be a swing high price and H_Price_T would be the candle number) This way I can simply use those variables to find divergence or wave sizes and simple things like that. Well I'm trying to write a small part (excuse the inefficient coding) to simply calculate the average size of the last 5 waves. If I remove the section of code that I'm sharing here, then everything works fine. These variables have been used in other parts of the code and worked. I don't understand what I've done differently. The divergence example is the part that works fine. When I add the code underneath it to calculate the average wave size then I get the error. I would appreciate any help. Please speak to me in layman's terms - I'm practically a baby when it comes to this stuff.

Also assuming the array size declarations so far given, then the following areas are also prone to Array out of Range errors:

if(H_Price_T[1] < L_Price_T[1])        // When the variable has the _T it represents the candle number.
{
   wave1 = H_Price[1] - L_Price[1];    // Without the _T it represents the price.
   wave2 = H_Price[2] - L_Price[1];
   wave3 = H_Price[2] - L_Price[2];
   wave4 = H_Price[3] - L_Price[2];
   wave5 = H_Price[3] - L_Price[3];
   avgWave = ((wave1 + wave2 + wave3 + wave4 + wave5)/5)*pipValue; //pipValue = 100 or 10,000 depending on the pair
   Comment("Average Wave: " + avgWave + " pips");
}
else
{
   wave1 = H_Price[1] - L_Price[1];
   wave2 = H_Price[1] - L_Price[2];
   wave3 = H_Price[2] - L_Price[2];
   wave4 = H_Price[2] - L_Price[3];
   wave5 = H_Price[3] - L_Price[3];
   avgWave = ((wave1 + wave2 + wave3 + wave4 + wave5)/5)*pipValue;
   Comment("Average Wave: " + avgWave + " pips");
//+------------------------------------------------------------------+
 
  1.             int j=iBarShift(NULL,0,PrevBullish,false);
                int k=iBarShift(NULL,0,PrevBearish,false);
                Peak_Bar=iLowest(NULL,0,MODE_LOW,k-j,j);

    There are k-j+1 bars between j and k.

  2.    if(Volume[0]==1){    //If the Volume at the current bar is equal to 1... ? I don't understand the purpose this serves.
    

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
              New candle - MQL4 programming forum #3 2014.04.04

Reason: