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 it is not triggered after 5 bars

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

    Cancel EnterLongStopMarket order if it is not triggered after 5 bars

    Hey,

    I want to cancel EnterLongStopMarket order, if it is not triggered after 5 bars.

    Can you help me with a code?

    #2
    Hello UltraNIX,

    To count bars you will need a counter integer variable.


    There are two ways to cancel an order.

    First, with managed approach when placing orders with isLiveUntilCancelled as false, or by not using the overload with this parameter which will default to false, will cause an order to automatically cancel when the submission bar closes unless the order method is called again with the same signal name.
    This means in the condition that submits the order the counter must be less than 5 for the order to be kept alive by re-submission.
    See isLiveUntilCancelled for limit and stop order methods in the help guide.


    The second would be by assigning the order to a variable in OnOrderUpdate(), and then when the counter is greater than 4 to call CancelOrder() and supply the variable holding the order.
    Below is a link to the help guide on CancelOrder().
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      I tried to adapt this code,

      private Order myEntryOrder = null;
      private int barNumberOfOrder = 0;

      protected override void OnBarUpdate()
      {
      // 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
      EnterLongLimit(0, true, 1, Low[0], "Long Entry");
      barNumberOfOrder = CurrentBar;
      }

      // If more than 5 bars has elapsed, cancel the entry order
      if (CurrentBar > barNumberOfOrder + 5)
      CancelOrder(myEntryOrder);
      }
      But no success. Instead of EnterLongLImit, I used EnterLongStopMarket, and there were other parts of code as well. Strategy imports fine, but when I test it for optimization, it gives all the same results, so it is not working.

      Comment


        #4
        Hello UltraNIX,

        Is the condition evaluating as true?
        Use prints to find out.


        Is the myEntryOrder.OrderState in the state OrderState.Working when then CancelOrder() is called?
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Not sure, as I am new to coding C#, but I have previous experience of coding FileMaker Pro. My statement "it doesn't work" comes from Backtesting. I ran test twice - once with code, other time - without code. Completely exact results. So I am making a point that it doesn't work.

          Originally posted by NinjaTrader_ChelseaB View Post
          Hello UltraNIX,

          Is the condition evaluating as true?
          Use prints to find out.


          Is the myEntryOrder.OrderState in the state OrderState.Working when then CancelOrder() is called?

          Comment


            #6
            Hello UltraNIX,

            The next step is to find out why the results are not changing.

            You will need to use prints and TraceOrders to understand the behavior.

            Below is a link to a forum post that demonstrates how to use prints to understand behavior.





            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. Please let me know if you would like our business development follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Yes, I am using prints, I used this link for reference: https://ninjatrader.com/support/help...ancelorder.htm

              However.. After 3 hours of debugging, I am not sure what is wrong.

              Basically, what I've done.
              Step 1, OnBarUpdate method: After entering LongStopMarket order, I set barNumberOfOrder value and run Print command. All prints work.
              Code:
              if (StopMarketForEntry && myEntryOrder == null) 
                              {
                                  EnterLongStopMarket(Qty, (High[0] + TickSize) , "ADX_ELS_Strong Uptrend");
                                  barNumberOfOrder = CurrentBar;
                                  Print(Time[0] + " 1- Long Entry | BarNumber: " + barNumberOfOrder);
                              }
              Step 2, OnBarUpdate method: Cancel order rules: NEVER PRINT.
              if (barNumberOfOrder !=0 && CancelAfterBars && CurrentBar > barNumberOfOrder + CancelAfterCount)
              Print(Time[0] + " 2- Cancel Order | CurrentBar: " + CurrentBar + " BarNumber: " + barNumberOfOrder);
              CancelOrder(myEntryOrder);
              CancelAfterBars is boolean, and is set to "true". CancelAfterCount = 5 (user editable number of bars to cancel the trade after)

              Steps 3 and 4. OnOrderUpdate Method:
              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 == "ADX_ELS_Strong Uptrend" || order.Name == "ADX_ESS_Strong Downtrend")
              myEntryOrder = order;
              Print(Time[0] + " 3- Set Order" + "Order: " + myEntryOrder);

              // Evaluates for all updates to myEntryOrder.
              if (myEntryOrder != null && myEntryOrder == order)
              {
              // Check if myEntryOrder is cancelled.
              if (myEntryOrder.OrderState == OrderState.Cancelled)
              {
              Print(Time[0] + " 4.0- Order State " + myEntryOrder.OrderState);
              // Reset myEntryOrder back to null
              myEntryOrder = null;
              barNumberOfOrder = 0;
              Print(Time[0] + " 4.1- Null Order");
              }
              }
              }
              Here is fragment from NinjaScript Output Window with prints:
              2020-01-08 04:05:04 3- Set OrderOrder: orderId='NT-00000-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Submitted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 04:05:04 3- Set OrderOrder: orderId='NT-00000-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Accepted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 04:05:04 3- Set OrderOrder: orderId='NT-00000-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Working instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 04:05:04 1- Long Entry | BarNumber: 125
              2020-01-08 04:05:42 3- Set OrderOrder: orderId='NT-00000-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=CancelPending instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 04:05:42 3- Set OrderOrder: orderId='NT-00000-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=CancelSubmitted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 04:05:42 3- Set OrderOrder: orderId='NT-00000-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Cancelled instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 04:05:42 4.0- Order State Cancelled
              2020-01-08 04:05:42 4.1- Null Order
              2020-01-08 13:00:33 3- Set OrderOrder: orderId='NT-00001-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Submitted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3232.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 13:00:33' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 13:00:33 3- Set OrderOrder: orderId='NT-00001-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Accepted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3232.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 13:00:33' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 13:00:33 3- Set OrderOrder: orderId='NT-00001-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Working instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3232.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 13:00:33' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 13:00:33 1- Long Entry | BarNumber: 223
              2020-01-08 13:06:47 3- Set OrderOrder: orderId='NT-00001-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=CancelPending instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3232.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 13:00:33' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 13:06:47 3- Set OrderOrder: orderId='NT-00001-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=CancelSubmitted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3232.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 13:00:33' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 13:06:47 3- Set OrderOrder: orderId='NT-00001-15583' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Cancelled instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3232.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 13:00:33' gtd='2099-12-01' statementDate='2020-06-10'
              2020-01-08 13:06:47 4.0- Order State Cancelled
              2020-01-08 13:06:47 4.1- Null Order
              I formatted Step numbers in bold, so you see it easier. I wonder where it cancells my order, as you can see, no print with "2- Cancel Order (...)" is made. So how does it go to Order State Cancelled?

              Comment


                #8
                Hello UltraNIX,

                I am happy to assist with analyzing the output from the output window.

                Please attach the saved output text file with your next post.


                To understand why a condition is not evaluating as true, print the time of the bar and all values used in the condition to the output window.

                Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks, that would be really helpful.

                  Can you tell me which values should I add for prints? Or is it enough as it is and you just need a full output text?

                  Originally posted by NinjaTrader_ChelseaB View Post
                  Hello UltraNIX,

                  I am happy to assist with analyzing the output from the output window.

                  Please attach the saved output text file with your next post.


                  To understand why a condition is not evaluating as true, print the time of the bar and all values used in the condition to the output window.

                  Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                  https://ninjatrader.com/support/foru...040#post786040

                  Comment


                    #10
                    Hello UltraNIX,

                    From the code you have provided:

                    if (barNumberOfOrder !=0 && CancelAfterBars && CurrentBar > barNumberOfOrder + CancelAfterCount)

                    It looks like you need to print barNumberOfOrder, CancelAfterBars, CurrentBar, and CancelAfterCount as well as the order OrderState.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Thanks, I've done what you asked. And I got an error message that is at the very bottom of the quoted text:

                      [That is all text in NinjaScript Output Window, previously I had more text and more entries, before updating Print code]


                      Code:
                      2020-01-08 04:05:04 3- Set Order | Order: orderId='NT-00000-1072' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Submitted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'| BarNumber: 0 | CancelAfterBar: True | CurrentBar: 125 | CancelAfterCount: 5 | myEntryOrder.OrderState: Submitted
                      2020-01-08 04:05:04 3- Set Order | Order: orderId='NT-00000-1072' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Accepted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'| BarNumber: 0 | CancelAfterBar: True | CurrentBar: 125 | CancelAfterCount: 5 | myEntryOrder.OrderState: Accepted
                      2020-01-08 04:05:04 3- Set Order | Order: orderId='NT-00000-1072' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Working instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'| BarNumber: 0 | CancelAfterBar: True | CurrentBar: 125 | CancelAfterCount: 5 | myEntryOrder.OrderState: Working
                      2020-01-08 04:05:04 1- Long Entry | BarNumber: 125 | CancelAfterBar: True | CurrentBar: 125 | CancelAfterCount: 5 | myEntryOrder.OrderState: Working
                      2020-01-08 04:05:42 3- Set Order | Order: orderId='NT-00000-1072' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=CancelPending instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'| BarNumber: 125 | CancelAfterBar: True | CurrentBar: 126 | CancelAfterCount: 5 | myEntryOrder.OrderState: CancelPending
                      2020-01-08 04:05:42 3- Set Order | Order: orderId='NT-00000-1072' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=CancelSubmitted instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'| BarNumber: 125 | CancelAfterBar: True | CurrentBar: 126 | CancelAfterCount: 5 | myEntryOrder.OrderState: CancelSubmitted
                      2020-01-08 04:05:42 3- Set Order | Order: orderId='NT-00000-1072' account='Backtest' name='ADX_ELS_Strong Uptrend' orderState=Cancelled instrument='ES 06-20' orderAction=Buy orderType='Stop Market' limitPrice=0 stopPrice=3206.25 quantity=1 tif=Gtc oco='' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2020-01-08 04:05:04' gtd='2099-12-01' statementDate='2020-06-10'| BarNumber: 125 | CancelAfterBar: True | CurrentBar: 126 | CancelAfterCount: 5 | myEntryOrder.OrderState: Cancelled
                      2020-01-08 04:05:42 4.0- myEntryOrder.OrderState |Cancelled| BarNumber: 125 | CancelAfterBar: True | CurrentBar: 126 | CancelAfterCount: 5 | myEntryOrder.OrderState: Cancelled
                      Strategy 'AI_ADX_Stop/-1': [B]Error on calling 'OnOrderUpdate' method on bar 126: Object reference not set to an instance of an object.[/B]

                      Comment


                        #12
                        I also attached a strategy file I use, maybe it would be easier to see it from the code right here.


                        It compiles without an error, but performance is still with errors.

                        Comment


                          #13
                          Hello UltraNIX,

                          This is an error stating there is a null value for a variable that was used.

                          We will need to find which line of code is causing the error.

                          I generally recommending adding prints every few lines. Where the prints stop appearing is typically where the error is.

                          Below is a link to a forum post that discusses adding prints to find which line in a script is causing an error.
                          https://ninjatrader.com/support/foru...121#post791121

                          Visual Studio can also be used for debugging.
                          https://ninjatrader.com/support/help..._debugging.htm


                          If the error is coming from the print, it may be from the order.

                          You can add a check for null.

                          Print(string.Format("{0} | {1}", Time[0], (myOrder != null ? myOrder.OrderState : "null"));

                          or

                          if (myOrder != null)
                          {
                          Print(string.Format("{0} | {1}", Time[0], myOrder.OrderState));
                          }
                          Last edited by NinjaTrader_ChelseaB; 06-10-2020, 10:47 AM.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #14
                            Installed Visual Studio, selected debug mode, attached to process, loaded strategy code in Visual studio, but was unable to set breakpoint (Followed this video: https://www.youtube.com/watch?v=olIwH8XtKJs). I searched for other Visual Studio with NinjaTrader strategy tutorials on youtube, found zero.

                            I am about to give up. I am not a true coder, so I am asking for help here. And please, do not refer me to paid consultants, I am not there yet to pay for coding and consulting. I would appreciate the assistance here. I put in the work, the time, the effort, read the manual, adapted the code and shared my code. Not sure if I can do better.

                            Comment


                              #15
                              Hello UltraNIX,

                              I have a video I've previously made that shows debugging in VS.
                              Demonstrates how to add breakpoints with VS.1) Open project in VS from button on NinjaScript Editor toolbar2) Enable Debugging then recompile in NinjaScript Editor3) In VS click Debug -> Attach to process -> NinjaTrader.exe4) Add breakpoint to script5) Run script


                              You could also use prints to find the line causing the error.
                              (I think its the order object but not sure.)

                              Learning C# does take time. But the more you learn the more you can do.
                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by lightsun47, Today, 03:51 PM
                              0 responses
                              4 views
                              0 likes
                              Last Post lightsun47  
                              Started by 00nevest, Today, 02:27 PM
                              1 response
                              8 views
                              0 likes
                              Last Post 00nevest  
                              Started by futtrader, 04-21-2024, 01:50 AM
                              4 responses
                              44 views
                              0 likes
                              Last Post futtrader  
                              Started by Option Whisperer, Today, 09:55 AM
                              1 response
                              13 views
                              0 likes
                              Last Post bltdavid  
                              Started by port119, Today, 02:43 PM
                              0 responses
                              9 views
                              0 likes
                              Last Post port119
                              by port119
                               
                              Working...
                              X