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

Unrealized P&L in a backtest

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

    Unrealized P&L in a backtest

    I am trying to backtest a strategy which involves holding certain positions for quite some time (ExitOnClose = false) and would like to see the cumulative PnL. It seems to list only the realized PnL and as a result the the Unrealized PnL lumps up only at the exit of the strategy at the end of the backtest period.


    Please advice.

    Best Regards,

    #2
    Correct, the trade would need to be closed for backtest to consider it then. You can always calculate the open pnl in your OnBarUpdate() for example via this call - https://www.ninjatrader.com/support/...profitloss.htm
    BertrandNinjaTrader Customer Service

    Comment


      #3
      is there an easy way to close the trade and then reopen it at the same price? just to get the unrealized pnl included in the strategy analytics.

      Comment


        #4
        So you mean doing for example and end of day exit and then retaking the trade at next session open if the trade holding would still be valid? That would be certainly doable via custom coding.
        BertrandNinjaTrader Customer Service

        Comment


          #5
          can I also get the realized pnl programmatically?

          Comment


            #6
            Yes, you would have programmatic access to all backtesting stats as well - for example for your realized trades pnl - https://www.ninjatrader.com/support/.../nt7/trade.htm
            BertrandNinjaTrader Customer Service

            Comment


              #7
              I am doing as you suggested and tring to get the PnL through the code:

              Code:
              		void CalcPnL()
              		{
              		    // If not flat print our unrealized PnL
              			
              			double realizedProfit=0;
              			if(Performance.RealtimeTrades.Count > 0)
              			{
              			
              				Print("# of trades "  + Performance.RealtimeTrades.Count);
              				
              				if (Position.MarketPosition != MarketPosition.Flat)
              					Print("Open PnL: " + Position.GetProfitLoss(Close[0], PerformanceUnit.Points));
              
              				foreach(Trade t in Performance.RealtimeTrades)
              				{
              					// Calculate the PnL for the last completed real-time trade
              					realizedProfit += t.ProfitCurrency * t.Quantity;
              				}
              				Print("Realized PnL: " + realizedProfit);
              			}
              
              		}
              I am not seeing any realized pnl tough I am closing trades through the code:

              Code:
              				// Condition set 1
              				if (flowStats.Score[0] > avgFlowstats.UpperbandScore[0] && !upcandleCondition)
              				{
              						if(Position.MarketPosition != MarketPosition.Long)
              						{
              							//Print("enter short "  + (Position.Quantity + 1).ToString());
              							EnterShort(DefaultQuantity, "short" + (Position.Quantity + 1).ToString());
              						}
              						else // long
              						{
              							Print("exitlong" + Position.Quantity.ToString());
              							ExitLong(1, "exitlong" + Position.Quantity.ToString(), "long" + Position.Quantity.ToString());
              						}
              
              				}
              
              				// Condition set 2
              				if (flowStats.Score[0] < avgFlowstats.LowerbandScore[0] && upcandleCondition)
              				{
              						if(Position.MarketPosition != MarketPosition.Short)
              						{
              							//Print("enter long "  + (Position.Quantity + 1).ToString());
              							EnterLong(DefaultQuantity, "long" + (Position.Quantity + 1).ToString());
              						}
              						else // short
              						{
              							Print("exitshort "  + Position.Quantity.ToString());
              							ExitShort(1, "exitshort" + Position.Quantity.ToString(), "short" + Position.Quantity.ToString());
              						}
              				}

              Comment


                #8
                Would this be used for backtesting or realtime time trade monitoring only? As you access the realtime colllection of trades only and not AllTrades which would contain historical + realtime results.
                BertrandNinjaTrader Customer Service

                Comment


                  #9
                  This is for backtesting. should I be using alltrades?

                  Comment


                    #10
                    Yes, as the realtime trades collection would not hold any entries otherwise for you to work with.
                    BertrandNinjaTrader Customer Service

                    Comment


                      #11
                      ok thanks. I want to take certain actions at the begining of a session in my strategy. I tried the code:

                      if (Bars.FirstBarOfSession && CurrentBar > 0)
                      {


                      but doesn't seem to work in the strategy, works in an indicator. please advice.

                      Comment


                        #12
                        Should work in both, what type of chart / interval are you on?
                        BertrandNinjaTrader Customer Service

                        Comment


                          #13
                          Sorry my bad. coding error. thanks

                          Comment


                            #14
                            Can you please recommend the best way to exit all open positions at sessions begining and reenter the same positions at the same price so that I can see all pnl as realized pnl.

                            thanks,

                            Comment


                              #15
                              There would be multiple ways, but of course same price could not be guaranteed here. You would then for example ExitOnClose and set a bool that would flag you want to reenter this trade on the opening of the next session as your longterm exit critieria have not been met. I think that would be the most straightforward approach to it.
                              BertrandNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by elirion, Today, 09:32 PM
                              0 responses
                              5 views
                              0 likes
                              Last Post elirion
                              by elirion
                               
                              Started by cre8able, Today, 09:15 PM
                              1 response
                              7 views
                              0 likes
                              Last Post bltdavid  
                              Started by cummish, Today, 08:43 PM
                              0 responses
                              13 views
                              0 likes
                              Last Post cummish
                              by cummish
                               
                              Started by Option Whisperer, Today, 07:58 PM
                              4 responses
                              21 views
                              0 likes
                              Last Post Option Whisperer  
                              Started by ETFVoyageur, 05-07-2024, 07:05 PM
                              13 responses
                              87 views
                              0 likes
                              Last Post ETFVoyageur  
                              Working...
                              X