Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Cancel orders in onmarketupdate

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

    Cancel orders in onmarketupdate

    How can i make sure to cancel order once its gotten filled in OnMarketData.
    Sometimes i get an error onMarketData when order left hanging without closing. It seems if i do trail and when in trail additional setup evaluates to true and gives out an error

    With current code i get an error. The name execution does not exist in current context
    Code:
    if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isXiphosLongSetup == true ){    
                                Print("334" + Time[0]);
                                Print("trailLong" + trailLong);
                                Print("bid" + bid);
                            stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Xiphos Long"); //Sets Stop
    //                            stopOrder = trailLong;
                            }
                            if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isDoryLongSetup == true ){
                                Print("444");
                                stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Dory Long");        
                            }
                            if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isKopisLongSetup == true){
                                stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Kopis Long");                                                    
                            }
                            if ((targetOrder != null && targetOrder == execution.Order))
                             {
                                 Print("stopOrder"+stopOrder);
                                  Print("execution.Order"+execution.Order);
                                 Print("targetOrder"+targetOrder);
                                 if (execution.Order.OrderState == OrderState.Filled)
                                 {
                                     CancelOrder(stopOrder);
                                 }    
                             }
                        if ((stopOrder != null && stopOrder == execution.Order))
                            {
                                Print("targetOrder" + targetOrder);
                                if (execution.Order.OrderState == OrderState.Filled)
                                {
                                    CancelOrder(targetOrder);
                                }
                            }​

    #2
    Hello tkaboris,

    The execution object comes from the OnExecutionUpdate method parameters.


    You would need to assign the order object to a variable in OnOrderUpdate().


    Then you can check that the variable is not null and the <order>.OrderState is OrderState.Working and if so, supply the variable to CancelOrder().
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      When I am trying to put order. in trail section, nothing comes up

      Code:
      #region On OrderUpdate variables
              private Order entryOrder = null; // This variable holds an object representing our entry order
      //        private Order entryOrder = null; // This variable holds an object representing our entry order
              private Order stopOrder = null; // This variable holds an object representing our stop loss order
              private Order targetOrder = null; // This variable holds an object representing our profit target order
              private int sumFilled = 0; // This variable tracks the quantities of each execution making up the entry order
              #endregion​
      Code:
      #region OnOrderUpdate
              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {
                  // Handle entry orders here. The entryOrder object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
                  // Assign entryOrder in OnOrderUpdate() to ensure the assignment occurs when expected.
                  // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting
                  if (order.Name == "Xiphos Long" || order.Name == "Xiphos Short"
                      || order.Name == "Kopis Long" || order.Name == "Kopis Short"
                      || order.Name == "Dory Long" || order.Name == "Dory Short")
                  {
                      entryOrder = order;
      
                      // Reset the entryOrder object to null if order was cancelled without any fill
                      if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                      {
                          entryOrder = null;
                          sumFilled = 0;
                      }
                  }
      
              }
              #endregion​
      Code:
      protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
              {
                  double bid = GetCurrentBid();
                  double ask = GetCurrentAsk();
      
                  /* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
                  which ensures your strategy has received the execution which is used for internal signal tracking. */
                  if (entryOrder != null && entryOrder == execution.Order)
                  {[INDENT]if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))[/INDENT]
                       {
                          // We sum the quantities of each execution making up the entry order
                          sumFilled += execution.Quantity;[INDENT=2]
      if (execution.Name == "Xiphos Long" && SetTrail)[/INDENT]
                                 {
                                  stopOrder = ExitLongStopMarket(1, true, execution.Order.Filled, execution.Order.AverageFillPrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");
                                  targetOrder = ExitLongLimit(1, true, execution.Order.Filled, execution.Order.AverageFillPrice + (TickSize * ProfitTargetTicks), "PTL", "Xiphos Long");
      
                                }​[INDENT]​​}[/INDENT]
       }
      and in my OnmarketData in onbarupdate for Trail section

      Code:
      if (
                          (Position.MarketPosition == MarketPosition.Long) //Needs to be in a long position
                              && (marketDataUpdate.Price >= trailTriggerLong )
                                  && (Low[1] > Low[2]) //Ensure the trail will only move up if the new candles low is higher.    
                              )
                          {
      //                    
      
      //                        stopLong1 = trailLong;
      
                              if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isXiphosLongSetup == true ){    
      
                              stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Xiphos Long"); //Sets Stop
      //                            stopOrder = trailLong;
                              }
                              else if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isDoryLongSetup == true ){
      
                                  stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Dory Long");        
                              }
                              else if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isKopisLongSetup == true){
                                  stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Kopis Long");                                                    
                              }
                              if ((targetOrder != null && targetOrder == execution.Order))
                               {
                                   Print("stopOrder"+stopOrder);
                                    Print("execution.Order"+execution.Order);
                                   Print("targetOrder"+targetOrder);
                                   if (execution.Order.OrderState == OrderState.Filled)
                                   {
                                       CancelOrder(stopOrder);
                                   }    
                               }
                              if ((stopOrder != null && stopOrder == execution.Order))
                              {
                                  Print("targetOrder" + targetOrder);
                                  if (execution.Order.OrderState == OrderState.Filled)
                                  {
                                      CancelOrder(targetOrder);
                                  }
                              }​

      Comment


        #4
        Hello tkaboris,

        The code you have suggested is assigning orders to variables from the order method call. You will need to assign orders to variables from OnOrderUpdate().

        "OnOrderUpdate() will run inside of order methods such as EnterLong() or SubmitOrderUnmanaged(), therefore attempting to assign an order object outside of OnOrderUpdate() may not return as soon as expected. If your strategy is dependent on tracking the order object from the very first update, you should try to match your order objects by the order.Name (signal name) from during the OnOrderUpdate() as the order is first updated."

        This is shown in the sample code in the help guide.


        Where you have stated:
        "nothing comes up"

        Add prints to understand the behavior.

        Print the time and all values used in the first condition.
        Is this evaluating as true or false?

        Below is a link to a forum post on using prints to understand behavior.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          i didnt understand this part
          The code you have suggested is assigning orders to variables from the order method call. You will need to assign orders to variables from OnOrderUpdate().
          I followed the code in the example page.
          can you briefly show an example of assigning order to variable from OnOrderUpdate? as i believe i did just that..

          Comment


            #6
            I cant print entryOrder from OnOrderUpdate ok but i cant print entryOrder from OnMarketData section. its blank

            Comment


              #7
              When i have the following code to make sure stopOrder is cancelled when target filled, it removes stoploss at the time of order not when it target fills. What is the correct syntax

              if ((targetOrder != null && entryOrder == execution.Order))
              {
              Print("cancel stop");
              Print("stopOrder"+stopOrder);
              Print("execution.Order"+execution.Order);
              Print("targetOrder"+targetOrder);
              if (execution.Order.OrderState == OrderState.Filled)
              {
              CancelOrder(stopOrder);
              }
              }​

              Comment


                #8
                Hello tkaboris,

                An assignment is when you have variableName = value. This assigns the variable the value of the object.

                Where you have:

                stopOrder = ExitLongStopMarket(1, true, execution.Order.Filled, execution.Order.AverageFillPrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");
                targetOrder = ExitLongLimit(1, true, execution.Order.Filled, execution.Order.AverageFillPrice + (TickSize * ProfitTargetTicks), "PTL", "Xiphos Long");​
                stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Xiphos Long");
                stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Dory Long");
                stopOrder = ExitLongStopMarket(1, true, stopOrder.Quantity, trailLong, "SLL", "Kopis Long");

                This is not supported. The ExitLongStopMarket() is an order method. While this does return an Order object, you cannot assign that directly to a variable.


                To print the order object in OnOrderUpdate():
                protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string comment)
                {
                Print(order.ToString());
                }

                To print the values used in the condition 'if ((targetOrder != null && entryOrder == execution.Order))​'

                Print("targetOrder null: " + (targetOrder != null).ToString());
                Print("entryOrder == execution.Order: " + (entryOrder == execution.Order).ToString());
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Is this part of the code valid?
                  I was following the example in the docs...
                  Code:
                  if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                                  {
                                      // We sum the quantities of each execution making up the entry order
                                      sumFilled += execution.Quantity;
                  
                                      // ==================================================================== Xiphos Trade ---------------------
                                      // Submit exit orders for partial fills
                                      if (execution.Order.OrderState == OrderState.PartFilled && Position.MarketPosition == MarketPosition.Long && !SetTrail)
                                      {            
                                          if(execution.Name == "Xiphos Long" && (execution.Order.AverageFillPrice - (TickSize * StopLossTicks)) <= bid){
                                          stopOrder = ExitLongStopMarket(1, true, execution.Order.Filled, execution.Order.AverageFillPrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");    
                                          }
                                          if(execution.Name == "Xiphos Long" &&(execution.Order.AverageFillPrice + (TickSize * ProfitTargetTicks)) >= bid){
                                          targetOrder = ExitLongLimit(1, true, execution.Order.Filled, execution.Order.AverageFillPrice + (TickSize * ProfitTargetTicks), "PTL", "Xiphos Long");
                                          }
                  }
                                      }​

                  Comment


                    #10
                    I cant fgure out how to not to submit same order. I keep on getting ignored submitted order managed output.
                    can you please hint on what condition i can have so it doesnt send repeat orders?

                    Code:
                    if (
                                        (Position.MarketPosition == MarketPosition.Long) //Needs to be in a long position
                                            && (marketDataUpdate.Price >= trailTriggerLong )
                                                && (Low[1] > Low[2]) //Ensure the trail will only move up if the new candles low is higher.    
                                            )
                                        {
                    
                                            if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isXiphosLongSetup == true && !isDoryLongSetup && !isKopisLongSetup){    
                                                Print("Trail Xiphos");
                                            ExitLongStopMarket(1, true, Position.Quantity, trailLong, "SLL", "Xiphos Long"); //Sets Stop
                    //                            stopOrder = trailLong;
                                            }
                                            else if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isDoryLongSetup == true && !isXiphosLongSetup && !isKopisLongSetup){
                    
                                                ExitLongStopMarket(1, true, Position.Quantity, trailLong, "SLL", "Dory Long");        
                                            }
                                            else if(Position.MarketPosition == MarketPosition.Long && trailLong <= bid && isKopisLongSetup == true && !isXiphosLongSetup && !isDoryLongSetup){
                                                ExitLongStopMarket(1, true, Position.Quantity, trailLong, "SLL", "Kopis Long");                                                    
                                            }
                    
                                            trailTriggeredCandle = false; //You can move around trail stop freely until new candle.
                                        }​
                    Entering Xiphos Long HTF 34B: 8/24/2023 8:38:49 AM
                    HTFLong34BSetup: False0
                    HTFSwingLong: True0
                    Close[2][1]15336
                    Long34BT8/24/2023 8:39:01 AM
                    Short34BT8/24/2023 8:39:35 AM
                    Short34BT8/24/2023 8:39:35 AM
                    Long34BT8/24/2023 8:39:35 AM
                    False
                    Trail Xiphos
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Entered internal SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long'
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Amended matching order at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long'
                    Trail Xiphos
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Entered internal SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long'
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Ignored SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'
                    Trail Xiphos
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Entered internal SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long'
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Ignored SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'
                    Trail Xiphos
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Entered internal SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long'
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Ignored SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'
                    Trail Xiphos
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Entered internal SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long'
                    8/24/2023 8:39:39 AM Strategy 'Sparta Algo/284766115': Ignored SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'
                    Trail Xiphos​

                    Comment


                      #11
                      Hello tkaboris,

                      Where you have inquired:
                      "Is this part of the code valid?"

                      Not all of that code is valid.

                      stopOrder = ExitLongStopMarket(1, true, execution.Order.Filled, execution.Order.AverageFillPrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");

                      Assigning an order to a variable from the order method return is not supported.

                      So that I may request the help guide be updated, which page in the help guide has this code where orders are being assigned from order methods?

                      Note, for the execution parameter this must be in OnExecutionUpdate() and not OnMarketData().


                      Where you have inquired:
                      "I cant fgure out how to not to submit same order. I keep on getting ignored submitted order managed output."

                      Ignored SubmitOrderManaged() method at 8/24/2023 8:39:39 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15336.00 SignalName='SLL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'

                      This TraceOrders message means that there is already an order with the signalName 'Xiphos Long' that is in a working state.

                      To submit a new order use a new unique signal name like 'Xiphos Long 2'.

                      Ensure that you have EntriesPerDirection set to the total number of entries orders you want to be able to place into the position or that you are using EntryHandling.UniqueEntries.

                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        I was referring to this example.
                        Do you have a strategy example so i can refer to for an example?
                        Attached Files

                        Comment


                          #13
                          Hello tkaboris,

                          The link to the page in question would be:


                          The reference sample was created before our development let us know about the issue with assigning order variables directly from order methods.
                          Thank you for catching this oversight. I will have the example modified to use the proper implantation and get the help guide updated soon.

                          Below is a link to examples that assign orders to variables from OnOrderUpdate().
                          Chelsea B.NinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by NullPointStrategies, Today, 05:17 AM
                          0 responses
                          48 views
                          0 likes
                          Last Post NullPointStrategies  
                          Started by argusthome, 03-08-2026, 10:06 AM
                          0 responses
                          126 views
                          0 likes
                          Last Post argusthome  
                          Started by NabilKhattabi, 03-06-2026, 11:18 AM
                          0 responses
                          66 views
                          0 likes
                          Last Post NabilKhattabi  
                          Started by Deep42, 03-06-2026, 12:28 AM
                          0 responses
                          42 views
                          0 likes
                          Last Post Deep42
                          by Deep42
                           
                          Started by TheRealMorford, 03-05-2026, 06:15 PM
                          0 responses
                          46 views
                          0 likes
                          Last Post TheRealMorford  
                          Working...
                          X