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

How to get closed position info in replay connection

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

    How to get closed position info in replay connection

    Hi.

    Say I am running a strategy in a playback conncetion, I want the strategy to determine what the last closed position market type is. Of course after a position is closed.

    I can do this on a live feed with this function, no problem. But how do I accomplish this in a replay connection??

    Code:
           /Function returns last trade type   OP_BUY=Long, OP_SELL=Short, -1=NoSignal            
           //OP_BUY/OP_SELL are already defined as const int
    
     int lastClosedPositionType() {
                if (SystemPerformance.AllTrades.Count > 1) {
                    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                    return((lastTrade.Entry.MarketPosition==MarketPosition.Long?OP_BUY:OP_SELL));
                }
                return(-1);            
            }​
    Thank you for your support
    Jess

    #2
    Hello Jess,

    Thanks for your post.

    You could use TradeCollection to get the last trade by using the following.

    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];

    Then, you would use the Entry.MarketPosition property to determine if the trade was long or short. This is seen in example # 2 in the help guide documentation below.

    TradeCollection - https://ninjatrader.com/support/help...collection.htm

    For example, the code might look something like this:
    Code:
    if (SystemPerformance.AllTrades.Count > 1)
    {
        Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
    
        if (lastTrade.Entry.MarketPosition == MarketPosition.Long)
            Print("lastTrade is " + lastTrade.Entry.MarketPosition);
    }
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Folks:
      Nevermind, my code on post 1 is detecting the trade operations on the playback connection. Except that now I have another issue....

      Take care and consider this thread closed.
      Jess

      Comment


        #4
        Ok here is the issue. I am trying to get the last trade operation (long/short) before I open a new trade, so I can compare the new signal with the closed signal and if they are both the same no trade.

        I do have post 1 code working properly. It grabs the last trade operation with no issues. HOWEVER, I only see the last trade operation AFTER a new trade has been executed.

        Ok, no worries so I use the OnAcctPositionUpdate() function to update a GLOBAL variable, but that does not work either. I am still only seeing the lat trade operation AFTER a new trade is just filled.

        Any ideas on how I could go about accomplishing this?? The root of the solution is that somehow I need to have the last trade operation BEFORE I attempt to open a new signal order.

        That way I can use the last trade operation info to determine if it is the same as the new signal and then from that make a decision.

        If code is required to make it clearer let me know...

        Jess

        Comment


          #5
          Hello Jess,

          Thanks for your notes.

          If you are getting the last trade (previous trade made) from SystemPerformance then there would not have to be another active trade before the lastTrade value prints to the Output window. Once the position is exited and the position updates, the lastTrade information would print to the Output window.

          For example, say a long order is placed. Once the long position is exited and the position updates, the lastTrade print will reflect the long order. A new order does not have to be active prior to the lastTrade printing to the Output window.

          Something you could try doing is creating a bool called something like 'LongBool'. You could flip the LongBool variable to true when the strategy calls EnterLong() to place a long entry order. When the strategy calls EnterShort() you could flip the bool to false.

          The bool could then be used in conditions to determine if the last trade made was long or short. When the bool is true, you entered into a long position and when the bool is false you entered into a short position.
          Last edited by NinjaTrader_BrandonH; 09-25-2023, 02:49 PM.
          Brandon H.NinjaTrader Customer Service

          Comment


            #6
            Originally posted by NinjaTrader_BrandonH View Post
            Hello Jess,

            Thanks for your notes.

            That is correct, this is the expected behavior. If you are getting the last trade (previous trade made) from SystemPerformance then this means that there would need to be a current trade that is active before the last trade prints to the Output window.

            Something you could try doing is creating a bool called something like 'LongBool'. You could flip the LongBool variable to true when the strategy calls EnterLong() to place a long entry order. When the strategy calls EnterShort() you could flip the bool to false.

            The bool could then be used in conditions to determine if the last trade made was long or short. When the bool is true, you entered into a long position and when the bool is false you entered into a short position.

            Brandon:
            Thnx alot for the information.

            What I am trying is to use a public variable (lastClosedSignal) that is set with Buy/Sell status in OnAcctPositionUpdate().
            But the variable does not stay with the value it resets back to its initial state (-1).
            I have done this before in other strategies but I don't see it working in this case..

            Please see example code snippets below, let me know if this is a valid route. (I shortened the code so it can illustrate the main intent)

            Jess

            Code:
            public class FMR  : Strategy
                {​
            
                    private const int OP_BUY = 0;
                    private const int OP_SELL = 1;    ​
            
                    int lastClosedSignal=-1;
                    int signal=-1;
            
               // ........
            
            protected override void OnBarUpdate()
                    {
                        if(State == State.Historical) return;
                        if (CurrentBars[0] < 1) return;        
            
                         if(!isNewBar()) return;    //isNewBar() function provides for test of new open candle
            
                         signal = -1;
                         signal=getSigna();   //getSignal() function provides for new signal if certain conditions happen, returns either OP_SELL or OP_BUY
            
                       if(lastClosedSignal!=-1)
                          if(signal==lastClosedSignal) return;  //Do not process new signal order if last trade had same type
            
                       openOrder(); //if we get to this line then we have a valid signal that is the opposite from the last trade direction.
            
                   }     ​
            
            
            private void OnAcctPositionUpdate(object sender, PositionEventArgs e)
                    {
                        if (e.Position.Instrument == Instrument)
                        {
            
                            if(SystemPerformance.AllTrades.Count>0) {
                                Trade lastTrade= SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                                Print("last trade name: "+lastTrade.Entry.Name+"  last trade type: "+(lastTrade.Entry.MarketPosition==MarketPosition.Long?"Buy":"Sell"));
                              //NinjaTrader.NinjaScript.AddOns.globalVarMethod.lastClosedType=lastClosedPositionType();    //YES I tried this too and same thing Global get reset at enew bar.
                                lastClosedSignal=(lastTrade.Entry.MarketPosition==MarketPosition.Long?OP_BUY:OP_SELL))
                            }                    
             }
            
            } // end of public class

            Comment


              #7
              Hello Jess,

              Thanks for your notes.

              You could create a class-level Trade variable in your script called lastTrade instead of instantiating Trade lastTrade within that SystemPerformance condition each time the condition is called.

              For example, private Trade lastTrade;

              Since it is a class-level variable, that variable could be used throughout the script.

              Further, OnAcctPositionUpdate() is not a documented method in the NinjaTrader help guide.

              To get position update information from an account, PositionUpdate can be used for subscribing to position update events. For example, account.PositionUpdate += OnPositionUpdate(). Then, you could use OnPositionUpdate() within your script. Note: Remember to unsubscribe if you are no longer using the subscription.

              See the help guide documentation below for more information and sample code.

              <Account>.PositionUpdate: https://ninjatrader.com/support/help...tionupdate.htm
              OnPositionUpdate(): https://ninjatrader.com/support/help...tionupdate.htm

              Please let us know if we may assist further.
              Brandon H.NinjaTrader Customer Service

              Comment


                #8
                Originally posted by NinjaTrader_BrandonH View Post
                Hello Jess,

                Thanks for your notes.
                .......
                Further, OnAcctPositionUpdate() is not a documented method in the NinjaTrader help guide.

                To get position update information from an account, PositionUpdate can be used for subscribing to position update events. For example, account.PositionUpdate += OnPositionUpdate(). Then, you could use OnPositionUpdate() within your script. Note: Remember to unsubscribe if you are no longer using the subscription.
                ......
                Hi, yes I considered PositionUpdate() but that would require to determine the account the user is using. So the better consideration is OnAcctPositionUpdate().

                The code is working properly now. Turns out that the code I posted above was the answer LOL!!
                How did this happen?? The code I posted was a simplified version of what I was using. I was trying anytying so I just cut and pasted the code from the post and BAM it started to work!!!!

                I do like your idea of making the variable lasttrade a class level variable, but for now I leave it like this cause finally its working!!!!!!!

                Here's the working version:
                Code:
                private void OnAcctPositionUpdate(object sender, PositionEventArgs e)
                {
                 if (e.Position.Instrument == Instrument)
                {
                    if(SystemPerformance.AllTrades.Count>0) {
                        Trade lastTrade= SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                        lastClosedSignal=(lastTrade.Entry.MarketPosition==MarketPosition.Long?OP_BUY:OP_SELL));  //lastClosedSignal is accesible to all of strategy as a class level variable
                  }​
                }
                PEACE
                Jess
                Last edited by xmess777; 09-25-2023, 02:23 PM.

                Comment


                  #9
                  Hello Jess,

                  Thanks for your notes.

                  I am happy to hear you were able to resolve this.

                  After further investigation, I have found that the expected behavior of printing lastTrade to the NinjaScript Output window is that lastTrade will print to the output window once the active position is exited and the position is updated. A new position does not have to be active as I previously noted.

                  For example, say a long order is placed. Once the long position is exited and the position updates, the lastTrade print would reflect the long order. A new order does not have to be active prior to the lastTrade printing to the Output window.

                  I have modified post # 5 to reflect this information
                  Last edited by NinjaTrader_BrandonH; 09-25-2023, 02:50 PM.
                  Brandon H.NinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by janio973, Today, 07:24 PM
                  0 responses
                  3 views
                  0 likes
                  Last Post janio973  
                  Started by aligator, 01-06-2022, 12:14 PM
                  4 responses
                  238 views
                  0 likes
                  Last Post john_44573  
                  Started by reynoldsn, Today, 05:56 PM
                  0 responses
                  12 views
                  0 likes
                  Last Post reynoldsn  
                  Started by bortz, 11-06-2023, 08:04 AM
                  51 responses
                  1,990 views
                  0 likes
                  Last Post aligator  
                  Started by dmking, 11-12-2019, 12:31 PM
                  4 responses
                  4,155 views
                  0 likes
                  Last Post jasonw
                  by jasonw
                   
                  Working...
                  X