Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Object reference not set to an instance of an object

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

    Object reference not set to an instance of an object

    Hi all,

    I've developed a custom indicator that has been working fine for the past few days and today, it suddenly gave me this "Error on calling 'OnBarUpdate' method on bar 100: Object reference not set to an instance of an object" message and failed to work properly. Also, sometimes the indicator displays wrong values and the values only update to the correct ones on the close of the current bar which should not be the case as it is set to update on each tick. Attached below is the code:

    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Indicators in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public class TestIndicator : Indicator
        {
            private int Counter = 0;
    
            private double[] HighMaximas;
            private double[] LowMinimas;
            private double[] SlidingWindow;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Indicator here.";
                    Name                                        = "Test Indicator";
                    Calculate                                    = Calculate.OnEachTick;
                    IsOverlay                                    = true;
                    DisplayInDataBox                            = false;
                    DrawOnPricePanel                            = false;
                    DrawHorizontalGridLines                        = true;
                    DrawVerticalGridLines                        = true;
                    PaintPriceMarkers                            = true;
                    ScaleJustification                            = NinjaTrader.Gui.Chart.ScaleJustification.Right;
                    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
                    //See Help Guide for additional information.
                    IsSuspendedWhileInactive                    = true;
                    NumberOfCandles                                = 100;
                    WindowLength                                = 3;
                    NumberOfValues                            = 3;
                }
                else if (State == State.Configure)
                {
                    SlidingWindow = new double[WindowLength];
                    HighMaximas = new double[NumberOfValues];
                    LowMinimas = new double[NumberOfValues];
                }
            }
    
            protected override void OnBarUpdate()
            {
                if(CurrentBar < NumberOfCandles) return;
    
                for(int i = 0; i < NumberOfCandles; i++)
                {
                    SlidingWindow[0] = Highs[0][i];
                    SlidingWindow[1] = Highs[0][i+1];
                    SlidingWindow[2] = Highs[0][i+2];
    
                    if((SlidingWindow[1] > SlidingWindow[0]) && (SlidingWindow[1] > SlidingWindow[2]))
                    {
    
                        if(Counter == 0)
                        {
                            HighMaximas[Counter] = SlidingWindow[1];
                            Counter ++;
                        }
    
                        else if(Counter >= 1)
                        {
    
                            if(SlidingWindow[1] > HighMaximas[Counter-1])
                            {
                                HighMaximas[Counter] = SlidingWindow[1];
                                Counter ++;
                            }
    
                            else
                            {
                                ;
                            }
                        }
                    }
    
                    else if(Counter == NumberOfValues)
                    {
                        Counter = 0;
                        break;
                    }
    
                    else
                    {
                        ;
                    }
                }
    
                for(int i = 0; i < NumberOfCandles; i++)
                {
                    SlidingWindow[0] = Lows[0][i];
                    SlidingWindow[1] = Lows[0][i+1];
                    SlidingWindow[2] = Lows[0][i+2];
    
                    if((SlidingWindow[1] < SlidingWindow[0]) && (SlidingWindow[1] < SlidingWindow[2]))
                    {
    
                        if(Counter == 0)
                        {
                            LowMinimas[Counter] = SlidingWindow[1];
                            Counter ++;
                        }
    
                        else if(Counter >= 1)
                        {
    
                            if(SlidingWindow[1] < LowMinimas[Counter-1])
                            {
                                LowMinimas[Counter] = SlidingWindow[1];
                                Counter ++;
                            }
    
                            else
                            {
                                ;
                            }
                        }
                    }
    
                    else if(Counter == NumberOfValues)
                    {
                        Counter = 0;
                        break;
                    }
    
                    else
                    {
                        ;
                    }
                }
    
                Draw.HorizontalLine(this, "Value1", HighMaximas[0], Brushes.Blue);
                Draw.HorizontalLine(this, "Value2", HighMaximas[1], Brushes.Blue);
                Draw.HorizontalLine(this, "Value3", HighMaximas[2], Brushes.Blue);
                Draw.HorizontalLine(this, "Value4", LowMinimas[0], Brushes.Red);
                Draw.HorizontalLine(this, "Value5", LowMinimas[1], Brushes.Red);
                Draw.HorizontalLine(this, "Value6", LowMinimas[2], Brushes.Red);
    
            }        [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="NumberOfCandles", Description="Candles to scan for values", Order=1, GroupName="Parameters")]
            public int NumberOfCandles
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="WindowLength", Description="Window length of sliding window", Order=2, GroupName="Parameters")]
            public int WindowLength
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="NumberOfValues", Description="Number of values to output", Order=3, GroupName="Parameters")]
            public int NumberOfValues
            { get; set; }
    
    
    
    
    
    
    
        }
    }
    
    #region NinjaScript generated code. Neither change nor remove.
    
    namespace NinjaTrader.NinjaScript.Indicators
    {
        public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
        {
            private TestIndicator[] cacheTestIndicato;
            public TestIndicator TestIndicator(int numberOfCandles, int windowLength, int numberOfValues)
            {
                return TestIndicator(Input, numberOfCandles, windowLength, numberOfValues);
            }
    
            public TestIndicator TestIndicator(ISeries<double> input, int numberOfCandles, int windowLength, int numberOfValues)
            {
                if (cacheTestIndicator != null)
                    for (int idx = 0; idx < cacheTestIndicator.Length; idx++)
                        if (cacheTestIndicator[idx] != null && cacheTestIndicator[idx].NumberOfCandles == numberOfCandles && cacheTestIndicator[idx].WindowLength == windowLength && cacheTestIndicator[idx].NumberOfValues == numberOfValues && cacheTestIndicator[idx].EqualsInput(input))
                            return cacheTestIndicator[idx];
                return CacheIndicator<TestIndicator>(new TestIndicator(){ NumberOfCandles = numberOfCandles, WindowLength = windowLength, NumberOfValues = numberOfValues}, input, ref cacheTestIndicator);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
        public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
        {
            public Indicators.TestIndicator TestIndicator(int numberOfCandles, int windowLength, int numberOfValues)
            {
                return indicator.TestIndicator(Input, numberOfCandles, windowLength, numberOfValues);
            }
    
            public Indicators.TestIndicator TestIndicator(ISeries<double> input , int numberOfCandles, int windowLength, int numberOfValues)
            {
                return indicator.TestIndicator(input, numberOfCandles, windowLength, numberOfValues);
            }
        }
    }
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
        {
            public Indicators.TestIndicator TestIndicator(int numberOfCandles, int windowLength, int numberOfValues)
            {
                return indicator.TestIndicator(Input, numberOfCandles, windowLength, numberOfValues);
            }
    
            public Indicators.TestIndicator TestIndicator(ISeries<double> input , int numberOfCandles, int windowLength, int numberOfValues)
            {
                return indicator.TestIndicator(input, numberOfCandles, windowLength, numberOfValues);
            }
        }
    }
    
    #endregion
    Any help offered would be greatly appreciated.
    Last edited by MrSomebody; 03-19-2020, 01:47 PM.

    #2
    Hello MrSomebody,

    Thank you for your note.

    I would advise you to add Print statements to your script with information on what the values are of the variables you are using on a given bar are. With Prints you can see what may be causing that null reference. I would specifically look at whether you're always assigning something to your LowMinimas and HighMaximas series - I suspect you may be trying to reference values for bars that did not have values assigned.

    This forum post goes into great detail on how to use prints to help figure out where issues may stem from — this should get you going in the correct direction.



    With the printout information you can assess what is different between the two.

    Please let us know if we may be of further assistance to you.

    Comment


      #3
      Hi Kate,

      Thanks for the prompt reply. I've added print statements and change the "if(CurrentBar < NumberOfCandles) return;" line to "if(CurrentBar <= NumberOfCandles) return;" and the indicator runs but however, the values displayed by the indicator has changed completely and only update to the correct ones on the end of the current bar. From the outputs, it looks like the loops are not executing completely before the OnBarUpdate method is called again and this problem still happens despite changing the OnBarUpdate settings to calculate on each bar close. I've added comment lines as such.

      Code:
      if(CurrentBar <= NumberOfCandles) return;
      
                  Update();
                  Print("Enough candles for loops");
      
                  for(int i = 0; i < NumberOfCandles; i++)
                  {
                      SlidingWindow[0] = Highs[0][i];
                      SlidingWindow[1] = Highs[0][i+1];
                      SlidingWindow[2] = Highs[0][i+2];
      
                      if((SlidingWindow[1] > SlidingWindow[0]) && (SlidingWindow[1] > SlidingWindow[2]))
                      {
      
                          if(Counter == 0)
                          {
                              HighMaximas[Counter] = SlidingWindow[1];
                              Counter ++;
                              Print("First Maxima Detected");
                          }
      
                          else if(Counter > 0)
                          {
      
                              if(SlidingWindow[1] > HighMaximas[Counter-1])
                              {
                                  HighMaximas[Counter] = SlidingWindow[1];
                                  Counter ++;
                                  Print("Subsequent Maxima Detected");
                              }
      
                              else
                              {
                                  ;
                              }
                          }
                      }
      
                      else if(Counter == NumberOfValues)
                      {
                          Print("Exiting the maxima loop");
                          Counter = 0;
                          break;
                      }
      
                      else
                      {
                          ;
                      }
                  }
      Vice versa for the minimas loop and the first few rows of the output window shows:

      Enough candles for loops
      First Maxima Detected
      Subsequent Maxima Detected
      Subsequent Maxima Detected
      Exiting the maxima loop
      First Minima Detected
      Subsequent Minima Detected
      Enough candles for loops
      Subsequent Maxima Detected
      Exiting the maxima loop
      First Minima Detected
      Subsequent Minima Detected
      Enough candles for loops
      Subsequent Maxima Detected
      Exiting the maxima loop
      First Minima Detected
      Subsequent Minima Detected
      Enough candles for loops
      Last edited by MrSomebody; 03-19-2020, 02:16 PM.

      Comment


        #4
        Hello MrSomebody,

        Thank you for your reply.

        I would suggest adding prints that print the values of LowMinimas[Counter], LowMinimas[Counter-1], HighMaximas[Counter-1] and HighMaximas[Counter] right before you reference them. I suspect it's when you try to reference one of those, but the value is null, that the error is occurring. You need to make sure that if you're referencing something that it has something to reference. Since you aren't assigning values to these on every pass through the loop, it's likely that it's trying to reference Counter-1 but there's nothing there.

        Please let us know if we may be of further assistance to you.

        Comment


          #5
          Hi Kate,

          It doesn't seem like it's trying to reference a null value. It's still the same issue of the OnBarUpdate method being called before the minima loop has completed. Current output window shows as such (Spaces added for clarity):

          Enough candles for loops

          First Maxima Detected

          Previous maxima value1.07964
          Subsequent Maxima Detected

          Previous maxima value1.07969
          Subsequent Maxima Detected

          Exiting the maxima loop

          First Minima Detected

          Previous minima value1.07909
          Subsequent Minima Detected

          Enough candles for loops

          Comment


            #6
            Issue solved. Could an admin kindly delete this thread? Thank you.
            Last edited by MrSomebody; 03-20-2020, 01:27 PM.

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by Geovanny Suaza, 02-11-2026, 06:32 PM
            0 responses
            649 views
            0 likes
            Last Post Geovanny Suaza  
            Started by Geovanny Suaza, 02-11-2026, 05:51 PM
            0 responses
            370 views
            1 like
            Last Post Geovanny Suaza  
            Started by Mindset, 02-09-2026, 11:44 AM
            0 responses
            109 views
            0 likes
            Last Post Mindset
            by Mindset
             
            Started by Geovanny Suaza, 02-02-2026, 12:30 PM
            0 responses
            574 views
            1 like
            Last Post Geovanny Suaza  
            Started by RFrosty, 01-28-2026, 06:49 PM
            0 responses
            576 views
            1 like
            Last Post RFrosty
            by RFrosty
             
            Working...
            X