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

Daily Total PnL

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

    Daily Total PnL

    Hi everyone

    I have a strategy running all week
    I want to get the total PnL of each day, the total PnL from 00:00 CT of each day. not including the PnL from the days before.

    How can I get that so I configure my daily loss limit when the daily Total PnL reach a certain amount, I exit the trade

    #2
    Create your own variable to hold the total pnl at midnight. The daily pnl would then be the difference between the total pnl and the variable that was set at midnight.

    Comment


      #3
      Originally posted by Tasker-182 View Post
      Create your own variable to hold the total pnl at midnight. The daily pnl would then be the difference between the total pnl and the variable that was set at midnight.
      Hello Tasker-182 Thanks for the reply,
      Would you care to give a code example for what you proposed. I tried doing it myself but I couldn't know how to start coding this idea.
      I would really appreciate it

      Comment


        #4
        To help you learn this, start with the help guide. If you don't want to learn then hire a coder.

        To find the total strategy PNL: https://ninjatrader.com/support/help...?cumprofit.htm

        Using that example assign the value of the total PNL to a double type variable that you would create.

        To execute the code at midnight you would need to compare the current bars date to the previous bars date, like this:

        if (Time[0].Day != Time[1].Day)
        {
        // do something here
        }

        The statement says if the current day is not equal to the previous bar day then we must be a new day which only happens at midnight. There are other ways to do this but this is the simplest example.

        Hopefully there are enough clues to help you out. The best thing you can do is to print out values to ensure what you are seeing what you are expecting.

        Comment


          #5
          Hello onlinebusiness,

          Thanks for your post.

          Tasker-182 is correct. You could create a Time comparison in your script to check if the current day is not equal to the previous day and assign the cumulative profit TradePerformance value from the SystemPerformance.AllTrades collection to a double variable. That variable could then be used for other conditions and actions later in the script.

          See this help guide page for information about accessing the cumulative profit value from the SystemPerformance.AllTrades collection: https://ninjatrader.com/support/help.../cumprofit.htm

          See this help guide page about Time: https://ninjatrader.com/support/help...eries_time.htm

          Please let me know if I may assist further.
          Brandon H.NinjaTrader Customer Service

          Comment


            #6
            Hello NinjaTrader_BrandonH
            Thanks for the reply

            So this what I tried to do so far:

            Code:
            if (Time[0].Day != Time[1].Day)
               {
               DayPnL = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit, Close[0]);
               }
            
            if ( SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DayPnL[0] <= StopLoss)
               {
               ExitLong(5,"Stop Loss" ,"Long");
               }
            I don't think it's going to work like this, but can you check it out and tell me if I need to add anything to it please

            Comment


              #7
              Hello onlinebusiness,

              Thanks for your note.

              You could use SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit as seen in the help guide page example code instead of your current syntax.

              To assign the Cumulative Profit TradesPerformance value from the SystemPerformance.AllTrades collection to a double variable and use it in a condition the syntax would look something like this.

              Code:
              //class-level variable
              private double DayPnL;
              
              //OnBarUpdate method
              if (Time[0].Day != Time[1].Day)
              {
                  DayPnL = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
              }
              
              if (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DayPnL <= StopLoss)
              {
                  //do something here
              }​
              Note that you must ultimately test you code to determine if it will function as you expect. If it does not, you would need to debug the script to determine why it is not behaving as expected.

              Below is a link to a forum post that demonstrates how to use prints to understand behavior.

              https://ninjatrader.com/support/foru...121#post791121

              Let us know if we may assist further.​
              Brandon H.NinjaTrader Customer Service

              Comment


                #8
                Hi NinjaTrader_BrandonH

                So this is what I did so far:
                Code:
                //This namespace holds Strategies in this folder and is required. Do not change it.
                namespace NinjaTrader.NinjaScript.Strategies
                {
                    public class DailyLossStrategy : Strategy
                    {
                        protected override void OnStateChange()
                        {
                            if (State == State.SetDefaults)
                            {
                                Description                                    = @"Enter the description for your new custom Strategy here.";
                                Name                                        = "DailyLosstrategy";
                                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;
                                MaxLoss                                        = -1000;
                            }
                            else if (State == State.Configure)
                            {
                            }
                        }
                        private double DayPnL;
                
                        protected override void OnBarUpdate()
                        {
                            if (Time[0].Day != Time[1].Day)
                            {
                                DayPnL = Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]);
                                  Print(SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit);
                            }
                        }
                
                        private void PnL()
                            {    
                            if (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DayPnL <= MaxLoss)
                
                                Account.FlattenEverything();
                            }
                
                        #region Properties
                        [NinjaScriptProperty]
                        [Range(-9999, double.MaxValue)]
                        [Display(Name="MaxLoss", Description="Max Loss By Trade", Order=1, GroupName="Parameters")]
                        public double MaxLoss
                        { get; set; }
                        #endregion
                    }
                }​
                When I enable this strategy to the chart and click apply, it get disabled instantly. I am sure something is wrong but I don't know what is it.

                Could you please take a look and tell me what I am doing wrong?

                Also if you see anything you would do better, feel free to edit it.

                Thank you

                Comment


                  #9
                  Hello onlinebusiness,

                  Thanks for your note.

                  Generally, when a script is automatically disabled after it has been enabled this indicates there is an error in your code.

                  Do you see any errors pop up on the screen? Do you see any errors occurring in the Log tab of the Control Center? If so, what exactly do those errors report?

                  When reviewing your script I see that you have created a private double variable in OnBarUpdate(). This would need to be created as a class-level variable outside of OnBarUpdate() as noted in the example code on post # 7. See the SampleMACrossOver strategy which demonstrates creating class-level SMA variables. You would do something similar in your script, except yours would be 'private double DayPnL' instead of 'private SMA smaFast', for example.

                  To view the SampleMACrossOver strategy that comes default with NinjaTrader, open a New > NinjaScript Editor window, open the Strategies folder, double-click on the SampleMACrossOver file, and note lines 33 and 34. These are considered class-level variables since they are made at the class level.

                  I also see that you are assigning Position.GetUnrealizedProfitLoss to the DayPnL variable but you are printing out SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit. Is this intentional to compare the Position.GetUnrealizedProfitLoss value to the CumulativeProfit TradesPerformance value?

                  Or, are you wanting to assign the CumulativeProfit value to the DayPnL variable as seen in post # 7?

                  Position.GetUnrealizedProfitLoss: https://ninjatrader.com/support/help...profitloss.htm
                  CumulativeProfit: https://ninjatrader.com/support/help.../cumprofit.htm

                  Note that strategies are only able to see positions that they specifically placed, not manually placed orders or orders placed by other strategies.​ This means Position.GetUnrealizedProfitLoss will get the Unrealized PnL value of that specific strategy's position.

                  And, I see that you created a custom method called PnL() but that method is not being called anywhere in the OnBarUpdate() method of your script. If this method is not called in OnBarUpdate() then the method will not fire since it isn't called.

                  Note that when a script is not behaving as expected, you should add debugging prints to the script (outside of the conditions) that print out each value being used so they could be compared in a New > NinjaScript Editor window. This allows you to see how the logic is evaluating and if logic is not being reached.

                  Below is a link to a forum post that demonstrates how to use prints to understand behavior.

                  https://ninjatrader.com/support/foru...121#post791121

                  Please let me know if I may assist further.
                  Last edited by NinjaTrader_BrandonH; 12-12-2022, 11:56 AM.
                  Brandon H.NinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by Segwin, 05-07-2018, 02:15 PM
                  14 responses
                  1,788 views
                  0 likes
                  Last Post aligator  
                  Started by Jimmyk, 01-26-2018, 05:19 AM
                  6 responses
                  837 views
                  0 likes
                  Last Post emuns
                  by emuns
                   
                  Started by jxs_xrj, 01-12-2020, 09:49 AM
                  6 responses
                  3,293 views
                  1 like
                  Last Post jgualdronc  
                  Started by Touch-Ups, Today, 10:36 AM
                  0 responses
                  12 views
                  0 likes
                  Last Post Touch-Ups  
                  Started by geddyisodin, 04-25-2024, 05:20 AM
                  11 responses
                  62 views
                  0 likes
                  Last Post halgo_boulder  
                  Working...
                  X