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

Closing a Position from within OnTermination()

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

    Closing a Position from within OnTermination()

    Greetings,

    In order to clean up outstanding orders and close positions when my strategy is terminated I have the following code in OnTermination(). For reference, theOrder is the IOrder structure associated with the order.

    if (theOrder != null)
    {
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    CancelOrder(theOrder);
    }
    else
    {
    if (Position.MarketPosition == MarketPosition.Long)
    ExitLong("Long");
    else if (Position.MarketPosition == MarketPosition.Short)
    ExitShort("Short");
    }
    }

    This code is, apparently, executing correctly, as positions are being closed and orders cancelled as appropriate. However, OnExecution() is not being called when these transactions occur. I've confirmed this with a Print("Execution: " + execution.Order.OrderState.ToString()) at the top of OnExecution(IExecution execution) which is not being hit when positions are closed in OnTermination() but is being hit when positions are closed elsewhere within the strategy. I do tabulations of orders and trade results in OnExecution(), and it is my understanding that it should be called whenever an execution is completed.

    Is this behaviour expected? It sure isn't expected by me!

    How can I ensure that an order which is cancelled or a position which is closed in OnTermination() will be reflected in OnExecution()? Or is there a better way to accomplish what I'm trying to do (ensure that I am flat relative to the strategy when the strategy is terminated while capturing those closing transactions in OnExecution())?

    Your assistance would be most appreciated.

    #2
    Hello cmt_Robert,

    Thank you for your post.

    The OnTermination will get called when the strategy has been terminated and would not receive the executions that are being received. You would need to create your own method that you can call and would clean up the orders and positions without having the termination of the strategy.

    Let me know if I can be of further assistance.
    Cal H.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_Cal View Post
      Hello cmt_Robert,

      Thank you for your post.

      The OnTermination will get called when the strategy has been terminated and would not receive the executions that are being received. You would need to create your own method that you can call and would clean up the orders and positions without having the termination of the strategy.

      Let me know if I can be of further assistance.
      Greetings Cal,

      Thank you for your response.

      To be clear, I am not requiring the termination of the strategy in order to close my positions. Rather, the intention of cleaning up outstanding orders in OnTermination is to ensure that things DO get cleaned up if and when the strategy is terminated, say by deselecting the "Enabled" check box. In that circumstance, where can I put the call for my own method which will clean up outstanding orders? Is there some internal method which is called PRIOR to OnTermination when the strategy terminates from which I could call my own method?

      Comment


        #4
        cmt_Robert,

        You would create a new method with the following
        Code:
        public void MyMethod()
        {
            //order clean up is done here
        }
        You would need to have the logic in your other methods such as OnBarUpdate() to call this method to clean up.

        OnBarUpdate()
        {
        if(condition that you want to execute for cleanup)
        MyMethod();
        }
        Cal H.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_Cal View Post
          cmt_Robert,

          You would create a new method with the following
          Code:
          public void MyMethod()
          {
              //order clean up is done here
          }
          You would need to have the logic in your other methods such as OnBarUpdate() to call this method to clean up.

          OnBarUpdate()
          {
          if(condition that you want to execute for cleanup)
          MyMethod();
          }
          Greetings Cal,

          Thank you again for your response.

          You seem to be missing the focus of my question.

          The "condition that you want to execute for cleanup" that you cite in your example is that the strategy has been terminated.

          Please understand that I do know how to program and I have written appropriate methods for exiting positions under ordinary circumstances. The extraordinary circumstance that I need to consider is that the strategy has been terminated.

          As I asked previously, is there an internal method which is called PRIOR to OnTermination() when the strategy terminates? Is there any documentation which discusses the sequence of events which occurs when a strategy terminates?
          Last edited by cmt_Robert; 05-10-2014, 02:39 PM.

          Comment


            #6
            cmt_Robert,

            There is no method that is called right before the OnTermination.

            You can take a look at the help section in the strategy section for the order of events-
            http://www.ninjatrader.com/support/h...l?strategy.htm
            Cal H.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_Cal View Post
              cmt_Robert,

              There is no method that is called right before the OnTermination.

              You can take a look at the help section in the strategy section for the order of events-
              http://www.ninjatrader.com/support/h...l?strategy.htm
              Greetings Cal,

              Thank you again for your response.

              I have reviewed the URL which you provided and do not see where it even alludes to the order of events. The closest that I have been able to find in http://www.ninjatrader.com/support/h...l?strategy.htm is "Advanced Event Driven Programming Concepts" and that just describes the events, rather than their order of occurrence.

              So, back to my question: given that I want to protect myself by closing out positions and cancelling pending orders in the event that a strategy is terminated, and given that I want to be able to account for the changes to my account which result from closing out positions in this extraordinary circumstance, how can I accomplish this? My current approach, using code within OnTermination(), is only accomplishing half of this goal (closing the positions) but not the other half (accounting for the changes in my account resulting from those extraordinary position closures).

              More specifically, given that the execution of an exit order placed from within OnTermination apparently doesn't pass through OnExecution, and having of necessity placed an exit order from within OnTermination to protect myself in the event of a strategy termination with an open position, how can I derive the equivalent of Execution.Order.AvgFillPrice from within OnTermination since that will give me the most important thing that I need.
              Last edited by cmt_Robert; 05-10-2014, 04:58 PM.

              Comment


                #8
                As a supplemental question, when I use the protective exit orders (as described by me throughout this thread) in OnTermination it appears that they work as expected in that the orders no longer appear in the SuperDOM window and the SuperDOM total is appropriately updated. HOWEVER, the Control Center window seems to indicate that the position has just disappeared as it does NOT update appropriately.

                Can you please explain this?

                -----------

                For the record, and for anyone else who is trying to do this, the solution appears to be that since you CAN access IOrder information from within OnTermination(), going back to my original code snippet you can have something like this, where theOrder is the original IOrder structure associated with an already active order and ExitOrder is an IOrder structure associated with the closing order:

                if (theOrder != null)
                {
                if (Position.MarketPosition == MarketPosition.Flat)
                {
                CancelOrder(theOrder);
                }
                else
                {
                if (Position.MarketPosition == MarketPosition.Long)
                ExitOrder = ExitLong("Long");
                else if (Position.MarketPosition == MarketPosition.Short)
                ExitOrder = ExitShort("Short");

                theExitValue = ExitOrder.AvgFillPrice;

                }
                }

                Assuming you have previously stored the Average Fill Price on entry (which I do in OnExecution() using theEntryValue = execution.Order.AvgFillPrice) and knowing the dollar value of a point (using Instrument.MasterInstrument.PointValue) you can readily calculate the impact of this extraordinary event on your account, which is primarily what I wanted to do in the first place.

                If for some reason this is breaking something in NinjaTrader please let me know. It seems to be working - except as noted above in that it seems to NOT update the Control Center panel properly whereas it DOES update the SuperDOM correctly. I'd really like to understand that anomaly.
                Last edited by cmt_Robert; 05-10-2014, 08:53 PM.

                Comment


                  #9
                  Hi Robert, OnTermination is the last method call your script would see before being disabled and ending the instance lifecycle, so there would be no way with this approach to pass anything to custom calcs as there is simply no event you could work in after OnTermination(). Is the idea to completely disable the script so you would need to start a new instance afterwards or would you rather want to pause the script programmatically? I was trying to reproduce your Control Center issue but I am unclear what exactly would report off compared to your SuperDOM, I would expect

                  a) account position being closed
                  b) strategy position being closed
                  c) strategy disabled
                  BertrandNinjaTrader Customer Service

                  Comment


                    #10
                    Originally posted by NinjaTrader_Bertrand View Post
                    Hi Robert, OnTermination is the last method call your script would see before being disabled and ending the instance lifecycle, so there would be no way with this approach to pass anything to custom calcs as there is simply no event you could work in after OnTermination(). Is the idea to completely disable the script so you would need to start a new instance afterwards or would you rather want to pause the script programmatically? I was trying to reproduce your Control Center issue but I am unclear what exactly would report off compared to your SuperDOM, I would expect

                    a) account position being closed
                    b) strategy position being closed
                    c) strategy disabled
                    Thanks for your response Bertrand.

                    Perhaps I am alone in this, but there are times when I choose to disable a strategy manually by deselecting the "Enable" check box in Control Center. Should I choose to do this (or should my strategy be disabled for any other reason) I need to ensure that, as regards that specific instantiation of the stategy, ALL pending orders are cancelled and ALL open positions are exited at market. In this extraordinary circumstance, where a position is closed upon termination, I ALSO need to ensure that I am able to determine the impact on my account.

                    Without these protections I have found that when a strategy is disabled for any reason there can be orders or even positions left untended as artifacts of the strategy. For me, this is not acceptable. Nor is it acceptable for me to not know the impact of a trade on my account.

                    You will find upon reading the entire thread that I have discovered a solution which appears to work and which provides results consistent with the results presented in the SuperDOM but inconsistent with the results presented in Control Center.

                    As I have described, what I am finding is that, if the enabled strategy opens a position and captures the entry price in OnExecution() using execution.Order.AvgFillPrice() (where execution is the IExecution structure representing the calling event) and then the strategy is disabled (either manually or programmatically) then the value derived within the strategy is consistent with the value presented in the SuperDOM but NOT with that presented in Control Center. The "Unrealized" value in Control Center disappears and is NOT reflected in the "Realized" value column. This is consistently demonstrable using Market Replay.

                    This is the anomaly about which I was asking. I hope that the issue is now clearer for you.

                    Comment


                      #11
                      Robert, the issue here is that you would not be able do anything really after OnTermination() has been called. The strategy lifecycle has ended then. There would unfortunately not be a workaround I can point you to. Per default we also have options to cancel pending entry and exit orders (Tools > Options > Strategies > NinjaScript). If you see a strategy disablement from an order rejection the Strategy realtime error handling is called, which will attempt then to close the open strategy position and cancel any orders.

                      BertrandNinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by NinjaTrader_Bertrand View Post
                        Robert, the issue here is that you would not be able do anything really after OnTermination() has been called. The strategy lifecycle has ended then. There would unfortunately not be a workaround I can point you to. Per default we also have options to cancel pending entry and exit orders (Tools > Options > Strategies > NinjaScript). If you see a strategy disablement from an order rejection the Strategy realtime error handling is called, which will attempt then to close the open strategy position and cancel any orders.

                        https://www.ninjatrader.com/support/...orhandling.htm
                        Thanks again for your response Bertrand.

                        I believe that I have demonstrated that I CAN do things from within OnTermination (i.e. after it has been called) to protect myself by cancelling outstanding orders and closing open positions. This is what I was trying to accomplish - and what I was asking for assistance with - when I created this thread.

                        Having (apparently) solved this myself, my question now is: why is there a difference in the way the results are presented in SuperDOM compared with how they are presented in Control Panel?

                        Please refer to the rest of this thread for details as I don't want to have this important question lost again in a lengthy post.

                        Comment


                          #13
                          Originally posted by cmt_Robert View Post
                          Thanks again for your response Bertrand.

                          I believe that I have demonstrated that I CAN do things from within OnTermination (i.e. after it has been called) to protect myself by cancelling outstanding orders and closing open positions. This is what I was trying to accomplish - and what I was asking for assistance with - when I created this thread.

                          Having (apparently) solved this myself, my question now is: why is there a difference in the way the results are presented in SuperDOM compared with how they are presented in Control Panel?

                          Please refer to the rest of this thread for details as I don't want to have this important question lost again in a lengthy post.
                          Still wondering about this...

                          Any thoughts, NinjaTraders?

                          Comment


                            #14
                            Originally posted by cmt_Robert View Post
                            Still wondering about this...

                            Any thoughts, NinjaTraders?
                            When you run OnTermination(), all the internal messaging for executions has been shut down, as the OnExecution() event handler has already been terminated, which is why there is nothing reflected in the OnExecution() event handler.

                            The DOM is simply a reflection of order and position state. As apparently the orders went through, the DOM will reflect that fact. However, the execution reporting engine has already been shut down and cannot update anything, such as the position data in the Control Panel.

                            If that information is critical (I think it is ), you may want to write it to an external file.
                            Last edited by koganam; 05-15-2014, 10:00 AM.

                            Comment


                              #15
                              Originally posted by koganam View Post
                              When you run OnTermination(), all the internal messaging for executions has been shut down, as the OnExecution() event handler has already been terminated, which is why there is nothing reflected in the OnExecution() event handler.

                              The DOM is simply a reflection of order and position state. As apparently the orders went through, the DOM will reflect that fact. However, the execution reporting engine has already been shut down and cannot update anything, such as the position data in the Control Panel.

                              If that information is critical (I think it is ), you may want to write it to an external file.
                              Thanks Koganam.

                              Is there a better way to accomplish what I am trying to accomplish? If not then this seems like (at least) a deficiency or (at worst) a bug in the way NinjaTrader works.

                              And yes, I completely agree that it IS critical information which I DO write to an external file. I log everything!

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by kevinenergy, Yesterday, 12:01 PM
                              6 responses
                              22 views
                              0 likes
                              Last Post kevinenergy  
                              Started by DawnTreader, 05-08-2024, 05:58 PM
                              15 responses
                              48 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by ZeroKuhl, Yesterday, 04:31 PM
                              7 responses
                              40 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by xepher101, Today, 12:19 PM
                              1 response
                              22 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by jpeep, 08-16-2020, 08:31 AM
                              16 responses
                              498 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Working...
                              X