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 Managed Enter Long and Short Limit Orders

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

    Cancel Managed Enter Long and Short Limit Orders

    Hello,

    I am running NT7.

    I used mainly the strategy wizard to create my logic and unlock if needed for more custom work.

    I use the following in my code
    EnterShortLimit
    EnterLongLimit
    SetProfitTarget
    SetStopLoss

    Questions:

    1. If a limit order is pending to be filled, are the setstoploss and setprofittarget order set once the limit order is filled?

    2. I would like to cancel a long pending limit order if say Close[0] >= EnterLongLimit_Price + 28*ticks AND Pending Order Open. So in other words, if market price exceeds 28 ticks from pending long limit order price AND there is an pending order open, then cancel the order.

    I added the attached code to Cancel order if a pending order is waiting and pending limit price (Variable2) price is 28 above market price. Does my code make sense.

    How can I determine if pending limit order is open or not filled? Is it how i did in the attachment?

    3. Please answer questions on the attachment.

    4. what does this mean "private IOrder myEntryOrder = null; " http://ninjatrader.com/support/helpG...ancelorder.htm

    5. If a limit order is pending at 2005.50 to be filled, can I use Position.AvgPrice in the code to reference this price? If not, how can I reference a pending limit order price to be filled?

    6. Once the limit order is cancel, do i need do anything with the setstoploss and setprofittarget orders?

    7. Does the CancelOrder(myEntryLongOrder) work in historical back testing?

    Thank you for your help
    Attached Files
    Last edited by simple_goodoboy; 03-28-2017, 08:46 PM.

    #2
    Hello simple_goodoboy,

    Thanks for opening the thread.

    1. If a limit order is pending to be filled, are the setstoploss and setprofittarget order set once the limit order is filled?
    SetStopLoss() and SetProfitTarget() will create static profit targets and stop lossed when they are added in Initialize(). There orders are placed after an entry order has been placed. They can be updated for dynamic profit targets and stop losses by calling these method with some logic in OnBarUpdate().

    2. I would like to cancel a long pending limit order if say Close[0] >= EnterLongLimit_Price + 28*ticks AND Pending Order Open. So in other words, if market price exceeds 28 ticks from pending long limit order price AND there is an pending order open, then cancel the order.

    I added the attached code to Cancel order if a pending order is waiting and pending limit price (Variable2) price is 28 above market price. Does my code make sense.

    How can I determine if pending limit order is open or not filled? Is it how i did in the attachment?
    Your code looks fine. You can use IOrders to manage your orders so you know if one is still pending or filled. There is an example on using protective orders that covers how to use IOrders as well as OnOrderUpdate() and OnExecution() to do this. I will provide a link at the end of my response.

    I will suggest to use Print() statements to debug your script so you understand exactly what is happening with your logic.

    3. Please answer questions on the attachment.
    1. You will have to set your IOrder to null within OnExecution() or OnOrderUpdate() when the order gets filled or cancelled
    2. myEntryOrder is an IOrder which "Represents a read only interface that exposes information regarding an order." It does not equal the price.
    3. If the order has not been filled, you can call CancelOrder to cancel the order. This will also cancel any profit targets or stop losses that would be invoked when the order fills.


    4. what does this mean "private IOrder myEntryOrder = null; " http://ninjatrader.com/support/helpG...ancelorder.htm
    The sample code is declaring a private variable of type IOrder named myEntryOrder. It is initializing it as null.

    5. If a limit order is pending at 2005.50 to be filled, can I use Position.AvgPrice in the code to reference this price? If not, how can I reference a pending limit order price to be filled?
    You can use the limit price property of an IOrder to monitor and change the price of the associated limit order.

    6. Once the limit order is cancel, do i need do anything with the setstoploss and setprofittarget orders?
    No. If you cancelled the order before it gets filled, your profit target and stop loss will not be placed.

    7. Does the CancelOrder(myEntryLongOrder) work in historical back testing?
    Yes. CancelOrder() will work in context to the logic it is written with. This means that your strategy will be able to cancel orders before they get filled if your logic allows you. You can add print statements and perform simple debugging to monitor this process.

    Please take the time to review the sample code and the associated documentation. All of the answers found here can be found in the documentation with more in depth examples.

    Strategy: Using OnOrderUpdate() and OnExecution() methods to submit protective orders - http://ninjatrader.com/support/forum...ead.php?t=7499


    Debugging tips - http://ninjatrader.com/support/forum...ead.php?t=3418

    Please let me know if you have any questions on the material.
    JimNinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Jim View Post
      ]If the order has not been filled, you can call CancelOrder to cancel the order.
      Thank you Jim for respond. But I am still confused. I need more simple explanation whats going on.

      My goal
      I want to know how to detect if a pending limit order is filled or not. Once I detect this I want to cancel the order.

      Question
      How do I determine "if the order has not filled or still pending"? Where is the code for this?

      Code Question
      Are the two codes below the same

      // If pending order has not been, filled and close greater then Open, cancel the pending Long order.
      if (entryOrder != null && Close[0] > Open[0])

      CancelOrder(myEntryLongOrder)

      entryOrder = null //reset the null, get ready for another order submission

      // If pending order has not been, filled and close greater then Open, cancel the pending Long order.
      if (Position.MarketPosition == MarketPosition.Flat && Close[0] > Open[0])
      CancelOrder(myEntryOrder)

      entryOrder = null //reset the null, get ready for another order submission

      Attached Code Questions

      Please help me with the questions in the attachment.

      Thank you for the help. Probably easier if you just call me. Private message me and I give you my number. I only need 10 minutes please.
      Attached Files
      Last edited by simple_goodoboy; 03-31-2017, 10:53 AM.

      Comment


        #4
        Hello simple_goodoboy,

        I have received your note. As per our call, let's keep our correspondence to this thread so we can potentially help others who are browsing the forum.

        To track when an order is in a Pending state, we will want to use an IOrder to keep track of when the order has been submitted and its state has become State.Accepted. You can use OnOrderUpdate() to track when the IOrder enters a State.Accepted state.

        Please consider the following sample code:

        Code:
        private IOrder entryOrder = null;
        private bool entryOrderPending = false;
        protected override void OnBarUpdate()
        {
            if (entryOrder == null && Close[0] > Open[0])
                 entryOrder = EnterLong();
        }
         
        protected override void OnOrderUpdate(IOrder order)
        {
        	// If the IOrder that has been updated is our entryOrder, check for Pending status
            if (entryOrder != null && entryOrder == order)
            {
                Print(order.ToString());
        		
        		// If the IOrder that has been updated has an OrderState of OrderState.Accepted,
        		// set our entryOrderPending bool to true.
                if (order.OrderState == OrderState.Accepted)
                      entryOrderPending = true;
        		
        		// Reset the IOrder when it has been filled or cancelled.
        		if ( (order.OrderState == OrderState.Filled)
        			|| (order.OrderState == OrderState.Cancelled))
        		{
        			entryOrderPending = false; // Set our bool to false
        			entryOrder = null; // Set the entryOrder IOrder to null
        		}
        			
            }
        }
        You can then use that bool along with your own logic within OnBarUpdate() to determine when you will want to cancel the limit order that you have assigned to the IOrder "entryOrder."

        Please refer to the documentation below for the components used:

        Order States:
        OrderState.Accepted
        OrderState.Cancelled
        OrderState.Filled
        OrderState.PartFilled
        OrderState.PendingCancel
        OrderState.PendingChange
        OrderState.PendingSubmit
        OrderState.Rejected
        OrderState.Working
        OrderState.Unknown


        * In a historical backtest, orders will always reach a "Working" state. In real-time, some stop orders may only reach "Accepted" state if they are simulated/held on a brokers server
        IOrder - https://ninjatrader.com/support/help...nt7/iorder.htm

        CancelOrder() - https://ninjatrader.com/support/help...ancelorder.htm

        To answer your question on your code examples, the two are not the same.

        // If pending order has not been, filled and close greater then Open, cancel the pending Long order.
        if (entryOrder != null && Close[0] > Open[0])

        CancelOrder(myEntryLongOrder)

        entryOrder = null //reset the null, get ready for another order submission
        The above checks if the IOrder that you called "entryOrder" has been created and if the current close price is greater than the open. It will then cancel the order associated with the IOrder that you have named "myEntryLongOrder."

        If this is a code snippet, you are missing semi colons and curly braces. You will receive compiler errors and the "entryOrder = null" will execute without regard to the if statement because there are no curly braces used. (if statements will only use the first line of code ending with a semi colon when vurly braces are not used.)

        // If pending order has not been, filled and close greater then Open, cancel the pending Long order.
        if (Position.MarketPosition == MarketPosition.Flat && Close[0] > Open[0])
        CancelOrder(myEntryOrder)
        In the above example, you are checking if the strategy's overall position is flat and the close price for the current bar is greater than the open price of the current bar. It will then cancel the order associated with the IOrder that you have named "myEntryOrder"

        I did not see any questions listed in your code example. Please review the information provided and reply to this post if there is something else that you would like me to answer.

        While I will not be able to provide assistance in developing your strategy or debugging your code, if you are looking for those services you can write in to platformsupport[at]ninjatrader[dot]com with the thread URL and the text "Attention Jim." I will be able to get you connected with a member of our Business Development team who can provide a list of NinjaScript Consultants who would be happy to develop and debug your code.

        The thread URL is: http://ninjatrader.com/support/forum...ad.php?t=98130

        Please let me know if I may be of further assistance.
        JimNinjaTrader Customer Service

        Comment


          #5
          Thanks Jim, I am understanding now.

          Few questions on your code understanding. Please check previous post I sent with attached questions I forgot to attach.

          Originally posted by NinjaTrader_Jim View Post

          // If the IOrder that has been updated is our entryOrder, check for Pending status
          if (entryOrder != null && entryOrder == order)

          Print(order.ToString());
          1. Does "entryOrder != null" means check if an order has taking place ?

          2. And does "entryOrder == order" means check if this is the long order?

          Originally posted by NinjaTrader_Jim View Post

          {
          if (entryOrder == null && Close[0] > Open[0])
          entryOrder = EnterLong();
          }
          3. Will this code (entryOrder = EnterLong() assign order id to the long position AND enter a long position at the same time?


          Originally posted by NinjaTrader_Jim View Post

          if (order.OrderState == OrderState.Accepted)
          entryOrderPending = true;
          4. OrderState.Accepted meaning that broker has placed this order and and order is awaiting fill?

          5. what is difference between OrderState.Accepted and OrderState.Working ?

          6. Why not use if (order.OrderState != OrderState.Filled) in your code snippet? Just curious

          Thank you

          Comment


            #6
            Hello simple_goodoboy,

            Thank you for the additional questions.

            1. Does "entryOrder != null" means check if an order has taking place ?
            This checks if the IOrder object called "entryOrder" has any data assigned to it.

            2. And does "entryOrder == order" means check if this is the long order?
            This checks if the IOrder that you called "entryOrder" is the same order that has been updated and being passed through OnOrderUpdate(IOrder order). As the sample strategy assigns the IOrder called "entryOrder" to the entry method "EnterLong()" yes this would represent the long entry.

            3. Will this code (entryOrder = EnterLong() assign order id to the long position AND enter a long position at the same time?
            Yes, EnterLong() will submit the an order and it will be assigned to the IOrder called entryOrder so you can track and manage it within your code.

            4. OrderState.Accepted meaning that broker has placed this order and and order is awaiting fill?
            Yes.

            5. what is difference between OrderState.Accepted and OrderState.Working ?
            Thanks for pointing this out.

            From the IOrder section of the help guide:
            OrderState.Accepted - Order has been acknowledged by the broker
            OrderState.Working - An order is working at the exchange


            You can use OrderState.Working as a better indicator for a pending order.

            6. Why not use if (order.OrderState != OrderState.Filled) in your code snippet? Just curious
            I don't know the full context of your question. In my sample code, I set a bool when an order has been submitted and the OrderState has become accepted. I then flip that bool to false when the order has been filled or cancelled. It is not necessary for me to check "when the order is not filled" within my sample.

            Screenshot_2.png

            The comment states "Checks to see if our Stop Order has been submitted already."

            The code literally checks if there isn't an order assigned to the IOrder called "stopOrder," and if that order's StopPrice is less than the average entry price. If both are true, then it updates the the IOrder called stopOrder by assigning it to a new ExitLongStop() order method. This order method updates the actual stop loss order because it uses the fromEntrySignal tags properly. Please read the ExitLongLimit() documentation to learn about what each argument and overload means.

            The price is set to Positon.AvgPrice, the average entry price. This is referred to as the breakeven point.


            Screenshot_3.png

            This would place the order but it would not assign it to the IOrder called stopOrder so the code can track and manage it.

            Screenshot_4.png

            If the IOrder object called entryOrder has data (is not null) and the IOrder being passed through OnOrderUpdate() (called "order") is the same IOrder as the IOrder called entryOrder.

            While I appreciate your questions, the direction of this thread is escaping the scope of services that we provide. I can answer your questions on NinjaScript, but their is a certain level of involvement we require from you to keep up with the programming aspects. We do not provide programming education in our scope of services.

            I will provide you with some links for introductory programming information and tutorials that you can use to develop your skills. After performing these tutorials, the basic programming concepts involved in understanding the sample strategies will come to you much easier.

            Please see review the tutorials below and have a look at this thread for more tips to learn C# and NinjaScript.

            Basic Programming Concepts - https://ninjatrader.com/support/help...g_concepts.htm

            NinjaScript tutorials - https://ninjatrader.com/support/help.../tutorials.htm

            Learning NinjaScript thread - http://ninjatrader.com/support/forum...d.php?p=488807

            I suggest to review these tutorials and documentation and then attempt to work with the sample code.

            Please let me know if I may be of further assistance.
            JimNinjaTrader Customer Service

            Comment


              #7
              Thank you Jim,

              You have provided lots of resources for me to continue from here.

              Thank you

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by TheMarlin801, 10-13-2020, 01:40 AM
              20 responses
              3,914 views
              0 likes
              Last Post Bidder
              by Bidder
               
              Started by timmbbo, 07-05-2023, 10:21 PM
              3 responses
              150 views
              0 likes
              Last Post grayfrog  
              Started by Lumbeezl, 01-11-2022, 06:50 PM
              30 responses
              805 views
              1 like
              Last Post grayfrog  
              Started by xiinteractive, 04-09-2024, 08:08 AM
              3 responses
              11 views
              0 likes
              Last Post NinjaTrader_Erick  
              Started by Johnny Santiago, 10-11-2019, 09:21 AM
              95 responses
              6,194 views
              0 likes
              Last Post xiinteractive  
              Working...
              X