Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Trade Limit within Any Hour

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

    Trade Limit within Any Hour

    Hi,

    I've seen posts that will limit the number of trades within the day. Is there a way to limit the number of trades taken within 30 mins or any hour?

    Thanks

    #2
    Hello AgriTrdr,

    Yes that is possible but really depends on your scripts configuration for its data.

    The easiest way to approach this would be to use a secondary series that matches the time you wanted. For example using a secondary series of 30 minutes. That lets you use the primary that you want and then you do resets based on the secondary series IsFirstTickOfBar property. This also would require using OnEachTick processing so you can do multiple actions within that time period.

    A simple example of the way that logic may look would be:

    Code:
    if(BarsInProgress == 0)
    {
        //trade logic and increment counter variable each time the trade is submitted
        //trade condition checks counter variable to make sure its less than the wanted amount
    }
    if(BarsInProgress == 1)
    {
        if(IsFirstTickOfBar)
        {
            //reset the counter variable because 30 minutes has elapsed
        }   
    }




    Comment


      #3
      Hello AgriTrdr,

      It's very possible to limit trade per 30 minutes. Here's an example that could help you out:

      Code:
      public class FewTradesPer30Minutes : Strategy
      {
          // Maximum number of trades per 30 minutes
          private int maxTrades = 3;
      
          // Counts trades per 30 minutes
          private int tradesCount = 0;
      
          protected override void OnStateChange()
          {
              if (State == State.SetDefaults)
              {
                  Description = @"This strategy could only make few trades per 30 minutes.";
                  Name = "FewTradesPer30Minutes";
                  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)
              {
              }
          }
      
          protected override void OnBarUpdate()
          {
              //Add your custom strategy logic here.
              if (CurrentBar >= BarsRequiredToTrade)
              {
      
                  // Supposed we have 1 minute data, we reset tradesCount to 0 every 30 minutes
                  if ((CurrentBar % 30) == 0) {
                      tradesCount = 0;
                  }
      
                  // Enter a position
                  if (tradesCount < maxTrades) {
                      if (Position.MarketPosition != MarketPosition.Long) EnterLong();
                  }
      
                  // Exit a position. Make sure we're in a position.
                  if (Position.MarketPosition == MarketPosition.Long)
                  {
                      ExitLong();
      
                      // Count trades after exiting a position
                      tradesCount++;
                  }
              }
          }
      }
      Supposed that we have 1 minute data. We can reset a variable that counts trades, which is tradesCount, per 30 bars (30 minutes in total). We increment tradesCount whenever we exit a position. if ((CurrentBar % 30) == 0), this validation resets tradesCount to 0 per 30 bar (30 minutes). if (tradesCount < maxTrades), this validation prevents entering a position when we reach the maximum trade within 30 minutes.

      I hope this helps you.
      I build useful software systems for financial markets
      Generate automated strategies in NinjaTrader : www.stratgen.io

      Comment


        #4
        Thank you Jesse and woltah231 for your help!

        Here's what I came up. Do you think this looks ok?

        private int tradeCounter = 0;
        private int maxTrades;

        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        Description = @"Enter the description for your new custom Strategy here.";
        Name = "CurrentDayOpen2";
        Calculate = Calculate.OnBarClose;
        EntriesPerDirection = 3;
        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;

        MaxTrades = 2;

        }

        else if (State == State.Configure)
        {
        AddDataSeries(Data.BarsPeriodType.Minute, 30);
        AddDataSeries(Data.BarsPeriodType.Tick, 1);
        }

        protected override void OnBarUpdate()
        {
        if (CurrentBar < BarsRequiredToTrade || CurrentBars[0] < 60 || CurrentBars[1] < 1 || CurrentBars[2] < 1)
        return;

        if ((Bars.IsFirstBarOfSession) || ((BarsInProgress == 1) && IsFirstTickOfBar))
        {
        Print("resetting tradeCounter");
        tradeCounter = 0;
        }

        if ((tradeCounter < MaxTrades) && (BarsInProgress == 0))
        {
        if (Close[0] > CurrentDayOHL1.CurrentOpen[0])
        EnterLong();
        tradeCounter++;
        }

        Comment


          #5
          Hello AgriTrdr,

          The provided code seems to reflect what has been described in this post, to make sure that it works as expected you need to run that code. The only item that I see is that you are adding a 1 tick series but this part of the code does not use that series. If you have other code that makes use of that series then it seems you have taken the information from this thread.

          The script as is would have BarsInProgress 0 meaning the primary and BarsInProgress 1 for the reset or the 30 minute. The 1 tick could also be used as BarsInProgress 2.

          Comment


            #6
            Good evening,

            Can you screenshot using the strategy builder?

            Comment


              #7
              Hello conniejforextrader,

              This type of code would need to be done in manual coding, you cannot execute code from any other bars in progress in the strategy builder.

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by NullPointStrategies, Today, 05:17 AM
              0 responses
              50 views
              0 likes
              Last Post NullPointStrategies  
              Started by argusthome, 03-08-2026, 10:06 AM
              0 responses
              126 views
              0 likes
              Last Post argusthome  
              Started by NabilKhattabi, 03-06-2026, 11:18 AM
              0 responses
              69 views
              0 likes
              Last Post NabilKhattabi  
              Started by Deep42, 03-06-2026, 12:28 AM
              0 responses
              42 views
              0 likes
              Last Post Deep42
              by Deep42
               
              Started by TheRealMorford, 03-05-2026, 06:15 PM
              0 responses
              46 views
              0 likes
              Last Post TheRealMorford  
              Working...
              X