Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Cancel Order on ATM Strategy

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

    #31
    No it doesn't show up in the output window,
    Print("91 Cancelled Order");

    ...but my other print statements do though. Leading me to believe it's not being called. I'll try and find another statement to use instead.

    Comment


      #32
      So instead of:
      PHP Code:
      if(CurrentBar==entrybar + 1 
      
      am trying this instead,
      PHP Code:
      if(CurrentBar > barNumberOfOrder + 2 
      
      Have modified the necessary private ints also. Here is the new strat with complete code after changes:
      PHP Code:
      public class TFSV2BATM : Strategy
          {
              #region Variables
              
              private string    atmStrategyId        = string.Empty;
              private string    orderId                = string.Empty;
              
              private int barNumberOfOrder = 0;
              
              private int prevBarsMinusTicks = 1; // Default setting for PrevBarsPlusTicks
              
              #endregion
      
              /// <summary>
              /// This method is used to configure the strategy and is called once before any strategy method is called.
              /// </summary>
              protected override void Initialize()
              {
                  CalculateOnBarClose = false;
              }
              
              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
                  
              {
                  // Make sure this strategy does not execute against historical data
                  if (Historical)
                      return;
      
      
                  // Submits an entry limit order to initiate an ATM Strategy if both order id and strategy id are in a reset state
                  
                  if (Position.MarketPosition == MarketPosition.Flat 
                      && orderId.Length == 0 
                      && atmStrategyId.Length == 0 
                      && FirstTickOfBar
                      && Close [1] <= Open [1]
                      && Low[1] - PrevBarsMinusTicks * TickSize < GetCurrentAsk())
                  
                  
                  {
                      
                      atmStrategyId = GetAtmStrategyUniqueId();
                      orderId = GetAtmStrategyUniqueId();
                      
                      AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Stop, 0, Low[1] - PrevBarsMinusTicks * TickSize , TimeInForce.Day, orderId, "TF_short_500T", atmStrategyId);    
                      barNumberOfOrder = CurrentBar;
                  }
      
      
                  // Check for a pending entry order
                  if (orderId.Length > 0)
                  {
                      string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                      
                      if(CurrentBar > barNumberOfOrder + 2 && (status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending"))
                      {
                          Print("91   Cancelled Order");
                          AtmStrategyCancelEntryOrder(orderId);
                          atmStrategyId = string.Empty;
                          orderId = string.Empty;
                      }
                      
                      // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
                       else if (status.GetLength(0) > 0)
                      {
                          // Print out some information about the order to the output window
                          Print("The entry order average fill price is: " + status[0]);
                          Print("The entry order filled amount is: " + status[1]);
                          Print("The entry order order state is: " + status[2]);
      
                          // If the order state is terminal, reset the order id value
                          if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
                              orderId = string.Empty;
                      }
                  } // If the strategy has terminated reset the strategy id
                  //else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                  //    atmStrategyId = string.Empty;
                  
                  else 
                  if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Flat)
                      {
      Print("302   reset the strategy id");
                      atmStrategyId = string.Empty;
                      orderId = string.Empty;
                      }
      
      
                  if (atmStrategyId.Length > 0)
                  {
                      
      
                      // Print some information about the strategy to the output window
                      Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
                      Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
                      Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
                      Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId));
                      Print("The current ATM Strategy Realized PnL is: " + GetAtmStrategyRealizedProfitLoss(atmStrategyId));
                  }
              }
      
              #region Properties
              
              [Description("")]
              [GridCategory("Parameters")]
              public int PrevBarsMinusTicks
              {
                  get { return prevBarsMinusTicks; }
                  set { prevBarsMinusTicks = Math.Max(1, value); }
              }
              
              
              #endregion
          }
      } 
      
      Will leave this running on live sim and see if it cancels pending entry order.

      Comment


        #33
        A few notes here that may help:
        • entrybar captures the current bar at the time of order submission, but not necessarily when the order is filled. Might need to work with the fill state for most accuracy.
        • You don't need to delcare it as int entrybar = CurrentBar. entrybar = CurrentBar is sufficient.
        • You're missing a status length check for your cancel actions, to make sure that the status string is not an empty array.
        if (status.GetLength(0) > 0)
        Ryan M.NinjaTrader Customer Service

        Comment


          #34
          Originally posted by NinjaTrader_RyanM View Post
          A few notes here that may help:
          • entrybar captures the current bar at the time of order submission, but not necessarily when the order is filled. Might need to work with the fill state for most accuracy.
          • You don't need to delcare it as int entrybar = CurrentBar. entrybar = CurrentBar is sufficient.
          • You're missing a status length check for your cancel actions, to make sure that the status string is not an empty array.

          if (status.GetLength(0) > 0)
          Thanks.

          I sorted points 1 and 2 by changing the int to private int barNumberOfOrder = 0;
          Got rid of the entry bar reference altogether.

          and declaring
          AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Stop, 0, High[1] + PrevBarsPlusTicks * TickSize, TimeInForce.Day, orderId, "TF_long_500T", atmStrategyId);
          barNumberOfOrder = CurrentBar;
          for the entry.

          Will sort out if (status.GetLength(0) > 0) now and test again.

          Comment


            #35
            Have sorted out those 3 points but it's still not canceling orders. Here is the latest strat code.

            PHP Code:
            public class TFS3BRATM : Strategy
                {
                    #region Variables
                    
                    private string    atmStrategyId        = string.Empty;
                    private string    orderId                = string.Empty;
                    
                    private int prevBarsMinusTicks = 1; // Default setting for PrevBarsPlusTicks
                    
                    private int barNumberOfOrder = 0;
                    
                    #endregion
            
                    /// <summary>
                    /// This method is used to configure the strategy and is called once before any strategy method is called.
                    /// </summary>
                    protected override void Initialize()
                    {
                        CalculateOnBarClose = false;
                    }
                    
                    /// <summary>
                    /// Called on each bar update event (incoming tick)
                    /// </summary>
                    protected override void OnBarUpdate()
                    {
                        // Make sure this strategy does not execute against historical data
                        if (Historical)
                            return;
            
            
                        // Submits an entry limit order to initiate an ATM Strategy if both order id and strategy id are in a reset state
                        if (Position.MarketPosition == MarketPosition.Flat 
                            && orderId.Length == 0 
                            && atmStrategyId.Length == 0 
                            && FirstTickOfBar
                            && Close [1] >= Open [1]
                            && Low   [1] - PrevBarsMinusTicks * TickSize < GetCurrentAsk())
                        
                        
                        {
                            atmStrategyId = GetAtmStrategyUniqueId();
                            orderId = GetAtmStrategyUniqueId();
                            AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Stop, 0, Low[1] - prevBarsMinusTicks * TickSize, TimeInForce.Day, orderId, "TF_short_500T", atmStrategyId);
                            barNumberOfOrder = CurrentBar; 
            
                        }
            
            
                        // Check for a pending entry order
                        if (orderId.Length > 0)
                        {
                            string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                            // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
            
                            if (status.GetLength(0) > 0)
                            
                            {
                                if(CurrentBar > barNumberOfOrder + 1 
                                && (status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending"))
                                AtmStrategyCancelEntryOrder(orderId);
                                Print("91   Cancelled Order");
                                atmStrategyId = string.Empty;
                                orderId = string.Empty;
                                                    
                            }
                            
                            // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
                             else if (status.GetLength(0) > 0)
                            {
                                // Print out some information about the order to the output window
                                Print("The entry order average fill price is: " + status[0]);
                                Print("The entry order filled amount is: " + status[1]);
                                Print("The entry order order state is: " + status[2]);
            
                                // If the order state is terminal, reset the order id value
                                if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
                                    orderId = string.Empty;
                            }
                        } 
                        
                        else 
                        if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == MarketPosition.Flat)
                            {
                            Print("302   reset the strategy id");
                            atmStrategyId = string.Empty;
                            orderId = string.Empty;
                            }
            
            
                        if (atmStrategyId.Length > 0)
                        {
                            // Print some information about the strategy to the output window
                            Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
                            Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
                            Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
                            Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId));
                            Print("The current ATM Strategy Realized PnL is: " + GetAtmStrategyRealizedProfitLoss(atmStrategyId));
                        }
                    } 
            
            I think it's to do with,

            if(CurrentBar > barNumberOfOrder + 1

            .........am going to try and find a different method to signify 1 bar printed since entry.

            Before that though, am going to test and see if I can just make the strat cancel the order straight away. Just to see if I can make it cancel pending orders with something like:

            PHP Code:
            // Check for a pending entry order
                        if (orderId.Length > 0)
                        {
                            string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                            // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
            
                            if (status.GetLength(0) > 0)
                            
                            {
                               if((status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending"))
                                AtmStrategyCancelEntryOrder(orderId);
                                Print("91   Cancelled Order");
                                atmStrategyId = string.Empty;
                                orderId = string.Empty;
                                                    
                            } 
            

            Comment


              #36
              I can't even make it cancel with a pending order in any state. Here is what I tried to do so that I could see if I could get the strat to cancel a pending order after a new order entry on the next tick/incoming bar.

              PHP Code:
              // Check for a pending entry order
                          if (orderId.Length > 0)
                          {
                              string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                              if (status.GetLength(0) > 0)
                          {                
                          if
                           ((status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending"))
                                  AtmStrategyCancelEntryOrder(orderId);
                                  Print("91   Cancelled Order");
                                  atmStrategyId = string.Empty;
                                  orderId = string.Empty;
                              } 
              
              I was hoping the above would terminate any orders with a status of "Accepted", "Working" or "Pending".

              Should I change
              (status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending")

              to

              (status[0] == "Accepted" || status[0] == "Working" || status[0] == "Pending")

              Will try that and see if it cancels on bar update.

              Comment


                #37
                MrTicks, please use as many Print() statements as possible to help you determine exactly what is going on. For example, to see everything that the ATM entry order method generates, you can do this:
                Code:
                [COLOR=#000000][COLOR=#0000BB][/COLOR][/COLOR]string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                Print("entry order info:\t" + status.ToString());
                You can print the value for almost any object you will encounter with NinjaScript, and that helps debugging tremendously.

                You can also set TraceOrders = true to see everything going on "under the hood" related to any and every order.
                AustinNinjaTrader Customer Service

                Comment


                  #38
                  Thanks for the suggestion. Will do that and check the output window.

                  Comment


                    #39
                    Originally posted by NinjaTrader_Austin View Post
                    MrTicks, please use as many Print() statements as possible to help you determine exactly what is going on. For example, to see everything that the ATM entry order method generates, you can do this:
                    Code:
                    string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                    Print("entry order info:\t" + status.ToString());
                    You can print the value for almost any object you will encounter with NinjaScript, and that helps debugging tremendously.

                    You can also set TraceOrders = true to see everything going on "under the hood" related to any and every order.
                    I set trace orders to true and added more print statements. From this it showed me that it is printing the cancel order to the output window but not canceling it.

                    This is what is shows:

                    **NT** Submitting order with strategy 'TFL3BRATM/8ea3c7a0f36c431eadd3013c718ec39a'
                    TFL3BRATM Cancelled Order

                    but doesn't cancel it.

                    When I rem out // CurrentBar > barNumberOfOrder + 1 the orders cancel straight away so I know that I'm on the right track, just need a different trigger in front of

                    && (status[1] == "Accepted" || status[1] == "Working" || status[1] == "Pending"))

                    So when I have the code below, it cancels straight away.
                    PHP Code:
                    // Check for a pending entry order
                                if (orderId.Length > 0)
                                {
                                    string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                                    Print("entry order info:\t" + status.ToString());
                                    // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
                    
                                    if (status.GetLength(0) > 0)
                                    
                                    {
                                        if(
                                            //CurrentBar > barNumberOfOrder + 1 
                                        && (status[1] == "Accepted" || status[1] == "Working" || status[1] == "Pending"))
                                        AtmStrategyCancelEntryOrder(orderId);
                                        Print("TFS3BRATM   Cancelled Order");
                                        atmStrategyId = string.Empty;
                                        orderId = string.Empty;
                                                            
                                    } 
                    

                    Comment


                      #40
                      MrTicks, good to hear you've got the order canceling now. It does sound like you might have to modify your if conditions a bit to get it exactly where you want it though.

                      Same advice still applies: print everything that has anything to do with your strategy and why it may not be working how you expect it to.
                      AustinNinjaTrader Customer Service

                      Comment


                        #41
                        Will do. Will post the code when it is working so others can have a working sample ATM strategy that contains a call to cancel the ATM order after certain conditions.

                        Comment


                          #42
                          MrTicks, that would be fantastic. You could even post it in the file-sharing section so more people see it.
                          AustinNinjaTrader Customer Service

                          Comment


                            #43
                            Used print statements and saw that the cancel call was not being met,

                            PHP Code:
                            if (barNumberOfOrder == 2 && (status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending"))
                                            
                                            {
                                            Print("108   Cancel the TFLV2Bjthom order ");    
                                            AtmStrategyCancelEntryOrder(orderId);
                                                
                                            } 
                            
                            So I created this AtmStrategyCancelEntryOrder(orderId); instead,

                            PHP Code:
                            if (Close [0] - 5 * TickSize < High[1] &&(status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending"))
                                            
                                            {
                                            Print("108 ATM cancel TFL3BR order");    
                                            AtmStrategyCancelEntryOrder(orderId);
                                            } 
                            
                            Now the orders are cancelling after Close [0] - 5 * TickSize < High[1] which is when current price dips 5 ticks below the high of the last bar.

                            Not ideal but I can work on it.

                            If I could just some how make the trigger be "n bars have passed and order still open" instead it would be ideal!!!

                            Oh yeah, status has to be 2 not zero as I mentioned in post#36 above.
                            (status[2] == "Accepted" || status[2] == "Working" || status[2] == "Pending")

                            Found that here,


                            I'll get there eventually.

                            Comment


                              #44
                              To get n bars has passed, you would need to keep track of the bar number of when you submitted your entry order. You can check the bar number by using CurrentBar. That means saving the current bar on entry, then comparing it against the CurrentBar on the most recent bar. When the difference between the two is n then you can cancel. You would need to use the status[] to determine what state the order was in.
                              Josh P.NinjaTrader Customer Service

                              Comment


                                #45
                                Sample ATM strategy with cancel pending order after &quot;n&quot; bars passed with no fill.

                                Originally posted by NinjaTrader_Austin View Post
                                MrTicks, that would be fantastic. You could even post it in the file-sharing section so more people see it.
                                Finally got that strategy working! I used the sample code from this post http://www.ninjatrader.com/support/f...ad.php?t=31224 as a template.

                                I would like to thank the following users for helping me with sample code jthom, daven, Trade1953 and monpere.

                                I'll post it up in the file sharing section also. This is a working strategy with an ATM template attached which also cancels after x bars have passed if the pending order has not been filled.
                                Attached Files

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by argusthome, 03-08-2026, 10:06 AM
                                0 responses
                                110 views
                                0 likes
                                Last Post argusthome  
                                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                                0 responses
                                59 views
                                0 likes
                                Last Post NabilKhattabi  
                                Started by Deep42, 03-06-2026, 12:28 AM
                                0 responses
                                37 views
                                0 likes
                                Last Post Deep42
                                by Deep42
                                 
                                Started by TheRealMorford, 03-05-2026, 06:15 PM
                                0 responses
                                41 views
                                0 likes
                                Last Post TheRealMorford  
                                Started by Mindset, 02-28-2026, 06:16 AM
                                0 responses
                                78 views
                                0 likes
                                Last Post Mindset
                                by Mindset
                                 
                                Working...
                                X