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

Re-Entry Order Crashing NT

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

    Re-Entry Order Crashing NT

    Having platform crashes with a line of script, and I'm not sure what's wrong.

    I’ve been creating a backtesting strategy where a new entry order is generated once an existing trade is stopped out. I’ve set it up so the very first entry is assigned to an object, and when the trade exits at either its target or protective stop, the object is set to null, and if the exit was a stop-out, the same object is assigned another entry order (at a price that's some distance from that stop-out). I’m using the very same line of code for the second entry order as the first one; however, when ran, NT either crashes or endlessly loops (frozen app, maxed CPU, nothing in the output window).
    Strange thing is, in the second entry assignment, if I substitute plain static numbers for the variables used for the limit and stop values, it doesn’t crash. The first entry assignment happens in the OnBarUpdate block, and I’ve tried the second one in the OnPositionUpdate and OnExecute blocks with the same crash behavior.

    #2
    Shogun SunTzu,

    We would love to help, but will need more information as to the exact lines of code you use and when you use them to help evaluate the scenario. Thank you.
    Josh P.NinjaTrader Customer Service

    Comment


      #3
      Re-Entry Crashing NT

      OK, here's the code I'm using. Look for the comment rows about 3/4 of the way down in the OnPositionUpdate block. The first line (the one I'd like to use) crashes NT, and either of the next two don't, and the only substitutions are hard numeric values instead of variables.
      FYI, the "crash" is probably more like an "endless loop" situation -- NT becomes frozen (stuck on "cannot abort this operation"), maxes the CPU, and the page file usage steadily grows, but if I force-quit it the computer is OK (not a system freeze).

      Code:
      #region Using declarations
      using System;
      using System.ComponentModel;
      using System.Diagnostics;
      using System.Drawing;
      using System.Drawing.Drawing2D;
      using System.Xml.Serialization;
      using NinjaTrader.Cbi;
      using NinjaTrader.Data;
      using NinjaTrader.Indicator;
      using NinjaTrader.Gui.Chart;
      using NinjaTrader.Strategy;
      #endregion
      
      namespace NinjaTrader.Strategy  {
      
      [Description("Enter the description of your strategy here")]
      
      public class CrashProblem1 : Strategy  {
      
          private double interval = 0.50;        // Default setting for Interval.
          private double limitOrderSlippage = 0.03;    // Slippage allowed on limit orders.
          private double DayOpenPrice;         // Value of the day's opening price.
          private int shareSize = 1;            // Integer value used in entry methods.
          private bool DoneForTheDay = false;    //    Used to shut off trading upon an exit at a profit target.
          private IOrder InLongOrder = null;
          private IOrder TargetOrder = null;
          private IOrder ProtectiveStopOrder = null;
      
      
          protected override void Initialize()  {
                  
              CalculateOnBarClose = true;
              ExitOnClose = true;
              ExitOnCloseSeconds = 120;
              TimeInForce = Cbi.TimeInForce.Day;
              DefaultQuantity = ShareSize;
                  
          }
      
          protected override void OnExecution(IExecution execution)  {
              
              // Actions for executions of InLongOrder.
              if (InLongOrder != null && InLongOrder.Token == execution.Order.Token)  {
                  // When the entry order fills, this sets protective stop and profit target orders.
                  if ((execution.Order.OrderState == OrderState.Filled) || (execution.Order.OrderState == OrderState.PartFilled) || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))  {
                      Print(Time[0] + "___FILLED InLongOrder at:  " + execution.Price);
                      // Protective Stop set to day's open price.
                      ProtectiveStopOrder = ExitLongStop(0, true, execution.Order.Filled, DayOpenPrice, "LongProtectiveStop", "InLong");
                      // Target set to 2 intervals above day's open.
                      TargetOrder = ExitLongLimit(0, true, execution.Order.Filled, (DayOpenPrice + (2 * interval)), "LongTarget", "InLong");
                      // Resets the InLongOrder object to null if the order has been filled or cancelled.
                      if (execution.Order.OrderState != OrderState.PartFilled)  {
                          InLongOrder = null;
                      }
                  }
              }
              // Actions for executions of ProtectiveStopOrder OR TargetOrder.
              if ((ProtectiveStopOrder != null && ProtectiveStopOrder.Token == execution.Order.Token) || (TargetOrder != null && TargetOrder.Token == execution.Order.Token))  {
                  // Reset ProtectiveStop and Target orders to null after the position closes.
                  if (execution.Order.OrderState == OrderState.Filled)  {
                      // Actions for ProtectiveStopOrder getting filled.
                      if (ProtectiveStopOrder != null && ProtectiveStopOrder.Token == execution.Order.Token) {
                          Print(Time[0] + "___STOPPED OUT at: " + execution.Price + ", target order cancelled");
                      }
                      if (TargetOrder != null && TargetOrder.Token == execution.Order.Token) {
                          Print(Time[0] + "___TARGET REACHED at: " + execution.Price + ", protective stop cancelled");
                          DoneForTheDay = true;
                      }
                      ProtectiveStopOrder = null;
                      TargetOrder = null;
                  }
              }
          }
      
          protected override void OnOrderUpdate(IOrder order)  {
      
              if (InLongOrder != null && InLongOrder.Token == order.Token)  {    
                  if (order.OrderState == OrderState.Cancelled && order.Filled == 0)  {    // Reset the Entry Order if cancelled without any fill.
                      Print(Time[0] + "___CANCEL InLongOrder");
                      InLongOrder = null;
                  }
              }
          }
      
          protected override void OnPositionUpdate(IPosition position)  {
      
              if (position.MarketPosition == MarketPosition.Flat)  { 
                  Print(Time[0] + "___FLAT");
                  if (! DoneForTheDay && (ToTime(Time[0]) < ToTime(12, 30, 0)) ) {
                      
                      //=====================>>>>   the following line CRASHES NJ   <<<<======================================
                      // InLongOrder = EnterLongStopLimit(0, true, ShareSize, (DayOpenPrice + Interval + LimitOrderSlippage), (DayOpenPrice + Interval), "InLong");
                      
                      //=====================>>>>   the following does NOT crash NJ   <<<<======================================
                      // InLongOrder = EnterLongStopLimit(0, true, ShareSize, 501, 500, "InLong"); // Stop and limit prices placed far above trading range for testing purposes.
                      
                      //=====================>>>>   the following does NOT crash NJ   <<<<======================================
                      // InLongOrder = EnterLongStopLimit(0, true, ShareSize, 51, 50, "InLong"); // Stop and limit prices placed far below trading range for testing purposes.
                      
                      Print (Time[0] + "___PLACED RE-ENTRY InLongOrder, for:  " + (DayOpenPrice + Interval));
                  }
              }
          }
      
          protected override void OnBarUpdate()  {
              
              //  INITIAL ORDERS upon first bar following market open.
              if ((ToTime(Time[0]) >= ToTime(9, 30, 0)) && (ToTime(Time[1]) < ToTime(9, 30, 0))) {
                  DoneForTheDay = false;
                  DayOpenPrice = Open[0];
                  InLongOrder = EnterLongStopLimit(0, true, ShareSize, (DayOpenPrice + Interval + LimitOrderSlippage), (DayOpenPrice + Interval), "InLong");
                  Print (Time[0] + "___PLACED InLongOrder, for:  " + (DayOpenPrice + Interval));
              }
          }
      
      
              #region Properties
              [Description("")]
              [Category("Parameters")]
              public double Interval {
                  get { return interval; }
                  set { interval = Math.Max(-1000000, value); }
              }
              [Description("")]
              [Category("Parameters")]
              public double LimitOrderSlippage {
                  get { return limitOrderSlippage; }
                  set { limitOrderSlippage = Math.Max(-1000000, value); }
              }
              [Description("")]
              [Category("Parameters")]
              public int ShareSize {
                  get { return shareSize; }
                  set { shareSize = Math.Max(-1000000, value); }
              }
              #endregion
          }
      }

      Comment


        #4
        I suggest you debug those values first.
        (DayOpenPrice + Interval + LimitOrderSlippage)
        (DayOpenPrice + Interval)

        You will want to ensure these actually produce valid numbers for use.

        Suggest you use some prints in OnOrderUpdate() and OnExecution() to try and see if the order is hanging elsewhere in your code. It may not necessarily be the submission causing the problem. Please use Print() throughout to confirm.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          Update 1

          All those variables return valid numbers, and when that one line is commented out, all the code blocks complete without hangs. Unfortunately, there's no output at all when the line is active and it freezes, so I don't know at what point the process hangs.
          The confounding part is that it doesn't crash with those two hard number values are used instead of the variables, yet the variables return valid numbers, so this shouldn't be a scope problem.


          An updated OnPositionUpdate block:

          Code:
              protected override void OnPositionUpdate(IPosition position)  {
          
                  if (position.MarketPosition == MarketPosition.Flat)  { 
                      Print(Time[0] + "___FLAT");
                      if (! DoneForTheDay && (ToTime(Time[0]) < ToTime(12, 30, 0)) ) {
                          
                          // These all return valid numbers.
                          Print("DayOpenPrice: " + DayOpenPrice);
                          Print("Interval: " + Interval);
                          Print("LimitOrderSlippage: " + LimitOrderSlippage);
                          Print("Open plus Interval plus Slippage: " + (DayOpenPrice + Interval + LimitOrderSlippage));
                          Print("Open plus Interval" + (DayOpenPrice + Interval));
                          
                          //=====================>>>>   the following line CRASHES NJ   <<<<======================================
                          // InLongOrder = EnterLongStopLimit(0, true, ShareSize, (DayOpenPrice + Interval + LimitOrderSlippage), (DayOpenPrice + Interval), "InLong");
                          
                          //=====================>>>>   the following does NOT crash NJ   <<<<======================================
                          // InLongOrder = EnterLongStopLimit(0, true, ShareSize, 501, 500, "InLong"); // Stop and limit prices placed far above trading range for testing purposes.
                          
                          //=====================>>>>   the following does NOT crash NJ   <<<<======================================
                          // InLongOrder = EnterLongStopLimit(0, true, ShareSize, 51, 50, "InLong"); // Stop and limit prices placed far below trading range for testing purposes.
                          
                          Print (Time[0] + "___PLACED RE-ENTRY InLongOrder, for:  " + (DayOpenPrice + Interval));
                      }
                  }
              }

          Comment


            #6
            Shogun,

            Strip down your code to bare necessities. Remove all of that extra things you have around your strategy and simply place an EnterLongStopLimit() order. Disregard all IOrder objects. Remove OnOrderUpdate/Execution. Then try again.
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              Backing Up

              Perhaps I should first ask whether or not there's an implicit problem with re-using that IOrder object for a second or third entry. I came to learn in the past that long and short orders can't be placed simultaneously in a single strategy, which is just one of those limitations that I don't remember seeing in the manual, so could this be another of those arcane limitations ?

              Similarly, could this be related to multiple entry issues, even though in this case my re-entry only happens after the previous entry's trade has closed out and the IOrder object has been reset to null ?

              Thanks !

              Comment


                #8
                Shogun,

                Normally you can recycle provided everything is tidy. You will need to bring it down to a base case that works and then slowly add on layers of complexity to figure out where it breaks.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  Unfortunately, I got to this point by adding piece by piece and making sure it works at each step before building on. I have it drilled down to not just that one order method, but two specific parameters passed to the method (remember if I put hard values in there, no crash).

                  It's possible (and likely, I hope) that there's something hidden going on that rebuilding all over again my reveal, but until I am able to do that, it would be really helpful if someone could duplicate my results, by running the strategy (posted earlier) in a simple backtest. If it's reproducable, I can eliminate the possibility of something strange going on in my local implementation. I could also pose this in the platform-related topic areas, too.

                  I really appreciate the help, guys !

                  Comment


                    #10
                    Shogun,

                    All I can suggest is to try simple cases. Try variables that are not user parameters. Bring it to where it breaks.

                    Try very simple cases for yourself too. Just try placing EnterLongStopLimit() with the variables in OnBarUpdate() and nothing else. Change OnPositionUpdate() to see when it is long to place another EnterLongStopLimit() order. See if that very basic case works. Remember to increase your EntriesPerDirection and also turn TraceOrders = true on.
                    Josh P.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by PaulMohn, Today, 03:49 AM
                    0 responses
                    7 views
                    0 likes
                    Last Post PaulMohn  
                    Started by inanazsocial, Today, 01:15 AM
                    1 response
                    9 views
                    0 likes
                    Last Post NinjaTrader_Jason  
                    Started by rocketman7, Today, 02:12 AM
                    0 responses
                    10 views
                    0 likes
                    Last Post rocketman7  
                    Started by dustydbayer, Today, 01:59 AM
                    0 responses
                    4 views
                    0 likes
                    Last Post dustydbayer  
                    Started by trilliantrader, 04-18-2024, 08:16 AM
                    5 responses
                    23 views
                    0 likes
                    Last Post trilliantrader  
                    Working...
                    X