I'm encountering an issue with my NinjaTrader strategy where I'm getting the following error message:
"Error on calling 'OnBarUpdate' method on bar 4: 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."
Here are the steps and code changes I've tried to resolve the issue:
Initial Check for Bars Count:
protected override void OnBarUpdate() { if (CurrentBar < Period + 1) return; // Rest of the code }
Data Series Initialization:
protected override void OnStateChange() { if (State == State.SetDefaults) { // Default settings } else if (State == State.DataLoaded) { priceData = new Series<double>(this); volumeData = new Series<double>(this); } }
Ensuring Data Availability:
priceData[0] = Close[0]; volumeData[0] = Volume[0]; if (priceData.Count < SomeThreshold || volumeData.Count < SomeThreshold) return; double[] filteredPriceData = ApplyFilter(priceData, SomeThreshold); double[] filteredVolumeData = ApplyFilter(volumeData, SomeThreshold); if (filteredPriceData.Length < Period + 1 || filteredVolumeData.Length < Period + 1) return;
Loop Adjustments:
private double CalculateER(double[] data, int period) { if (data.Length < period + 1) return 0; double priceChange = Math.Abs(data[data.Length - 1] - data[data.Length - 1 - period]); double sumOfAbsChanges = 0.0; for (int i = data.Length - period + 1; i < data.Length; i++) { sumOfAbsChanges += Math.Abs(data[i] - data[i - 1]); } return sumOfAbsChanges == 0 ? 0 : priceChange / sumOfAbsChanges; }
Despite these efforts, the error persists. I suspect it might be related to how the logic checks bar indexes before there are enough bars in the series.
Could someone provide guidance on the best practices to ensure that I am not accessing indexes that are out of range? Specifically, how should I handle conditions
in OnBarUpdate to prevent this error from happening?
Any advice or examples would be greatly appreciated!
Thank you!
António

Comment