Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Cancelling Order if Conditions Change

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

    #16
    I have a simple logic that determines if a long or short trend is in place, and if it is, places a long limit order for a long trend, and a short limit order for a short trend. The limit entry for a long is the last bar close - the equivalent of 1 ATR, and the stop for that entry is the max ATR over the last X periods, and the profit target for the long entry is one ATR from the fill price. The problem I have been having with this srategy is that once place, a limit entry can last for several bars, but over that several bar period the trend can end or even reverse, so one no longer wants to do that entry. That is why I have been messing with all of this, I need the program to cancel the order if the nature of the trend changes. Initially I am trying to get at that performance by using the sample cancel order as a guide implementing the bar count as a cancel criteria. Once I have all of that working, I plan on changing the bar code count criteria to one which measures the change in trend and cancelling and entry order based on a trend change.
    That's the summary of what I am trying to do. The problem I am specifically having is sensing, in the case of an order execution, whether it was a long entry or a short entry so I can then implement stops and targets for a long or a short. It is that selection that is causing me the grief here, determining whether I need a short set of profit and stop or a long set. To set the stop and profit I just use my ATRTick indicator which I know works because I have been using them in an earlier version which runs fine, but has this problem with the trend change. Here's the construct I use for setting the stop and profit for a long entry:
    Code:
    					stopOrder = ExitLongStop(0, true, 1, execution.Price - ATRTicks(14).Max_ATR[0] , "long_stop", "LAbv_Band");
    					targetOrder = ExitLongLimit(0, true, 1, execution.Price + ATRTicks( 14).ATRinTicks[0] - Offset * TickSize, "long_target", "LAbv_Band");

    Comment


      #17
      If it would help, I"d be happy to send you the code,
      DaveN

      Comment


        #18
        dave,

        Why not just use SetStopLoss() and SetProfitTarget() here?

        Code:
        SetStopLoss("SBlo_Band", CalculationMode.Price, execution.Price - ATRTicks(14).Max_ATR[0], false)
        SetProfitTarget("SBlo_Band", CalculationMode.Price, execution.Price + ATRTicks(14).ATRinTicks[0] - Offset * TickSize)
        You can basically remove most of that stuff in the reference example and just check that an order filled, and that it was short. The idea is to use the OnExecution() method to detect you were filled, then change the stop loss orders to be what you want.

        Likely you will want to add another stop loss and profit target reset here when you detect an order was closed. For example whenever you call another SetStopLoss("SBlo_Band", other_parameters_here); it resets the internal managed approach stop loss to something else.

        In the managed approach it will automatically submit stop losses / profit targets for the relevant orders you are making as well. The only time you need to separate into Long/Short side is if you have specific prices you need to set for them really.
        Adam P.NinjaTrader Customer Service

        Comment


          #19
          That is how I originally had it but I changed it in order to make it look just like the sample. So one question, the stop and profit orders have to execute right after the order fills so the ATR-based settings for stop and profit are relevant to conditions at time of order entry. You indicated I just check the order to see if it was filled and whether it was short or long. How do I do that test, is the fill for a short entry or a long entry?
          Thanks
          DaveN

          Comment


            #20
            Dave,

            Basically whatever the last called SetProfitTarget() set the profit target to, this is the profit target that is used for all subsequent filled orders. It is the same for SetStopLoss(). This is basically why I mentioned you may want to reset these when you first place your limit order. You can just set it to some static tick-based values then refine your stop immediately when it detects the order filled in the OnExecution method.

            For checking if an execution was a short :

            if ( execution.Order.OrderAction == OrderAction.Sell ) //it was a short order that caused the execution

            You can read more about "OrderAction" here : http://www.ninjatrader.com/support/h...tml?iorder.htm
            Adam P.NinjaTrader Customer Service

            Comment


              #21
              How is this possible?

              I am continuing to work on this strategy, and making a bit of progress. However, I was doing some work on my original strategy, (which by the way tests spectacularly well, but runs not as well but still is profitable). I notice in recent back tests that I am getting trades which are exiting before they are entering. I've attached a text document extracted from the backtest report, which demonstrates what I am talking about. How is this possible?
              Thanks
              Dave
              Attached Files

              Comment


                #22
                Dave,

                I am not sure here unfortunately. Where are you getting these numbers from? I.e. which tab, etc.?
                Adam P.NinjaTrader Customer Service

                Comment


                  #23
                  That came from a backtest report, I simply extracted the cs file, converted it to a text file so I could send it to you.It comes from the "trades" tab on the optimizer report in the strategy analyzer.

                  Comment


                    #24
                    Dave,

                    Can you post a screenshot of your Executions tab?

                    The complete guide to capturing screenshots on Windows Need to take a screenshot on your Windows PC? Whether you want to capture the full screen or just one window or area, there are several quick and easy ways to take screenshots in...
                    Adam P.NinjaTrader Customer Service

                    Comment


                      #25
                      I haven't been able to reproduce the error but I think I know what happened. When my order hangs around to long, it executes, but I think that execution messes up the order of order placement plus profit and stop execution. I think the order executes a stop that should have been a profit and vice versa so it looks like trades are being executed out of sequence. If I can reproduce the problem I will send along the screen shot, but in the meantime, the strategy is now working better and I am focusing on how to change the existing order if conditions change, hence my next post.

                      Comment


                        #26
                        Cancelling Automated Orders

                        I'm back workiing on checking an existing order and cancelling it if conditions change. I am using the construct from the Sample Cancel Order strategy but I am getting compiler errors so I don't think I have constructed the statements properly. Here's what I have:

                        Code:
                        			// Check if Unfilled order is still a good order.
                        		protected override void OnOrderUpdate(IOrder order)	
                        			{
                        			if( entryOrder != null && entryOrder == order)
                        				{
                        				[COLOR="Red"]if (order.OrderState == OrderState.Working && OrderAction == OrderAction.Buy)[/COLOR]					{
                        					if (EMAProgression(14, 5).Progression[0] < EMAProgression(14, 5).Progression[1]
                        						&& EMAProgression(14, 5).Progression[1] < EMAProgression(14, 5).Progression[2])
                        						{
                        						[COLOR="Red"]CancelOrder("LAbv_Band");[/COLOR]						}
                        					}
                        				[COLOR="red"]else if(order.OrderState == OrderState.Working && OrderAction == OrderAction.Sell)[/COLOR]					{
                        					if (EMAProgression(14, 5).Progression[0] > EMAProgression(14, 5).Progression[1]
                        						&& EMAProgression(14, 5).Progression[1] > EMAProgression(14, 5).Progression[2])
                        						{
                        						[COLOR="red"]CancelOrder("SBlo_Band");[/COLOR]						}					
                        					}
                        				}
                        			}
                        I have highlighted in red the statements which are giving me compiler errors and those errors are (in order):

                        'NinjaTrader.Cbi.OrderAction' is a 'type' but is used like a 'variable'
                        The best overloaded method match for 'NinjaTrader.Strategy.StrategyBase.CancelOrder(Nin jaTrader.Cbi.IOrder)' has some invalid arguments
                        Argument '1': cannot convert from 'string' to 'NinjaTrader.Cbi.IOrder'
                        'NinjaTrader.Cbi.OrderAction' is a 'type' but is used like a 'variable'
                        The best overloaded method match for 'NinjaTrader.Strategy.StrategyBase.CancelOrder(Nin jaTrader.Cbi.IOrder)' has some invalid arguments
                        Argument '1': cannot convert from 'string' to 'NinjaTrader.Cbi.IOrder'

                        The first compiler error relates to line 141 which is the first red colored line above. Clearly something is not right, but it is lifted from the IOrder syntax in the guidebook so I'm just not sure what is wroing. Also in line 146 (thie first cancel order), I must not be referrng to the order id properly but aside from the label I apply when I create the order, I'm not sure what other ID I should be using.
                        Hope you can help.
                        DaveN

                        Comment


                          #27
                          Dave,

                          CancelOrder(IOrder order) this take an IOrder object so likely you will need to track these.

                          For example : My_Order = EnterLong();

                          The other error you are getting is because OrderAction doesn't exist here, it is a enum.

                          OrderAction == OrderAction.Buy

                          Needs to be :

                          order.OrderAction == OrderAction.Buy
                          Adam P.NinjaTrader Customer Service

                          Comment


                            #28
                            Cancel Orders

                            It appears to be working, here is what I have so far:

                            Code:
                            		protected override void OnOrderUpdate(IOrder order)	
                            			{
                            			if( entryOrder != null)
                            				{
                            				if (order.OrderState == OrderState.Working && order.OrderAction == OrderAction.Buy)
                            					{
                            					if (EMAProgression(14, 5).Progression[0] < EMAProgression(14, 5).Progression[1]
                            //						&& EMAProgression(14, 5).Progression[1] < EMAProgression(14, 5).Progression[2]
                            						&& Close[0] < Close[1])
                            						{
                            						CancelOrder(entryOrder);
                            						}
                            					}
                            				else if(order.OrderState == OrderState.Working && order.OrderAction == OrderAction.Sell)
                            					{
                            					if (EMAProgression(14, 5).Progression[0] > EMAProgression(14, 5).Progression[1]
                            //						&& EMAProgression(14, 5).Progression[1] > EMAProgression(14, 5).Progression[2])
                            						&& Close[0] > Close[1])
                            						{
                            						CancelOrder(entryOrder);
                            						}					
                            					}
                            				}
                            			}
                            I am going to add a text draw object so that I can tell when an order has been cancelled.

                            Comment


                              #29
                              Apparent Reversed Trades

                              I'm continuing to work on this strategy but my results are extraordinarily frustrating. On backtest in the system analyzer as well as historically on charts I am getting very good results. However, the results in real-time are pretty far away from the backtested or historical results. I understand that certain bar types make this inevitable but this fact is true for minute or second bars, BetterRenko Bars or Range Bars. I'm also noticing that trade labeling on the chart is reversed. A long trade when entered is labeled with "LAbv_Bar" and a short trade is labeled with "SBl_Bar", When I look on the chart, sometimes the trade initiation is correct with the trade label starting the trade and either the profit or stop loss ending the trade. Often however the trade is labeld with Profit target for the trade initiation, and the actual label for the trade conclusion. when I look at the trade sequencing in the trades list it is the same showing trade initiation with a profit target and trade completion with the trade label. If you look at the last two trades on the screen shot and the trade list you will see what I mean. Here's the weird thing, I don't open the trade unless there is no open trade present, and when the strategy is flat, I make both the stop and profit targets extra big, then reset them when the trade initiates, Is there something about trade management that I have to do, once the trade is open, when I am using a multitime frame strategy. The trade is configured on the Better Renko data, but actually initiated on the minute data. I did this to get better resolution in back-testing. The profit target and stop are not configured for the minute bar, since I don't know how to do that, and didn't see it in any example, so if that needs to be done, could you give me an example?
                              Thanks
                              DaveN
                              Attached Files

                              Comment


                                #30
                                What order methods are you using for your stops and targets? If you're using SetStopLoss and SetProfitTarget, they will only be on the primary series.

                                However if you're using an ExitLongLimit or ExitLongStop, there is a barsInProgressIndex where you can set these orders to the added bar object.

                                EnterLongLimit(int barsInProgressIndex, bool liveUntilCancelled, int quantity, double limitPrice, string signalName)


                                Code:
                                EnterLongLimit(1, true, 1, myTargetPrice, "profitTarget");
                                EnterLongStop(1, true, 1, myStopPrice, "StopLoss");
                                You can also just use a BarsInProgress filter to specify which bars array they are submitted on.

                                I'm also including a reference sample on entering on one time frame and exiting on another to show this alternative method:
                                MatthewNinjaTrader Product Management

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by CarlTrading, 03-31-2026, 09:41 PM
                                1 response
                                71 views
                                0 likes
                                Last Post NinjaTrader_ChelseaB  
                                Started by CarlTrading, 04-01-2026, 02:41 AM
                                0 responses
                                39 views
                                0 likes
                                Last Post CarlTrading  
                                Started by CaptainJack, 03-31-2026, 11:44 PM
                                0 responses
                                63 views
                                2 likes
                                Last Post CaptainJack  
                                Started by CarlTrading, 03-30-2026, 11:51 AM
                                0 responses
                                63 views
                                0 likes
                                Last Post CarlTrading  
                                Started by CarlTrading, 03-30-2026, 11:48 AM
                                0 responses
                                53 views
                                0 likes
                                Last Post CarlTrading  
                                Working...
                                X