Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to debug Object reference not set to an instance of an object.

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

    How to debug Object reference not set to an instance of an object.

    My strategy sometimes displays error and later on starts working. Is there a good way to figure out whats causing it?
    Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.

    Code:
     protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description = @"Second Entries Strategy";
                    Name = "SecEntryStrat";
                    Calculate = Calculate.OnEachTick;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution = OrderFillResolution.Standard;
                    Slippage = 0;
                    StartBehavior = StartBehavior.WaitUntilFlat;
                    TimeInForce = TimeInForce.Gtc;
                    TraceOrders = false;
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade = 5;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration = true;
    
                    #region Default Settings
    
    
                    UseTPByATR = true;
                    ATRPeriod = 14;
                    All2Entries = false;
    //                ProfitTarget = 25;
    //                PositionSize = 1;
                    BounceEMAPeriod    = 21;
                    FilterEMAPeriod    = 89;
                    UseFilterEMA = false;
                    UseBounceOnly = true;
                    IsEMARisingFalling = false;
                    LimitRisk = 100;
                    StopLossOffset = 2;
                    EntryOffSet = 2;
                    DistEMAToSignal = 15;
                    Start = DateTime.Parse("08:35", System.Globalization.CultureInfo.InvariantCulture);
                    End = DateTime.Parse("15:00", System.Globalization.CultureInfo.InvariantCulture);
    
                    TickOffsetTrail = 1;
                    TrailTriggerAmount = 20;
    
                    //Breakeven
                    BreakevenTriggerAmount = 10;
    
                    //Daily Limits
                    DailyProfitLimit = 2000;
                    DailyLossLimit = 2000;
                    X = 50;
    
                    //Position Size
                    PositionSize = 1;
                    ProfitTargetTicks = 50;
                    StopLossTicks = 50;
    
                    //User Option to set the following
                    FixedStopLoss = false;
                    DynamicStopLoss = true;
                    ProfitTarget = false;
                    SetBreakeven = false;
                    SetTrail = false;
                    OHLFilter = true;
    
                    countOnce = true;
    
                    //Prints to Output
                    SystemPrint = true;
    
                    #endregion
    
                }
                else if (State == State.Configure)
                {
                }
    
    
    
                //Not part of the strategy.
    
                else if (State == State.DataLoaded)
                {
                    ClearOutputWindow(); //Clears Output window every time strategy is enabled
                    _patsIndicator = TDUPriceAction(Close, TDUPatsRules.Mack, false,
                        TDUPatsTradeManagement.Internal,0, 2, 95, 2, TDUPATSPositionSizing.Contracts, 1, 200, 1, 1,
                        TDUPATSPositionSizingRunner.None, 1, 1, 1, 1, "[email protected]", 00000000000);
                    _patsIndicator.Show01 = true;
                    _patsIndicator.ShowTraps = false;
                    _patsIndicator.ShowSLTP = true;
                    AddChartIndicator(_patsIndicator);
    
                    slShort = new Series<double>(this);
                    slLong = new Series<double>(this);
    //                signalBarStrengthShort = new Series<double>(this);
    //                signalBarStrengthLong = new Series<double>(this);
    //                trapShort = new Series<double>(this);
    //                trapLong = new Series<double>(this);
                    atrIndicator  = ATR(ATRPeriod);
                    bounceEMA    = EMA(BounceEMAPeriod);
                    filterEMA    = EMA(FilterEMAPeriod);
                     currentSHigh = CurrentDayOHL(Close);
                    currentSLow = CurrentDayOHL(Close);
                }
    
                else if (State == State.Realtime)
                {
                    if (ChartControl != null && !IsToolBarButtonAdded)
                    {
                        var unused1 = ChartControl.Dispatcher.InvokeAsync(() =>
                        {
                            AddButtonToToolbar();
                        });
                    }
                }
                else if (State == State.Terminated)
                {
                    if (chartWindow != null)
                    {
                        var unused = ChartControl.Dispatcher.InvokeAsync(() =>
                        {
                            DisposeCleanUp();
                        });
                    }
                }
            }
    ​

    #2
    Yes. Right click on the script and check Debug Mode then recompile it. Then, when you get the error message, go into Documents -> NinjaTrader 8 -> trace and look at the most recent one. In that file will be the full stack trace with the line number of your script that caused the exception.
    Bruce DeVault
    QuantKey Trading Vendor Services
    NinjaTrader Ecosystem Vendor - QuantKey

    Comment


      #3
      Hi Boris, you can also use Visual Studio debugging to find the exact line of code causing the exception:

      Comment


        #4
        Thank you. I got this line x 25 times. What would this mean?
        Code:
        2023-05-10 11:36:25:508 ERROR: Strategy 'Mystrategy': Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.
        2023-05-10 11:36:26:252 (Lets Trady Rithmic) Rithmic.Adapter.PnlUpdate: symbol='' Position.Use=True​
        Last edited by tkaboris; 05-10-2023, 09:45 AM.

        Comment


          #5
          That looks like a log line. All you know from this is that the error is somewhere in OnStateChange. If you did enable Debug Mode, and recompiled, and had the error happen again, you can find the trace file and it will have the line number.
          Bruce DeVault
          QuantKey Trading Vendor Services
          NinjaTrader Ecosystem Vendor - QuantKey

          Comment


            #6
            Is 447 below means a line in my code? No it cant be. Where to look for line numbers in trace? Also i dont know what MNQM3 means but then it goes blank

            2023-05-10 08:20:31:447 (Lets Trady Rithmic) Rithmic.Adapter.PnlUpdate: symbol='MNQM3' Position.Use=True
            2023-05-10 08:20:31:447 (Lets Trady Rithmic) Rithmic.Adapter.PnlUpdate: symbol='MNQM3' Position.Use=True
            2023-05-10 08:20:31:447 (Lets Trady Rithmic) Rithmic.Adapter.PnlUpdate: symbol='' Position.Use=True​
            Last edited by tkaboris; 05-10-2023, 10:16 AM.

            Comment


              #7
              MNQM3 is the June 2023 contract of micro-NQ futures.

              Those lines are routine order lines, and are not an error message.

              The 447 is the milliseconds portion of the timestamp.
              Bruce DeVault
              QuantKey Trading Vendor Services
              NinjaTrader Ecosystem Vendor - QuantKey

              Comment


                #8
                my strategy is running and prints debugs for me and opens trades. however when i right click on chart/Strategies it imideatly throws Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.
                Is this normal?

                Comment


                  #9
                  No. You clearly have a bug in your OnStateChange method code. Check the trace file for the line number of your error after enabling debug mode and recompiling as described above.
                  Bruce DeVault
                  QuantKey Trading Vendor Services
                  NinjaTrader Ecosystem Vendor - QuantKey

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                  0 responses
                  655 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
                  577 views
                  1 like
                  Last Post RFrosty
                  by RFrosty
                   
                  Working...
                  X