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

Error when using CancelOrder

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

    Error when using CancelOrder

    Hello, I am using NT 8.0.25.0 with IB gateway 978 to run a strategy on the S&P500 on 20 minute bars. With unmanaged order entry, it creates short or long entry limit orders, then adjusts those orders until they either fill or are cancelled. I am attempting to cancel the orders using, for example, CancelOrder(longOrder);

    Sometimes the order does cancel, but more often than not the strategy attempts to cancel the order but fails, and generates this error in the log:

    "Received unknown error/warning: OrderID 181848 that needs to be cancelled cannot be cancelled, state: Cancelled."

    With whichever OrderId there is for that order. Everything works no problem in a backtest. It occurs whether I'm running the strategy on 500 instruments simultaneously or a single instrument. All of the orders seem normal in the Orders tab, with expected oco, OrderId, names, etc.

    Here is a watered down version with what I think would be relevant:



    public class CancelErrors : Strategy
    {
    private Order longOrder = null;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "BCAfterhours";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = false;
    ExitOnSessionCloseSeconds = 60;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    OrderFillResolutionType = BarsPeriodType.Minute;
    OrderFillResolutionValue = 1;
    Slippage = 2;
    IsAdoptAccountPositionAware = true;
    StartBehavior = StartBehavior.AdoptAccountPosition;
    IsUnmanaged = true;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.IgnoreAllErrors;
    StopTargetHandling = StopTargetHandling.ByStrategyPosition;
    BarsRequiredToTrade = 20;
    IncludeCommission = true;
    IgnoreOverfill = true;
    IsInstantiatedOnEachOptimizationIteration = true;

    }

    }


    protected override void OnBarUpdate()
    {

    if (BarsInProgress == 0)
    {

    if (State == State.Historical)
    return;

    if (CurrentBars[0] < 30)
    return;


    if ((ToTime(Time[0]) < 174000))
    {

    if ((Position.MarketPosition == MarketPosition.Flat)
    && (longOrder != null)
    && (ToTime(Time[0]) > 71900)
    )

    {
    CancelOrder(longOrder);
    }


    if ((Position.MarketPosition == MarketPosition.Flat)
    && (shortOrder != null)
    && (ToTime(Time[0]) > 71900)
    )

    {
    CancelOrder(shortOrder);
    }

    }

    if (ToTime(Time[0]) >= 21000 && ToTime(Time[0]) < 71900)

    {


    if ((longOrder == null)
    && (Position.MarketPosition == MarketPosition.Flat)
    && ((((Account.Get(AccountItem.NetLiquidation, Currency.UsDollar) * .95) - Account.Get(AccountItem.MaintenanceMargin, Currency.UsDollar)) > (Close[0] * CurrentShares)))
    && (Ready == 0)
    )

    {
    SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Limit, CurrentShares, (MAX1[0] * (1 - ((NATR1[0] * LongEntryFx) / 100))), 0, GetAtmStrategyUniqueId() + "LongEntry", "longOrder");
    }


    if ((shortOrder == null)
    && (Position.MarketPosition == MarketPosition.Flat)
    && ((((Account.Get(AccountItem.NetLiquidation, Currency.UsDollar) * .95) - Account.Get(AccountItem.MaintenanceMargin, Currency.UsDollar)) > (Close[0] * CurrentShares)))
    && (Ready == 0)
    )
    {

    SubmitOrderUnmanaged(0, OrderAction.SellShort, OrderType.Limit, CurrentShares, (MIN1[0] * (1 + ((NATR1[0] * LongEntryFx) / 100))), 0, GetAtmStrategyUniqueId() + "ShortEntry", "shortOrder");

    }

    }




    However, if the strategy has created an entry limit order, but has not filled it, and then the time is > 71900, it frequently attempts to cancel the order as directed but fails to do so and gives me that error.

    Any ideas?? Thanks!

    #2
    Hello RobotSyndicate,

    It sounds like an order that is already cancelled is attempted to be cancelled again. An order can only be cancelled once.

    Check the <order>.OrderState to be OrderState.Working or OrderState.Accepted, before allowing CancelOrder() to be called with the order.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Hi Chelsea, the order is not getting cancelled. It tries to cancel, the error says it cannot be cancelled, and the order is still on the chart and live with the broker. Any other ideas?

      Thanks
      Last edited by RobotSyndicate; 05-02-2022, 01:03 AM.

      Comment


        #4
        Hello RobotSyndicate,

        From the message NinjaTrader sent the cancellation.

        Have you contacted Interactive Brokers to inquire about why the order could not be cancelled? Was it in a state it could not be cancelled in?

        Is the order in OrderState.Working or OrderState.Accepted when the cancellation is submitted?
        Can you provide the output from print showing this?
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          That error I was getting that I mentioned above seems to be a much smaller issue, and I think I figured out what my main problem is. My strategy runs on 20 minute bars, and the CancelOrder logic is within OnbarUpdate. All of it is supposed to run in the premarket and aftermarket only. Essentially the strategy places entry orders in the premarket, then it is supposed to cancel any unfilled entry orders before the regular market hours begin (I'm trying to cancel at time greater than 9:19am EST using ToTime(). BUT because this is nested within OnBarUpdate, if there are no orders on an instrument between 9:19am and 9:30am (this frequently occurs) when the market opens, then no time bar is created during that time, and the CancelOrder logic does not run. Resulting in unwanted left over orders getting filled after the market opens, until the next 20 minute bar is at last created at 9:40am now that there is data for the bar. Similarly, my after hour entry orders are supposed to be placed after the 4pm EST market close and then any unfilled entry orders are supposed to be cancelled at time > 7:30pm and < 8pm eastern time, to cancel the orders while IB still processes the cancellation that day. BUT when there are no orders on an instrument between 7:30pm and 8pm (happens all the time), then there is no data, no 20 minute bar is created, and the CancelOrder logic does not run. Again leaving me with hundreds of uncancelled orders.

          So my NEW question, if I may gratefully ask for your help, is this. Is there an event method for time? Or something that is called often enough that I could get my CancelOrder logic to run within a 20 minute window, even if there are no orders to make a new 20 minute bar and trigger OnBarUpdate? Or is there another supported or unsupported way for me to just cancel an order at a certain time, even if there are no orders at that time for an instrument to make a new bar with?? Would this is a time to use TriggerCustomEvent() with a timer? And if so, do you have any example code of something like that?

          Also, I seem to get a lot of inconsistencies when using ToTime... Is there a reason to not use DateTime.Now.Hour or Minute instead?

          Thank you very much for your help!
          Last edited by RobotSyndicate; 06-17-2022, 07:44 PM.

          Comment


            #6
            Hello RobotSyndicate,

            You can use a C# timer.


            'Delaying logic for a particular time interval' - https://ninjatrader.com/support/help...tm#Performance

            What inconsistencies with ToTime() are you seeing? Are you printing the DateTime object and the ToTime() of that object together?
            DateTime.Now is the computer time, not the time of the bar or playback time. We suggest using Core.Globals.Now instead of DateTime.Now.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hello, thank you for the C# timer help.

              It could be that my ToTime() "inconsistencies" are just me not using it in the way I should be. I am trying to get a value of the actual local time, not the time of the last bar. But even when I use a timer to trigger the code at intervals between bars, it continues to give the time of the last bar. For example, if I make a simple strategy to create a timer and then compare NinjaTrader.Core.Globals.Now with ToTime() like this:

              public class FatherTime : Strategy
              {


              private System.Timers.Timer myTimer;

              protected override void OnStateChange()
              {
              if (State == State.SetDefaults)
              {
              Description = @"Enter the description for your new custom Strategy here.";
              Name = "FatherTime";
              Calculate = Calculate.OnBarClose;
              EntriesPerDirection = 1;
              EntryHandling = EntryHandling.AllEntries;
              IsExitOnSessionCloseStrategy = false;
              ExitOnSessionCloseSeconds = 60;
              IsFillLimitOnTouch = false;
              MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
              OrderFillResolution = OrderFillResolution.Standard;
              OrderFillResolutionType = BarsPeriodType.Minute;
              OrderFillResolutionValue = 1;
              Slippage = 1;
              IsAdoptAccountPositionAware = true;
              StartBehavior = StartBehavior.AdoptAccountPosition;
              IsUnmanaged = true;
              TimeInForce = TimeInForce.Gtc;
              TraceOrders = false;
              RealtimeErrorHandling = RealtimeErrorHandling.IgnoreAllErrors;
              StopTargetHandling = StopTargetHandling.ByStrategyPosition;
              BarsRequiredToTrade = 20;
              IncludeCommission = true;
              IgnoreOverfill = true;
              // Disable this property for performance gains in Strategy Analyzer optimizations
              // See the Help Guide for additional information
              IsInstantiatedOnEachOptimizationIteration = true;
              }

              else if (State == State.Configure)
              {
              }


              else if (State == State.DataLoaded)
              {
              myTimer = new System.Timers.Timer(60000 * 1 * 10);
              myTimer.Elapsed += TimerEventProcessor;
              myTimer.Enabled = true;
              }

              else if (State == State.Realtime)
              {
              }

              else if (State == State.Terminated)
              {
              if (myTimer != null)
              {
              myTimer.Enabled = false;
              myTimer.Elapsed -= TimerEventProcessor;
              myTimer = null;
              }
              }

              }



              protected override void OnBarUpdate()
              {
              }


              private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
              {
              if (CurrentBar > 0)
              {
              TriggerCustomEvent(CheckTheTime, Close[0]);
              }
              }


              private void CheckTheTime(object price)
              {
              Print("The Current Time Is: " + NinjaTrader.Core.Globals.Now);
              Print("ToTime Comparison: " + ToTime(Time[0]));
              }

              }

              ---------This is what I get in the output window:

              The Current Time Is: 6/26/2022 5:28:21 PM
              ToTime Comparison: 175500
              The Current Time Is: 6/26/2022 5:38:21 PM
              ToTime Comparison: 175500
              The Current Time Is: 6/26/2022 5:48:21 PM
              ToTime Comparison: 175500


              I assume that this is because Time[0] refers to the time of the last bar. Is there something I can reference, like ToTime(Time.Now) or something to get the current time?

              Thank you.
              Last edited by RobotSyndicate; 06-26-2022, 10:52 PM.

              Comment


                #8
                Hello RobotSyndicate,

                Time[0] is the close time of the most recently updated bar.
                Below is a link to the help guide on the Time series.


                Try using ToTime(NinjaTrader.Core.Globals.Now) if you want to print the current computer time.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Chelsea,

                  I only used the print function to test ToTime vs Globals.Now, but what I actually need to do is get a value for time that I can use to trigger code for order management and communication at certain times after hours. It sounds like I can't use ToTime if its limited to the time of bar updates. Is there a way to just pull the hour and minute out of NinjaTrader.Core.Globals.Now so I can check the time and use that in an if () statement? I know this can be done in c# with DateTime Hour and Minute properties, so could this be similarly done with NinjaTrader.Core.Globals.Now or using ToTime in a different way?

                  Thanks

                  Comment


                    #10
                    Hello RobotSyndicate,

                    OnBarUpdate() only runs when the bar updates.

                    You would need some other event triggering like a timer.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hi Chelsea,

                      As above, we already discussed using a timer, and I used one in my example code. but if I want to trigger different code at 2am, 7am, 2pm, and 5:30pm, then it seems like it would be easiest to check the system time when the timer triggers and then run the desired code (or not) depending on what time it is. As discussed, this wont work with ToTime if it can only return the time of the last bar. SO I need a way to return actual system time after the timer is triggered. That's what I'm saying. As I said, there are ways to do this with c# and DateTime, but you suggested I use Core.Globals.Now instead of DateTime.Now, so I'm asking if it is possible to return a numerical value for hours and minutes with Core.Globals.Now in a way that can be evaluated with an if statement.

                      For example, if I use 2 integers hour and minute, I can separate out and evaluate the local system time hour and minute using DateTime like this: <assuming that this is within a Timer event triggered every 10 minutes>

                      DateTime now = DateTime.Now;
                      hour = now.Hour;
                      minute = now.Minute;

                      if ((hour == 7) && (minute >= 30) && (minute < 40))
                      {
                      Do stuff that I want to happen at 1730ish;
                      }

                      else if ((hour == 17) && (minute >= 30) && (minute < 40))
                      {
                      Do stuff that I want to happen at 1730ish;
                      }


                      --> This would allow me to trigger certain code at certain times based on actual current local system time. Is there a way to do this with Core.Globals.Now and why would I do that instead?
                      Last edited by RobotSyndicate; 06-28-2022, 12:34 AM.

                      Comment


                        #12
                        Hello RobotSyndicate,

                        What is going to run your method to check the time?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Here is some of the time checking related code. In a nutshell, I have 500 instances of a strategy running, and then I have this one other strategy checking the time and canceling out live orders on the account at certain times. Because one of these times I need to cancel orders is late in after hours trading, there are frequently no recent bars, so ToTime does not reliably work.

                          else if (State == State.DataLoaded)
                          {

                          myTimer = new System.Timers.Timer(60000 * 1 * 10);
                          myTimer.Elapsed += TimerEventProcessor;
                          myTimer.Enabled = true;

                          }

                          private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
                          {
                          if (CurrentBar > 0)
                          {
                          TriggerCustomEvent(CheckTheTime, Close[0]);
                          }
                          }

                          private void CheckTheTime(object price)
                          {

                          DateTime now = DateTime.Now;
                          hour = now.Hour;
                          minute = now.Minute;

                          Print("The Current Time Is: " + NinjaTrader.Core.Globals.Now);
                          Print("Hour: " + hour);
                          Print("Minute: " + minute);


                          if ((hour == 1)
                          && (minute >= 20)
                          && (minute < 40)
                          )
                          {
                          AMcancel = 1;
                          PMcancel = 1;
                          }

                          if ((hour == 7)
                          && (minute >= 10)
                          && (minute < 20)
                          && (AMcancel == 1)
                          )
                          {

                          Print("AM Orders Canceled At: " + NinjaTrader.Core.Globals.Now);
                          AMcancel = 0;

                          foreach (Order order in Account.Orders)
                          {
                          if (order.OrderState == OrderState.Working || order.OrderState == OrderState.Accepted)
                          {
                          CancelOrder(order);
                          }
                          }
                          }



                          if ((hour == 17)
                          && (minute >= 40)
                          && (minute < 50)
                          && (PMcancel == 1)
                          )
                          {
                          Print("PM Orders Canceled At: " + NinjaTrader.Core.Globals.Now);
                          PMcancel = 0;

                          foreach (Order order in Account.Orders)
                          {
                          if (order.OrderState == OrderState.Working || order.OrderState == OrderState.Accepted)
                          {
                          CancelOrder(order);
                          }
                          }

                          }


                          }

                          Comment


                            #14
                            Hello RobotSyndicate,

                            "Because one of these times I need to cancel orders is late in after hours trading, there are frequently no recent bars, so ToTime does not reliably work."

                            This would not be related to bars. I suggested using NinjaTrader.Core.Globals.Now with ToTime().
                            Hello, I am using NT 8.0.25.0 with IB gateway 978 to run a strategy on the S&amp;P500 on 20 minute bars. With unmanaged order entry, it creates short or long entry limit orders, then adjusts those orders until they either fill or are cancelled. I am attempting to cancel the orders using, for example, CancelOrder(longOrder);


                            ToTime() provides an int representing the time part of a DateTime object.


                            Can you clarify why ToTime() would not reliably work?

                            May I have the output from your prints showing why this is not working?
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Hi Chelsea, would you please be able to tell me what to put inside the () of ToTime() in order to get the current time? The examples in your second reference appear to only be for getting the time of the most recent bar, or for using ToTime to format a predetermined time into Hmmss and then comparing the predetermined time to the most recent bar time. And the your first reference is just our same post here... Thank you for your time.
                              Last edited by RobotSyndicate; 06-29-2022, 11:12 AM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by algospoke, 05-13-2024, 06:53 PM
                              4 responses
                              28 views
                              0 likes
                              Last Post algospoke  
                              Started by dtl-saw, 12-29-2022, 09:12 AM
                              46 responses
                              3,177 views
                              1 like
                              Last Post sonia0101  
                              Started by AlphaOptions, 06-18-2013, 08:24 AM
                              7 responses
                              2,186 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Started by FAQtrader, 04-25-2024, 12:00 PM
                              14 responses
                              213 views
                              0 likes
                              Last Post sonia0101  
                              Started by bsbisme, Today, 05:08 PM
                              0 responses
                              8 views
                              0 likes
                              Last Post bsbisme
                              by bsbisme
                               
                              Working...
                              X