Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

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.

    This test strategy was generated in the strategy builder. I have made no changes. It is throwing out an error.

    Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.

    Questions:

    1. Why is it giving me this error when I'm not even coding by hand?
    2. I have always struggled with having the target and stop set to a var that is set in the OnBarUpdate. Is that possible?
    3. Once the stop and target are set, will I be able to reset or move them if they are located in the DataLoaded section of the code?
    ....a. If not which three methods can be called in the OnBarUpdate that work together in unison?
    ........- ExitLongStopMarket(MyStop);
    ........- ExitLongLimit(MyTarget);
    ........- EnterLong()?

    Code:
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class BollingerTest : Strategy
    {
    private EMA EMA1;
    private Bollinger Bollinger1;
    
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "BollingerTest";
    Calculate = Calculate.OnBarClose;
    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 = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    EMA1 = EMA(Close, 20);
    Bollinger1 = Bollinger(Close, 2, 14);
    SetStopLoss("", CalculationMode.Currency, Bollinger1.Lower[0], false);
    SetProfitTarget("", CalculationMode.Currency, Bollinger1.Upper[0]);
    }
    }
    
    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;
    
    if (CurrentBars[0] < 1)
    return;
    
    // Set 1
    if (Close[0] > EMA1[0])
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    }
    
    }
    }
    }
    Last edited by coopgrafik; 05-16-2021, 05:15 PM.

    #2
    Hello coopgrafik,

    Thanks for your post.

    The reason for the errors is that in the Strategy Builder the Set methods are established outside of OnBarUpdate() which means they can be of a fixed value only. The use of an indicator in the set methods will cause the error. The methods, when used in the strategy builder should be set for fixed value only that do not change. For example, setting them to their CalculationMode of ticks and setting the specific number of ticks from the entry. Using ticks, the methods can be used in either long or short entries as the method automatically adjusts to the direction. So no, you cannot set the set methods to a variable value in the Strategy Builder.

    It is possible to use the Set methods with variables in an unlocked strategy and moving the code into the OnBarUpdate() method.

    You cannot move a strategy's stop or profit target manually if that was your question. This can be done but would require a hybrid strategy that uses an ATM template and would need to be created entirely in Ninjscript.

    In the Strategy Builder, you can use the exit methods for your profit and stop, however, these are submitted as limit type orders and limit type orders in the strategy builder are automatically canceled when the bar closes that they are submitted on. You can overcome this by creating a set that resubmits these orders on each new bar. For example in a set you have your entry conditions and when they are true, you create and set the stop and profit prices targets into two double type variables. In another set you would check to see that the market condition is long (or short) and the action then would be to submit the exitlongstopmarket and exitlonglimit at the prices you saved in the double type variables. If the position is closed by the stop or the target the market position changes which would prevent resending the orders
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      So no, you cannot set the set methods to a variable value in the Strategy Builder.
      Thanks for your reply.

      Well, I'm sure you can understand my confusion because I can actually have a var in the method and pass a value via the user inputs by setting them up in properties.

      Code:
      else if (State == State.DataLoaded)
      {
      
      SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
      SetStopLoss("", CalculationMode.Ticks, StopLoss, false);
      
      }
      
      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="ProfitTarget", Order=1, GroupName="Parameters")]
      public int ProfitTarget
      { get; set; }
      
      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="StopLoss", Order=2, GroupName="Parameters")]
      public int StopLoss
      { get; set; }

      So because this was working it would seem logical that I could pass other values to those vars but I guess not.

      Would the below be an acceptable way to insert vars into the stop loss and profit target orders? This is just a snippet and not real code. I'm trying to understand the structure and which methods work together.


      Code:
      protected override void OnBarUpdate()
      {
      
      if ((Position.MarketPosition == MarketPosition.Flat)
      
      && ( Some conditions ))
      
      {
      
      EnterLong(Convert.ToInt32(DefaultQuantity), "");
      
      }
      
      if ((Position.MarketPosition == MarketPosition.Long)
      && (!StopAndTargetIsSet))
      
      {
      StopAndTargetIsSet = true;
      MyStop = Bollinger1.Lower[0];
      MyTarget = Bollinger1.Upper[0];
      
      ExitLongStopMarket(MyStop);
      ExitLongLimit(MyTarget);
      
      }
      
      if (Position.MarketPosition == MarketPosition.Flat)
      {
      StopAndTargetIsSet = false;
      }
      
      
      }

      Last edited by coopgrafik; 05-17-2021, 10:59 AM.

      Comment


        #4
        Hello coopgrafik,

        Thanks for your reply.

        Correct you can pass a variable from the state that you apply the strategy but the difference of using an indicator is the need for a dynamically changing value which is simply not available to the set methods when they are invoked in the OnStateChange() method.

        Yes, your example would work in general but keep in mind that on each update to the OnBarUpdate, the variables myStop and MyTarget are going to change. You might want to save those values that are in place at the time of the entry (unless moving them constantly is what you wanted).


        If you want to write in Ninjascript then you can use the set methods dynamically, here is a simple pseudo-code example:

        if (Condition to enter)
        {
        SetStopLoss(CalculationMode.Price, Bollinger1.Lower[0]); // Requirement is to set stop and target before actual entry.
        SetProfitTarget(CalculationMode.Price, Bollinger1.Upper[0]);
        EnterLong();
        }
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          I also got the error"Object reference not set to an instance of an object"
          Can you advise what wrong with the code?



          public class RINGOStrategy2 : Strategy
          {
          private MACD MACD1;

          private MACD MACD2;

          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"Enter the description for your new custom Strategy here.";
          Name = "RINGOStrategy2";
          Calculate = Calculate.OnBarClose;
          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 = 20;
          // Disable this property for performance gains in Strategy Analyzer optimizations
          // See the Help Guide for additional information
          IsInstantiatedOnEachOptimizationIteration = true;
          }
          else if (State == State.Configure)
          {
          AddDataSeries(Data.BarsPeriodType.Minute, 5);
          AddDataSeries(Data.BarsPeriodType.Minute, 1);




          }
          else if (State == State.DataLoaded)
          {
          MACD1 = MACD(Closes[1], 20, 32, 8);
          MACD1.Plots[0].Brush=Brushes.SeaGreen;
          MACD1.Panel=3;
          MACD2 = MACD(Closes[2], 20, 32, 8);
          MACD2.Plots[0].Brush=Brushes.Gold;
          MACD2.Panel=4;
          SetProfitTarget(@"RR", CalculationMode.Ticks, 15);
          SetStopLoss(@"RR", CalculationMode.Ticks, 15, false);

          }
          }

          protected override void OnBarUpdate()
          {
          if (BarsInProgress != 0)
          return;
          if (CurrentBar < BarsRequiredToTrade)
          return;

          // Set 1
          if ((MACD2.Diff[0] > 0)
          && (MACD1.Diff[0] < 0)
          && MACD1.Diff[4] > MACD1.Diff[3]
          && MACD1.Diff[3] > MACD1.Diff[2]
          && MACD1.Diff[2] > MACD1.Diff[1]
          && (Slope(MACD1.Diff, 1, 0) > 0))
          {
          EnterLong(Convert.ToInt32(DefaultQuantity), @"RR");
          }

          }
          }


          Comment


            #6
            Hello stantenlee,

            I do not see an "object reference not set to an instance of an object" error if I copy and paste the strategy into the NinjaScript Editor and test on a chart, but I see an error where the code is trying to access an index with a value that is out of range.

            This is often seen when referencing a BarsAgo value on a data series, when that data series has not processed that many bars yet.

            Please keep in mind the resource below that advises on adding CurrentBars checks to make sure you have processed enough bars before making a reference for that many BarsAgo.



            Please also see how this would apply to a multi time frame script:

            JimNinjaTrader Customer Service

            Comment


              #7
              [QUOTE=NinjaTrader_Jim;n1190422]Hello stantenlee,

              I do not see an "object reference not set to an instance of an object" error if I copy and paste the strategy into the NinjaScript Editor and test on a chart, but I see an error where the code is trying to access an index with a value that is out of range....>>are you talking about the MACD.diff[5],MACD.diff[4]??how it out of range I required 20 bars to trade?Can you let me know which part?

              This is often seen when referencing a BarsAgo value on a data series, when that data series has not processed that many bars yet.>>I set required bars to trade is 20?not this one can solve this?

              Please keep in mind the resource below that advises on adding CurrentBars checks to make sure you have processed enough bars before making a reference for that many BarsAgo.>>hhow to write the code to checkCan you give me example?I did add set f (CurrentBar < BarsRequiredToTrade)??what its mean by BarsInProgress == 0?i dun quite understand even after reading https://ninjatrader.com/support/help...gThePriceDataI nAMultibarsninjascript



              Comment


                #8
                Hello stantenlee,

                When you add a data series, OnBarUpdate gets called for each data series as you update. CurrentBar reflects the bar index of the bar that is currently updating for the data series that is currently updating.

                Please see the example from the code segment from the "Accessing the Price Data in a Multi-Bars NinjaScript" section of the Help Guide. CurrentBars[X] is used to check how many bars have been processed in X data series.

                Code:
                protected override void OnBarUpdate()
                {
                    // Checks to ensure all Bars objects contain enough bars before beginning
                    // If this is a strategy, use BarsRequiredToTrade instead of BarsRequiredToPlot
                [B]if (CurrentBars[0] <= BarsRequiredToPlot || CurrentBars[1] <= BarsRequiredToPlot || CurrentBars[2] <= BarsRequiredToPlot)[/B]
                        return;
                Last edited by NinjaTrader_Jim; 02-17-2022, 02:07 PM.
                JimNinjaTrader Customer Service

                Comment


                  #9
                  What its mean by BarsInProgress??Normally when and where i will use it?

                  Comment


                    #10
                    Hello stanlee,

                    BarsInProgress is explained in the section above "Accessing the Price Data in a Multi-Bars NinjaScript." Example on how you would use it is included as well.



                    Please be sure to review the entire Multi Time Frame and Instruments documentation when working with MuIti Time Frame scripts as there are several items to note for how to know which data series is updating, how to reference data from specific data series, know how many bars have processed in a specific data series, etc.
                    JimNinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by llanqui, Yesterday, 03:51 PM
                    1 response
                    18 views
                    0 likes
                    Last Post NinjaTrader_Gaby  
                    Started by kujista, Yesterday, 12:39 AM
                    5 responses
                    18 views
                    0 likes
                    Last Post NinjaTrader_Gaby  
                    Started by nleitman, Yesterday, 11:46 AM
                    9 responses
                    27 views
                    0 likes
                    Last Post NinjaTrader_ChelseaB  
                    Started by cmtjoancolmenero, 04-25-2024, 03:58 PM
                    18 responses
                    105 views
                    0 likes
                    Last Post NinjaTrader_ChelseaB  
                    Started by Mindset, Yesterday, 06:19 AM
                    2 responses
                    15 views
                    0 likes
                    Last Post Mindset
                    by Mindset
                     
                    Working...
                    X