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

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




    JesseNinjaTrader Customer Service

    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.

          JesseNinjaTrader Customer Service

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by Segwin, 05-07-2018, 02:15 PM
          14 responses
          1,789 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
          13 views
          0 likes
          Last Post Touch-Ups  
          Started by geddyisodin, 04-25-2024, 05:20 AM
          11 responses
          63 views
          0 likes
          Last Post halgo_boulder  
          Working...
          X