Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

limit orders to once per bar

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

    limit orders to once per bar

    What is the snippet I should use in my strategy code to limit entries/exits from a signal to once per bar? So if I set it to "On Each Tick" It will not enter/exit the same bar again until next bar. Thank you.

    #2
    Hello designer01,

    Thanks for your post.

    A bool could be used to control when trades are placed by a strategy.

    You could create a bool variable named something like "OkToTrade", create a condition that checks IsFirstTickOfBar to see if a new bar has formed, and set the bool to true within that condition.

    Then, in your order entry condition check if the bool is true, call your order entry method within the condition, and flip the bool to false.

    By doing so, the order will only be placed when the bool is true and the bool will only be flipped to true when a new bar has formed.

    See the help guide documentation below for more information.

    IsFirstTickOfBar: https://ninjatrader.com/support/help...ttickofbar.htm
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      Hello, I've tried IsFirstTickOfBar but it is not sending the exit order.
      Here is the situation I want to partial exit half of the current position when the Close crosses the ATRTrailing stop 2 and the rest at ATRtrailing Stop 3. But it exits everything at ATRTrailing Stop2 see image below. This is due to having OnEachTick which I want. OnBarClose works fine.

      Code:
      if ((CrossBelow(Close, ATRTrailingStop2, 1))
                       && (MarketPosition.Long == MarketPosition.Long))
                      {
                          ExitLong(Convert.ToInt32(Position.Quantity / 2), @"LX1", @"ATRLE");
                      }
      
                  if ((CrossBelow(Close, ATRTrailingStop3, 1))
                       && (MarketPosition.Long == MarketPosition.Long))
                  {
                      ExitLong(Convert.ToInt32(Position.Quantity ), @"LX2", @"ATRLE");
                  }​
      Click image for larger version  Name:	NTExit.jpg Views:	0 Size:	235.3 KB ID:	1259733
      Last edited by designer01; 07-10-2023, 08:28 AM.

      Comment


        #4
        Hello designer01,

        Thanks for your notes.

        IsFirstTickOfBar would be used to reset the bool variable when a new bar is formed.

        It does not seem like you are implementing a bool variable check in your condition to place the exit orders. You would need to create a bool variable in your script and implement it in your logic as explained in post # 2.

        Code:
        //class level variable
        private bool OkToTrade;
        
        //OnBarUpdate()
        if (IsFirstTickOfBar)
            OkToTrade = true;
        
        if (condition && OkToTrade)
        {
            ExitLong(Convert.ToInt32(Position.Quantity / 2), @"LX1", @"ATRLE");
            OkToTrade = false;
        }
        This means the Exit order would only be placed when the bool OkToTrade is true and the bool will only be flipped to true when a new bar has formed.
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment


          #5
          Thank you that works great!

          Comment


            #6
            How would I add a condition so the next consecutive exit is barsSinceLastTrade >= 5? In other words I don't want 2 exits next to each other that is wait for 5 bars for the next exit to occur? Thanks.

            Code:
            //class level variable
            private bool OkToTrade;
            
            //OnBarUpdate()
            if (IsFirstTickOfBar)
            OkToTrade = true;
            
            if (condition && OkToTrade)
            {
            ExitLong(Convert.ToInt32(Position.Quantity / 2), @"LX1", @"ATRLE");
            OkToTrade = false;
            }​

            Comment


              #7
              Hello designer01,

              Thanks for your notes.

              You could use BarsSinceExitExecution() to detect if a certain number of bars have passed since the last exit order execution.

              If you want to detect if a certain number of bars have passed since the last entry order execution, BarsSinceEntryExecution() could be used.

              See the help guide documentation below for more information and sample code.

              BarsSinceExitExecution(): https://ninjatrader.com/support/help...texecution.htm
              BarsSinceEntryExecution(): https://ninjatrader.com/support/help...yexecution.htm
              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

              Comment


                #8
                && (BarsSinceEntryExecution(0, "", 0) > 0)

                && (BarsSinceExitExecution(0, "", 0) > 0)

                I have tried both on the current strategy I am working with, but when I add either of these to my condition set code, my trades no longer trigger at all ON BACKTEST strategy analyzer, its after hours so cannot test live

                I am running OnPriceChange

                Thanks
                Last edited by DTSSTS; 07-14-2023, 03:56 PM.

                Comment


                  #9
                  Hello DTSSTS,

                  Thanks for your notes.

                  The BarsSinceExitExecution() code below would check if at least 5 bars have passed since the last exit or if you have never traded yet.

                  (BarsSinceExitExecution() > 5 || BarsSinceExitExecution() == -1)

                  Note that the Strategy Analyzer only processes OnBarUpdate with OnBarClose, not OnPriceChange.

                  Please review the help guide document on the differences on real-time vs backtest (historical).
                  http://ninjatrader.com/support/helpG...ime_vs_bac.htm

                  When in historical data, only the Open, High, Low, and Close will be available and there will be no intra-bar data. This means actions cannot happen intra-bar, fills cannot happen intra-bar. All prices and actions come from and occur when the bar closes as this is all the information that is known.

                  Because of this, OnBarUpdate will only update 'On bar close' as it does not have the intra-bar information necessary for 'On price change' or 'On each tick' and the script will not have the intra-bar information to accurately fill an order at the exact price and time.

                  See this NinjaTrader Forum post for more information about this topic:
                  https://ninjatrader.com/support/forum/forum/ninjatrader-8/strategy-development/100192-comparing-real-time-historical-and-replay-performance?t=102504​​​

                  Ultimately, if the strategy is not behaving as expected, you must add debugging prints to the script to understand exactly how your logic is behaving.

                  Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                  https://ninjatrader.com/support/foru...121#post791121
                  <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                  Comment


                    #10

                    Note that the Strategy Analyzer only processes OnBarUpdate with OnBarClose, not OnPriceChange

                    so you think these will work properly live trading

                    && (BarsSinceEntryExecution(0, "", 0) > 0)

                    && (BarsSinceExitExecution(0, "", 0) > 0)​​

                    thanks

                    Comment


                      #11
                      Hello DTSSTS,

                      Thanks for your notes.

                      You would need to test out your strategy to determine if your custom logic behaves as you expect it to.

                      You could consider testing the strategy using the Sim101 account while connected to a live data feed connection to see how your script behaves. Or, you could use the Playback connection with Market Replay data to see how the strategy behaves and places orders.

                      If the strategy does not behave as you expect it to, debugging prints should be added to the strategy to understand how your custom logic is evaluating. Note that when working with any issue in a script, it is important to take steps to isolate the issue so that the exact line of code causing the behavior can be found. This is a process of reducing code and a process of debugging by adding prints.​

                      Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                      https://ninjatrader.com/support/foru...121#post791121
                      <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                      Comment


                        #12
                        && (BarsSinceEntryExecution(0, "", 0) > 0)

                        I have 10 entries condition sets, 5 Long, and 5 Short

                        If I use this condition set on all 10 I get zero trades, If I use this on 9 of the 10 I get trades on all condition sets but ONLY after the 1 condition set the DOES NOT have the

                        && (BarsSinceEntryExecution(0, "", 0) > 0) trades first, then other triggers after that time will trade


                        when testing with Strategy Performance historical data it generates an error if ALL condition sets have that line of code

                        it is too long to type and ninja connections email and twitter has gone crazy and no longer work with the recent updates

                        the Lines contain alot about SQLite3 and SQLite3DataReader

                        the first part is

                        Error on executing DB command: code = Constraint (19). message = System.Data.SQLite.SQLiteException (0x8000027AF),
                        constraint failed the FOREIGN KEY constraint failed at..................

                        Last edited by DTSSTS; 07-18-2023, 01:30 PM.

                        Comment


                          #13
                          Hello DTSSTS,

                          Thanks for your notes.

                          The BarsSinceEntryExecution() method will return the number of bars that have elapsed since the last entry execution that occurred.

                          BarsSinceEntryExecution() == -1 should be added to the condition to check if a previous entry does not exist.

                          From the help guide:

                          // Only enter if at least 10 bars has passed since our last entry
                          if ((BarsSinceEntryExecution() > 10 || BarsSinceEntryExecution() == -1) && CrossAbove(SMA(10), SMA(20), 1))
                          EnterLong();


                          You could also consider giving your Entry orders a Signal Name and supply the signal name in the BarsSinceEntryExecution() method to get the number of bars that have elapsed since that last specific entry.

                          BarsSinceEntryExecution(int barsInProgressIndex, string signalName, int entryExecutionsAgo)

                          See this help guide page for more information: https://ninjatrader.com/support/help...yexecution.htm

                          If the expected trade(s) are not appearing, this would indicate that the condition to place the order is not evaluating as true or the order is being ignored for other reasons. It is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

                          If the script is not behaving as expected, you should add debugging prints to the script that print out your BarsSinceEntryExecution() value one line above the condition where you are using the method to see how exactly it is evaluating. Also, add prints that print out the other values and variables being used in the conditions to place orders.

                          ​See the forum thread posted on post # 11 which demonstrates how to use prints to understand behavior.
                          <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                          Comment


                            #14
                            IsFirstTickOfBar would be used to reset the bool variable when a new bar is formed.
                            Would this be used to enter trades as well? I've tried like so but it does not trigger any trades.

                            Code:
                            //class level variable
                            private bool OkToTrade;
                            
                            //OnBarUpdate()
                            if (IsFirstTickOfBar)
                                OkToTrade = true;
                            
                            if (condition && OkToTrade)
                            {
                                EnterLong(Convert.ToInt32(100), @"ATRLE");
                                OkToTrade = false;
                            }​

                            Comment


                              #15
                              Hello designer01,

                              Thanks for your notes.

                              IsFirstTickOfBar will detect if the incoming tick is the first tick of a new bar. This could be used to flip the bool to true when a new bar is forming.

                              Note that if you are backtesting the strategy in the Strategy Analyzer you would need to enable Tick Replay to have ticks process on historical data.

                              When in historical data, only the Open, High, Low, and Close will be available and there will be no intra-bar data. This means actions cannot happen intra-bar, fills cannot happen intra-bar. All prices and actions come from and occur when the bar closes as this is all the information that is known.

                              Please review the help guide document on the differences on real-time vs backtest (historical).
                              http://ninjatrader.com/support/helpG...ime_vs_bac.htm

                              TickReplay: https://ninjatrader.com/support/help...ick_replay.htm

                              Ultimately, if the strategy is not behaving as expected, such as placing orders or not placing orders, you would need to add debugging prints to the script to see how the logic is behaving.

                              ​In the strategy add prints (outside of any conditions) that print the values of every variable used in every condition that places an order along with the time of that bar. Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

                              Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                              https://ninjatrader.com/support/foru...121#post791121​​
                              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by AHamxa, Today, 11:22 PM
                              0 responses
                              3 views
                              0 likes
                              Last Post AHamxa
                              by AHamxa
                               
                              Started by AHamxa, Today, 11:17 PM
                              0 responses
                              4 views
                              0 likes
                              Last Post AHamxa
                              by AHamxa
                               
                              Started by Spiderbird, 07-27-2018, 07:52 PM
                              12 responses
                              9,240 views
                              2 likes
                              Last Post Mountain_cast  
                              Started by chrischongpdx, Today, 09:39 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post chrischongpdx  
                              Started by Mountain_cast, Today, 12:41 PM
                              2 responses
                              10 views
                              0 likes
                              Last Post Mountain_cast  
                              Working...
                              X