Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Daily loss limit examples

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

    #76
    Hi!

    I'm using this to check the profit, but for any reason I disable the strategy and it resets. How can I solve this problem?

    SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit

    Comment


      #77
      Hello claudiorrb21,

      This is expected. The SystemPerformance collection holds all trades, historical and real-time, submitted by the strategy since it was enabled.

      When the strategy is disabled and re-enabled, the strategy recalculates the historical data and trades.

      If you need the strategy to remember something, you would need to write and read that from a text file.

      Chelsea B.NinjaTrader Customer Service

      Comment


        #78
        I have tested this script several times and it behaves as expected. However, when incorporating into my own strategy, it does not work and I cannot figure out for the life of me why not. I've added several prints to debug, and it seems like it doesn't reset the currentPnL to 0 at the proper time. Basically, it will close a trade and draw the correct text on the chart, and then the next time entry conditions are met it will enter again. I have triple checked that I have cut and pasted all the neccessary language from this script. Any advice would be greatly appreciated. Thanks.

        Comment


          #79
          Hello zrobfrank,

          In the DailyLossLimitExample the currentPnL variable is reset on the first bar of a new session on lines 53-54.

          Is your script also resetting this variable on the first bar of a new session?

          What code is in your script?
          Chelsea B.NinjaTrader Customer Service

          Comment


            #80
            I've included a stripped down version of the script below.

            Code:
            
            
            private double currentPnL;
            
            protected override void OnStateChange()
            
            {
            
            if (State == State.SetDefaults)
            
            {
            
            Description = @"Enter the description for your new custom Strategy here.";
            
            Name = "zzzzzzzzzzzzrandom2";
            
            Calculate = Calculate.OnEachTick;
            
            EntriesPerDirection = 3;
            
            EntryHandling = EntryHandling.AllEntries;
            
            IsExitOnSessionCloseStrategy = true;
            
            ExitOnSessionCloseSeconds = 30;
            
            IsFillLimitOnTouch = false;
            
            MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
            
            OrderFillResolution       = OrderFillResolution.Standard;              
            
                // OrderFillResolutionType   = BarsPeriodType.Tick;
            
                // OrderFillResolutionValue  = 1;      
            
            Slippage = 1;
            
            StartBehavior = StartBehavior.WaitUntilFlatSynchronizeAccount;
            
            IsAdoptAccountPositionAware = true;
            
            IncludeCommission = true;
            
            TimeInForce = TimeInForce.Day;
            
            TraceOrders = true;
            
            RealtimeErrorHandling = RealtimeErrorHandling.StopCancelCloseIgnoreRejects;
            
            StopTargetHandling = StopTargetHandling.ByStrategyPosition;
            
            BarsRequiredToTrade = 20;
            
            // Disable this property for performance gains in Strategy Analyzer optimizations
            
            // See the Help Guide for additional information
            
            IsInstantiatedOnEachOptimizationIteration = true;
            
            
            
            
            
            
            
            LossLimit = 300;
            
            ProfitLimit = 12000;
            
            
            
            
            
            }
            
            else if (State == State.Configure)
            
            {
            
            AddDataSeries(Data.BarsPeriodType.Tick, 20);
            
            
            }
            
            else if (State == State.DataLoaded)
            
            {
            
            
            
            ClearOutputWindow();
            
            
            
            
            
            }
            
            }
            
            
            
            
            
            
            protected override void OnBarUpdate()
            
            {
            
            if (CurrentBars[0] < 20 )
            
                            return;
            
            
            
            // at the start of a new session, reset the currentPnL for a new day of trading
            
            if (Bars.IsFirstBarOfSession && BarsInProgress == 0)
            
            currentPnL = 0;
            
            
            
            
            
            
            
            
            
            if(BarsInProgress == 0 && IsFirstTickOfBar == true)
            
            
            
            
            
            {
            
            
            
            
            SetProfitTarget("Long", CalculationMode.Ticks, 20, false);
            
            SetProfitTarget("Short", CalculationMode.Ticks, 20, false);
            
            
            
            }
            
            
            
            
            
            
            
            #region Time
            
            // Time
            
            if (((ToTime(Time[0]) >= 125900
            
            && ToTime(Time[0]) < 150000))
            
            && (Position.MarketPosition != MarketPosition.Flat))
            
            //&& BarsInProgress == 0)
            
            {
            
            if (Position.MarketPosition == MarketPosition.Long)
            
            {
            
            ExitLong(0, Position.Quantity, "time", "");
            
            }
            
            else if (Position.MarketPosition == MarketPosition.Short)
            
            {
            
            ExitShort(0, Position.Quantity, "time", "");
            
            }
            
            }
            
            #endregion
            
            
            
            
            
            if ( ( (ToTime(Time[0]) > 50000
            
            
            
            && ToTime(Time[0]) < 93000))
            
            
            && Position.Quantity < 3
            
            
            && currentPnL > -LossLimit
            
            && currentPnL < ProfitLimit
            
            && BarsInProgress == 0
            
            
            
            &&  (BarsSinceEntryExecution(0, "Long", 0) > 5 || BarsSinceEntryExecution(0, "Long", 0) == -1))
            
            
            {
            
            
            
            if(
            
             Close[1] > Open[1]
            
            )
            
            
            
            {
            
            EnterLong(1,Convert.ToInt32(DefaultQuantity),"Long");
            Draw.Diamond(this, "tag1" + CurrentBar, true, 0, Low[0] - TickSize, Brushes.Green);
            
            Print(currentPnL);
            
            }
            
            
            
            }
            
            
            
            if (Position.MarketPosition == MarketPosition.Long
            
            && (currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0])) <= -LossLimit)
            
            {
            
            //Print((currentPnL+Position.GetProfitLoss(Close[0], PerformanceUnit.Currency)) + " - " + -LossLimit);
            
            // print to the output window if the daily limit is hit in the middle of a trade
            
            Print("daily limit hit, exiting order " + Time[0].ToString());
            
            Print(currentPnL);
            
             ExitLong("Daily Limit Exit", "Long");
            
            }
            
            if (Position.Quantity > 1
            
            && BarsInProgress == 0
            
            && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) > 0
            
            && Close[0] < Open[0]
            
            && Close[1] < Open[1]
            
            )
            
            {
            
            ExitLong("Long");
            
            }
            
            
            
            if ( ( (ToTime(Time[0]) > 50000
            
            
            
            && ToTime(Time[0]) < 93000))
            
            
            && Position.Quantity < 3
            
            && currentPnL > -LossLimit
            
            && currentPnL < ProfitLimit
            
            && BarsInProgress == 0
            
            &&  (BarsSinceEntryExecution(0, "Short", 0) > 5 || BarsSinceEntryExecution(0, "Short", 0) == -1))
            
            
            {
            
            
            
            if( Close[1] < Open[1]
            
            
            
            
            
            
            
            )
            
            
            
            {
            
            // SetStopLoss("Long", CalculationMode.Price, Low[2] - .5, false);
            
            // EnterShortStopLimit(0,false, Convert.ToInt32(DefaultQuantity) , Low[0] + (5 * TickSize),  Low[0] + (2 * TickSize), "Short");
            
            EnterShort(1,Convert.ToInt32(DefaultQuantity),"Short");
            
            // entryOrder = EnterLong(Convert.ToInt32(Quant),"Long");
            
            // Draw.Diamond(this,"tag" + CurrentBar, true, 0, High[0] + TickSize, Brushes.Red);
            
            
            
            }
            
            
            
            }
            
            
            
            if (Position.MarketPosition == MarketPosition.Short
            
            && (currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0])) <= -LossLimit)
            
            {
            
            //Print((currentPnL+Position.GetProfitLoss(Close[0], PerformanceUnit.Currency)) + " - " + -LossLimit);
            
            // print to the output window if the daily limit is hit in the middle of a trade
            
            Print("daily limit hit, exiting order " + Time[0].ToString());
            
            Print(currentPnL);
            
            LongTradeSwitch = false;
            
            ShortTradeSwitch = false;
            
            // ExitShort("Daily Limit Exit", "Short");
            
            }
            
            
            
            if (Position.Quantity > 1
            
            && BarsInProgress == 0
            
            && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) > 0
            
            && Close[0] > Open[0]
            
            && Close[1] > Open[1]
            
            )
            
            {
            
            ExitShort("Short");
            
            }
            
            
            
            
            
            }
            
            
            
            protected override void OnPositionUpdate(Position position, double averagePrice, int quantity, MarketPosition marketPosition)
            
            {
            
            if (SystemPerformance.AllTrades.Count > 0)
            
            {
            
            // when a position is closed, add the last trade's Profit to the currentPnL
            
            currentPnL += SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency;
            
            
            
            
            // print to output window if the daily limit is hit
            
            if (currentPnL <= -LossLimit)
            
            {
            
            Print("daily limit hit, no new orders" + Time[0].ToString());
            
            Print(currentPnL);
            
            }
            
            }
            
            }
            ​

            Comment


              #81
              Hello zrobfrank,

              How do you know this variable is not being reset when the primary series is the first bar of a new session?

              Print the bar time and the value of this variable after resetting it to confirm when and if it is being reset.


              Save the output to a text file (right-click the output window select Save as) and attach this to your next post.
              Chelsea B.NinjaTrader Customer Service

              Comment


                #82
                ChelseaB,
                Thank you for your help, and sorry it took a bit to get back to you. What I found through using prints was that it was resetting the currentPnL constantly, and through trial and error I figured out that even thought the script was copied exactly from the example, adding braces {} around "currentPnL = 0" seemed to solve that problem. I have attached a text as you suggested in the previous post, because I noticed that on 3/19 for example, the currentPnL was definitely reset to 0, but a trade was exited right after entry because it appeared to be adding the unrealized PL to the previous currentPnL. Let me know you thoughts for fixing that. Thanks.

                Rob​ NinjaScript Output 4_21_2024 1_31 PM.txt

                Comment


                  #83
                  ChelseaB,

                  Scratch that last reply. I realized that while tinkering with the script I had removed the Marketposition.Flat criteria for adding the last trade to the currentPnL, and so as soon as a trade was entered it was adding the last trade's PL. Sorry about that. Thanks again for the help.
                  Rob

                  Comment


                    #84
                    Originally posted by NinjaTrader_Jim View Post
                    Hello Trader17,

                    OnBarUpdate is a data processing that we regularly use for NinjaScripts. It is controlled by the Calculate setting.

                    When Calculate is set to OnEachTick or OnPriceChange, the developing bar (BarsAgo 0 I.E. Close[0]) will constantly be updated in OnBarUpdate with each new tick or price change.

                    When Calculate is set to OnBarClose, the developing bar will not update on each tick/price change, and we will be working with the bar that had just closed instead of the developing bar.

                    In other words, when using Calculate.OnBarClose, Close[0] will update only when a bar closes. With OnEachTick/OnPriceChange, Close[0] will update with each tick or price change.

                    Calculating on bar closes can be done with Calculate.OnEachTick/OnPriceChange if you add a check for IsFirstTick of bar and use BarsAgo 1 references within that block.

                    I encourage you to test the Help Guide example code with prints to observe how OnBarUpdate works using different Calculate modes.

                    Demo - https://drive.google.com/file/d/1KdV...w?usp=drivesdk

                    Please let me know if you have any additional questions.
                    Is it possible to Change the Calculate setting from OnBarClose to OnPriceChange (and vice-versa) on the fly?
                    For example, initially set it to OnBarClose, then when a trade is opened change to OnPriceChange. Then when the trade is complete/closed revert back to OnBarClose.
                    And then do a check like if Calculate == OnBarClose do X, else if Calculate == OnPriceChange do Y
                    Though, this might not be the way to go...

                    The reason I ask is my current Strategy's code is built on OnBarClose. But, I only need OnPriceChange when in a trade, to see if I need to Flatten ALL open orders (across ALL symbols on an account) the moment Max Account Profit, Max Daily Profit, Max Account Loss or Max Daily Loss is hit. And flag a variable to stop trading for the day.

                    Basically, if I have a few charts open with different symbols and the Strategy running on each - if the Account Max's are hit on any one of these charts - Flatten ALL open orders on the Account, and stop trading for the Account.

                    How would you recommend accomplishing this?
                    Last edited by Trader4Life; 10-24-2024, 11:21 PM.

                    Comment


                      #85
                      Hello Trader4Life,

                      Unfortunately no, it is not supported to change the Calculate setting after the script is running. This should be set in State.Configure or State.SetDefaults only.

                      You can however, evaluate the logic only when the bar closes when not in a trade by returning from a condition that checks IsFirstTickOfBar.


                      You can use <Account>.Flatten() to flatten an account.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #86
                        Originally posted by NinjaTrader_ChelseaB View Post
                        Hello Trader4Life,

                        Unfortunately no, it is not supported to change the Calculate setting after the script is running. This should be set in State.Configure or State.SetDefaults only.

                        You can however, evaluate the logic only when the bar closes when not in a trade by returning from a condition that checks IsFirstTickOfBar.


                        You can use <Account>.Flatten() to flatten an account.
                        https://ninjatrader.com/support/help...t8/flatten.htm
                        Thanks, Chelsea!
                        I could work around it, then.

                        Looking at the Flatten Link you sent me, it seems it only closes based on Symbol.
                        How would I Flatten ALL open positions across 1 account? If Flatten only works by symbol, then how do I gather all the symbols with open positions for an account?

                        Comment


                          #87
                          Hello Trader4Life,

                          You would need to make an array of instrument symbols that have a position open.

                          The <Account>.Positions collection holds the positions.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #88
                            Originally posted by NinjaTrader_ChelseaB View Post
                            Hello Trader4Life,

                            You would need to make an array of instrument symbols that have a position open.

                            The <Account>.Positions collection holds the positions.
                            https://ninjatrader.com/support/help...ns_account.htm
                            Perfect, thanks!!!!
                            I'll check it out this weekend

                            Comment


                              #89
                              Hello Trader4Life,

                              I noted shorthand for this I've mentioned on another thread on the forum.
                              Chelsea B.NinjaTrader Customer Service

                              Comment


                                #90
                                I downloaded and imported this to test but after I enable it ( using bar close), this bot is not taking any trades. Is there a way to automate this?

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                                0 responses
                                624 views
                                0 likes
                                Last Post Geovanny Suaza  
                                Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                                0 responses
                                359 views
                                1 like
                                Last Post Geovanny Suaza  
                                Started by Mindset, 02-09-2026, 11:44 AM
                                0 responses
                                105 views
                                0 likes
                                Last Post Mindset
                                by Mindset
                                 
                                Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                                0 responses
                                562 views
                                1 like
                                Last Post Geovanny Suaza  
                                Started by RFrosty, 01-28-2026, 06:49 PM
                                0 responses
                                567 views
                                1 like
                                Last Post RFrosty
                                by RFrosty
                                 
                                Working...
                                X