Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Object reference not set to instance of an object

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

    Object reference not set to instance of an object

    Code:
    protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "EquityEdgeSpike";
                    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                            = 20;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration    = true;
                    Multiplier                    = 2;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    ATR1                = ATR(Close, 14);
                    ATR1.Plots[0].Brush = Brushes.DarkCyan;
                    AddChartIndicator(ATR1);
                    SetTrailStop(@"Long", CalculationMode.Ticks, ATR1[0], false);
                }
            }​

    Setting SetTrailStop generate this error -

    Code:
    SetTrailStop(@"Long", CalculationMode.Ticks, ATR1[0], false);

    ​Error on Calling OnStateChange method: Object reference not set to instance of an object
    Attached Files

    #2
    Inside State.DataLoaded, you cannot use ATR1[0] since
    the ATR values are not available until OnBarUpdate has
    executed and calculated them. Because there is no value
    stored at the '[0]' slot yet, you get that error.

    Even then, because you've said 14, you should wait for
    the 14th bar in OnBarUpdate before you use the ATR
    value in ATR1[0].

    Wait, did I say 'use' -- I meant 'trust'.

    Don't you want the full range of 14 bars to be used in
    calculating your ATR values? Well, then, any ATR value
    before 14 bars have passed is not 'fully formed', right?

    Your period is 14, so the first 13 ATR values calculated
    for the first 13 bars are not to be trusted.

    But, for sure inside State.DataLoaded, not a single
    ATR value is available yet -- because OnBarUpdate has
    not executed yet, not even once.
    Last edited by bltdavid; 12-08-2023, 09:59 AM. Reason: typo -- OnDataLoaded should be DataLoaded -- bad fingers, bad

    Comment


      #3
      Hello futtrader,

      Thank you for your post.

      bltdavid is correct that you may not access ATR1[0] in OnStateChange() when the state is State.Dataloaded where you are currently calling SetStopLoss(). For a dynamic stop loss, you will need to call SetStopLoss() in OnBarUpdate(). The following reference sample demonstrates how you can modify the price of stop loss and profit target orders:


      More information about what is happening when each state is called may be found on this page:


      There has been discussion about using an indicator for a stop loss value and helpful information on this topic, including some examples that use ATR for the stop loss, may be found in the following thread:
      Hello support team, I have 2 dataseries, a 1minute to detect the ATR value. Now I would like to set the stoploss and profit target based on the actual ATR Value Example: Stoploss 2xATR Profittarget 3xATR value 1. How can this be done with builder, I have no coding experience 2. Later I would like to have the possibility to


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

      Comment


        #4
        Originally posted by bltdavid View Post
        Inside State.DataLoaded, you cannot use ATR1[0] since
        the ATR values are not available until OnBarUpdate has
        executed and calculated them. Because there is no value
        stored at the '[0]' slot yet, you get that error.

        Even then, because you've said 14, you should wait for
        the 14th bar in OnBarUpdate before you use the ATR
        value in ATR1[0].

        Wait, did I say 'use' -- I meant 'trust'.

        Don't you want the full range of 14 bars to be used in
        calculating your ATR values? Well, then, any ATR value
        before 14 bars have passed is not 'fully formed', right?

        Your period is 14, so the first 13 ATR values calculated
        for the first 13 bars are not to be trusted.

        But, for sure inside State.DataLoaded, not a single
        ATR value is available yet -- because OnBarUpdate has
        not executed yet, not even once.
        thanks you for your response but my concern is I am using Strategy Builder and I assume Strategy Builder will place this code at the right place. I've not chosen to put the following line of code inside OnStateChange block, strategy builder has inserted into OnStateChange block.

        Code:
        SetTrailStop(@"Long", CalculationMode.Ticks, ATR1[0], false);

        Comment


          #5
          Originally posted by NinjaTrader_Emily View Post
          Hello futtrader,

          Thank you for your post.

          bltdavid is correct that you may not access ATR1[0] in OnStateChange() when the state is State.Dataloaded where you are currently calling SetStopLoss(). For a dynamic stop loss, you will need to call SetStopLoss() in OnBarUpdate(). The following reference sample demonstrates how you can modify the price of stop loss and profit target orders:


          More information about what is happening when each state is called may be found on this page:


          There has been discussion about using an indicator for a stop loss value and helpful information on this topic, including some examples that use ATR for the stop loss, may be found in the following thread:
          Hello support team, I have 2 dataseries, a 1minute to detect the ATR value. Now I would like to set the stoploss and profit target based on the actual ATR Value Example: Stoploss 2xATR Profittarget 3xATR value 1. How can this be done with builder, I have no coding experience 2. Later I would like to have the possibility to


          Please let us know if we may be of further assistance.
          thanks you for reference link but I am using Strategy Builder to build this Strategy.

          Comment


            #6
            Hello futtrader,

            Thank you for your reply.

            Since you are using the Strategy Builder, the link I shared is even more helpful and relevant. As stated in that post, "Unfortunately, a limitation of the Strategy Builder is the Stops and Targets cannot use dynamic values. These are set once in State.Configure, and are not updated during the life of the script in OnBarUpdate."

            You are not able to use dynamic price values, such as an indicator value, on the Stops and Targets screen of the Strategy Builder. You must instead set up details on the Conditions and Actions page using actions to "Exit" a position so that Exit() orders are used rather than SetStopLoss() orders. The sample posted on that page is called IndicatorAsOrderPriceBuilderExample_NT8 and is an example of using an indicator for an order's price in the Strategy Builder. You may view how it is set up by downloading the .zip file, then go to Control Center > Tools > Import > NinjaScript AddOn to import the downloaded .zip. Next, once the import is successful, open a Strategy Builder and select the IndicatorAsOrderPriceBuilderExample strategy to click through the screens and see how it is set up. Here is the link again:
            Hello support team, I have 2 dataseries, a 1minute to detect the ATR value. Now I would like to set the stoploss and profit target based on the actual ATR Value Example: Stoploss 2xATR Profittarget 3xATR value 1. How can this be done with builder, I have no coding experience 2. Later I would like to have the possibility to


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

            Comment


              #7
              Originally posted by NinjaTrader_Emily View Post
              Hello futtrader,

              Thank you for your reply.

              Since you are using the Strategy Builder, the link I shared is even more helpful and relevant. As stated in that post, "Unfortunately, a limitation of the Strategy Builder is the Stops and Targets cannot use dynamic values. These are set once in State.Configure, and are not updated during the life of the script in OnBarUpdate."

              You are not able to use dynamic price values, such as an indicator value, on the Stops and Targets screen of the Strategy Builder. You must instead set up details on the Conditions and Actions page using actions to "Exit" a position so that Exit() orders are used rather than SetStopLoss() orders. The sample posted on that page is called IndicatorAsOrderPriceBuilderExample_NT8 and is an example of using an indicator for an order's price in the Strategy Builder. You may view how it is set up by downloading the .zip file, then go to Control Center > Tools > Import > NinjaScript AddOn to import the downloaded .zip. Next, once the import is successful, open a Strategy Builder and select the IndicatorAsOrderPriceBuilderExample strategy to click through the screens and see how it is set up. Here is the link again:
              https://forum.ninjatrader.com/forum/...tr#post1142942

              Please let us know if we may be of further assistance.
              thanks while trying this I am getting below error. I think I know the issue but I don't know how can I say for
              exitlongEntryLimitOrder EntryPrice + (2 * ATR[0] )
              exitlongEntryStopOrder EntryPrice - (2 * ATR[0] )

              Attached Files

              Comment


                #8
                Originally posted by futtrader View Post

                thanks while trying this I am getting below error. I think I know the issue but I don't know how can I say for
                exitlongEntryLimitOrder EntryPrice + (2 * ATR[0] )
                exitlongEntryStopOrder EntryPrice - (2 * ATR[0] )

                What error are you referring to? I do not see an error message in the screenshot you provided.

                I look forward to your response.

                Comment


                  #9
                  I can still see in Snapshot not sure why you can not see.

                  Basically error is it set the StopLimit order to just ATR[0] value while instrument is trading at 16300

                  Bascially I need
                  entry price [+|-] ATR[0]

                  Comment


                    #10
                    Originally posted by futtrader View Post
                    I can still see in Snapshot not sure why you can not see.

                    Basically error is it set the StopLimit order to just ATR[0] value while instrument is trading at 16300

                    Bascially I need
                    entry price [+|-] ATR[0]
                    To get the entry price, you can expand the Strategy folder and select Average position price. From there, you can apply an offset to add or subtract the value of the ATR. Here is a short video where I select an action of "Exit short position by a stop order" and set the stop price to the average position price plus the ATR of the current bar:
                    World's leading screen capture + recorder from Snagit + Screencast by Techsmith. Capture, edit and share professional-quality content seamlessly.


                    On another note, I see you have your entry and exit orders all in the same set of conditions and actions. Stop and limit orders are only kept active if the condition to submit them remains true; this means you will need to have one set for your entry conditions and action and a separate set for your exit orders. Typically for exit orders, you could set the condition to something like if the current market position is short/long, then set the action to the desired exit orders. This way the condition to submit the exit orders remains true while there is an open position and the orders continue to stay active. Otherwise, the orders are canceled as soon as the condition to submit the orders is no longer true.

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

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by NullPointStrategies, Yesterday, 05:17 AM
                    0 responses
                    62 views
                    0 likes
                    Last Post NullPointStrategies  
                    Started by argusthome, 03-08-2026, 10:06 AM
                    0 responses
                    134 views
                    0 likes
                    Last Post argusthome  
                    Started by NabilKhattabi, 03-06-2026, 11:18 AM
                    0 responses
                    75 views
                    0 likes
                    Last Post NabilKhattabi  
                    Started by Deep42, 03-06-2026, 12:28 AM
                    0 responses
                    45 views
                    0 likes
                    Last Post Deep42
                    by Deep42
                     
                    Started by TheRealMorford, 03-05-2026, 06:15 PM
                    0 responses
                    50 views
                    0 likes
                    Last Post TheRealMorford  
                    Working...
                    X