Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Trades not closing in strategy analyzer

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

    #16
    Hello tkaboris,

    I believe you are not understanding the core concepts here about live until cancelled orders.

    A live until cancelled order is a order you submit one time and it works until filled or cancelled. If you call that order method again you get the ignored warning because you are trying to submit a separate duplicate order. Your condition that calls ExitShortStopMarket needs to happen only 1 time, the code you have now its happening more than one time.

    If you wanted to later update the price for example to trail with that order that is active you need to use ChangeOrder and supply the order object for the order you want to change.

    Comment


      #17
      Oh, well I guess I need to keep that live until canceled as I might use trail stop. What condition can I use so it check only once?

      Comment


        #18
        Hello tkaboris,

        That would be up to how you want your strategy to work. You would usually use Order variables to know when an order has been submitted and is active. Please thoroughly review the following example and make sure you firmly understand what this sample is doing in each part. After you completely understand what the sample is doing you can implement that type of logic in your own script.



        The places to pay attention to would be how OnOrderUpdate and OnExecutionUpdate are used to track orders. You would also need to track orders in your code because you are using live until cancelled orders. If you follow the stopOrder you will see that it is only submitted once when the entry order fills. Later in OnBarUpdate it has a break even and that works without being ignored because a new price is used, its not an identical order submission.

        Comment


          #19
          HI, I have implemented the following to my strategy, followed the example from Onbarupdate. however i am still getting Ignored SubmitOrderManaged() logs.
          I also had code in onexecutionupdate to cancel orders and I am not sure how to go about that. Do I still need to keep code for cancelled orders? What else should i do to prevent duplicate submission.?
          Thank you
          Code:
          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​
          
           EnterLong(1,PositionSize, "Xiphos Long");
            isXiphosLongSetup = true;                                  
           myFreeTradeLong = true;​
          //======================
          
          if (Position.MarketPosition == MarketPosition.Long && isXiphosLongSetup == true)                
                          if (UseFixedSLTP)
          
                              {
          
                                  if(stopOrder != null && (Position.AveragePrice - (TickSize * StopLossTicks)) <= bid){
                                  stopOrder =    ExitLongStopMarket(1, true, stopOrder.Quantity, Position.AveragePrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");
                                  }
                                  if(Position.MarketPosition == MarketPosition.Long && (Position.AveragePrice + (TickSize * ProfitTargetTicks)) >= bid){
                                  targetOrder =    ExitLongLimit(1, true, targetOrder.Quantity, Position.AveragePrice + (TickSize * ProfitTargetTicks), "PTL", "Xiphos Long");
                                  }
                              }​
          
          //===============================
          
          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")
                      {
                          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;
                          }
                      }
                  }​
          //=======================
          
          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)
                      {
                          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;
          
                              // Submit exit orders for partial fills
                              if (execution.Order.OrderState == OrderState.PartFilled)
                              {
                                  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");
                              }
                              // Update our exit order quantities once orderstate turns to filled and we have seen execution quantities match order quantities
                              else if (execution.Order.OrderState == OrderState.Filled && sumFilled == execution.Order.Filled)
                              {
                                  // Stop-Loss order for OrderState.Filled
                                  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");
                              }
          
                              // Resets the entryOrder object and the sumFilled counter to null / 0 after the order has been filled
                              if (execution.Order.OrderState != OrderState.PartFilled && sumFilled == execution.Order.Filled)
                              {
                                  entryOrder = null;
                                  sumFilled = 0;
                              }
                          }
                      }
          
                      // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
                      if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
                      {
                          if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                          {
                              stopOrder = null;
                              targetOrder = null;
                          }
                      }​
          // Code to cancel orders
          if (execution.Name == "Xiphos Long")
                    {
          
          
                        if (stopOrder == null && targetOrder == null)
                        {
          
                            if(Position.MarketPosition == MarketPosition.Long && (Position.AveragePrice - (TickSize * StopLossTicks)) <= bid){
                                stopOrder = ExitLongStopMarket(1, true, Position.Quantity, Position.AveragePrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");
                            }
                            if(Position.MarketPosition == MarketPosition.Long && (Position.AveragePrice + (TickSize * ProfitTargetTicks)) >= bid){
                                targetOrder = ExitLongLimit(1, true, Position.Quantity, Position.AveragePrice + (TickSize * ProfitTargetTicks), "PTL", "Xiphos Long");
                            }
          
                        }
          
                        if ((stopOrder != null && stopOrder == execution.Order))
                          {
                              if (execution.Order.OrderState == OrderState.Filled)
                              {
                                  CancelOrder(targetOrder);
                              }
                          }
                       if ((targetOrder != null && targetOrder == execution.Order))
                           {
                               if (execution.Order.OrderState == OrderState.Filled)
                               {
                                   CancelOrder(stopOrder);
                               }    
                           }
          
                    }​
          }
          Entering Xiphos Long 34B:8/23/2023 9:45:01 AM
          8/23/2023 9:45:02 AM Strategy 'Sparta Algo/284766076': Entered internal SubmitOrderManaged() method at 8/23/2023 9:45:02 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15025.75 SignalName='SLL' FromEntrySignal='Xiphos Long'
          8/23/2023 9:45:02 AM Strategy 'Sparta Algo/284766076': Ignored SubmitOrderManaged() method at 8/23/2023 9:45:02 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15025.75 SignalName='SLL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'
          8/23/2023 9:45:02 AM Strategy 'Sparta Algo/284766076': Entered internal SubmitOrderManaged() method at 8/23/2023 9:45:02 AM: BarsInProgress=1 Action=Sell OrderType=Limit Quantity=1 LimitPrice=15036.75 StopPrice=0 SignalName='PTL' FromEntrySignal='Xiphos Long'
          8/23/2023 9:45:02 AM Strategy 'Sparta Algo/284766076': Ignored SubmitOrderManaged() method at 8/23/2023 9:45:02 AM: BarsInProgress=1 Action=Sell OrderType=Limit Quantity=1 LimitPrice=15036.75 StopPrice=0 SignalName='PTL' FromEntrySignal='Xiphos Long' Reason='There already is a matching order with same prices and quantity'
          after myFreeTradeShortFalse​
          Last edited by tkaboris; 09-04-2023, 07:24 PM.

          Comment


            #20
            Hello tkaboris,

            If you are still getting ignored order warnings that means you are still calling that order multiple times. You would need to use prints now to monitor how your logic is working.

            The only reason the ignored warning would come up is if you try and call the order with the signal name SLL with the exact same values more than one time.

            Reason='There already is a matching order with same prices and quantity'

            Comment


              #21
              Ok i will keep on looking for a cause. Question does my logic for cancelling order should stay there? so both functions To Cancel orders and To setting stopOrder and targetOrders for tracking should stay in onExecutionUpdate?

              Comment


                #22
                Hello tkaboris,

                That would be outside of the scope that I could answer, that depends on your overall logic and needs. For the question about the ignored order that is not relevant.

                If you are trying to submit targets based on an entry fill that needs to go in OnExecutionUpdate.

                Comment


                  #23
                  Ok i moved stoploss and take profit from onbarupdate to onexecution update. it seems I dont get ignored message anymore. Can you please glance at output to see if it behaves as suppose to?
                  I mean these parts of the output..
                  - Entered internal SubmitOrderManaged()
                  - Cancelled pending exit order

                  Thank you

                  Enabling NinjaScript strategy 'SpartaAlgo/284766077' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On each tick IsUnmanaged=False MaxRestarts=4 in 5 minutes
                  Long34B8/23/2023 2:55:00 AM
                  XiphosTradeTrue
                  Long34BSetupTrue
                  8/23/2023 2:55:01 AM Strategy 'Sparta Algo/284766077': Entered internal SubmitOrderManaged() method at 8/23/2023 2:55:01 AM: BarsInProgress=1 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Xiphos Long' FromEntrySignal=''
                  condition2
                  8/23/2023 2:55:01 AM Strategy 'Sparta Algo/284766077': Entered internal SubmitOrderManaged() method at 8/23/2023 2:55:01 AM: BarsInProgress=1 Action=Sell OrderType=StopMarket Quantity=1 LimitPrice=0 StopPrice=15028.75 SignalName='SLL' FromEntrySignal='Xiphos Long'
                  8/23/2023 2:55:01 AM Strategy 'Sparta Algo/284766077': Entered internal SubmitOrderManaged() method at 8/23/2023 2:55:01 AM: BarsInProgress=1 Action=Sell OrderType=Limit Quantity=1 LimitPrice=15039.75 StopPrice=0 SignalName='PTL' FromEntrySignal='Xiphos Long'
                  condition3
                  Current Trade Count 1 8/23/2023 2:55:00 AM
                  ===============================
                  Entering Xiphos Long 34B:8/23/2023 2:55:00 AM
                  8/23/2023 2:56:51 AM Strategy '284766077/Sparta Algo: Cancelled pending exit order, since associated position is closed, orderId='ea8efd3a21084c1f986020f3286ee499' account='Playback101' name='PTL' orderState=Working instrument='NQ 09-23' orderAction=Sell orderType='Limit' limitPrice=15039.75 stopPrice=0 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=330747 time='2023-08-23 02:55:01' gtd='2099-12-01' statementDate='2023-08-23'
                  condition4
                  The last trade profit is -114.18
                  Current PNL Realized >> -114.18 << 8/23/2023 2:56:50 AM
                  Cumulative PNL >> 0 << 8/23/2023 2:56:50 AM
                  Daily PNL >> -114.18 << 8/23/2023 2:56:50 AM
                  The last trade was Long
                  The last trade's profit in currency is -114.18
                  LOOSER​

                  Comment


                    #24
                    Hello tkaboris,

                    That would not be something I can answer, you need to run it in the use case where it will be used and test it. You can additionally add prints into your logic to make sure the logic is working as you had expected it to.

                    Comment


                      #25
                      ok i understand.

                      I still want to understand if i need to keep code for cancelling order then. Conditions 5,6 and 7 never get reached for cancellation.

                      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)
                                  {
                                      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;
                      
                                          // Submit exit orders for partial fills
                                          if (execution.Order.OrderState == OrderState.PartFilled)
                                          {
                                              Print("condition1");
                                              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");
                                          }
                                          // Update our exit order quantities once orderstate turns to filled and we have seen execution quantities match order quantities
                                          else if (execution.Order.OrderState == OrderState.Filled && sumFilled == execution.Order.Filled)
                                          {
                                              // Stop-Loss order for OrderState.Filled
                                              Print("condition2");
                                              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");
                                          }
                      
                                          // Resets the entryOrder object and the sumFilled counter to null / 0 after the order has been filled
                                          if (execution.Order.OrderState != OrderState.PartFilled && sumFilled == execution.Order.Filled)
                                          {
                                              Print("condition3");
                                              entryOrder = null;
                                              sumFilled = 0;
                                          }
                                      }
                                  }
                      
                                  // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
                                  if ((stopOrder != null && stopOrder == execution.Order) || (targetOrder != null && targetOrder == execution.Order))
                                  {
                                      if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                                      {
                                          Print("condition4");
                                          stopOrder = null;
                                          targetOrder = null;
                                      }
                                  }
                      // Code to cancel orders
                                #region Xiphos Long
                                if (execution.Name == "Xiphos Long")
                                {
                      
                               Print("condition5");
                                    if (stopOrder == null && targetOrder == null)
                                    {
                                        Print("condition6");
                                        if(Position.MarketPosition == MarketPosition.Long && (Position.AveragePrice - (TickSize * StopLossTicks)) <= bid){
                                            stopOrder = ExitLongStopMarket(1, true, Position.Quantity, Position.AveragePrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");
                                        }
                                        if(Position.MarketPosition == MarketPosition.Long && (Position.AveragePrice + (TickSize * ProfitTargetTicks)) >= bid){
                                            targetOrder = ExitLongLimit(1, true, Position.Quantity, Position.AveragePrice + (TickSize * ProfitTargetTicks), "PTL", "Xiphos Long");
                                        }
                      
                                    }
                      
                                    if ((stopOrder != null && stopOrder == execution.Order))
                                      {
                                          Print("condition7");
                                          if (execution.Order.OrderState == OrderState.Filled)
                                          {
                                              CancelOrder(targetOrder);
                                          }
                                      }
                                   if ((targetOrder != null && targetOrder == execution.Order))
                                       {
                                           if (execution.Order.OrderState == OrderState.Filled)
                                           {
                                               CancelOrder(stopOrder);
                                           }    
                                       }
                      
                                }
                                if (execution.Name == "Xiphos Long" && SetTrail)
                                    {
                                     ExitLongStopMarket(1, true, Position.Quantity, Position.AveragePrice - (TickSize * StopLossTicks), "SLL", "Xiphos Long");
                                    }
                                ​

                      Comment


                        #26
                        Hello tkaboris,

                        That would also not be something I can answer, you would need to keep the code that is relevant to your goal. If you want to know if that's needed you need to debug your script and see if that logic is used in any situations. I can only suggest how to approach specific tasks or link samples that relate to the question like using order objects. How your code ends up looking will be completely up to how you designed it.


                        Comment


                          #27
                          in post 23, in the output there is a cancelled order output. is this a valid output?

                          Comment


                            #28
                            Hello tkaboris,

                            If you read the reason for the cancellation that explains why it happened. That is a normal message, to know why that happened you need to debug your logic.

                            Cancelled pending exit order, since associated position is closed,

                            Comment


                              #29
                              Can you provide me with ideas of how to debug why i am getting that order that needed to be cancelled?

                              Comment


                                #30
                                Upon debugging it shows that strategy cancels stop order but not the targerorder and cancelled order is associated with targetOrder

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by NullPointStrategies, 03-13-2026, 05:17 AM
                                0 responses
                                87 views
                                0 likes
                                Last Post NullPointStrategies  
                                Started by argusthome, 03-08-2026, 10:06 AM
                                0 responses
                                151 views
                                0 likes
                                Last Post argusthome  
                                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                                0 responses
                                80 views
                                0 likes
                                Last Post NabilKhattabi  
                                Started by Deep42, 03-06-2026, 12:28 AM
                                0 responses
                                53 views
                                0 likes
                                Last Post Deep42
                                by Deep42
                                 
                                Started by TheRealMorford, 03-05-2026, 06:15 PM
                                0 responses
                                62 views
                                0 likes
                                Last Post TheRealMorford  
                                Working...
                                X