Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Reset Max Daily Trade Count Limit

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

    Reset Max Daily Trade Count Limit

    Good morning everyone,

    [I posted this on another post I found about a similar issue but it was outdated without a response so started a new one here. I have searched and saw this issue come up a lot but did not find an exact answer anywhere]


    Request: I am looking to reset the max daily trade count in my ninjascript editor strategy.


    Other Info: The counter itself is working as intended, and limiting to max 3 trades as it should, but in backtest it only shows it for the first day where it encounters this max 3 trades condition.


    Current Script
    I use the following script to attempt to reset:

    bool newDay = Bars.IsFirstBarOfSession;
    if (newDay == true)
    {
    totalTradesToday = 0;
    }​


    Problem: But it does not seem to take. Is this an issue where this function doesn't work in Backtest and Optimization? It seems like it is working properly and printing the correct values. But then it won't reset on a new day

    In summary, my end goal is to limit my script to 3 trades per day. My strategy's biggest losses are when it takes more trades than that per day.

    Sure, I could do this manually. But what I am trying to do is run the Optimization to see the best parameters if I have this max 3 trades per day in place.

    Any help is appreciated.

    Thank you!

    Steve​

    #2
    Hello eleximp224,

    IsFirstBarOfSession works in backests, have you tried using a Print to trace how your logic is working in that situation? It sounds like you are using a counter which would be the correct approach for what you want to do.

    Comment


      #3
      Thank you for your response. I have tried putting the following in my code:

      Print(String.Format("newDay is true on bar {0} with time: {1}", CurrentBar, Time[0]));

      But I am missing where to look for this as the trading day progresses. Where would I see these print outputs?

      Currently, I make edits to my script, save, compile, then run the backtest or optimizer. Then I enable the strategy on the chart when using it.

      Comment


        #4
        Hello eleximp224,

        You can see prints in the control center -> new -> ninjascript output window.

        Comment


          #5
          Thank you.

          This is very helpful. I am following the logic, and it zeroes properly on newDay when appropriate. However, then it reverts totalTradesToday to 4+ which was the value it left off on the previous day.

          This is bizarre. Equally as bizarre is my trade counter is 4.34 when it stopped counting, instead of a whole number like 5.

          newDay is true on bar 92 with time: 1/2/2024 6:15:00 PM
          totalTradesToday = 0 when newDay at time: 1/2/2024 6:15:00 PM
          totalTradesToday = 0 after 15 minute bar close at Time: 1/2/2024 6:15:00 PM
          totalTradesToday = 4.34523809523809 after 15 minute bar close at Time: 1/2/2024 6:30:00 PM


          and remains this way the next day:

          totalTradesToday = 4.34523809523809 after 15 minute bar close at Time: 1/3/2024 9:30:00 AM

          Am I placing the counter in the wrong area?​

          Comment


            #6
            Hello eleximp224,

            Do you have a sample that you can provide that shows where in the code you are resetting the variable and where it is used? I would need to see how your script is structured to get a better idea on that.

            Comment


              #7
              Absolutely. Please see code below. This is an example I am testing on:

              Code:
                      protected override void OnBarUpdate()
                      {
                          if (BarsInProgress != 0)
                              return;
                          
              
                          //double totalTradesToday = 0;
                      
                          //const int MaxTrades = 4;
              
                          
                          double totalTradesToday = SystemPerformance.AllTrades.TradesPerformance.TradesPerDay;
                          double MaxTrades = totalTradesToday + 4;
                          
                          bool newDay = Bars.IsFirstBarOfSession;
                          if (newDay == true)
                          {
                              totalTradesToday = 0;
                              Print(String.Format("newDay is true on bar {0} with time: {1}", CurrentBar, Time[0]));
                              Print(String.Format("totalTradesToday = {0} when newDay at time: {1}", totalTradesToday, Time[0]));
                          }
               
                              
                          //Check if RTH
                          //bool market_reset = ToTime(Time[0]) == 092500;
                          bool market_open = ToTime(Time[0]) >= 093000 && ToTime(Time[0]) <= 154500;
                          //bool market_open = ToTime(Time[0]) >= 110000 && ToTime(Time[0]) <= 150000; //For MA 183 test
                          //bool market_open = ToTime(Time[0]) >= 093000 && ToTime(Time[0]) <= 110000;
                          
                          // Moving Average
                          bool cross_above = CrossAbove(EMA(FastMA), EMA(SlowMA), 1);
                          bool cross_below = CrossBelow(EMA(FastMA), EMA(SlowMA), 1);    
                          
                          Values[0][0] = EMA(FastMA)[0];
                          Values[1][0] = EMA(SlowMA)[0];
                          
                  
                          
                          //Enter Positions
                              
                          if (market_open && (totalTradesToday < 4))
                          {
                              if (Close[0] >= EMA(SlowMA)[0])
                              {
                              EnterLong(Convert.ToInt32(DefaultQuantity), "");
                                  if (Close[0] <= EMA(FastMA)[0])
                                  {
                                      ExitLong();
                                      totalTradesToday = totalTradesToday + 1;
                                  }                    
                              }
                              else if (Close[0] <= EMA(SlowMA)[0])
                              {
                              EnterShort(Convert.ToInt32(DefaultQuantity), "");
                                  if (Close[0] >= EMA(FastMA)[0])
                                  {    
                                      ExitShort();
                                      totalTradesToday = totalTradesToday + 1;
                                  }
                              }
                                  
                          }
                          
                          Print(String.Format("totalTradesToday = {0} after 15 minute bar close at Time: {1}", totalTradesToday, Time[0]));
              
                          
                          //Exit Positions
                          if (!market_open)
                          {
                              
                              ExitLong();
                              ExitShort();
              
                          }
              
                          
                      }​

              Comment


                #8
                Hello eleximp224,

                That may be due to the following line.

                double totalTradesToday = SystemPerformance.AllTrades.TradesPerformance.Trad esPerDay;

                I would suggest printing the value right after this line to see if that is when its reset to 4.

                Comment


                  #9
                  Thank you so much! That helped me figure it out. The counter line was at the wrong part of the trade. It should've been on entry, not exit. Once I fixed that, all works smoothly.

                  Comment


                    #10
                    While on this similar topic, could I tag on an additional question along the same concept?

                    Another I am testing uses a maximum daily loss limit. I am using the following to calculate what I would like to be a daily net profit:

                    Code:
                    double DailyProfit = SystemPerformance.AllTrades.TradesPerformance.NetProfit;
                    However, this variable I am truly struggling to reset. It will not reset like the trade counter above. Is there something different about the SystemPerformance functions? It seems as though it still calculated the cumulative net profit and will not reset back to $0 on each newDay.

                    Any help or guidance is appreciated. Thank you again for all your help,

                    Steve

                    Comment


                      #11
                      Hello eleximp224,

                      You can find a sample that shows how to correctly use that value in the following link. You have to do some math and use a variable to get the current sessions pnl.

                      Comment


                        #12
                        Thank you! This has been very helpful. I figured it out based on OnBarUpdate(). The issue here is the max loss could have gotten much higher by the time a 15m bar closes.

                        Is there a way to calculate this real time so that I can liquidate and close the strategy immediately once it hits my max loss?

                        Here is how I currently have it-- and outputs are functioning properly, but of course only when a bar closes. So it won't open a new trade after if my max loss is hit, but I still may have taken well over the maximum daily loss I wanted to by the time the bar closes:

                        Code:
                                    DailyProfit = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - priorTradesCumProfit;
                                    Print(String.Format("At Time {1} - DailyProfit: {0}", DailyProfit, Time[0],DailyProfit));    
                                    
                                    if (market_open && (DailyProfit >= -1200))
                          //Entry Strategy programmed below
                                    {​
                        Thank you very much

                        Comment


                          #13
                          Hello eleximp224,

                          You can run the strategy OnPriceChange or OnEachTick to get OnBarUpdate called more frequently in real-time. You would otherwise have to add a secondary series and execute code on that more granular series.

                          Comment


                            #14
                            Thank you. I did see that I could run it like that, but I did not find a way to run it backtest or optimizer with that option selected.

                            Would I set up an OnPriceChange strategy to run this line before running my OnBarUpdate strategy?
                            Code:
                            DailyProfit = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - priorTradesCumProfit;

                            Comment


                              #15
                              Hello eleximp224,

                              You can use tick replay to simulate that in a backtest but that does add more resource usage. The playback connection is generally the suggestion for testing OnEachTick or OnPriceChange logic.

                              If some of your logic should execute OnBarClose you can surround that logic with a IsFirstTickOfBar condition.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              63 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              139 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              75 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              45 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              50 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X