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

Canceling on close in multi-instrument strategy

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

    Canceling on close in multi-instrument strategy

    Hi,

    I'm evolving from a single-instrument into multi-instrument strategy. As a single-instrument strategy, I know when the strategy is canceled, all open orders are also canceled.

    I'm finding that with a multi-instrument strategy, only pending orders on the "primary" instrument are canceled. Pending orders on the "secondary" instrument are not.

    So, two questions:

    - is this a design feature, or a bug? Any way to automatically close out secondary open orders?

    - alternatively, how do I implement this in my code? How do I "catch" a stopping strategy and cancel all of my open orders programmatically?

    #2
    Do you have an easy as possible sample demonstrating the scenario you are experiencing?

    To explicitly cancel your orders please see this reference sample: http://www.ninjatrader-support2.com/...ead.php?t=4804
    Josh P.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Josh View Post
      Do you have an easy as possible sample demonstrating the scenario you are experiencing?

      To explicitly cancel your orders please see this reference sample: http://www.ninjatrader-support2.com/...ead.php?t=4804
      I don't have any "easy" code right now. I'll see if I can put something together. It might not be worth my time... not this week, while Im' putting out so many other fires.

      That link is interesting though, I hadn't looked at OnMarketUpdate() before. How does *that* work in a multi-bar strategy? I don't see any way to pull up the instrument that it's being called on.

      Comment


        #4
        Please see Tip 1 on the bottom of this article: http://www.ninjatrader-support.com/H...arketData.html
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          Josh,

          I believe that not only does "cancel on close", trying to CancelOrder in a multi-instrument strategy doesn't work. It seems to get ignored.

          Comment


            #6
            Hi Heech,

            It would be helpful if you post the sample code producing your issue.

            Meanwhile, you can check the second advanced sample from the link Josh posted below - http://www.ninjatrader-support2.com/...ead.php?t=4804

            It contains a section with OnOrderUpdate(), which is used to monitor all your order state changes. http://www.ninjatrader-support.com/H...derUpdate.html
            BertrandNinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_Bertrand View Post
              Hi Heech,

              It would be helpful if you post the sample code producing your issue.

              Meanwhile, you can check the second advanced sample from the link Josh posted below - http://www.ninjatrader-support2.com/...ead.php?t=4804

              It contains a section with OnOrderUpdate(), which is used to monitor all your order state changes. http://www.ninjatrader-support.com/H...derUpdate.html
              Bertrand,

              I'll try to get around to building a sample for ya.

              I already use OnOrderUpdate() and monitor for canceled stops. It's not firing. I've also checked the trace logs... looks like CancelOrder is just ignored. I had TraceOrders turned on at one point, and I saw a message that said "canceling managed order"... it didn't seem to be an error message saying the cancel wouldn't go through, but now in hindsight... maybe that's what it was.

              Not sure what a managed order is exactly. I've used CancelOrder successfully before... FYI, this is on a stop order I enter using EnterStopLong(BarsInProgress, ....);

              Comment


                #8
                CancelOrder() will work for EnterLongStop() when you give it the liveUntilCancelled flag to be true.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_Josh View Post
                  CancelOrder() will work for EnterLongStop() when you give it the liveUntilCancelled flag to be true.
                  Josh,

                  That's the version I'm using:

                  currentState.stopOrder.Order = ExitLongStop(BarsInProgress, true, currentState.config.NumShares, currentState.config.HoldPrice * currentState.config.stopMultiple, currentState.config.OrderName, currentState.config.OrderName);

                  If it means anything, my ExitLongStop() order is only being called while historical. It's never repeated while I'm live.

                  Comment


                    #10
                    Not sure what you mean by "it's never repeated". If you have a reproducible scenario of CancelOrder() not working please let us know with an as-simple-as-possible sample. Thank you.
                    Josh P.NinjaTrader Customer Service

                    Comment


                      #11
                      I write up dummy code, tested it, and it is repeatable.

                      I already am long shares of HOG/LNC, which is why I'm running with this code. You can run this strategy on any chart, I ignore the primary bar. Be sure to set EntryHandling = UniqueEntries, ExitOnClose = false. (I should've put that in the initialize code... but whatever.)

                      When I ran in sim mode, it worked correctly... so the logic is sound. But when I run live auto-trading connected with TDA, I see the two stop orders for 100 shares go live/working. The stop orders are not canceled at 30 minutes.

                      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
                      
                      // This namespace holds all strategies and is required. Do not change it.
                      namespace NinjaTrader.Strategy
                      {
                          /// <summary>
                          /// Enter the description of your strategy here
                          /// </summary>
                          [Description("Enter the description of your strategy here")]
                          public class Dummy : Strategy
                          {
                              #region Variables
                              // Wizard generated variables
                              private int myInput0 = 1; // Default setting for MyInput0
                              // User defined variables (add any user defined variables below)
                              #endregion
                      
                              /// <summary>
                              /// This method is used to configure the strategy and is called once before any strategy method is called.
                              /// </summary>
                              protected override void Initialize()
                              {
                                  CalculateOnBarClose = true;
                      			TraceOrders = true;
                      			Add("HOG", PeriodType.Minute, 30);
                      			Add("LNC", PeriodType.Minute, 30);
                              }
                      
                      		bool firstHog = true;
                      		bool firstLNC = true;
                      		
                      		IOrder hogStop = null;
                      		IOrder lncStop = null;
                      
                      		/// <summary>
                              /// Called on each bar update event (incoming tick)
                              /// </summary>
                              protected override void OnBarUpdate()
                              {
                      			if (BarsInProgress == 0)  // I don't use primary symbol.
                      				return;
                      			
                      			if (BarsInProgress == 1) // Hog
                      			{
                      				if (firstHog)
                      				{
                      					EnterLong(100, "enterhog");
                      					firstHog = false;
                      				}
                      				else
                      				{
                      					if (Historical && (hogStop == null))
                      					{
                      						hogStop = ExitLongStop(BarsInProgress, true, 100, 12.0, "exithog", "enterhog");	
                      					}
                      					if (!Historical && (hogStop != null))
                      					{
                      						CancelOrder(hogStop);	
                      					}
                      				}		
                      			}
                      			if (BarsInProgress == 2) // LNC
                      			{
                      				if (firstLNC)
                      				{
                      					EnterLong(100, "enterlnc");
                      					firstLNC = false;
                      				}
                      				else
                      				{
                      					if (Historical && (lncStop == null))
                      					{
                      						lncStop = ExitLongStop(BarsInProgress, true, 100, 10.0, "exitlnc", "enterlnc");	
                      					}
                      					if (!Historical && (lncStop != null))
                      					{
                      						CancelOrder(lncStop);	
                      					}
                      				}		
                      			}
                              }
                      		
                      		protected override void OnOrderUpdate(IOrder order) 
                      		{
                      			if (order.OrderState == OrderState.Cancelled)
                      			{
                      				if (order.Token == lncStop.Token)
                      				{
                      					Print("LNC stop order canceled!");
                      				}
                      				if (order.Token == hogStop.Token)
                      				{
                      					Print("HOG stop order canceled!");	
                      				}
                      			}
                      		}
                      		
                      		
                      
                              #region Properties
                              [Description("")]
                              [Category("Parameters")]
                              public int MyInput0
                              {
                                  get { return myInput0; }
                                  set { myInput0 = Math.Max(1, value); }
                              }
                              #endregion
                          }
                      }

                      Comment


                        #12
                        By the way, I guess there's an even easier test than waiting for CancelOrder() to fire.

                        Just go long these two positions in your strategy, see the two stop orders go live, and then terminate the strategy (with "cancel on close" enabled). The orders aren't canceled, which was the original problem I reported.

                        Comment


                          #13
                          heech,

                          Please just use a simple as possible test. Place an order and try to cancel that order. No multi-time frame. No OnOrderUpdate or anything. You should find that it works. When debugging you want to start with the least amount of complexity and add on layers. If you find the base case to not even work then we can work to isolate it out and determine if it is a bug.

                          Just do something like this:
                          Code:
                          if (Historical)
                               return;
                          
                          if (entryOrder == null)
                               entryOrder = EnterLongLimit(... price that will never be filled for your instrument);
                          
                          if (count == 2)
                               CancelOrder(entryOrder);
                          
                          count++;
                          Josh P.NinjaTrader Customer Service

                          Comment


                            #14
                            Originally posted by NinjaTrader_Josh View Post
                            heech,

                            Please just use a simple as possible test. Place an order and try to cancel that order. No multi-time frame. No OnOrderUpdate or anything. You should find that it works. When debugging you want to start with the least amount of complexity and add on layers. If you find the base case to not even work then we can work to isolate it out and determine if it is a bug.
                            [/code]
                            Josh,

                            First of all, as I said before, this ONLY happens in a multi-instrument strategy; look at the subject header. I can't get rid of multi-instruments if I still want to repeat it.

                            Second, there is only one time frame here. (30 minute bars in all cases.)

                            Finally, OnOrderUpdate does nothing except print out an error message. Strip it out, the problem is still there.

                            Read through the code before you dismiss this. It doesn't get simpler than this.

                            Comment


                              #15
                              heech,

                              We do not have the bandwidth to closely dissect every single code snippet every user posts in depth. The best we can offer is a quick glance over and at a glance over you created a complex strategy. In these cases it would be even better if you just attached the file instead of copy pasting.
                              Josh P.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by burtoninlondon, Today, 12:38 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post burtoninlondon  
                              Started by AaronKoRn, Yesterday, 09:49 PM
                              0 responses
                              14 views
                              0 likes
                              Last Post AaronKoRn  
                              Started by carnitron, Yesterday, 08:42 PM
                              0 responses
                              11 views
                              0 likes
                              Last Post carnitron  
                              Started by strategist007, Yesterday, 07:51 PM
                              0 responses
                              13 views
                              0 likes
                              Last Post strategist007  
                              Started by StockTrader88, 03-06-2021, 08:58 AM
                              44 responses
                              3,983 views
                              3 likes
                              Last Post jhudas88  
                              Working...
                              X