Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Cancelling Order if Conditions Change

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

    #31
    Cancelling Orders

    Thanks Matthew, your last suggestion really helped. I adjusted my exit signals as you suggested and it is working better now. But I do now have a new problem. It appears the section of my code which enters stops and targets after a fill execution isn't working. I had to add a test to see if I had an open position without stops and targets, then I had to add them in. That fixed my immediate problem but now, I have positions open for a bar or two with no stops or targets. I used the code right out of the sample, for onExecution, but I'm wondering if I somehow messed it up by adding my test for whether the execution was a long position or a short position. Here's the code I am using:

    Code:
            protected override void OnExecution(IExecution execution)
            {
    			/* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
    			which ensures your strategy has received the execution which is used for internal signal tracking. */
    [COLOR="Red"]			if (entryOrder != null && entryOrder == execution.Order && entryOrder.OrderAction == OrderAction.Buy)[/COLOR]
    			{
    				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
    				{
    					// Stop-Loss order 4 ticks below our entry price
    					stopOrder 	= ExitLongStop(1, true, DefaultQuantity, Position.AvgPrice - ATRTicks(14).Max_ATR[0] * TickSize, "LAbv_Stop", "LAbv_Band");
    					
    					// Target order 8 ticks above our entry price
    					targetOrder = ExitLongLimit(1, true, DefaultQuantity, Position.AvgPrice + (ATRTicks(14).ATRinTicks[0] - P_Offset) * TickSize, "LAbv_Trgt", "LAbv_Band");
    					
    					// Resets the entryOrder object to null after the order has been filled or partially filled
    					if (execution.Order.OrderState != OrderState.PartFilled)
    					{
    						entryOrder 	= null;
    					}
    				}
    			}
    			if(entryOrder != null && entryOrder == execution.Order && entryOrder.OrderAction == OrderAction.SellShort)
    			{
    				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0) )
    				{
    						// Stop-Loss order max ATR above entry price
    						stopOrder 	= ExitShortStop(1, true, DefaultQuantity, Position.AvgPrice + ATRTicks(14).Max_ATR[0] * TickSize, "SBlo_Stop", "SBlo_Band");
    					
    						// Target order one ATR below entry price
    						targetOrder = ExitShortLimit(1, true, DefaultQuantity, Position.AvgPrice - (ATRTicks(14).ATRinTicks[0] - P_Offset) * TickSize, "SBlo_Trgt", "SBlo_Band");
    					
    
    				// Resets the entryOrder object to null after the order has been filled or partially filled					
    				if (execution.Order.OrderState != OrderState.PartFilled)
    					{
    					entryOrder 	= null;
    					}
    				}
    			}
    			
    			// Reset our stop order and target orders' IOrder objects after our position is closed.
    			if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
    			{
    				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
    				{
    					stopOrder = null;
    					targetOrder = null;
    				}
    			}
    		}
    The section of the code formatted in red, is where I have a question. This statement
    entryOrder.OrderAction == OrderAction.Buy)
    I am using to determine if the executed action was a buy, (later I have the same test for a sell) so I can determine what the stop and target need to be. Is it possible that I have that incorrectly formatted so I'm not getting my stop and target placed on execution? Is there an easy way I can test for that to see if it is working as I expect?
    Thanks
    DaveN

    Comment


      #32
      daven,

      I would suggest trying this :

      Code:
      if (entryOrder != null && entryOrder == execution.Order && entryOrder.OrderAction == OrderAction.Buy)
      			{
                                      Print("Order is a buy");
      				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
      				{
                                              Print("Orderstate valid for submitting stops");
      					// Stop-Loss order 4 ticks below our entry price
      					stopOrder 	= ExitLongStop(1, true, DefaultQuantity, Position.AvgPrice - ATRTicks(14).Max_ATR[0] * TickSize, "LAbv_Stop", "LAbv_Band");
      					
      					// Target order 8 ticks above our entry price
      					targetOrder = ExitLongLimit(1, true, DefaultQuantity, Position.AvgPrice + (ATRTicks(14).ATRinTicks[0] - P_Offset) * TickSize, "LAbv_Trgt", "LAbv_Band");
      					
      					// Resets the entryOrder object to null after the order has been filled or partially filled
      					//if (execution.Order.OrderState != OrderState.PartFilled)
      					//{
      					//	entryOrder 	= null;
      					//}
      				}
      			}
      Use print statements liberally to check for things. You can then open the Tools > Output window and run your strategy, checking values you print out and/or that the code is getting through your if statements, etc.

      You can also perhaps check the "targetOrder" in the "OnOrderUpdate" method to make sure its getting submitted.

      Code:
      protected override void OnOrderUpdate(IOrder order)
      {
          if (targetOrder != null && targetOrder == order)
          {
               Print(order.ToString());
              if (order.OrderState == OrderState.Working)
               {
                    Print("The target is working");
               }
          }
      }
      Adam P.NinjaTrader Customer Service

      Comment


        #33
        Cancelling Orders

        I implemented your suggestion to help me better see what is happening during trade executions, Thanks for those suggestions. What I am seeing is the section of my onExecution code is not consistently working. Sometimes I get the orders on the same bar as the limit entry executes but sometimes I do not. I'm not sure why it is working sometimes but not at other times. To refresh your memory, I started down this path of setting trade conditions on the main bar, (using BetterRenko bars which seem to perform better than other types of bars) but to improve the accuracy of my backtesting, I execute the trades on minute bars added as a secondary data set). Here is what the code looks like in the onExecution section:

        Code:
                protected override void OnExecution(IExecution execution)
                {
        		if(BarsInProgress == 0)
        		{
        			/* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
        			which ensures your strategy has received the execution which is used for internal signal tracking. */
        			if (entryOrder != null && entryOrder == execution.Order && entryOrder.OrderAction == OrderAction.Buy)
        			{
        				Print(" Order is a BUY for " + Instrument.FullName + " in Account " + Account.Name);
        				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
        				{
        					Print(" Orderstate is valid for submitting stop and target for a BUY in " + Instrument.FullName);
        					// Stop-Loss order 4 ticks below our entry price
        					stopOrder 	= ExitLongStop(1, true, DefaultQuantity, Position.AvgPrice - ATRTicks(14, false).Max_ATR[0] * TickSize, "LAbv_Stop", "LAbv_Band");
        					
        					// Target order 8 ticks above our entry price
        					targetOrder = ExitLongLimit(1, true, DefaultQuantity, Position.AvgPrice + (ATRTicks(14, false).ATRinTicks[0] - P_Offset) * TickSize, "LAbv_Trgt", "LAbv_Band");
        					
        					// Resets the entryOrder object to null after the order has been filled or partially filled
        					if (execution.Order.OrderState != OrderState.PartFilled)
        					{
        						entryOrder 	= null;
        					}
        				}
        			}
        			if(entryOrder != null && entryOrder == execution.Order && entryOrder.OrderAction == OrderAction.SellShort)
        			{
        				Print(" Order is a SELL for " + Instrument.FullName + " in Account " + Account.Name);
        				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0) )
        				{
        					Print(" Orderstate is valid for submitting stop and target for a SELL in " + Instrument.FullName);
        						// Stop-Loss order max ATR above entry price
        						stopOrder 	= ExitShortStop(1, true, DefaultQuantity, Position.AvgPrice + ATRTicks(14, false).Max_ATR[0] * TickSize, "SBlo_Stop", "SBlo_Band");
        					
        						// Target order one ATR below entry price
        						targetOrder = ExitShortLimit(1, true, DefaultQuantity, Position.AvgPrice - (ATRTicks(14, false).ATRinTicks[0] - P_Offset) * TickSize, "SBlo_Trgt", "SBlo_Band");
        					
        
        				// Resets the entryOrder object to null after the order has been filled or partially filled					
        				if (execution.Order.OrderState != OrderState.PartFilled)
        					{
        					entryOrder 	= null;
        					}
        				}
        			}
        			
        			// Reset our stop order and target orders' IOrder objects after our position is closed.
        			if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
        			{
        				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
        				{
        					stopOrder = null;
        					targetOrder = null;
        				}
        			}
        		}
        I added the BarsinProgress == 0 filter into the same section thinking that may have been preventing the execution, but it didn't seem to make a difference either way. Since the strategy is detecting conditions on Data1 but executing on Data2 should that BarsinProgress qualifier be equal to "1" since that is the data set the actual execution is taking place on?
        Thanks
        DaveN

        Comment


          #34
          Hello DaveN,

          You may want to use Print() statements to verify values are what you expecting and see how your code is being processed to be able to find out why it is working sometimes but not others.Debugging your NinjaScript code.

          For orders/strategies add TraceOrders = true to your Initialize() method and you can then view valuable output related to strategy submitted orders through Tools > Output window - TraceOrders

          It may also help to add drawing objects to your chart for signal and condition confirmation - Drawing Objects.

          When using a Multi-Time Frame strategy it is important to know what how bar data is referenced.
          http://www.ninjatrader.com/support/h...nstruments.htm
          JCNinjaTrader Customer Service

          Comment


            #35
            Hello DaveN,
            To assist you further can you please send a toy NinjaScript code* replicating the behavior to support[AT]ninjatrader[DOT]com

            Please let me also know the exact scenario you are facing.

            Please append Attn:Joydeep in the subject line of the email and give a reference of this thread in the body of the email.

            I look forward to assisting you further.

            *The "toy" just means something that is a stripped down version that isn't necessarily the whole logic. It makes things easier to rout out.
            JoydeepNinjaTrader Customer Service

            Comment


              #36
              Cancel Order cont

              I can do that and I will work on trimming down the code to it's bare essentials. However, in the process of doing that, and with further observation after I inserted a whole slew of print statements I was able to isolate the problem down to the section of code which cancels an active stop or target order when either of them is filled. Here is the section of the code that is doing that:
              Code:
              				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
              				{
              					Print(" Strategy is cancelling a sell entryOrder and the targetOrder for a filled order" + Instrument.FullName + "  in Account #  " + Account.Name);
              					stopOrder = null;
              					targetOrder = null;
              				}

              And here is the sample code it is based on from the "SampleonOrderUpdate" sample

              Code:
              			// Reset our stop order and target orders' IOrder objects after our position is closed.
              			if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
              			{
              				if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
              				{
              					stopOrder = null;
              					targetOrder = null;
              				}
              			}
              The logic I am trying to execute is that if either the protective stop or the target order is filled, cancel both of them. What I find when observing the strategy during execution is that some of the time (more than half, but not always) the stop and target order are cancelled so quickly, they never actually show up on the dom. When I commented out this section it seemed to improve performance, though I just noticed one of my sim positions appears to be open with no stop and target. I missed that fill because I was typing this message.
              At any rate, perhaps it is obvious to a more knowledgeable person than me, what I have done wrong here.
              Thanks
              DaveN

              Comment


                #37
                Hello DaveN,

                Thanks for all the information.

                Your logic looks fine to cancel the orders, but do you have a condition before that to determine when to cancel the order?
                JCNinjaTrader Customer Service

                Comment


                  #38
                  My logic is the condition to cancel the order is a fill of the associated stop order or target order. If either of them fill, then the other order is no longer needed and is cancelled. I think the section that does that is the following:

                  Code:
                  // Reset our stop order and target orders' IOrder objects after our position is closed.
                  			if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
                  			{
                  				[COLOR="Red"]if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)[/COLOR]				{
                  					Print(" Strategy is cancelling a sell entryOrder and the targetOrder for a filled order" + Instrument.FullName + "  in Account #  " + Account.Name);
                  					stopOrder = null;
                  					targetOrder = null;
                  				}
                  			}
                  I marked it in red to make it readily visible. Am I wrong about that code, is it doing something different?
                  Thanks

                  Comment


                    #39
                    I have sent a copy of the stripped down strategy to JoyDeep so you can get a deeper look at the code and hopefully the problem.
                    Thanks
                    DaveN

                    Comment


                      #40
                      Resolution?

                      Hi Guys - I assume this was resolved given that haven't been any new posts

                      I was wondering if one of you could post the "resolution" as I having the same issues as daven (and this thread really left me hanging off the edge of my seat for a conclusion/solution...)

                      Comment


                        #41
                        Joydeep or NinjaTrader_JC

                        Hi Guys,

                        I was wondering if one of you could post the "resolution" as I having the same issues as daven (and this thread really left me hanging off the edge of my seat for a conclusion/solution...)

                        Thx very much !

                        Comment


                          #42
                          Resolution

                          I looked through my old e-mails to see what the resolution was. Here's is my best attempt at identifying it. The problems was that the limit and stop orders that were submitted after the order fill were sometimes (not always) immediately cancelled and I never did determine why that was going on. I got a suggested code sample from Joydeep, that would allow me to cancel an order if a certain number of bars occurred after the order was submitted. I finally resolved the situation, as best I could, by going to an ATM version of the strategy, which I actually liked better, because it gives me more control over the strategy for real-time trade management. Of course, testing it is a different issue, since you really can only test an atm strategy by running in real-time or using market replay. Each of these alternatives is time consuming but reasonably effective.
                          Sorry I don't have better information for you. Here is the code that Joydeep provided regarding cancelling existing orders:


                          Yes, you cancel an order after it has been submitted. A sample code will be like
                          Code:
                          //in variables
                          int currentBar = 0;
                          IOrder entryBar = null;
                           //in OnBarUpdate
                          if (entryOrder == null && entryconditions)
                          {
                              entryOrder = EnterLongLimit(...);
                              currentBar = CurrentBar;
                          }
                          //cancel order if not filled within next 5 bars
                          if (Position.MarketPosiition == MarketPosition.Flat && entryOrder != null && CurrentBar - currentBar > 5)
                          {
                             CancelOrder(entryOrder);
                          }

                          Comment


                            #43
                            Thanks !!!

                            Hi Daven,

                            Thank you very much for taking the time to look thru your emails; I really appreciate it.

                            I was trying to avoid going the ATM route, but it looks like it may be the best way...

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by lorem, Today, 09:18 AM
                            0 responses
                            1 view
                            0 likes
                            Last Post lorem
                            by lorem
                             
                            Started by hazylizard, Today, 08:38 AM
                            4 responses
                            10 views
                            0 likes
                            Last Post hazylizard  
                            Started by geddyisodin, Today, 05:20 AM
                            2 responses
                            18 views
                            0 likes
                            Last Post geddyisodin  
                            Started by Max238, Today, 01:28 AM
                            5 responses
                            47 views
                            0 likes
                            Last Post Max238
                            by Max238
                             
                            Started by giulyko00, Yesterday, 12:03 PM
                            3 responses
                            13 views
                            0 likes
                            Last Post NinjaTrader_BrandonH  
                            Working...
                            X