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

Best practice to OCO-Orders in code ...

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

    Best practice to OCO-Orders in code ...

    Hi,

    I enter a trade and submit a stop and profit target with two orders. What is the best way to link these orders? I don't see a OCO option ...

    Another question related to this ... I have some other stop-types in my code, like timestops, which exits the position too. How can I be sure to exit the position only once and don't have an immediate reverse-trade?

    BTW.: What are the CancelOrdersOnStop Option?

    Thx,
    DT

    #2
    If you are using Set() they are already OCOed. If you are using Exit() you will need to self check order states to place in Cancel orders when one gets filled. Otherwise, it will auto cancel after the position has closed as it will not be able to find a position to close.

    The only risk of hitting reversals is if you have an Enter() method called. Exit() by themselves will not double fire since once one gets filled the others will cancel. From OnOrderUpdate() you can also force cancels whenever you wish with CancelOrder() as well.
    Josh P.NinjaTrader Customer Service

    Comment


      #3
      How are the OCOed? I don't see it in the under the Orders-Tab in the column OCOed.

      I don't know if I understand your answer, so here is the code which fails for me in live trading (OnBarCLose=True), showed only for Long-Positions to simplify it:

      Entries:

      Code:
      protected override void OnBarUpdate()
      { 
         ...
         entryOrder = EnterLongLimit(quantity, Low[0], this.Name);
         ...
      }
      Exits immediately after Order-Fill in OnExecution()
      Code:
       protected override void OnExecution(IExecution execution)
      {            
          if (entryOrder != null && 
              entryOrder.Token == execution.Order.Token && 
              (execution.Order.OrderState == OrderState.Filled ||
               execution.Order.OrderState == OrderState.PartFilled || 
              (execution.Order.OrderState == OrderState.Cancelled &&  
               execution.Order.Filled > 0)))
          {
              double entryPrice = entryOrder.AvgFillPrice;
                      
              if (Position.MarketPosition == MarketPosition.Long)
              {                        
                  stopLevel   = entryPrice - stopLossTicks * TickSize;                     
                  targetLevel = entryPrice + profitTargetTicks * TickSize;                     
                  stopOrder = ExitLongStop   (execution.Order.Filled, stopLevel, "Initial-Stop", entryOrder.Name);
                  targetOrder = ExitLongLimit(execution.Order.Filled, targetLevel, "Profit-Target", entryOrder.Name);
               }
               ....
           }           
      }
      Exits checking on every Bar in OnBarUpdate()
      Code:
      ...
      if (entryOrder != null)
      {
         double entryPrice = entryOrder.AvgFillPrice;
                               
         // LONG-Exits
         if (Position.MarketPosition == MarketPosition.Long &&
            entryOrder.OrderState == OrderState.Filled)
         {                                
             // Exit after "X" - Bars
             if (xBarClose > 0 &&
                BarsSinceEntry(0, this.Name, 0) >= xBarClose-1)
             {
                   ExitLong (0, quantity, "XBarStop", this.Name);    
                   cancelOpenOrders();   // cancel target and stop order
             }
              ....
          }
           ....
      }
      As you can see I already cancel my stop and target orders. I don't see that the stop- and target-order are connected, aren't they?

      The problem is, that after exiting an order with profitTarget and XBar-Close is on the same bar the XBar-Close is executed additionally and in the above situation, in very rare cases, I am short because of my own XBar-Close-order.

      So the important questions are:

      1) What must I change in the above code to work correctly with my orders? (Maybe the cancelOrder()-call must be before the own exit?)
      2) How are the orders OCOed as you said?
      3) What about CancelOrdersOnStop=true;, what does it mean?

      Thx,
      DT

      Comment


        #4
        When you use Exit() methods you don't explicitly OCO link them. You need to work within OnOrderUpdate() to cancel. Using OnBarUpdate() is too slow. Check OnOrderUpdate() for filled event. When received, CancelOrder() the other IOrder.

        CancelOrdersOnStop determines what to do with any remaining active orders as you stop the strategy.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          Hm ... I think you don't understand the core of the problem. You are right, because I have to add OnOrderUpdate() or OnExecution() because I thought about this point from your helpguide:

          "CRITICAL: If you want to drive your strategy logic based on order fills you must use OnExecution() instead of OnOrderUpdate(). OnExecution() is always triggered after OnOrderUpdate(). There is internal strategy logic that is triggered after OnOrderUpdate() is called but before OnExecution() that can adversely affect your strategy if you are relying on tracking fills within OnOrderUpdate()."

          But it is correct, I have to Cancel my Exit-Orders myself. Is it possible to move the whole OnExecution-Code in OnOrderUpdate() although your CRITICAL-hint forbid it?

          But back to the root cause .... of my question ...
          The core problem here is that I have another exit (XBar) and after that exit I cancel both (stop and target) other orders, but sometimes they are executed too. So I have another reverse position. I cannot test my own exits in OnOrderUpdate ... so I don't know what I'm able to do with own exits.

          Thx,
          DT

          Comment


            #6
            DT,

            Here is the deal. You should maintain order placement and things like that in OnExecution(). Like, Enter() starts to receive part fill events = you want to submit stop/targets based on those events in OnExecution(). For cancelling orders you can use OnOrderUpdate() because you are not pulling any quantity information. You just want to cancel an order so cancellation is safe from OnOrderUpdate() and is in fact preferred there since it comes before OnExecution().

            All of your exit orders should have IOrders. When any of your exits fills you need to immediately cancel the others. Now if all your orders are extremely close together it is possible to be double filled. You should not do this. Instead you should just have on exit order. If price is closer to the first exit you want, use that one. If it is closer to the other, amend the exit to be the second. Does that make sense?
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              Josh, thanks for clarifying about OnOrderUpdate(). I will put my cancel logic in this method.

              Only one Exit-Order .... ok, I understand you but with my XBar-Exit, for example, I have an Exit-On-Market and no limit or stop exit. So in my code below I always have two separate exit orders, one is placed as stop order and the other as market, when a condition is true ..

              >> All of your exit orders should have IOrders.

              Ahhhhhh, ok wait am moment .... this second I got .... do you mean something like that ...

              Code:
              ...
              IOrder xBarExit = ExitShort (0, quantity, "XBarStop", this.Name);               
              ...
              Then I can test the fill of the XBar-Stop and the other stop-order in OnOrderUpdate() .... the order which comes first leads to a cancellation of the other one ... because OnOrderUpdate() is called sequentially ...
              is that right?

              Sorry for my misunderstanding so far, but it's not so easy to get all the order things together ...

              DT

              Comment


                #8
                OnOrderUpdate() triggers whenever any of your orders have order state changes. It will trigger in the sequence the events are received.

                If you have a condition to send a market order to be absolutely safe you can send CancelOrder() on your limit/stop orders first, wait for cancelled state in OnOrderUpdate() and when you receive both of them being successfully cancelled, then place in your market order.
                Josh P.NinjaTrader Customer Service

                Comment


                  #9
                  Ok, that is one way, but what are with the suggestion of my previous post. Is this way not possible. Does my market order (saved as Exit-Order) go through the OnOrderUpdate()-method?

                  What about my code, is it correct? It would be more clear for me if you provide some code, too ...

                  First you said I need for all order an own exit order-object and then you give me an completely other alternative. I don't understand your answer-scheme. Please answer my questions that's all I want ... that's the only way to understand it for me ...

                  Comment


                    #10
                    The market order does go to OnOrderUpdate(). All orders make it to OnOrderUpdate() regardless if you saved the IOrder reference or not. If you don't save the reference it just makes it hard for you to identify which order is triggering the OnOrderUpdate() event.

                    Your code works, but the approach may not be the safest. The steps I outlined will be the safest route to take. My alternative does not contradict the fact that all your orders should have an IOrder stored. You need all IOrder objects to be able to manage all of them.
                    Josh P.NinjaTrader Customer Service

                    Comment


                      #11
                      Thx, Josh, for the detailed explanation. Now it is clear for me and I understand it

                      I will implement the OnOrderUpdate() in my code and hope to make it more save ... for live trading ...

                      Thx,
                      DT
                      Last edited by DarthTraderson; 11-05-2009, 12:54 PM.

                      Comment


                        #12
                        Hi Josh,

                        one additional question. Is OnOrderUpdate() only called on Cancel and Rejection of on Order or on every state-change?

                        Ok, got it with debugging ... OnOrderUpdate is called on every state-change ...

                        Thx,
                        DT
                        Last edited by DarthTraderson; 11-07-2009, 10:09 AM.

                        Comment


                          #13
                          Hi,

                          for my own 'market' orders the todos are now already clear, but what about OCOing limit and stop orders?

                          First, I can't use SetStopLoss and SetProfitTarget because I'm not able to cancel them by myself, otherwise the market-order handling will not work for me.

                          So I have to use

                          Code:
                          stopOrder = ExitLongStop(0, true, ...);
                          limitOrder = ExitLongLimit(0, true, ...)
                          But what is the correct way to OCO them? Is it possible?
                          Or need I cancel one of them, when the other get triggered in OnExecution-method? Because in OnOrderUpdate() I should not ask for fill state like documented in the help guide ...

                          My fear is that OnExecution is to late to ask for filling of the limit or stop order.

                          Thx,
                          DT

                          Comment


                            #14
                            DT, correct in this case you would need to provide the OCO logic yourself in the code as per default with the Exit() methods there's no such linking in place, please also see this sample here for structure - http://www.ninjatrader-support2.com/...ead.php?t=7499

                            You can check fillstates for each part of the OCO bracket in OnExecution() and then cancel the other not anymore needed one then...
                            BertrandNinjaTrader Customer Service

                            Comment


                              #15
                              That is ok for me ... will it be possible in NT7 to self OCO a limit and stop order?

                              That would be much easier to handle, and the logic already exists as you can see with SetStopLoss and SetProfitTarget ... ?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by fx.practic, 10-15-2013, 12:53 AM
                              5 responses
                              5,404 views
                              0 likes
                              Last Post Bidder
                              by Bidder
                               
                              Started by Shai Samuel, 07-02-2022, 02:46 PM
                              4 responses
                              95 views
                              0 likes
                              Last Post Bidder
                              by Bidder
                               
                              Started by DJ888, Yesterday, 10:57 PM
                              0 responses
                              8 views
                              0 likes
                              Last Post DJ888
                              by DJ888
                               
                              Started by MacDad, 02-25-2024, 11:48 PM
                              7 responses
                              159 views
                              0 likes
                              Last Post loganjarosz123  
                              Started by Belfortbucks, Yesterday, 09:29 PM
                              0 responses
                              8 views
                              0 likes
                              Last Post Belfortbucks  
                              Working...
                              X