Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Error on calling 'OnBarUpdate' method on bar 0

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Error on calling 'OnBarUpdate' method on bar 0

    I'm trying to modify a Indicator I downloaded here in the forum from one of the support people. It worked great until I added 4 parameters, StartMonth, StartDay, EndMonth, EndDay. I now get this error

    Indicator 'SampleGetHighLowByTimeRange': Error on calling 'OnBarUpdate' method on bar 0: 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.

    Can someone explain, like I'm a 5 year old what this means? To me, it says there are not enough bars on the chart. Well, there are hundreds of bars on the chart.

    All I want to do is draw a line at the Premarket High and Premarket Low. Any assistance would be appreciated.

    PHP Code:
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public class SampleGetHighLowByTimeRange : Indicator
        {
            protected override void OnStateChange()
            {
                
                if (State == State.SetDefaults)
                {
                    Description                    = @"Determines the highest high and lowest low in a specified time range";
                    Name                        = "Sample get high low by time range";
                    Calculate                    = Calculate.OnBarClose;
                    IsOverlay                    = true;
                    DisplayInDataBox            = true;
                    DrawOnPricePanel            = true;
                    DrawHorizontalGridLines        = true;
                    DrawVerticalGridLines        = true;
                    PaintPriceMarkers            = true;
                    ScaleJustification             = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                    StartMonth                    = 12;
                    StartDay                    = 11;
                    StartHour                    = 7;
                    StartMinute                    = 30;
                    EndMonth                    = 12;
                    EndDay                        = 12;
                    EndHour                        = 15;
                    EndMinute                    = 00;
                    AddPlot(Brushes.Green, "HighestHigh");
                    AddPlot(Brushes.Red, "LowestLow");
                }
            }
            
            private DateTime startDateTime;
            private DateTime endDateTime;
            protected override void OnBarUpdate()
            {
                // Check to make sure the end time is not earlier than the start time
                if (EndHour < StartHour)
                    return;
                
                
                //Do not calculate the high or low value when the ending time of the desired range is less than the current time of the bar being processed
                if (ToTime(EndHour,EndMinute,0) > ToTime(Time[0]))
                    return;  
                
                
    
                // If the stored date time date is not the same date as the bar time date, create a new DateTime object
                if (startDateTime.Date != Time[0].Date)
                {
                    startDateTime = new DateTime(Time[0].Year, StartMonth, StartDay, StartHour, StartMinute, 0);
                    endDateTime = new DateTime(Time[0].Year, EndMonth, EndDay, EndHour, EndMinute, 0);    
                }
    
                // Calculate the number of bars ago for the start and end bars of the specified time range
                int startBarsAgo = Bars.GetBar(startDateTime);
                int endBarsAgo = Bars.GetBar(endDateTime);
                
                /* Now that we have the start and end bars ago values for the specified time range we can calculate the highest high for this range
                
                Note: We add 1 to the period range for MAX and MIN to compensate for the difference between "period" logic and "bars ago" logic.
                "Period" logic means exactly how many bars you want to check including the current bar.
                "Bars ago" logic means how many bars we are going to go backwards. The current bar is not counted because on that bar we aren't going back any bars so it would be "bars ago = 0" */
                double highestHigh = MAX(High, endBarsAgo - startBarsAgo  + 1)[CurrentBar - endBarsAgo];
                
                // Now that we have the start and end bars ago values for the specified time range we can calculate the lowest low for this range
                double lowestLow = MIN(Low, endBarsAgo - startBarsAgo + 1)[CurrentBar - endBarsAgo];
    
                // Set the plot values
                HighestHigh[0] = highestHigh;
                LowestLow[0] = lowestLow;    
                                //Print("Start Time: " + startDateTime + " End Time: " + endDateTime);
                                //Print("HighestHigh[0]: " + HighestHigh[0] + " LowestLow[0]: " + LowestLow[0]);
    
            }&#8203; 
    

    #2
    Hello nelslynn,

    Thank you for your post.

    This message is indicating the specific index requested from a collection does not exist. Indexes must be a non-negative number and less than the size of the collection. The error may be indicating the index requested is larger than the number of elements in the collection.

    In the case of barsAgo values with Series, any barsAgo index must be less than CurrentBar (the total number of bars is the size of a Series collection).

    Code:
    // require BarsInProgress 0 to have 3 bars processed, require BarsInProgress 1 to have 4 bars processed
    if (CurrentBars[0] < 3 || CurrentBars[1] < 4)
    return;
    
    Print(Times[0][3]); // this does not cause an error as CurrentBars[0] is equal to or greater than 3
    
    Print(Times[1][4]); // this does not cause an error as CurrentBars[1] is equal to or greater than 4
    
    Print(Times[0][5]); // this line of code will cause an invalid index error. When CurrentBars[0] is 4 there is no bar 5 bars ago​
    For a simpler example with one series, imagine OnBarUpdate has only processed 4 bars. Keep in mind, OBU only processes 1 bar update at a time. Since you're using OnBarClose, essentially OBU is updating 1 bar at at time. If you try to access 5 bars ago when only 4 bars have been processed, there is no 5th bar to check so you'll get an index error.

    A good way to ensure you don't run into any indexing errors is to include a simple CurrentBar check.

    Code:
    if (CurrentBar < BarsRequiredToPlot) return;
    https://ninjatrader.com/support/helpguides/nt8/NT%20HelpGuide%20English.html?barsrequiredtoplot.h tm

    The help guide discusses ‘Make sure you have enough bars in the data series you are accessing’ .

    NinjaScript > Educational Resources > Tips > Make sure you have enough bars in the data series you are accessing

    Comment


      #3
      I tried both:
      if (CurrentBar < BarsRequiredToPlot) return;
      and
      if (CurrentBar < 500) return;

      and get the same error.

      How do I know how many bars are required? Isn't based on the date entered?

      Is this code just too old? it was from a post in 2018

      Comment


        #4
        Hello,

        BarsRequiredToPlot can be set from State.SetDefaults, the default value is 20.



        It is not based on the date entered, the index error is solely based on the specific index being requested in relation to the size of the collection.

        This code doesn't look outdated, if the CurrentBar check isn't working you'll need to debug the script to figure out which line of code in particular is throwing the error. It is likely coming from the highestHigh or lowestLow MAX and MIN calculations, but I would still recommend debugging to make sure.

        To do this quickly you could comment out all the logic in OBU, compile and test the script to make sure you aren't seeing the error anymore.

        Then, uncomment line by line, testing after each uncommented line. When the error returns, what was the last line uncommented?

        This is likely the line throwing the error. We can then examine that line more closely.

        Comment


          #5
          The issue is I cannot add a variable for Day. I want to get the LOW/HIGH from the prior day at 15:00:00 to the current day 7:30:00

          This works
          //startDateTime = new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, StartHour, StartMinute, 0);
          //endDateTime = new DateTime(Time[0].Year, Time[0].Month, Time[0].Day, EndHour, EndMinute, 0);

          This does not
          startDateTime = new DateTime(Time[0].Year, Time[0].Month, StartDay, StartHour, StartMinute, 0);
          endDateTime = new DateTime(Time[0].Year, Time[0].Month, EndDay, EndHour, EndMinute, 0);

          Any hints?​

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by Geovanny Suaza, 02-11-2026, 06:32 PM
          0 responses
          553 views
          0 likes
          Last Post Geovanny Suaza  
          Started by Geovanny Suaza, 02-11-2026, 05:51 PM
          0 responses
          324 views
          1 like
          Last Post Geovanny Suaza  
          Started by Mindset, 02-09-2026, 11:44 AM
          0 responses
          100 views
          0 likes
          Last Post Mindset
          by Mindset
           
          Started by Geovanny Suaza, 02-02-2026, 12:30 PM
          0 responses
          543 views
          1 like
          Last Post Geovanny Suaza  
          Started by RFrosty, 01-28-2026, 06:49 PM
          0 responses
          546 views
          1 like
          Last Post RFrosty
          by RFrosty
           
          Working...
          X