amibroker

HomeKnowledge Base

Do NOT make assumptions on number of bars

From time to time some users face “Error 10. Subscript out of range” in their formulas. The error itself is described in the manual, but still a few words of explanation why it happens may be useful.

The error usually occurs when formula uses hard-coded number of bars in the loop statements like this:

for( 0300i++ ) // MISTAKE: FIXED number of bars
{
  
Close]; // ERROR 10. because 'i' becomes greater than BarCount
}

or like this:

for( BarCount 1BarCount 300i-- ) // MISTAKE: FIXED number of bars
{
  
Close]; // ERROR 10. because 'i' becomes LESS than zero
}

In both cases the code will FAIL if it is run on symbol that has LESS than 300 bars (BarCount < 300). In fact it will even fail on symbol that has more than 300 bars because of two facts:

  1. during AFL Editor’s Verify Syntax not more than 200 most recent bars are used
  2. a chart may be zoomed in so number of visible bars may be much lower and QuickAFL kicks in (so your AFL is executed with visible bars only).

This all means that one should never make any assumptions on number of bars your formula would get, because if you do, the formula will fail.

The formula should be written so it is able to execute without errors with BarCount as small as 1 (ONE).

This is normally done by writing a ‘for’ loop in a way recommended in the manual:

for( 0BarCounti++ )
{
   
Close]; // this will never produce Error 10 because i is in the range 0..BarCount-1
}

If your formula references past data, say 10-bars earlier, you should start your loop with index 10, as below:

for( 10BarCounti++ )
{
  
x] = Close] - Close10 ]; // both subscripts will be OK
}

What to do if your formula, for some reason, really requires fixed number of bars? Well, the answer is that you should check if you really get as many bars as you think:

if( BarCount 300 // check first if you have enough bars
{
   
// here we know that we have more than 300 bars
   
for( 0300i++ )
   {
      
Close]; 
   }
}

Comments are closed.