Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

CancelOrder() possible for order that needs refreshing every bar?

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

    CancelOrder() possible for order that needs refreshing every bar?

    Hi,

    I have a strategy that runs on a chart with 2 symbols, but only trades the main symbol.

    It has COBC = true and sends an entry order that remains active only for the next bar: MyEntryOrder = EnterLongStop(0, false, MyUnits_G, MyEntryPrice_G, MyEntryText);

    Since the traded symbol can sometimes have no tick for several seconds I tried to cancel the order if the second symbol already completed the last bar where the entry was valid by using: CancelOrder(MyEntryOrder);

    That doesn't work and the order only gets cancelled by timing out (no refresh on next bar).

    Is it in general not possible to cancel the orders that expire after one bar? Or is there something wrong/missing in my code?

    Thanks,
    NutFlush

    #2
    By employing the use of IOrder objects, one can fully control how and when orders get canceled, thus not being restricted to the default implementation of canceling at end of next bar. However, if you want to cancel an order INTRAbar, then you'll have to look into COBC = false or perhaps (if your logic warrants it) look at other places than OnBarUpdate to do the canceling, perhaps OnMarketDepth or whatever. You can even do things with custom timers or other custom events. Lots of possibilities.

    Comment


      #3
      Originally posted by coolmoss View Post
      By employing the use of IOrder objects, one can fully control how and when orders get canceled, thus not being restricted to the default implementation of canceling at end of next bar. However, if you want to cancel an order INTRAbar, then you'll have to look into COBC = false or perhaps (if your logic warrants it) look at other places than OnBarUpdate to do the canceling, perhaps OnMarketDepth or whatever. You can even do things with custom timers or other custom events. Lots of possibilities.
      Hi coolmoss,

      I am using an IOrder object: MyEntryOrder

      Since I have two symbols in that strategy that can both trigger the OnBarUpdate() event I was trying to use that event for whichever of the 2 symbols completes the bar first. As that symbol is now moving to the next bar for which the entry should no longer be valid I tried calling: CancelOrder(MyEntryOrder);

      Any idea why it doesn't work?

      Thanks,
      NutFlush

      Comment


        #4
        Thanks for the suggestion coolmoss!

        Post #2 is correct. You'd need to consider using other events to cancel the order. You can always develop your own custom trigger method to call whenever you wish:

        MatthewNinjaTrader Product Management

        Comment


          #5
          Originally posted by NinjaTrader_Matthew View Post
          Thanks for the suggestion coolmoss!

          Post #2 is correct. You'd need to consider using other events to cancel the order. You can always develop your own custom trigger method to call whenever you wish:

          http://www.ninjatrader.com/support/h...ustomevent.htm
          Hi Matthew,

          I have a print statement that comes right after: CancelOrder(MyEntryOrder);
          So I know that the part of my code that includes the cancellation was processed. Yet the cancellation didn't really get executed.

          Could the problem be that the order is for the symbol with BIP == 0, but my code was processed when OnBarUpdate() was trigger by the other symbol and BIP == 1?

          If so, then following your advice I would
          1) set a variable "myBIP" to the index of the symbol that I want to cancel the entry for: myBIP = 0;
          2) use TriggerCustomEvent(MyCustomHandler, myBIP, "myText")
          3) use the cancel statement from inside of MyCustomEventHandler
          Code:
          private void MyCustomHandler(object state)
          {
               CancelOrder(MyEntryOrder);
          }
          Would that be the correct way? And is the synchronization to the correct smybol/BIP the reason why the cancellation didn't work?

          Thanks,
          NutFlush

          Comment


            #6
            Yes, that should work.

            Are you sure the order exists when you call CancelOrder? Are you tracking these using IOrder Objects?
            MatthewNinjaTrader Product Management

            Comment


              #7
              Originally posted by NinjaTrader_Matthew View Post
              Yes, that should work.

              Are you sure the order exists when you call CancelOrder? Are you tracking these using IOrder Objects?
              Hi Matthew,

              yes the order exists (I also watched this happening today in realtime with the order sitting in IB's TWS order window for my simulated account). The code of the cancelling method that gets called from inside the OnBarUpdate() method looks like this:
              Code:
              private void CancelMyEntryOrder()
                      {
                          // check state of the order before cancelling
                          if (MyEntryOrder != null)
                          {
                              if (MyEntryOrder != null && (MyEntryOrder.OrderState == OrderState.Accepted || MyEntryOrder.OrderState == OrderState.Initialized || MyEntryOrder.OrderState == OrderState.PendingSubmit || MyEntryOrder.OrderState == OrderState.Unknown || MyEntryOrder.OrderState == OrderState.Working))
                              {
                                  CancelOrder(MyEntryOrder);
                                  MyLogString = MySym  + " BIP: " + BarsInProgress.ToString() + "; BarTimeH: " + Time[0].ToString(MyTimeFormat) + "; PCtimeH: " + DateTime.Now.ToString(MyTimeFormat) + "; ### Entry order CANCELLED! " + MyEntryText + "; shares: " + MyUnits_G.ToString("N0") + "; price: " + MyEntryPrice_G.ToString("N2")+"$";
                                  Print(MyLogString);
                                  if (logTrades == true) SendTextToFile(MyLogFile, MyLogString);
                              }
                              else
                              {
                                  MyLogString = MySym  + " BIP: " + BarsInProgress.ToString() + "; BarTimeH: " + Time[0].ToString(MyTimeFormat) + "; PCtimeH: " + DateTime.Now.ToString(MyTimeFormat) + "; ### Entry order NOT CANCELLED! Order state: " + MyEntryOrder.OrderState.ToString() + "; " + MyEntryText + "; shares: " + MyUnits_G.ToString("N0") + "; price: " + MyEntryPrice_G.ToString("N2")+"$";
                                  Print(MyLogString);
                                  if (logTrades == true) SendTextToFile(MyLogFile, MyLogString);
                              }
                          }
                          else
                          {
                              MyLogString = MySym  + " BIP: " + BarsInProgress.ToString() + "; BarTimeH: " + Time[0].ToString(MyTimeFormat) + "; PCtimeH: " + DateTime.Now.ToString(MyTimeFormat) + "; ### There is NO entry order to be cancelled! " + MyEntryText + "; shares: " + MyUnits_G.ToString("N0") + "; price: " + MyEntryPrice_G.ToString("N2")+"$";
                              Print(MyLogString);
                              if (logTrades == true) SendTextToFile(MyLogFile, MyLogString);
                          }
                      }
              As I said, the print statement was executed, but the order kept sitting another 20 seconds until finally the main symbol made the first tick for the next bar and the order expired after not being resent.

              If you are interested, here's an excerpt of my output window:
              Code:
              // order was resent for bar ending at 18:18 when XIV started the bar for 18:18
              
              09.08.2013 [COLOR=Blue][B]18:17:33[/B][/COLOR] Entered internal PlaceOrder() method at 09.08.2013 18:17:33: BarsInProgress=0 Action=Buy OrderType=Stop Quantity=2.044 LimitPrice=0 StopPrice=27,95 SignalName='L_Piv_SPY_XIV_S' FromEntrySignal=''
              09.08.2013 [COLOR=Blue][B]18:17:33[/B][/COLOR] Ignored PlaceOrder() method: Action=Buy OrderType=Stop Quantity=2044 LimitPrice=0 StopPrice=27,95 SignalName=L_Piv_SPY_XIV_S' FromEntrySignal='' Reason='There already is a matching order with same prices and quantity'
              #FFF# First tick in bar for symbol: XIV; BarEndTime: 09.08.2013 18:18:00; PC-Time: 09.08.2013 [COLOR=Blue][B]18:17:33.827[/B][/COLOR]; price: 27,90$; Volume: 100
              
              // cancellation was attempted when SPY started the 18:19 bar (finished the 18:18 bar)
              
              XIV_Piv BIP: 1; BarTimeH: 09.08.2013 18:18:00.000; PCtimeH: 09.08.2013 [COLOR=DarkRed][B]18:18:00.282[/B][/COLOR]; ### Entry order CANCELLED! L_Piv_SPY_XIV_S; shares: 2.044; price: 27,95$
              #FFF# First tick in bar for symbol: SPY; BarEndTime: 09.08.2013 [B][COLOR=Blue]18:19[/COLOR][/B]:00; PC-Time: 09.08.2013 [COLOR=DarkRed][B]18:18:00.285[/B][/COLOR]; price: 169,27$; Volume: 600
              
              // only when XIV started a new bar the order EXPIRED automatically after the "manual" cancellation didn't have any effect
              
              09.08.2013 [COLOR=Red][B]18:18:26[/B][/COLOR] Cancelled expired order: BarsInProgress=0: Order='1710537946/DU116276' Name='L_Piv_SPY_XIV_S' State=Accepted Instrument='XIV' Action=Buy Limit price=0 Stop price=27,95 Quantity=2.044 Strategy='tkSV1mPivotPower' Type=Stop Tif=Gtc Oco='' Filled=0 Fill price=0 Token='fc3d3a8b52d049c48aa51f3ecafb0479' Gtd='01.12.2099 00:00:00'
              #FFF# First tick in bar for symbol: XIV; BarEndTime: 09.08.2013 [B][COLOR=Blue]18:19[/COLOR][/B]:00; PC-Time: 09.08.2013 [COLOR=Red][B]18:18:26.648[/B][/COLOR]; price: 27,90$; Volume: 2.000
              Cheers,
              NutFlush

              Comment


                #8
                I see no reason from the information you have provided that the order should not have been canceled if that print statement was issued. Are you doing any checks in OnOrderUpdate to check the state of the order? You may want to run some additional debugging in that area to see where the order may be hung up.
                MatthewNinjaTrader Product Management

                Comment


                  #9
                  I am trying to implement TriggerCustomEvent() to do the cancellation so that I can sync to the BIP of the order.

                  Could it be possible that TriggerCustomEvent() doesn't work on historical data? I realized that the whole method wouldn't be processed at all. Here's the simplified code:
                  Code:
                  OnBarUpdate()
                  {
                   Print("Now as method:");
                   JustPrintHi("");
                   Print("Now through CustomEvent:");
                   TriggerCustomEvent(JustPrintHi, 0, "");
                   Print("Now again as method:");
                   JustPrintHi("");
                  }
                  private void JustPrintHi(object whatever)
                  {
                    Print("Hi!");
                  }
                  This is the output:
                  Code:
                  Now as method:
                  Hi!
                  Now through CustomEvent:
                  Now again as method:
                  Hi!
                  As you can see it's not executing the method when called via TriggerCustomEvent().

                  Is that normal when the code runs on historical data?

                  Cheers,
                  NutFlush
                  Last edited by NutFlush; 08-12-2013, 09:29 AM.

                  Comment


                    #10
                    When is your custom trigger supposed to be called? Is it on a system timer?

                    You would need to come up with some sort of condition that will call the custom event. If the main issue is that some instruments do not get ticks for several seconds, using the tick data/bar processing enough alone is not enough. I really do not have a specific solution for your problem, but you may want consider perhaps creating a historical file you can read that would call your custom timer event on a DateTime series that would accommodate for every minute/second in time historically.
                    MatthewNinjaTrader Product Management

                    Comment


                      #11
                      Originally posted by NinjaTrader_Matthew View Post
                      When is your custom trigger supposed to be called? Is it on a system timer?

                      You would need to come up with some sort of condition that will call the custom event. If the main issue is that some instruments do not get ticks for several seconds, using the tick data/bar processing enough alone is not enough. I really do not have a specific solution for your problem, but you may want consider perhaps creating a historical file you can read that would call your custom timer event on a DateTime series that would accommodate for every minute/second in time historically.
                      Hi Matthew,

                      please forget anything we discussed so far.

                      Let's concentrate on a simple question: When running on historical data (Historical == true) will TriggerCustomEvent() be executed or not?

                      My example above has nothing to do with timers or orders. All it does is call the identical method in 2 ways:
                      a) directly (first and third call)
                      b) through TriggerCustomEvent() (second call)

                      If OnBarUpdate() is called while still on historical data the third call is not executed. Once OnBarUpdate() gets to live data it works.

                      Is this the expected behaviour?

                      Thanks,
                      NutFlush

                      P.S. I just exported a small strategy to demonstrate: open a chart with a few historical bars and set it to 1min interval. Check the output window and how the output changes once you get to live data.
                      Attached Files
                      Last edited by NutFlush; 08-12-2013, 09:45 AM.

                      Comment


                        #12
                        The expected behavior would depend on how the TiggerCustomEvent is defined. Can we take a step back here and show me how you setup TriggerCustomEvent()? Was it based on a timer like our example? If so, then no, the Timer Class is not called on historical data.

                        If TriggerCustomEvent() is not working at all, it may be you have not correctly configured your custom event:



                        There are also so many .MaxProcessedEvents allowed between NT events - if that was not called when you expected, you may be calling the custom event too frequently and may not be called when you expect.
                        MatthewNinjaTrader Product Management

                        Comment


                          #13
                          Originally posted by NinjaTrader_Matthew View Post
                          The expected behavior would depend on how the TiggerCustomEvent is defined. Can we take a step back here and show me how you setup TriggerCustomEvent()?
                          Certainly!

                          Please see the example file I added in my last post (while you were writing your reply).

                          The output looks like this (color added):
                          Code:
                          Now as method for bar: 12.08.2013 17:41:00, Historical: [B][COLOR=Red]True[/COLOR][/B]
                          Hi! 12.08.2013 17:41:00
                          [B][COLOR=Red]Now through CustomEvent:[/COLOR][/B]
                          [COLOR=Blue] [B]Now again as method:
                          Hi! 12.08.2013 17:41:00[/B][/COLOR]
                          Now as method for bar: 12.08.2013 17:42:00, Historical: [COLOR=SeaGreen][B]False[/B][/COLOR]
                          Hi! 12.08.2013 17:42:00
                          [B][COLOR=SeaGreen]Now through CustomEvent:
                          Hi! 12.08.2013 17:42:00[/COLOR][/B]
                          [B][COLOR=Blue] Now again as method:
                          Hi! 12.08.2013 17:42:00[/COLOR][/B]
                          Cheers,
                          NutFlush
                          Last edited by NutFlush; 08-12-2013, 09:55 AM.

                          Comment


                            #14
                            NutFlush,

                            Thanks for your patience. The custom trigger method doesn't work as I expect in the strategy base. We're looking into this further.

                            I believe a better approach here would be to tie into a finer series in OnBarUpdate such as a 1-tick or 1-second series and check on the orders when these bars update.

                            You can use the 1-tick series in BarsInProgress == 2 for example and process all of your orders on this series.
                            MatthewNinjaTrader Product Management

                            Comment


                              #15
                              Originally posted by NinjaTrader_Matthew View Post
                              NutFlush,

                              Thanks for your patience. The custom trigger method doesn't work as I expect in the strategy base. We're looking into this further.

                              I believe a better approach here would be to tie into a finer series in OnBarUpdate such as a 1-tick or 1-second series and check on the orders when these bars update.

                              You can use the 1-tick series in BarsInProgress == 2 for example and process all of your orders on this series.
                              Hi Matthew,

                              I did some intensive testing and observed this:
                              - Orders with GTC = true can be cancelled in various ways with no problem.
                              - Orders with GTC = false can NOT be cancelled IN ANY WAY; they have to time out!

                              If you want to verify my tests I included 2 strategies:
                              1) Test2SymbolsOrderCancelGTC:
                              - GoodTillCancel = true
                              - run on XIV as main symbol & SPY as second symbol
                              - XIV: 1 minute bars
                              - SPY 1 minute bars

                              2) Test2SymbolsOrderCancelGNB ("GoodNextBar"):
                              - GoodTillCancel = false
                              - run on XIV as main symbol & SPY as second symbol
                              - XIV: 3 minutes bars
                              - SPY 1 minute bars

                              Is that by design that those orders cannot be cancelled or possibly an error in my code or in my NT platform?

                              Cheers,
                              NutFlush
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              647 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              368 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              108 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              571 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              573 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X