September 22, 2014
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( i = 0; i < 300; i++ ) // MISTAKE: FIXED number of bars
x = Close[ i ]; // ERROR 10. because 'i' becomes greater than BarCount
or like this:
for( i = BarCount - 1; i > BarCount - 300; i-- ) // MISTAKE: FIXED number of bars
x = Close[ i ]; // 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:
- during AFL Editor’s Verify Syntax not more than 200 most recent bars are used
- 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( i = 0; i < BarCount; i++ )
x = Close[ i ]; // 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( i = 10; i < BarCount; i++ )
x[ i ] = Close[ i ] - Close[ i - 10 ]; // 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( i = 0; i < 300; i++ )
x = Close[ i ];
Filed by Tomasz Janeczko at 4:59 pm under AFL
Comments Off on Do NOT make assumptions on number of bars