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

Retreive the last partially closed trade ProfitCurrency

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

    Retreive the last partially closed trade ProfitCurrency

    Hi NT8 Forum,

    Im trying to tally the profit/loss from each trade within backtesting for position sizing purposes. The code below is what i have found on the forum, however i noticed that this only provides the last tposition that has been fully closed. I am sclaing out of my position and i would like to retreive the last partially closed trade profit/loss. Just like you would see in the Trades Tab of the Strategy Analyzer. I would of expected the trade number in the trades list would be the last trade trade. This doesn't appear to be the case. Can someone help me out with this?

    Code:
    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
    // Calculate the PnL for the last completed real-time trade
    double lastProfit = lastTrade.ProfitCurrency;
    Thanks! Very much appreciated!

    #2
    Hi mr_trade,
    Interesting. Perhaps an idea to check, if the quantity of the (remaining) position is updated after each scaling. If "Yes", you could search for quantity changes while(!) your market position is not flat. The outcome of the last scaling should be the difference between Position.GetUnrealizedProfitLoss before and immediately after the quantity change. You will likely need to add some variables (Quantity, BarsSinceNotFlat, UnrealizedProfitLoss) and fill them On(Each)Bar.Update to make this work. Thx.
    NT-Roland

    Comment


      #3
      Hi mr_trade, thanks for your post.

      You should override OnExecutionUpdate to track partially filled orders. On every scale-out you will get a call to OnExecutionUpdate. From there you can keep a tally of what has been filled.

      Please let me know if I can assist any further with this item.
      Chris L.NinjaTrader Customer Service

      Comment


        #4
        Originally posted by NT-Roland View Post
        The outcome of the last scaling should be the difference between Position.GetUnrealizedProfitLoss before and immediately after the quantity change. You will likely need to add some variables (Quantity, BarsSinceNotFlat, UnrealizedProfitLoss) and fill them On(Each)Bar.Update to make this work. Thx.
        NT-Roland
        Thanks for the pointers NT-Roland, I was going down this route but thought surely an easier way of tracking these as its already tracked in the strategy analyser.

        Hi ChrisL,
        Thanks for your reply. When you say..
        You should override
        OnExecutionUpdate
        to track partially filled orders.
        Does this mean I need to use the order object in the unmanaged approach? As I tried to avoid going down that route and simply use EnterLong ExitLong for quickness?

        Comment


          #5
          Hi, I have had some success playing with the above code within OnExecutionUpdate, I can now see my partial closes being recognised and adding up to the backtest Balance.
          However as you can see by the attached screenshots I am still missing the "Close Position" previous trade Profit/Loss. Am I missing something here?

          This is the current code I have:

          Code:
          protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                  {
                      if (IsBackTest)
                      {
                          if (entryOrder == null && execution.Order.OrderState == OrderState.Filled)// || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                          {
                              // Check to make sure there is at least one trade in the collection
                              if (SystemPerformance.AllTrades.Count > 0)
                              {
                                  // Get the last completed real-time trade (at index 0)
                                  Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
          
                                  // Calculate the PnL for the last completed real-time trade
                                  double lastProfit = lastTrade.ProfitCurrency;
          
                                  xAccountSize = xAccountSize + lastProfit;
                                  Print("The last trade's profit/loss is " + (double)Math.Round(lastProfit, 2));
                                  Print("New Account Balance " + (double)Math.Round(xAccountSize, 2)); //Prints Account Size
                              }
                          }
                       }
                   }
          Am I missing something really simple here to get the closed position to display?
          Attached Files

          Comment


            #6
            Hi mr_trade, thanks for your reply.

            I can not tell why you're not seeing that signal from the code posted. Try identifying the order by its signal name. Checking if(execution.Name == "Close position") should return something of use to you. Or you can just print out execution.Name and observe the signal names being printed.

            If this does not resolve your inquiry I will be happy to take a look at your script.

            Best regards.
            Chris L.NinjaTrader Customer Service

            Comment


              #7
              Thanks ChrisL,

              Yes your right that worked! So I am capturing each position close profit/loss using OnPositionUpdate….
              Code:
              protected override void OnPositionUpdate(Cbi.Position position, double averagePrice, int quantity, Cbi.MarketPosition marketPosition)
                {
              
                 if (IsBackTest)
                          {
                  //Each Position Profit/Loss is added to the backtesting balance to calculate the new position size based on capital
                              if (position.MarketPosition == MarketPosition.Flat)
                              {
                                  // Check to make sure there is at least one trade in the collection
                                  if (SystemPerformance.AllTrades.Count > 0)
                                  {
                                      // Get the last completed real-time trade (at index 0)
                                      Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
              
                                      // Calculate the PnL for the last completed real-time trade
                                      double lastProfit = lastTrade.ProfitCurrency;
              
                                      xAccountSize = xAccountSize + lastProfit;
                                      Print("The last trade's profit/loss is " + (double)Math.Round(lastProfit, 2));
                                      Print("New Account Balance " + (double)Math.Round(xAccountSize, 2)); //Prints Account Size
                                  }
                              }
                          }
                }
              and then adding the missing partial Profits using the exit names within OnExecutionUpdate….

              Code:
              if (IsBackTest)
                          {
                  //Each Position Profit/Loss is added to the backtesting balance to calculate the new position size based on capital
                              if (execution.Name == "LE TP1" && execution.Order.OrderState == OrderState.Filled)
                              {
                                  // Check to make sure there is at least one trade in the collection
                                  if (SystemPerformance.AllTrades.Count > 0)
                                  {
                                      // Get the last completed real-time trade (at index 0)
                                      Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
              
                                      // Calculate the PnL for the last completed real-time trade
                                      double lastProfit = lastTrade.ProfitCurrency;
              
                                      xAccountSize = xAccountSize + lastProfit;
                                      Print("The last trade's profit/loss is " + (double)Math.Round(lastProfit, 2));
                                      Print("New Account Balance " + (double)Math.Round(xAccountSize, 2)); //Prints Account Size
                                  }
                              }
                          }
              [LEFT][COLOR=#252C2F][FONT=Helvetica][SIZE=13px][/SIZE][/FONT][/COLOR][/LEFT]

              Seems a bit strange doing this in 2 places, but it works!

              Thanks for the pointer

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by yertle, Today, 08:38 AM
              5 responses
              14 views
              0 likes
              Last Post NinjaTrader_BrandonH  
              Started by frankthearm, Today, 09:08 AM
              2 responses
              5 views
              0 likes
              Last Post NinjaTrader_Clayton  
              Started by adeelshahzad, Today, 03:54 AM
              3 responses
              16 views
              0 likes
              Last Post NinjaTrader_BrandonH  
              Started by bill2023, Yesterday, 08:51 AM
              6 responses
              27 views
              0 likes
              Last Post NinjaTrader_Erick  
              Started by NinjaTrader_ChelseaB, 01-08-2017, 06:59 PM
              80 responses
              19,667 views
              5 likes
              Last Post NinjaTrader_ChelseaB  
              Working...
              X