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

Sample for Primary Instrument Realized and Unrealized Profit for Day

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

    Sample for Primary Instrument Realized and Unrealized Profit for Day

    I've searched throughout the forum looking for a code sample that includes only the instrument that the strategy is running on which includes both realized profit and unrealized profit for the current day only. Is there a sample out there?

    Thanks!

    #2
    Hello AgriTrdr,

    I am not aware of a sample that combines both but you can see two examples from the help guide.

    This is how to work with realized PnL in a strategy: https://ninjatrader.com/support/help...nce_statis.htm

    This is how you can get an open positions PnL in a strategy: https://ninjatrader.com/support/help...profitloss.htm

    If you were to use the unrealized PnL code inside the example realized PnL strategy you could reference both realized and unrealized values. Depending on how you wanted to use the values you would form a condition with each of the PnL variables.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Here's what I've done with Prints. On the first bar under CurrentPL is showing at 0. After first trade exits the Total PL shown above is different than the Current PL when the numbers should be the same or relatively close if we factor the commission difference.

      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class CurrentPL : Strategy
      {
      private double Accumulated = 0;
      private double UnrealizedPL;
      private double RealizedProfit;
      private double CurrentPL;
      private double ProfitLoss;

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Strategy here.";
      Name = "CurrentPL";
      Calculate = Calculate.OnBarClose;
      EntriesPerDirection = 3;
      EntryHandling = EntryHandling.AllEntries;
      IsExitOnSessionCloseStrategy = true;
      ExitOnSessionCloseSeconds = 30;
      IsFillLimitOnTouch = false;
      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
      OrderFillResolution = OrderFillResolution.Standard;
      Slippage = 0;
      StartBehavior = StartBehavior.WaitUntilFlat;
      TimeInForce = TimeInForce.Gtc;
      TraceOrders = false;
      RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
      StopTargetHandling = StopTargetHandling.PerEntryExecution;
      BarsRequiredToTrade = 20;
      // Disable this property for performance gains in Strategy Analyzer optimizations
      // See the Help Guide for additional information
      IsInstantiatedOnEachOptimizationIteration = true;
      IsInstantiatedOnEachOptimizationIteration = true;
      }
      else if (State == State.Configure)
      {
      }
      else if (State == State.DataLoaded)
      {
      }

      protected override void OnBarUpdate()
      {
      ProfitLoss = StopLoss*1.25*EntriesPerDirection*2.00;

      RealizedProfit = SystemPerformance.RealTimeTrades.TradesPerformance .Curr ency.CumProfit - Accumulated;

      UnrealizedPL = PositionAccount.GetUnrealizedProfitLoss(Performanc eUnit.Currency, Close[0]);

      CurrentPL = RealizedProfit + UnrealizedPL;

      // Reset the tradeCounter value at the first tick of the first bar of each session.
      if (Bars.IsFirstBarOfSession)
      {
      Print(Instrument.FullName + "|" + "ProfitLoss:" + "|" + ProfitLoss);
      Print(Instrument.FullName + "|" + "CurrentPL:" + "|" + CurrentPL);
      Accumulated = SystemPerformance.RealTimeTrades.TradesPerformance .Currency.CumProfit;
      }​​
      Attached Files
      Last edited by AgriTrdr; 09-29-2022, 09:51 AM.

      Comment


        #4
        Hello AgriTrdr,

        I would suggest to use the help guide sample that I linked as a starting point for the realized PnL. What you have provided would not reset correctly to start at 0. The sample I linked to is set up to work for multiple days and reset at the beginning of the session.

        That is specifically done by subtracting the previous sessions profit:

        SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit - priorTradesCumProfit

        JesseNinjaTrader Customer Service

        Comment


          #5
          I've changed to below to say AllTrades instead RealTimeTrades, and it still doesn't add up.

          SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit - priorTradesCumProfit

          Comment


            #6
            Hello AgriTrdr,

            If you use the sample from the help guide you won't need to debug the code you provided, its already set up to do what you wanted to do. In the code you provided you are not doing the reset correctly or how the one in the help guide does it, without doing it that way the result wont be 0.

            JesseNinjaTrader Customer Service

            Comment


              #7
              If I use the below for realised, I would still need to calculate UnrealizedPL by the following right?

              UnrealizedPL = PositionAccount.GetUnrealizedProfitLoss(Performanc eUnit.Currency, Close[0]);

              RealizedPL = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit - priorTradesCumProfit;

              Comment


                #8
                Hello AgriTrdr,

                Here is what the help guide sample shows and what is suggested for how you control the variable used for PnL:


                Code:
                private int priorTradesCount = 0;
                private double priorTradesCumProfit = 0;​
                
                protected override void OnBarUpdate()
                {
                    if (CurrentBar < BarsRequiredToTrade) return;
                   // At the start of a new session
                   if (Bars.IsFirstBarOfSession)
                   {
                      // Store the strategy's prior cumulated realized profit and number of trades
                      priorTradesCount = SystemPerformance.AllTrades.Count;
                      priorTradesCumProfit = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
                
                      /* NOTE: Using .AllTrades will include both historical virtual trades as well as real-time trades.
                      If you want to only count profits from real-time trades please use .RealtimeTrades. */
                   }
                
                /* Prevents further trading if the current session's realized profit exceeds $1000 or if realized losses exceed $400.
                Also prevent trading if 10 trades have already been made in this session. */
                if (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - priorTradesCumProfit >= 1000
                || SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - priorTradesCumProfit <= -400
                || SystemPerformance.AllTrades.Count - priorTradesCount > 10)
                {
                
                      return;
                   }
                
                   // ENTRY CONDITION: If current close is greater than previous close, enter long
                   if (Close[0] > Close[1])
                   {
                      EnterLong();
                   }
                }

                The first bar of the session the priorTradesCumProfit is set. After that point you subtract that amount from the current PnL. You need to have the condition set up before the use like shown here.

                To get the zeroed out Pnl you would Print(SystemPerformance.AllTrades.TradesPerformanc e.Currency.CumProfit - priorTradesCumProfit)
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  Thanks for the above links. I was testing it on Playback and it wasn't working, but it's working in Real Time. If I'm in a trade, and I want to get Unrealized PL, which option below would be the correct way:

                  1. Position.GetUnrealizedProfitLoss(PerformanceUnit.P oints, Close[0]);
                  2. SystemPerformance.RealTimeTrades.TradesPerformance .Currency.CumProfit;

                  Comment


                    #10
                    Hello AgriTrdr,

                    When you are in a trade you have a Position, you need to use the Position object and its method GetUnrealizedProfitLoss to get the unrealized profit or loss. Realized PnL is when you have closed the trade which is what the sample I provided in post 8.

                    JesseNinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by chbruno, Today, 04:10 PM
                    0 responses
                    3 views
                    0 likes
                    Last Post chbruno
                    by chbruno
                     
                    Started by josh18955, 03-25-2023, 11:16 AM
                    6 responses
                    436 views
                    0 likes
                    Last Post Delerium  
                    Started by FAQtrader, Today, 03:35 PM
                    0 responses
                    6 views
                    0 likes
                    Last Post FAQtrader  
                    Started by rocketman7, Today, 09:41 AM
                    5 responses
                    19 views
                    0 likes
                    Last Post NinjaTrader_Jesse  
                    Started by frslvr, 04-11-2024, 07:26 AM
                    9 responses
                    127 views
                    1 like
                    Last Post caryc123  
                    Working...
                    X