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

Get Realized PnL

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

    Get Realized PnL

    Hi guys,

    I'm trying to get the actual Realized PnL for today because I need to set a maximum loss per day, so I've doing research and found this line of code:
    SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit

    Which is supposed to be the one to get it but when I print that line is not even close to the number I see on my account, which should match because I'm running the strategy only for that account.
    Any ideas?

    #2
    Hello vcapeluto, thanks for your post and welcome to the NinjaTrader forum.

    The Cumulative Profit you are seeing from the SystemPerformance class is including the virtual historical trades that the strategy completed when it loaded onto a chart. This is why you will see executions on your chart when a strategy is enabled. To get real-world account values, use the Account class:


    We have an existing example on setting a daily loss limit:
    Hello, I've updated the DailyLossLimit and DailyLosLimitMultiTrade examples that were posted on the forum for NinjaTrader 7 for NinjaTrader 8. These are often requested and I felt they are good examples to have for NT8. DailyLossLimitExample_NT7 - http://ninjatrader.com/support/forum...241#post451241 (http://ninjatrader


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

    Comment


      #3
      Hi Chris L.,
      It worked!
      However the commissions and fees are not there right? So I would need to calculate them manually or what?

      Thank you very much!

      Comment


        #4
        Hello vcapeluto, thanks for your reply.

        You must have a Commission Template set up for the account for commission values to reflect on trades, see here for documentation:



        Kind regards.
        Chris L.NinjaTrader Customer Service

        Comment


          #5
          I think maybe the issue is my strategy is on bar close but realized PnL I think has to be calculated per tick?
          So upon bar close it's executing another order perhaps because the variable is both true/false at the same time?
          That said is there maybe a way to have a different strategy set the value for a variable that I can refer to in another strategy?

          Comment


            #6
            Hello Matthew,

            You can use the either of the following:
            • SystemPerformance.AllTrades.TradesPerformance.NetP rofit - Get Net Profit (Overall PnL)
            • Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]) - Get PnL per bar
            Let me know if this was helpful.
            I build useful software systems for financial markets
            Generate automated strategies in NinjaTrader : www.stratgen.io

            Comment


              #7
              woltah231 thank you for that I had to figure out how to unlock code and change that but looks like it's working!
              Question is do I just disable/re-enable the strategy to reset the net profit pnl it's seeing?

              Comment


                #8
                Yeah for some reason it doesn't work if my first trade is a loss that doesn't exceed my max loss amount.
                // Set 2
                if ((SystemPerformance.AllTrades.TradesPerformance.Ne tProfit >= MinProfitPerDay)
                || (SystemPerformance.AllTrades.TradesPerformance.Net Profit <= LossLimitPerDay))
                {
                DailyLimitReached = true;
                }

                With this, my part of my strategy that kicks in will only stop trading after netting more than my MinProfitPerDay.
                However if the first 2 trades are losers, each loss does not go below my LossLimitPerDay but combined they do, it will still make another trade.

                Comment


                  #9
                  Hello MatthewLesko,

                  I believe, for this case, you don't even need to use either SystemPerformance.AllTrades.TradesPerformance.NetP rofit or Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]). You should start calculating your PnL after you enter a position. Here's an example code:

                  Code:
                  public class MyCustomStrategy : Strategy
                  {
                      private int qty = 1;
                      private double enteredPrice = 0;
                  
                      protected override void OnStateChange()
                      {   
                          if (State == State.SetDefaults)
                          {
                              Description = @"Enter the description for your new custom Strategy here.";
                              Name = "MyCustomStrategy";
                              Calculate = Calculate.OnBarClose;
                              EntriesPerDirection = 1;
                              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;
                          }
                          else if (State == State.Configure)
                          {
                          }
                          else if (State == State.DataLoaded)
                          {
                          }
                      }
                  
                      protected override void OnBarUpdate()
                      {
                          double LossLimitPerDay = 2000;
                          double bigPointValue = Bars.Instrument.MasterInstrument.PointValue;
                  
                          // Always make sure that number of bars that have passed are greater than BarsRequiredToTrade
                          if (CurrentBar >= BarsRequiredToTrade)
                          {
                              // NOTE: I'm using CL 1 Day data series that's why I'm using $2000 stop loss and profit.
                              // NOTE: Feel free to change Stop Loss and Profit price
                              EnterLong(qty, "Entered Long");
                  
                              int barsSinceEntry = BarsSinceEntryExecution();
                  
                              // Get entered price
                              if (barsSinceEntry == 0) {
                                  // Get actual price of instrument using big point value
                                  enteredPrice = Position.AveragePrice * bigPointValue;
                              }
                  
                              // Make sure we're in long position
                              if (Position.MarketPosition == MarketPosition.Long)
                              {
                                  // If profit is greater than 2000, exit long.
                                  if (((Close[0] * bigPointValue) - 2000) > enteredPrice)
                                  {
                                      ExitLong(qty, "Exit with Profit", "Entered Long");
                                  }
                  
                                  // If loss is lesser than 2000, exit long
                                  if (((Close[0] * bigPointValue) + LossLimitPerDay) < enteredPrice)
                                  {
                                      ExitLong(qty, "Stop Loss", "Entered Long");
                                  }
                              }
                          }
                      }
                  }
                  In this code, I used CL 1 Day data series so the LossLimitPerDay and Profit Target is big. if (((Close[0] * bigPointValue) - 2000) > enteredPrice), this validation basically checks if the gap of current Close and Entered Price is greater than $2000. The same logic is used for Stop Loss.

                  Let me know if this works for you.
                  I build useful software systems for financial markets
                  Generate automated strategies in NinjaTrader : www.stratgen.io

                  Comment


                    #10
                    Thanks sorry but dO i copy whole code or replace my part with another part?
                    I'm really just trying to get my on bar close strategy to simply stop trading if I've lost more than a certain amount which I would if there were 2 executed trades that lost in a row. Or if I won a certain amount, which i would reach if I had 1 win, or 1 loss and then 1 win right after.

                    Comment


                      #11
                      Ok so I think with what I already is working, it's just that if immediately upon bar close of 2nd trade that is a loser, if the next bar open matches conditions to make a trade, it will still fire off one more trade.
                      however if there's a bar in between my 2nd loss and the next potential bar to execute a trade, it will not fire off since I've reached the loss limit

                      Comment


                        #12
                        Click image for larger version

Name:	mjSs91n[1].png
Views:	931
Size:	55.6 KB
ID:	1210257

                        Comment


                          #13
                          Hello MatthewLesko,

                          We have an example that demonstrates how to stop trading after certain conditions are met. (Linked below.)



                          You will want to ensure that after the condition to stop is met, a bool is set (or you do something similar) so the logic can no longer reach your order submission methods.


                          JimNinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by usazencort, Today, 01:16 AM
                          0 responses
                          1 view
                          0 likes
                          Last Post usazencort  
                          Started by kaywai, 09-01-2023, 08:44 PM
                          5 responses
                          603 views
                          0 likes
                          Last Post NinjaTrader_Jason  
                          Started by xiinteractive, 04-09-2024, 08:08 AM
                          6 responses
                          22 views
                          0 likes
                          Last Post xiinteractive  
                          Started by Pattontje, Yesterday, 02:10 PM
                          2 responses
                          20 views
                          0 likes
                          Last Post Pattontje  
                          Started by flybuzz, 04-21-2024, 04:07 PM
                          17 responses
                          230 views
                          0 likes
                          Last Post TradingLoss  
                          Working...
                          X