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

Error: Object reference not set to an instance of an object

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

    Error: Object reference not set to an instance of an object

    I am receiving this error and I believe it has to so with this bit of code. I am create a second entry by referencing entryOrder1's fill price. It compiles with no errors but creates this error in my output window and control center. I am sure it is something simple but my programming capabilities are limited.

    Code:
    if (entryOrder2 == null && entryOrder1.AvgFillPrice >= (entryOrder1.AvgFillPrice + n/2))
    **NT** Error on calling 'OnBarUpdate' method for strategy 'NTDonchianTurtleSystem/02f1b55108bf45d8b41dbb7b3a9ddbf3': Object reference not set to an instance of an object.

    #2
    cfree,

    This means you probably aren't instantiating entryOrder1 or entryOrder2. You probably need to check to make sure entryOrder1 isn't null when you try to access it, as I suspect this is the issue.
    Adam P.NinjaTrader Customer Service

    Comment


      #3
      entryOrder1 is null at the moment because it has already triggered, been filled, and reset back to null. These are my two orders under OnBarUpdate(). It it is not null, then how would it have an average fill price? Or should I enter entryOrder2 under OnExecution? Probably a better way, yes? Thanks again and I am sorry for my lack of experience.

      Code:
      			// Submit an entryOrder1 if we currently don't have an entryOrder1 open
      			if (entryOrder1 == null && Close[0] >= DonchianChannelATR(EntryPeriod).UpperLine[1])
      			{
      				entryOrder1 = EnterLongLimit((int)oneUnit, longEntryPrice, "LongPosition1");
      			}
      			
      			// Submit an entryOrder2 if we currently don't have an entryOrder2 open and entryOrder1 has increased by n/2 over fill price
      			if (entryOrder2 == null && entryOrder1.AvgFillPrice >= (entryOrder1.AvgFillPrice + n/2))
      			{
      				entryOrder2 = EnterLongLimit((int)oneUnit, Close[0], "LongPosition1");
      			}
      Last edited by cfree5119; 02-27-2012, 01:00 PM.

      Comment


        #4
        cfree,

        I would suggest using a Try/Catch to see exactly which line is causing the issue.

        http://www.ninjatrader.com/support/f...ead.php?t=9825

        If you print to the output window it will show you which line caused the exception.
        Adam P.NinjaTrader Customer Service

        Comment


          #5
          I ran the try catch on the OnBarUpdate() section of my code and received this message below. Looks like your suspicion was correct. Would it be best to move my entryOrder2 to to OnExecution() and submit this order once entryOrder1 is executed but before I reset it to null as well?


          2/27/2012 11:00:00 PM System.NullReferenceException: Object reference not set to an instance of an object.
          at NinjaTrader.Strategy.NTDonchianTurtleSystem.OnBarU pdate()

          Comment


            #6
            cfree,

            Its a good idea to check if the order is null before you reference it ever. So in any conditions where you access EntryOrder1 or entryOrder2 you also check that entryOrder1 != null and entryOrder2 != null respectively.

            You can use OnExecution() but its also a good idea to check that the order object is not null here.

            From our help guide : http://www.ninjatrader.com/support/h...nexecution.htm

            Code:
            protected override void OnBarUpdate()
            {
                if (entryOrder == null && Close[0] > Open[0])
                     entryOrder = EnterLong();
            }
             
            protected override void OnExecution(IExecution execution)
            {
                if (entryOrder != null && entryOrder == execution.Order)
                     Print(execution.ToString());
            }
            Adam P.NinjaTrader Customer Service

            Comment


              #7
              Hello Adam,

              I try to find with Try/Catch the reason for a message in log tab with "object reference..." but I do not get in output window the line that is causing the issue as you posted. It shows "NullReferenceException" but not the line(?)

              But another question in this concern please: would it be correct to do

              if(entryOrderA!=null || entryOrderB!=null)
              {CancelOrder(entryOrderA); CancelOrder(entryOrderB; )}

              or might this cause the message with "...not set to an instance..."?

              But if there are more orders and one doesn´t know wich one is not null, then one has to code every possible combination of orders that might not be null (?)

              (if a or a+b or a+c or a+d or b+c.....)??

              Thank you
              Tony
              Last edited by tonynt; 07-14-2017, 09:48 AM. Reason: clearification

              Comment


                #8
                Hello Tony,

                Thank you for your post.
                Originally posted by tonynt View Post
                I try to find with Try/Catch the reason for a message in log tab with "object reference..." but I do not get in output window the line that is causing the issue as you posted. It shows "NullReferenceException" but not the line(?)
                You would reference back to the line(s) in your code that are within the Try.

                Originally posted by tonynt View Post
                if(entryOrderA!=null || entryOrderB!=null)
                {CancelOrder(entryOrderA); CancelOrder(entryOrderB; )}
                This would cause the object reference error as you are checking if one order or another are null and then referencing both. I would suggest the following instead:
                Code:
                if(entryOrderA!=null)
                CancelOrder(entryOrderA);
                if (entryOrderB!=null)
                CancelOrder(entryOrderB;
                This way you are checking specifically for the order as null before proceeding.

                Originally posted by tonynt View Post
                But if there are more orders and one doesn´t know wich one is not null, then one has to code every possible combination of orders that might not be null (?)
                This is correct to a certain extent. You would use your knowledge of your script and follow it's logic to the cause. Try Catch blocks can help to break down the script into chunks that you check for null at. If you have several orders and are unsure of which is causing the null reference then try running separate Try Catch blocks around each order reference and outputting specific messages to that section so you can easily refer back to the section in the code.

                Please let me know if you have any questions.

                Comment


                  #9
                  Hello,

                  I am having a similar issue with this line:

                  Code:
                  myLong1 = EnterLongLimit(Convert.ToInt32(1), KeltnerChannel1.Lower[0], @"myLong1");
                  It is causing the error "object reference not set to an instance of an object", even though the order is null (as I declare it null at the beginning of the code, with other variables):

                  Code:
                  private Order myLong1 = null;
                  The code compiles properly, but I cannot start the strategy because of this error. How can I resolve this issue? I do need to access the order later in the code, in order to update it, which is why I try to assign enterlonglimit to an order.

                  Thank you!
                  Guillaume

                  Comment


                    #10
                    Hello Guillaume,

                    What is KeltnerChannel1 ?

                    Is this is custom indicator that you have created? (perhaps this is a copy and modified version of the KeltnerChannel indicator?)

                    Are you able to print the value for this above the line of code that is causing an error?
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hello Chelsea,

                      It is the usual keltner channel indicator, that I initialize in the OnStateChange() method:

                      Code:
                      else if (State == State.DataLoaded)
                                  {                
                                      KeltnerChannel1                = KeltnerChannel(Close, 1.5, 10);
                                      //ATR1                = ATR(Close, 14);
                      
                      
                                      //SetTrailStop(@"myLong2", CalculationMode.Ticks, KeltnerChannel1.Midline[0], false);
                                  }
                      I took this from the structure given by your strategy builder. I do not update this indicator in the OnBarUpdate() method, as I assume it is done automatically.

                      I have also tried to change the KeltnerChannel1.Midline[0] to KeltnerChannel1.Midline[1], and also the other parameters in the order function, but I get the same issue...

                      Comment


                        #12
                        Hello Guillaume,

                        With the code provided I would not expect an error.

                        No objects appear to be called other than the KeltnerChannel1.Lower[0]..

                        If you comment this line out, does the error stop?

                        Is there a different line of code that is causing the error that you have not provided?

                        I've copied this code into a test script. I did not receive any errors.

                        Attached is the test script.

                        Below is a link to a video of the test.
                        https://drive.google.com/file/d/1MCb...w?usp=drivesdk


                        Btw, you are assigning an order to myLong1 from the order call. Instead, you need to assign the order object from OnOrderUpdate().

                        From the help guide:
                        "OnOrderUpdate() will run inside of order methods such as EnterLong() or SubmitOrderUnmanaged(), therefore attempting to assign an order object outside of OnOrderUpdate() may not return as soon as expected. If your strategy is dependent on tracking the order object from the very first update, you should try to match your order objects by the order.Name (signal name) from during the OnOrderUpdate() as the order is first updated."
                        https://ninjatrader.com/support/help...rderupdate.htm

                        This wouldn't really have an effect on the code you have provided so far, but would be necessary if myLong1 was attempted to be called after this.

                        Below are links to some examples I have that use Order variable types assigned from OnOrderUpdate().
                        https://ninjatrader.com/support/foru...269#post802269

                        As well as a link to a forum post that demonstrates how to use prints to debug a script and find a line of code that is causing an error.
                        https://ninjatrader.com/support/foru...121#post791121
                        Attached Files
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Thank you very much Chelsea for your answer and for sending me so much material! I think the issue was that I need to access the myLong1 object later. I will study the code examples you have sent and I will adapt them to my code. I'll let you know how it goes.

                          Comment


                            #14
                            Hello Chelsea,

                            Analyzing and getting to understand your code has been a great learning curve, thank you for sharing it!

                            I adapted your ProfitChaseStopTrailExitOrdersExample and it now trades following a very basic strategy.

                            When I backtest the strategy and look at the chart from the strategy analyzer, I realized that there seems to be some inconsistencies, with profit targets hit on bars at prices that do not exist on such bars (for instance, see screenshot attached). Does it mean that there is something wrong in my code? This is a screenshot for a session in December 2018, using a 1 minute chart and adding a 1 tick series to the strategy, as per your code.

                            Click image for larger version

Name:	NinjaTrade Strategy Analyzer.png
Views:	789
Size:	96.2 KB
ID:	1057043

                            Thank you!
                            Guillaume

                            Comment


                              #15
                              Hello ggingembre,

                              It could be an issue with the historical tick data.

                              If you open a 1 tick chart over that time period do you see data for the entire time period?

                              (edit)
                              Open a 1 tick chart over the same time period, then right-click the chart and select Reload All Historical Data.

                              Also are you using 8.0.18.0?
                              Last edited by NinjaTrader_ChelseaB; 05-14-2019, 07:21 AM.
                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by ticktradr, Today, 09:28 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post ticktradr  
                              Started by dibDab, Today, 07:33 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post dibDab
                              by dibDab
                               
                              Started by hamdan, Yesterday, 05:57 PM
                              2 responses
                              37 views
                              0 likes
                              Last Post hamdan
                              by hamdan
                               
                              Started by NIncash, 09-21-2022, 02:20 PM
                              3 responses
                              36 views
                              0 likes
                              Last Post NIncash
                              by NIncash
                               
                              Started by brenthilburn, Today, 06:19 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post brenthilburn  
                              Working...
                              X