How to Fix a Common Index Out of Range Error on Multi Timeframe Strategies

Welcome back, guys! In this article, I will give out a secret that will save you some headache time. I bet many of you might have come across this issue already and if you have not then you will 100% meet it if you ever design a multi-timeframe trading system for NinjaTrader where one of the symbols is slower than the other.


The error is quite common. “You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.”.


Let’s imagine we want to build our strategy on 2 timeframes. The first timeframe is 15min and the second one is 1 hour. Our main timeframe is 15min and we want to access data for both timeframes from within it.


if (BarsInProgress == 0)

{

var secondTimeFrameLastBarClosed = Closes[1][0];

}


If you do this on the first bar close you will get the index is outside the bounds of array error because the bar has not closed yet on the slower timeframe and you are already trying to access it.


In this particular case, the workaround can be


If (CurrentBar >= 4) then do stuff..


However, this would mean that you are glued to the selected timeframes of 1 hour for the slower and 15 min for the faster and this is not very flexible.


A more flexible approach could be to initialize a boolean flag when the first bar closes on the slower timeframe and only then allow the code to pass down the OnBarUpdate method for the primary faster timeframe.


If (BarsInProgress == 1)

{

_isInitialized = true;

}


If (BarsInProgress != 1)

   return;


If (!_initialized)

  return;


var secondTimeFrameLastBarClosed = Closes[1][0];


It is now safe to call the last closed bar of the slower timeframe from the faster timeframe because we are 100% that at least one bar has closed there.


Please subscribe to stay updated!