Make sure you have enough bars in the data series you are accessing

View as Markdown

A common programming error is not checking to ensure there are enough bars contained in the data series you are accessing. This will explain some of the concepts to check for this situation.

For example:

1protected override void OnBarUpdate()
2{
3 if (Close[0] > Close[1])
4 // Do something
5}

In the code snippet above, the OnBarUpdate() method is called for each bar contained in your data series.

On the very first bar (think of the 1st bar on the chart from left to right) the value of “close of 1 bar ago” (Close[1]) does not yet exist and your indicator/strategy will not work and throw an exception to the Control Center Log tab “Index was out of range…”.

Following are two ways to resolve this:

1protected override void OnBarUpdate()
2{
3 if (CurrentBar < 1)
4 return;
5 if (Close[0] > Close[1])
6 // Do something
7}

The resolution above is to check how many bars we have seen (CurrentBar) and to exit the OnBarUpdate() method if an insufficient number of bars has been seen.

1protected override void OnBarUpdate()
2{
3 if (Close[0] > Close[Math.Min(CurrentBar, 1)])
4 // Do something
5}

The resolution above substitutes the minimum value between the current bar being processed and the desired number of bars ago value, in this case 1.

1protected override void OnStateChange()
2{
3 if (State == State.SetDefaults)
4 {
5 Name = "Multi-Time Frame & Instruments Example";
6 }
7 else if (State == State.Configure)
8 {
9 // Adds a secondary bar object to the script.
10 AddDataSeries(BarsPeriodType.Minute, 5);
11
12 // Adds an additional bar object to the script.
13 AddDataSeries(BarsPeriodType.Minute, 5);
14 }
15}
16
17protected override void OnBarUpdate()
18{
19 // Checks to ensure all Bars objects contain enough bars before beginning
20 // If this is a strategy, use **BarsRequiredToTrade** instead of **BarsRequiredToPlot**
21 if (CurrentBars[0] <= BarsRequiredToPlot || CurrentBars[1] <= BarsRequiredToPlot || CurrentBars[2] <= BarsRequiredToPlot)
22 return;
23}

The resolution above would be used in a Multi Time Frame script. Since OnBarUpdate() processes multiple data series, we need to make sure each Data Series we reference has processed enough bars.