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

Cancel Order Execution After 5 Bars If No Fill

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

    Cancel Order Execution After 5 Bars If No Fill

    Hello,

    For the strategy I'm developing, I would like to design a backstop that cancels active orders if they do not fill within a certain number of bars in the unmanaged approach. What is the best way to go about doing this? I've tried searching the forum and cannot find the answer. I'm relatively new to programming, so I'm likely making a rudimentary error here. Currently I have it coded like this, but it is not working.

    private Order Long = null;
    private Order Short = null;
    private Order BTC = null;
    private Order STC = null;
    private int barNumberOfOrder = 0;​

    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
    if ((OrderAction.BuyToCover == OrderAction.BuyToCover) && (CurrentBar > barNumberOfOrder + 5) && (execution.Order.OrderState != OrderState.Filled))
    {
    CancelOrder(BTC);
    }

    if ((OrderAction.Buy == OrderAction.Buy) && (CurrentBar > barNumberOfOrder + 5) && (execution.Order.OrderState != OrderState.Filled))
    {
    CancelOrder(Long);
    }

    if ((OrderAction.Sell == OrderAction.Sell) && (CurrentBar > barNumberOfOrder + 5) && (execution.Order.OrderState != OrderState.Filled))
    {
    CancelOrder(STC);
    }

    if ((OrderAction.SellShort == OrderAction.SellShort) && (CurrentBar > barNumberOfOrder + 5) && (execution.Order.OrderState != OrderState.Filled))
    {
    CancelOrder(Short);
    }
    }

    Any assistance, preferably with example code, is much appreciated.​

    #2
    How about using BarsSinceEntry or is it some other problem


    you may want to do something like if (execuion.Name.Contains("Limit"))
    ///do something

    Comment


      #3
      Hello odea82,

      Thank you for your post.

      When the order is submitted, are you saving the value of the CurrentBar to barNumberOfOrder? I do see that you have this logic placed inside of OnExecutionUpdate, which is an event-driven method that is only called when an execution/order fill occurs. If you are checking to see if a certain number of bars has passed since an order was submitted, I suggest moving your logic to OnBarUpdate. I have created an example script that submits a Buy Limit order with the Unmanaged Approach. There is a variable "BarsSinceOrderSub" that can be changed in the strategy settings before enabling it, in case you want to adjust the amount of bars to pass since an order is submitted.

      What it does is it saves the bar index when the bar is submitted to the int orderBar, and then in OnBarUpdate it checks if the CurrentBar - orderBar is greater than or equal to the BarsSinceOrderSub (as well as if the order is not null and not filled). If the condition is met, the order will be canceled.

      I also enabled Trace Orders and added Print statements to be able to monitor the strategy's behavior in the NinjaScript Output window. For more information about adding debugging prints:


      Here is the example:
      orderFillBarsTest_NT8.zip

      Please let me know if I may be of further assistance.
      Emily C.NinjaTrader Customer Service

      Comment


        #4
        Hi NinjaTrader_Emily,

        I am not able to get it to execute the way I want. I do have multiple entries and exits in my algo. Do they all need to be defined independently for the order cancellation? Lets say I've opened a short position and I place an order to buy to cover if the price is rising. Using the code you sent, I'm not able to get it to actually cancel the order if x number of bars elapse and it hasn't filled. How would I do that in this example:

        if ((Close[0] > Close[1])
        && (Position.MarketPosition != MarketPosition.Long)
        && (ToTime(Time[0]) >= 083000)
        && (ToTime(Time[0]) <= 145000))
        {
        SubmitOrderUnmanaged(0, OrderAction.BuyToCover, OrderType.Limit, 4, Close[0], 0, "", "@BTC");
        orderBar = CurrentBar;
        }

        Thanks​

        Comment


          #5
          Hello odea82,

          Thank you for your reply.

          In your example, I see you are checking if Position.MarketPosition != MarketPosition.Long. I understand that you are saying you have opened a short position; if the position is not long, this means it could evaluate to true if the position is either short or flat. It might be better to specify in your condition if Position.MarketPosition == MarketPosition.Short instead, just to prevent an order from unintentionally being submitted when the position is flat.

          Based on your initial post, I suspect you have already reviewed the following reference sample for Using CancelOrder() method to cancel orders:



          Tying in similar logic from that sample to the example you have provided, here is what it would look like to assign the order object to BTC in OnOrderUpdate:

          Code:
          if (BTC == null && order.Name == "BTC")
          {
          // Assign BTCin OnOrderUpdate() to ensure the assignment occurs when expected.
          // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not guaranteed to be complete if it is referenced immediately after submitting
          BTC = order;
          }
          
          if (BTC! = null && order.Name == "BTC")
          {
          // Check if BTC is canceled
          if (order.OrderState == OrderState.Cancelled)
          {
          // Reset BTCback to null
          BTC= null;
          }
          }


          This is what it would look like to add a condition in OnBarUpdate() that will cancel the order if it has not been filled within a specific number of bars:

          Code:
          if (BTC != null && CurrentBar > barNumberOfOrder + 5)
          {
          CancelOrder(BTC);
          }​
          This would need to be defined for each of your four orders (BTC, STC, Short, and Long). If your strategy still does not behave as expected after making some adjustments, please describe what behavior is occurring vs. what you are expecting, as well as if there are any errors in the Log tab of the Control Center or in the NinjaScript Output window.

          Thank you for your patience.
          Emily C.NinjaTrader Customer Service

          Comment


            #6
            NinjaTrader_Emily,

            Thank you so much. I'll run this on Monday to see if it works. I have one other question, albeit an unrelated one. Is it possible to set a maximum position quantity in the unmanaged approach?

            Thanks.

            Comment


              #7
              Hello odea82,

              Thank you for your reply.

              Maximum Position Quantity is set up in the risk settings for the account. If you are using a simulated account, then you could apply a risk template via the Accounts tab of the Control Center. If you are using a live account, the maximum position quantity is set by your broker.

              The settings for a strategy do include a maximum entries per direction, and this would be applicable whether you are trading on a managed or unmanaged strategy:


              Please don't hesitate to reach out if you have any additional questions or concerns.
              Emily C.NinjaTrader Customer Service

              Comment


                #8
                Hello Emily,

                I've found that no matter what number I put into the entries per direction, when I run the strategy in my simulated account the strategy blows straight past the entries per direction that I've set in the defaults. I've had one iteration of the algo where I had entries per direction set to 10 and the orders set to buy and sell 100 shares per order, and ended up in a long position of 50,000 shares. I'm not sure why this has not seemed to limit the algo when it should. I see that the managed approach I can set a condition such as

                && (Position.Quantity < 1000)

                Is there an equivalent condition in the unmanaged approach?

                Thank you so much.

                Comment


                  #9
                  Hello odea82,

                  Thank you for your patience.

                  What do you have configured for the EntryHandling?


                  Unless your entries are all named/tagged the same, you may need to toggle this to AllEntries to ensure that every entry, even with a unique name, will be counted toward your maximum Entries Per Direction value. If you have it configured this way and still experience the same behavior, please provide a screenshot of your settings and/or test the same settings out on the SampleMACrossover strategy to see if you experience the same behavior.

                  You could certainly still use Position.Quantity as a condition in your logic, even with the unmanaged approach. This will just check the position quantity based on the last call of OnPositionUpdate()


                  I appreciate your patience and look forward to your reply with the results.
                  Emily C.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Emily,

                    This is what I have for calculating orders and entry handling:

                    Calculate = Calculate.OnEachTick;
                    EntriesPerDirection = 10;
                    EntryHandling = EntryHandling.AllEntries;​

                    My strategy has three triggers for long entries, all named "Long", seven triggers to sell all named "STC", three triggers to short all named "Short", and seven triggers to buy to cover all named "BTC". All of my triggers execute orders in lots of 100 shares. Since the entries per direction is set to 10, my assumption is that this would make the maximum position at any given time 1000 shares long or short.

                    I have been simulating my strategy on 10 instruments since market open today and I have had multiple instances where on a given instrument my position was greater than 10,000 shares long or 10,000 short.

                    I have been having an issue of an individual trigger making multiple entries per bar, so perhaps part of the problem is the delay between orders being placed and orders being filled allowing for more than 10 orders per direction to be placed before filled orders trigger the entries per direction limit, however when I've watched in real time I have seen numerous instances of positions exceeding 1000 shares sitting still for a time and then increasing beyond 1000 shares when the entry orders are once again triggered.

                    Any help on how to solve this is much appreciated.

                    Thanks

                    Comment


                      #11
                      Hello odea82,

                      Thank you for your patience.

                      Please try enabling Trace Orders and adding Print() statements to debug your strategy's behavior. When a strategy isn't behaving as expected, by printing the variables used in your conditions both outside of the conditions and inside of the conditions when they are triggered, this can help to diagnose the cause of the behavior. I mentioned these debugging tools briefly in post number 3: https://ninjatrader.com/support/foru...07#post1219507

                      If you are not sure of the output from the NinjaScript Output window after enabling Trace Orders and/or adding print statements, please feel free to right-click and Save As then reply here with the file of the output for review.

                      I hope this information is insightful and helps to resolve this item.
                      Emily C.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Segwin, 05-07-2018, 02:15 PM
                      14 responses
                      1,788 views
                      0 likes
                      Last Post aligator  
                      Started by Jimmyk, 01-26-2018, 05:19 AM
                      6 responses
                      837 views
                      0 likes
                      Last Post emuns
                      by emuns
                       
                      Started by jxs_xrj, 01-12-2020, 09:49 AM
                      6 responses
                      3,293 views
                      1 like
                      Last Post jgualdronc  
                      Started by Touch-Ups, Today, 10:36 AM
                      0 responses
                      13 views
                      0 likes
                      Last Post Touch-Ups  
                      Started by geddyisodin, 04-25-2024, 05:20 AM
                      11 responses
                      63 views
                      0 likes
                      Last Post halgo_boulder  
                      Working...
                      X