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 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

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by aligator, 01-06-2022, 12:14 PM
                  2 responses
                  225 views
                  0 likes
                  Last Post john_44573  
                  Started by dmking, 11-12-2019, 12:31 PM
                  4 responses
                  4,140 views
                  0 likes
                  Last Post jasonw
                  by jasonw
                   
                  Started by roblogic, Today, 04:31 PM
                  0 responses
                  10 views
                  0 likes
                  Last Post roblogic  
                  Started by morrnel, 05-12-2024, 06:07 PM
                  4 responses
                  57 views
                  0 likes
                  Last Post NinjaTrader_Manfred  
                  Started by xepher101, 05-10-2024, 12:19 PM
                  6 responses
                  74 views
                  0 likes
                  Last Post xepher101  
                  Working...
                  X