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

Close Trades - Exit Positions

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

    Close Trades - Exit Positions

    Hello,

    I want to ask please what is the correct way to go flat. I have assigned to my customized buttons (I have modified from a sample and it works all fine) the actions and with my close button I have;

    if(Position.MarketPosition == MarketPosition.Long) {ExitLong;}
    if(Position.MarketPosition == MarketPosition.Short) {ExitShort;}

    Is this OK or is there the risk to run in an overfill and have a trade in opposite direction, eg when target or stop is hit exactly same time when clicking the button? Should one close/exit in another way to avoid this risk (or another risk)?

    Thank you!
    Tony

    #2
    Hello tonynt,

    Thanks for your question.

    Calling the Exit methods would be enough to cancel orders and close the position.

    What you describe with having the Exit submitted at the same time a target or stop fills could result in an inflight execution/overfill.

    Something to consider to avoid that possibility would be to have the button press call CancelOrder, and set a bool "WaitingToCancel" to true. Then, you can check in OnOrderUpdate when that order has cancelled and then you can call ExitLong/ExitShort to close the position, and you will not have to worry about the stop target filling along with the market order to ExitLong/ExitShort. You may then set the bool back to false since you will no longer be waiting for the order to cancel.

    CancelOrder requires that you track your orders with Order objects. Please see our SampleOnOrderUpdate strategy for further detail on how to use Order objects and the OnOrderUpdate method.

    SampleOnOrderUpdate - https://ninjatrader.com/support/help...and_onexec.htm

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

    We look forward to assisting.
    JimNinjaTrader Customer Service

    Comment


      #3
      Originally posted by tonynt View Post
      Hello,

      I want to ask please what is the correct way to go flat. I have assigned to my customized buttons (I have modified from a sample and it works all fine) the actions and with my close button I have;

      if(Position.MarketPosition == MarketPosition.Long) {ExitLong;}
      if(Position.MarketPosition == MarketPosition.Short) {ExitShort;}

      Is this OK or is there the risk to run in an overfill and have a trade in opposite direction, eg when target or stop is hit exactly same time when clicking the button? Should one close/exit in another way to avoid this risk (or another risk)?

      Thank you!
      Tony
      From my experience, and IMO, the overfill risk can be avoided if, instead of Exit() e.g. a Long Position, you just Enter() a Short Position and vice versa, otherwords if you just reverse your position. - Thanks.

      Comment


        #4
        Hello Jim,

        thank you for your reply. I have those samples and working with them.

        I can set the bool, but I do not understand what is the advantage, it can happen also with the bool that stop is hit same time as the close position executed.

        How you mean "can check when that order has cancelled..."? When I click the close button and it is checked then also this moment the stop can be hit. No?

        Thank you!
        Tony

        Comment


          #5
          Hello tonynt,

          Inflight executions and overfills can be hit when a position is closed before the cancel for that order reaches the exchange. It can happen with automated trading strategies or manual order submissions, or a combination. Hitting the Close button as the order is filling can cause this, too.

          You could take steps to protect yourself from that situation by doing the following when you press your button instead of simply calling ExitLong/ExitShort:

          1. Use CancelOrder to cancel active orders (This requires tracking Order objects)
          2. Check for the Cancel in OnOrderUpdate (You would check if order.OrderState == OrderState.Cancelled)
          3. Then call ExitLong/ExitShort.

          You would set a bool I.E. "WaitingToCancel" or "WaitingToCancelToExit" in step one so when the cancel is seen in step 2, you know you will want to exit the position.

          Worst case, you will get an error that the order cannot be cancelled if it is already filled and there would not be an open position because the cancel failed and ExitLong/ExitShort would not be called. (These orders exit positions based on the Strategy Position, but if they are called before the Strategy Position is modified as a target/stop fill, we could get an inflight exectution/overfill. This approach would protect you in that case.)

          We look forward to assisting.
          JimNinjaTrader Customer Service

          Comment


            #6
            Hello Jim,

            OK, I think I got now what you mean (sorry, but when translating to my language its in technical stuff hard to understand accurately every screw)

            You mean that with cancelling I would cancel the stop order so that this can not be hit when I then ExitLong/ExitShort.

            If this is what you mean this is clear for me to do, but this means that there might be the position then naked without a stop because it might happen (and for sure it happens to me after what I experienced the last 10 years) that I cancel the stop and the internet connection is lost next moment and my next action with ExitLong/ExitShort is not executed.

            Please let me know if I understand correctly what you mean and if it can happen what I described. Because if it can happen then I go another way: my ExitLong/ExitStop is only executed when I´m away a certain number of ticks from my stop.

            Thank you!
            Tony

            Comment


              #7
              Hello tonynt,

              Your understanding is correct so far.

              However, we would also be setting a bool and waiting for the Cancel to come back in OnOrderUpdate. At this moment the strategy would exit the position instead of immediately when the button is pressed.

              Yes, the position would be unprotected between the time the cancel is processed, and when your strategy sees the cancel and calls ExitLong/ExitShort. This would be a very very small amount of time and the strategy logic would be prepared for this case since you set a bool in the strategy so when it sees the cancel, it knows to exit the position.

              We look forward to assisting.
              JimNinjaTrader Customer Service

              Comment


                #8
                Originally posted by tonynt View Post
                You mean that with cancelling I would cancel the stop order so that this can not be hit when I then ExitLong/ExitShort.
                Not just the stop order -- you must cancel ALL active orders -- including any profit targets.

                Originally posted by tonynt View Post
                If this is what you mean this is clear for me to do, but this means that there might be the position then naked without a stop because it might happen (and for sure it happens to me after what I experienced the last 10 years) that I cancel the stop and the internet connection is lost next moment and my next action with ExitLong/ExitShort is not executed.
                Yes, for a very brief amount of time, this risk will exist. A very small risk, esp when
                compared to the plethora of other risks for the hundreds of other 'bad moments
                to lose your internet connection' kind of problems. Don't worry about the raindrops,
                my friend, worry about the river.

                The point Jim makes is:
                You're going to need to add extra logic to your OnOrderUpdate such that when it detects
                a canceled order --AND-- no other active orders exist (because this is the cancellation of
                the last active order, whether it be stop or target) --AND-- that bool that you set to true
                to exit the entire position is actually true --THEN-- you submit a market order to sell the long
                position (or cover the short position) specifying entire Position.Quantity (if needed) and reset
                your bool to false.

                I do the same thing as what Jim suggested and it works perfectly.

                Here's what I do (using unmanaged mode):
                I use a bool name 'IsStrategyExiting' which I set to true in my Flatten() routine.

                [This bool means the strat is exiting the current position, and its only true when
                the 'exiting chain of events' is in progress. The only way it gets set to true is via
                my Flatten() routine.]

                In my case, when my custom 'Close' toolbar button is pressed, it calls Flatten(),
                which starts the whole process by 1) cancelling all current stop/target orders,
                and 2) setting IsStrategyExiting to true. That's it, OnOrderUpdate does the rest.

                Inside my OnOrderUpdate, special handling of cancelled orders also checks
                if IsStrategyExiting is true and pending orders == 0 and Position.Quantity > 0
                then OnOrderUpdate knows to exit the current position right there.

                Good luck!

                Comment


                  #9
                  Hello bltdavid,

                  thank you for your reply!

                  Tony

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by NRITV, Today, 01:15 PM
                  1 response
                  5 views
                  0 likes
                  Last Post NinjaTrader_Jesse  
                  Started by maybeimnotrader, Yesterday, 05:46 PM
                  5 responses
                  24 views
                  0 likes
                  Last Post NinjaTrader_ChelseaB  
                  Started by quantismo, Yesterday, 05:13 PM
                  2 responses
                  16 views
                  0 likes
                  Last Post quantismo  
                  Started by frankthearm, Today, 09:08 AM
                  6 responses
                  27 views
                  0 likes
                  Last Post frankthearm  
                  Started by adeelshahzad, Today, 03:54 AM
                  5 responses
                  33 views
                  0 likes
                  Last Post NinjaTrader_BrandonH  
                  Working...
                  X