Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Cancel EnterLongStopMarket order if no trigger in next bar

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

    Cancel EnterLongStopMarket order if no trigger in next bar

    I want to EnterLongStopMarket 1 tick above previous bar's high, but cancel the order if it doesn't trigger within the next bar.

    How can this be done?

    #2
    Hello UltraNIX,

    You can use High[1] if CurrentBar is greater than once to get the price of the previous bar's high, and add multiples of TickSize to the value.

    if (CurrentBar > 1)
    EnterLongStopMarket(High[1] + 1 * TickSize);





    If you do not use isLiveUntilCancelled as true, the order will automatically expire when the submission bar closes. When the overload signature with this parameters is not used this property will default to false.

    Alternatively, if you do use isLiveUntilCancelled and set this to true, you can cancel an order by assigning the order object to a variable in OnOrderUpdate() and then when not null and in OrderState.Working or OrderState.Accepted, call CancelOrder() on the order variable containing the order.

    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Ok,

      Straight from help:


      Pasted this code into a strategy:
      Code:
      #region Using declarations
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.ComponentModel.DataAnnotations;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows;
      using System.Windows.Input;
      using System.Windows.Media;
      using System.Xml.Serialization;
      using NinjaTrader.Cbi;
      using NinjaTrader.Gui;
      using NinjaTrader.Gui.Chart;
      using NinjaTrader.Gui.SuperDom;
      using NinjaTrader.Gui.Tools;
      using NinjaTrader.Data;
      using NinjaTrader.NinjaScript;
      using NinjaTrader.Core.FloatingPoint;
      using NinjaTrader.NinjaScript.Indicators;
      using NinjaTrader.NinjaScript.DrawingTools;
      #endregion
      
      //This namespace holds Strategies in this folder and is required. Do not change it.
      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class AI_Cancel_201012 : Strategy
      {
      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Strategy here.";
      Name = "AI_Cancel_201012";
      Calculate = Calculate.OnBarClose;
      EntriesPerDirection = 1;
      EntryHandling = EntryHandling.AllEntries;
      IsExitOnSessionCloseStrategy = true;
      ExitOnSessionCloseSeconds = 30;
      IsFillLimitOnTouch = false;
      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
      OrderFillResolution = OrderFillResolution.Standard;
      Slippage = 0;
      StartBehavior = StartBehavior.ImmediatelySubmitSynchronizeAccount;
      TimeInForce = TimeInForce.Gtc;
      TraceOrders = false;
      RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
      StopTargetHandling = StopTargetHandling.PerEntryExecution;
      BarsRequiredToTrade = 20;
      // Disable this property for performance gains in Strategy Analyzer optimizations
      // See the Help Guide for additional information
      IsInstantiatedOnEachOptimizationIteration = true;
      }
      else if (State == State.Configure)
      {
      }
      else if (State == State.DataLoaded)
      {
      }
      }
      
      private Order myEntryOrder = null;
      private int barNumberOfOrder = 0;
      
      protected override void OnBarUpdate()
      {
      
      if (CurrentBar < BarsRequiredToTrade) // Stop running the script, if current bar is less than bars required to trade
      return;
      
      // Submit an entry order at the low of a bar
      if (myEntryOrder == null)
      {
      // use 'live until canceled' limit order to prevent default managed order handling which would expire at end of bar
      EnterLongStopMarket(1, High[0] + TickSize, "Long Entry");
      barNumberOfOrder = CurrentBar;
      }
      
      // If more than 5 bars has elapsed, cancel the entry order
      if (CurrentBar > barNumberOfOrder + 5)
      CancelOrder(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 gauranteed to be complete if it is referenced immediately after submitting
      if (order.Name == "Long Entry")
      myEntryOrder = order;
      
      // Evaluates for all updates to myEntryOrder.
      if (myEntryOrder != null && myEntryOrder == order)
      {
      // Check if myEntryOrder is cancelled.
      if (myEntryOrder.OrderState == OrderState.Cancelled)
      {
      // Reset myEntryOrder back to null
      myEntryOrder = null;
      }
      }
      }
      }
      }
      2 Adjustments:

      1) Added

      if (CurrentBar < BarsRequiredToTrade) // Stop running the script, if current bar is less than bars required to trade
      return;

      2) Changed EnterLongLimit order to EnterLongStopMarket.

      What is wrong? Only 1 trade is made. I tested from 6th of May, 2019 till 30th of September, 2020, so there definately should have been much more trades. As it is NinjaTrader help section code, maybe you could inspect it see the flaw.

      Comment


        #4
        Hello UltraNIX,

        To confirm, you are no longer getting the error you were originally getting and this is a new inquiry about the orders, is this correct?

        The entry is only submitted if the myEntryOrder is null correct?
        It is null when starting up, and set to null only if the entry is cancelled.
        This is example is only designed to show an entry order being cancelled.
        Are you expecting this to have other logic that places orders that are not cancelled?

        With this new inquiry about order fills, in order to better understand how the code is working, it will be necessary to use Print and enable TraceOrders to see how the conditions are evaluating and if orders are being submitted, ignored, or cancelled.

        Below is a link to a forum post that demonstrates using prints to understand behavior.
        https://ninjatrader.com/support/foru...121#post791121

        Enable TraceOrders, print the time of the bar and all values used in the conditions that submit entry orders.
        Let me know if you need any assistance creating a print or enabling TraceOrders.
        Save the output from the output window to a text file and provide this with your next post.
        I'll be happy to assist with analyzing the output.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_ChelseaB View Post
          Hello UltraNIX,

          To confirm, you are no longer getting the error you were originally getting and this is a new inquiry about the orders, is this correct?

          The entry is only submitted if the myEntryOrder is null correct?
          It is null when starting up, and set to null only if the entry is cancelled.
          This is example is only designed to show an entry order being cancelled.
          Are you expecting this to have other logic that places orders that are not cancelled?

          With this new inquiry about order fills, in order to better understand how the code is working, it will be necessary to use Print and enable TraceOrders to see how the conditions are evaluating and if orders are being submitted, ignored, or cancelled.

          Below is a link to a forum post that demonstrates using prints to understand behavior.
          https://ninjatrader.com/support/foru...121#post791121

          Enable TraceOrders, print the time of the bar and all values used in the conditions that submit entry orders.
          Let me know if you need any assistance creating a print or enabling TraceOrders.
          Save the output from the output window to a text file and provide this with your next post.
          I'll be happy to assist with analyzing the output.
          Yes, no errors, because it's different kind of thing. I am using blank template with code adapted from NinjaTrader help section. It compiles, it runs, but it enters only 1 trade throughout 16 month period. And I don't use any complex logic to prevent it from entering trades. As it is shown in the code (which, again, was copied from Help section) - if (myEntryOrder == null), THEN EnterLongStopMarket(1, High[0] + TickSize, "Long Entry").

          Maybe, after filling the order, it's not resetting myEntryOrder back to null, that's the only way I can explain it.

          Comment


            #6
            Hello UltraNIX,

            The example on the CancelOrder() page in the help guide demonstrates how to cancel orders.

            It does not have code to demonstrate filling orders.

            It would not be expected that cancelled orders would be filled.

            Are you wanting an example that shows how to place orders that fill, and not how to cancel orders?
            (I may be confused. From post #1 I was under the impression that you wanted to learn how to cancel an order.)

            Below is a link to an example that has entry orders placed that fill and exit orders that continue working and are not designed to be cancelled.
            https://ninjatrader.com/support/foru...596#post806596
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Yes, I want to cancel order, if it does not get filled within a certain number of bars. Example in NinjaTrader help was with 5 bars, if no fill within those - cancel.

              I was able to increase number of trades from 1 to much more, substituting previous code with this line: if (myEntryOrder.OrderState == OrderState.Cancelled || myEntryOrder.OrderState == OrderState.Filled)

              (Previously it did not include latter part).

              However, I use prints and what not, and still cancel order is not showing up correctly.

              Comment


                #8
                Hello UltraNIX,

                The example in the help guide on CancelOrder() is showing you how to cancel an order.

                The entry order is getting submitted, then cancelled, and is not intended to fill. It is intended to be cancelled to show you how to cancel an order.

                This is showing you how to assign an order to a variable in OnOrderUpdate(), then later supply this variable holding the order to CancelOrder(), which if the order is working or accepted, will cancel that order..

                The order is cancelled after 5 bars.


                So, to be clear, you would not be looking for order fills with this example.

                Instead, you would be looking for order cancellations.

                Do you see order cancellations in the Strategy Performance on the Orders display after enabling the script?

                If you print the order object in OnOrderUpdate(), do you see the orders changing states? Do you see orders being cancelled?

                If orders are being cancelled and not filled, then the example code is working correctly.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  I was able to adapt the code and it cancels orders.

                  However. I started to get this error frequently: An Enter() method to submit an entry order at '2019-05-06 17:31:51' has been ignored. Please search on the term 'Internal Order Handling Rules' in the Help Guide for detailed explanation.

                  What is that and how can I solve that?

                  Comment


                    #10
                    Hello UltraNIX,

                    Is that the full error message appearing from TraceOrders in the NinjaScript Output window?

                    What orders are appearing from TraceOrders before this order?

                    Below is a link to the help guide on the internal order handling rules.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Here, you can see it in attachments.

                      P.s. I've never used TraceOrders and not familiar with it. I only use Print.
                      Click image for larger version

Name:	201012-230403-TRADE.png
Views:	255
Size:	240.9 KB
ID:	1122360

                      Comment


                        #12
                        Hello UltraNIX,

                        Are there any orders submitted before this?

                        Can you save the output (Save As) to a text file to provide the full output?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Yes, what is interesting, it works partially, for example, I added conditions to select whether to trade long/short/both in Strategy Analyzer. All shorts were submitted perfectly. But only 4 long trades. Yet, I could clearly see from the chart that there should have been much more long trades.

                          It appeared working well on 900 tick chart for MES, but when I switched to Weekly chart and ES, it started giving errors.

                          Comment


                            #14
                            Hello UltraNIX,

                            The message you are getting is that an internal order handling rule is being violated (linked in post #10).

                            This means there is a working order when you are trying to place an order, and because of the order type one of the internal handling rules is being violated.

                            With the output I've requested we would be able to see what orders were placed before this, and identify which internal handing rule has been violated.

                            Let us know if you would like to investigate.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Of course I would. Tell me what to do next.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by bortz, 11-06-2023, 08:04 AM
                              47 responses
                              1,611 views
                              0 likes
                              Last Post aligator  
                              Started by jaybedreamin, Today, 05:56 PM
                              0 responses
                              9 views
                              0 likes
                              Last Post jaybedreamin  
                              Started by DJ888, 04-16-2024, 06:09 PM
                              6 responses
                              19 views
                              0 likes
                              Last Post DJ888
                              by DJ888
                               
                              Started by Jon17, Today, 04:33 PM
                              0 responses
                              6 views
                              0 likes
                              Last Post Jon17
                              by Jon17
                               
                              Started by Javierw.ok, Today, 04:12 PM
                              0 responses
                              22 views
                              0 likes
                              Last Post Javierw.ok  
                              Working...
                              X