Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Object reference not set to an instance of an object error when optimizing

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

    Object reference not set to an instance of an object error when optimizing

    I set a code to backtest parameters in bulk from a text file.

    This works fine to backtest, but when I set the Strategy Analyzer to optimize, the error "Error on calling 'OnStateChange' method: Object reference not set to an instance of an object" appears.

    I added some prints and the error appears in State.Configure. In State.Configure there is method that simply reads the timeframe of a strategy and adds a DataSeries.

    I insist, it works fine for backtesting.

    I paste the code:


    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "MyOptimizerTakeProfis";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.ImmediatelySubmit;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;


    IsInstantiatedOnEachOptimizationIteration = false;

    PositionType = 0;
    IndType = @"Indicator1";
    PercStopProfit = 0;
    TakeProfits = 0;
    TakeProf1 = 10;
    TakeProf2 = 25;

    }
    else if (State == State.DataLoaded)
    {

    }
    else if (State == State.Configure)
    {
    Print("Configure 1");

    Instr = Instrument.FullName;

    ReadMyTimeFrame();
    AddDataSeries(BarsPeriodType.Minute, MyTimeFrame); //BIP = 1

    Print("Configure 2");
    }

    }


    #2
    Instr = Instrument.FullName; //Instrument properties cant be called before State.DataLoaded

    Comment


      #3
      Would it be possible to assign a value to a variable and keep its value across every iteration when optimizing?

      Comment


        #4
        Hello guillembm,

        Leeroy_Jenkins is correct, the Instrument or anything else related to the Data Series cannot be used until State.DataLoaded.
        "Warning: The properties in this class should NOT be accessed within the OnStateChange() method before the State has reached State.DataLoaded​"


        Further, it is not supported to use variables to dynamically call AddDataSeries().
        "Arguments supplied to AddDataSeries() should be hardcoded and NOT dependent on run-time variables which cannot be reliably obtained during State.Configure (e.g., Instrument, Bars, or user input). Attempting to add a data series dynamically is NOT guaranteed and therefore should be avoided. Trying to load bars dynamically may result in an error similar to: Unable to load bars series. Your NinjaScript may be trying to use an additional data series dynamically in an unsupported manner.​"
        https://ninjatrader.com/support/help...dataseries.htm

        There would not be a supported way of saving this to a variable across every iteration, but using unsupported static classes this may be possible.
        https://ninjatrader.com/support/foru...ork#post712245

        Can you clarify why you need to save this to a variable?
        (The instrument would not be changing for each iteration and the Instrument property is already available to each iteration once the script has passed State.DataLoaded)
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          This is exactly what I needed.

          I optimise in two steps. In the second step I need to read the results of the first step from a text file. But I need to retrieve the value of the Time Frame to create and AddDataSeries related to an instrument and this data is related to the instrument name that is being executed. Thus I need it in State.Configure.

          Thanks

          Comment


            #6
            Hello guillembm,

            This will not be available in State.Configure and will not be available until the data loads.
            You can use null as the instrument in AddDataSeries() to add an additional data series using the same instrument as the primary.
            It is not supported to dynamically call AddDataSeries(). The parameters must be hard coded.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              I am not trying to dinamically set a data series. The data series is set in State.Configure and then it is the same for all the iterations.

              As an example, if I set this code:

              else if (State == State.Configure)
              {
              Instr = Instrument.FullName;

              if (Instr == "EURUSD")
              MyTimeFrame = 30;
              else if (Instr == "GBPUSD")
              MyTimeFrame = 50;​

              AddDataSeries(BarsPeriodType.Minute, MyTimeFrame); //BIP = 1
              }​

              this works perfectly when backtesting, but when I apply the same code to an optimization I get the mentioned error: "Error on calling 'OnStateChange' method: Object reference not set to an instance of an object"

              Comment


                #8
                Hello guillembm,

                MyTimeFrame is a variable. Using a variable with AddDataSeries() is dynamic, in that the value of the variable can change. Hardcode values, do not use variables in AddDataSeries().

                Leeroy_Jenkins has also stated that the Instrument property is null in State.Configure, which I have confirmed is correct.

                Instr = Instrument.FullName;

                This is causing the error because Instrument is null. There is no object assigned to the Instrument (object reference). You cannot use this here.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  I insist. If I code Print(Instrument.FullName) in state.Configure the instrument name is printed in a backtest. Is just in an optimization when the error appears.

                  Comment


                    #10
                    Hello guillembm,

                    See post # 4 with a quote from the help guide. This is not supported. Specifically because it causes issues with optimizations and with cloning.
                    Chelsea B.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by argusthome, 03-08-2026, 10:06 AM
                    0 responses
                    65 views
                    0 likes
                    Last Post argusthome  
                    Started by NabilKhattabi, 03-06-2026, 11:18 AM
                    0 responses
                    41 views
                    0 likes
                    Last Post NabilKhattabi  
                    Started by Deep42, 03-06-2026, 12:28 AM
                    0 responses
                    23 views
                    0 likes
                    Last Post Deep42
                    by Deep42
                     
                    Started by TheRealMorford, 03-05-2026, 06:15 PM
                    0 responses
                    26 views
                    0 likes
                    Last Post TheRealMorford  
                    Started by Mindset, 02-28-2026, 06:16 AM
                    0 responses
                    52 views
                    0 likes
                    Last Post Mindset
                    by Mindset
                     
                    Working...
                    X