Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Cancel Order Logic

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

    Cancel Order Logic

    Forgive me on this one, I have perused the help on this but it's a bit vague when it comes to precise examples of syntax. I do get the impression I'm missing a declaration of some sort.

    Objective.
    Limit orders are submitted when conditional statements are met and said limit order is attached to an indicator which moves the limit order placement along with it. Once price hits that indicator the limit order is filled. The limit order is deliberately being kept alive until this occurs.

    As of 2 PM Chicago time, if any unfilled limit orders are still outstanding, they need to be cancelled. So:


    // Kill Open Limit orders if exist at 2.00 PM Chicago time

    if
    (Times[0][0].TimeOfDay = End_Time.TimeOfDay)
    // User Interface Time Value set to 2PM

    {

    CancelOrder(Order "Long");
    CancelOrder(Order "Short");


    }

    The limit order names are simply either Long or Short. I know above is incorrect. Not understanding the help guide explanation.

    #2
    Hello johnMoss,

    Thank you for your post.

    The CancelOrder() method takes an order object in its argument. This is not the same as the string for the order name. For more details regarding order objects:There are also details about the order class on the "Advanced Order Handling" page here:
    You could consider having a private Order variable, and then check for the order.Name in OnOrderUpdate() to assign the Order object to the variable as demonstrated on the examples from those pages. Then, when you call CancelOrder() you could use the order variable, such as CancelOrder(myLimitEntry;

    For a full strategy sample that uses order objects and calls CancelOrder() please see the following:
    Please let us know if we may be of further assistance.

    Comment


      #3
      Thank You... The sample script is bit confusing, i.e. I see what it is asking for but don't quite see how to ensure its properly applied. The sample has several applications, I only need one, which is the cancel open limit orders (if any) logic. So far I have the following: (Condensed)

      Public

      private Order entryOrder = null;


      else if (State == State.Realtime)
      {
      if (entryOrder != null)
      entryOrder = GetRealtimeOrder(entryOrder);
      }​



      protected override void OnBarUpdate()

      // Limit Entry Sample

      if (
      ((Long == true)
      && (Position.MarketPosition != MarketPosition.Long)
      && (Position.MarketPosition != MarketPosition.Short)
      && (Times[0][0].TimeOfDay >= Start_Time.TimeOfDay)
      && (Times[0][0].TimeOfDay <= End_Time.TimeOfDay)
      && (Bar1Long == true)
      && (Bar2Long == true)))

      {
      EnterLongLimit(0, true, Contracts, EMA2[0], "Long");
      EvalHold = true;

      }​


      If a limit order is fired at say 1:42 PM and remains unfilled by 2:00 PM I need the order to cancel...

      if

      (Times[0][0].TimeOfDay == End_Time.TimeOfDay)
      {

      CancelOrder(entryOrder);

      }

      So I assume I'm only missing one other method to tie this "entryOrder" to the example Long limit order above? Any other declarations?​ Or is the above entryOrder automatically applied to any orders which may exist in realtime?

      Thanx

      Comment


        #4
        Hello johnMoss,

        Thank you for your reply.

        I suggest taking the example from the Order page into account:
        Code:
        private Order entryOrder = null;
        
        protected override void OnBarUpdate()
        {
          if (entryOrder == null && Close[0] > Open[0])
              EnterLong("myEntryOrder");
        }
        
        protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
        {
          // 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 guaranteed to be complete if it is referenced immediately after submitting
          if (order.Name == "myEntryOrder")
              entryOrder = order;
        
          if (entryOrder != null && entryOrder == order)
          {
              Print(order.ToString());
              if (order.OrderState == OrderState.Filled)
                  entryOrder = null;
          }
        }​
        With this in mind, you could add the OnOrderUpdate() method to your strategy to assign the order when it is updated and set the entryOrder object back to null when that order is filled or canceled. Here is an example of what OnOrderUpdate() would look like based on your example using "Long" for the order name. If you want to do this for "Long" and "Short" I suggest using two different Order variables, such as longEntryOrder and shortEntryOrder instead of just entryOrder:
        Code:
        protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
        {
          // 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 guaranteed to be complete if it is referenced immediately after submitting
        
        // this will check if the order name is "Long" in OnOrderUpdate() and if so, it assigns the entire Order object to the entryOrder variable
          if (order.Name == "Long")
              entryOrder = order;
        
          if (entryOrder != null && entryOrder == order)
          {
              Print(order.ToString());
        // check if the order is filled or cancelled - if so, set the object to null so it is ready and waiting to be used again the next time the order with name "Long" is submitted
              if (order.OrderState == OrderState.Filled || order.OrderState == OrderState.Cancelled)
                  entryOrder = null;
          }
        }​
        More details about OnOrderUpdate(), including possible order states that would trigger this to be called, may be found here:


        Hopefully this helps to illustrate how to assign the Order object and maintain a reference to that Order object in the variable you create. The variable holding the Order object can then be used for CancelOrder() to reference the desired Order object to be canceled.

        Please let us know if we may be of further assistance.

        Comment


          #5
          Hello - I am also having trouble with the OnOrderUpdate() and canceling open orders. I am submitting GTC stop orders when conditions are met and I want to add a condition to cancel working orders if another condition is met.


          I am not successfully applying the CancelOrder() method.

          I have been troubleshooting by adding print statements to verify what blocks of code are executing to no avail and I am at the limit of my knowledge to fix it.


          I would be happy to pay someone to help me with this.

          I have a multiple contract strategy so I reference BarsInProgress.


          Here is the part of the strategy I am having trouble with and would greatly appreciate help:

          if(Positions[BarsInProgress].MarketPosition == MarketPosition.Flat) //If we're flat...
          {
          if(contract_oversize_limit == false){return;} //If it's too hot, skip it
          if (channel_trend_filter_long && EMA_trend_filter_long) //Else, if the trend filters are both pointing Up
          {
          if(entry_trigger_long) //If the price broke out...
          {
          // EnterLong(BarsInProgress, contracts, "Long Entry"); //ENTER A LONG POSITION THAT GETS FILLED AT THE OPEN THE NEXT DAY
          EnterLongStopMarket(BarsInProgress, true, contracts, High[MRO(() => CrossAbove(High, DonchianChannel(TradePeriod).Upper[1], 1), 1, TradePeriod)], "Long Entry");
          // if(BarsInProgress == 0){Print(Time[0].Date + " - Long Order Stop Entry Set At " + High[MRO(() => CrossAbove(High, DonchianChannel(TradePeriod).Upper[1], 1), 1, TradePeriod)] + " " + CrossAbove(High, DonchianChannel(TradePeriod).Upper[1], 1) + CrossAbove(Open, DonchianChannel(TradePeriod).Upper[1], 1));}
          }
          }


          if (channel_trend_filter_short && EMA_trend_filter_short && Shorts == 1)
          {
          if(entry_trigger_short)
          {
          // EnterShort(BarsInProgress, contracts, "Short Entry"); //ENTER SHORT POSITION THAT GETS FILLED AT THE OPEN THE NEXT DAY
          EnterShortStopMarket(BarsInProgress, true, contracts, Low[MRO(() => CrossBelow(Low, DonchianChannel(TradePeriod).Lower[1], 1), 1, TradePeriod)], "Short Entry");
          }
          }
          foreach (var order in Orders)
          {
          Print("Order: " + order.Name + ", State: " + order.OrderState);
          }

          Print("Before checking for open orders...");
          if(Orders.Cast<Order>().Any(order => order.OrderState == OrderState.Working)) //Cancel open orders if the trends have reversed and the orders haven't filled
          {
          Print("Inside the block...");
          // if(Low[0] < DonchianChannel(TradePeriod).Lower[0] + stop_points) // if price falls below lower atr line, cancel "long entry" order
          // {
          // CancelOrder(order.Name == "Long Entry");
          // }

          if(High[0] > DonchianChannel(TradePeriod).Upper[0] - stop_points) // if price moves above upper atr line, cancel "short entry" order
          {
          Print("Found open orders. Cancelling...");
          foreach(var order in Orders)
          {
          if(order.Instrument == Instrument)
          {
          int barsInProgressForOrder = GetBarsInProgress(order.Instrument);
          if(order.Name == "Short Entry" && order.OrderState == OrderState.Working)
          {
          Print("Cancelling order: " + order.Name + ", State: " + order.OrderState);
          CancelOrder(order);
          }
          }

          }
          }

          }
          Print("After checking for open orders...");
          foreach (var order in Orders)
          {
          Print("Order: " + order.Name + ", State: " + order.OrderState + ", Type: " + order.OrderType + ", Quantity: " + order.Quantity);
          }
          }
          #endregion //ENTER POSITIONS


          region
          if(Positions[BarsInProgress].MarketPosition == MarketPosition.Long) //IF WE DO HAVE A LONG POSITION
          {
          ExitLongStopMarket(BarsInProgress, true, Position.Quantity, (DonchianChannel(TradePeriod).Upper[0] - stop_points), "Long Stop loss", "Long Entry"); //CREATE & MAINTAIN A STOP MARKET ORDER AT THE CORRECT LEVEL FOR CORE POSITION

          if(Close[0] <= DonchianChannel(TradePeriod).Upper[1] - stop_points_yesterday || Low[0] <= DonchianChannel(TradePeriod).Upper[1] - stop_points_yesterday || High[0] <= DonchianChannel(TradePeriod).Upper[1] - stop_points_yesterday || Open[0] <= DonchianChannel(TradePeriod).Upper[1] - stop_points_yesterday)
          ExitLong(BarsInProgress, Position.Quantity, "Long UberWhispaw exit", "Long Entry"); //EXIT POSITION
          }

          if(Positions[BarsInProgress].MarketPosition == MarketPosition.Short) //WE DO HAVE A SHORT POSITION
          {
          ExitShortStopMarket(BarsInProgress, true, Position.Quantity, (DonchianChannel(TradePeriod).Lower[0] + stop_points), "Short Stop loss", "Short Entry"); //CREATE & MAINTAIN A STOP MARKET ORDER AT THE CORRECT LEVEL

          if(Close[0] >= DonchianChannel(TradePeriod).Lower[1] + stop_points_yesterday || Low[0] >= DonchianChannel(TradePeriod).Lower[1] + stop_points_yesterday || High[0] >= DonchianChannel(TradePeriod).Lower[1] + stop_points_yesterday || Open[0] >= DonchianChannel(TradePeriod).Lower[1] + stop_points_yesterday)
          ExitShort(BarsInProgress, Position.Quantity, "Short UberWhipsaw exit", "Short Entry"); //EXIT POSITION
          }
          #endregion //MANAGE POSITIONS
          if(BarsInProgress == 0)
          {
          // Print(Time[0].Date + " - Long Order Stop Entry Set At " + High[MRO(() => CrossAbove(High, DonchianChannel(TradePeriod).Upper[1], 1), 1, TradePeriod)]);
          }
          }

          Comment


            #6
            Hello ashlantz,

            May I confirm you are assigning the order to a variable in OnOrderUpdate()?


            You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services.

            You can search our extensive library of NinjaScript consultants through the link below. Simply enter a consultant name or search by using our filter categories. Once you have identified your consultants of choice, please visit each consultant's site for more information or contact them directly to learn more!
            Programming Services - https://ninjatraderecosystem.com/sea...mming-services
            Educators - https://ninjatraderecosystem.com/sea...ures=education

            You can locate the contact information for the consultants on their direct websites for any additional questions you may have. Since these consultants are third party services for NinjaTrader all pricing and support information will need to be obtained through the consultant.

            This NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The companies and services listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.​
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hi Ash,
              Yeah this one was new territory, level up... If you get stuck send me an email [email protected]....

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by NullPointStrategies, Yesterday, 05:17 AM
              0 responses
              54 views
              0 likes
              Last Post NullPointStrategies  
              Started by argusthome, 03-08-2026, 10:06 AM
              0 responses
              130 views
              0 likes
              Last Post argusthome  
              Started by NabilKhattabi, 03-06-2026, 11:18 AM
              0 responses
              72 views
              0 likes
              Last Post NabilKhattabi  
              Started by Deep42, 03-06-2026, 12:28 AM
              0 responses
              44 views
              0 likes
              Last Post Deep42
              by Deep42
               
              Started by TheRealMorford, 03-05-2026, 06:15 PM
              0 responses
              49 views
              0 likes
              Last Post TheRealMorford  
              Working...
              X