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


Triggering strategy by movement of price up or down X number of points

  • Filter
  • Time
  • Show
Clear All
new posts

    Hello Jeff,

    Thanks for your note.

    It is possible that the strategy is resubmitting the orders at a new price level because the condition to place the orders again is becoming true.

    You may use a bool to prevent the stop and target orders from being resubmitted. The example script attached in post # 20 and in post # 36 in this forum thread demonstrate using a bool to control when Exit orders are placed by the strategy.

    Note in the sample script that we check if the bool is true in the condition to place the Exit order methods and the bool is flipped to false after the orders are submitted. By doing this the Exit orders would only be submitted when the bool is true. Since we are flipping the bool to false after the Exit orders are being placed, the Exit orders will not continue to be submitted until the bool is flipped to true again.

    Please let me know if I may assist you further.
    Brandon H.NinjaTrader Customer Service


      Thanks. I will test that out. One thing I have noticed that is a big problem for me (and possibly others) is that since stop loss and target orders are not being created when the limit entry is created (only when the entry is filled), if price hits my limit entry and drops through quickly, I dont have any stop loss in place.

      I will rely on the market stop being created in that moment, which may cause me to get an inferior stop depending on how quickly the market drops and the volume. This is assuming I am also using 'on each tick' method, which I can't use because I need to evaluate the bar at close to make sure it meets my conditions such as the bar not exceed certain volume and certain movement up or down in ticks. This is why buying or selling a MARKET stop is so important as it assure there is that stop in place, the moment you get your entry limit sent.

      Even if I was able to use 'on each tick', my issue is that need to have the stop loss created at the same time as the entry limit order for this to work for me.

      There must be an alternative approach to have stops orders created at the same time a stop entry is created.


        Hello Jeff,

        Thanks for your note.

        To have the strategy submit orders intrabar instead of only at the close of a bar, you could run you strategy with Calculate.OnPriceChange or Calculate.OnEachTick.

        If you run the strategy with Calculate.OnPriceChange, once the limit order is filled and there is a change in price, the stop and target orders would be submitted.

        If you run the strategy with Calculate.OnEachTick, once the limit order is filled, the stop and target orders would be submitted on the next incoming tick. This means the stop and target orders would be submitted one tick after the limit order is filled.


        To see this concept in action, you could test running the ExitMethodsSample script attached in post # 20 and post # 36 using Calculate.OnPriceChange or Calculate.OnEachTick.

        As previously stated, Exit orders should be submitted when the Entry order is filled.

        If you would like to separate some logic to occur with Calculate.OnBarClose and other logic to process with Calculate.OnEachTick, you may certainly do so.

        Please note that a hosted script will inherit the Calculate mode of the script that hosts it. You can take the following approach to differentiate logic between OnBarClose and OnEachTick processing.

        See this reference sample which demonstrates a technique used for those who need to separate their logic to calculate some values on each tick and others only on the close of a bar. You will set your host script to Calculate.OnEachTick and use if(IsFirstTickOfBar) and place all code that needs to calculate once every bar within that condition check. Then place all code that you want to calculate OnEachTick outside of the IsFirstTickOfBar condition check.

        SampleEnterOnceExitEveryTick -

        Please let us know if we may assist further.
        Brandon H.NinjaTrader Customer Service


          I am trying my best to figure out how to seperate my logic to entry order gets calculated using on the next bar and exit orders use on each tick. Would it be possible for you to show me how using the code I am using below so the entry position logic sections are on bar close and exist position logic is on each tick

          Last edited by Jdmtrader; 03-29-2023, 03:47 PM.


            Hello Jeff,

            Thanks for your inquiry.

            To have your Entry order logic calculate OnBarClose, you would include IsFirstTickOfBar to your entry order condition as seen in the SampleEnterOnceExitEveryTick reference sample linked in the previous post.

            For example, your long entry logic might look something like this.

            if ((IsFirstTickOfBar
            && IsRising(Close) == true
            && Position.MarketPosition == MarketPosition.Flat
            && Volume[0] <= MaxVolume
            && Volume[0] >= MinVolume
            && Close[0] > (Open[0] + (MovementUpTrigger * TickSize)))
                EnterLongLimit(0, true, Convert.ToInt32(Quantity), High[1], @"MyEntry");
                myBool = true;
            You would also need to include IsFirstTickOfBar in your short entry order condition similar to what is seen above.

            The Exit order conditions would remain as they are. Calculate mode in State.SetDefaults should be set to Calculate.OnEachTick.

            Please let me know if you have further questions.​
            Brandon H.NinjaTrader Customer Service


              I have managed to get my strategy working acceptably, however, when I try to back test it in the strategy analyzer, it will not work and produces no trades.

              I can test my strategy in playback connection using replay mode just fine.

              Would you be able to look over my strategy and let me know if you see anything that might be causing the strategy analyzer from working properly?
              Last edited by Jdmtrader; 03-29-2023, 06:00 PM.


                Hello Jeff,

                Thanks for your note.

                Please review the help guide document on the differences on real-time vs backtest (historical).

                A strategy running real-time (live brokerage account, live market simulation, Playback connection etc...) will produce different results than the performance results generated during a backtest.

                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.

                Below is a link to the help guide on Calculate.

                Additional information about this may be found in this NinjaTrader Forum post including how to improve the accuracy of a backtest by adding a 1-Tick added data series to the script and submitting orders to that 1-Tick series.

                Further, below is a link to a forum post about comparing historical, playback, and real-time.

                Are you skipping historical data processing in your script by calling 'if (State == State.Historical) return;' in the OnBarUpdate() method of your script?

                If so, the strategy would not be able to process historical data which is required to use for backtesting in the Strategy Analyzer.

                Ultimately, if the strategy is not behaving as expected then debugging prints should be added to the script to understand how the script is behaving when backtesting it.

                Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                Let me know if I may assist further.
                Last edited by NinjaTrader_BrandonH; 03-30-2023, 08:40 AM.
                Brandon H.NinjaTrader Customer Service


                  Yes, I do have the line if (State == State.Historical) return. That must be it. I will test and let you know if I have any further trouble. Thanks


                    NinjaTrader_BrandonH I am still having trouble getting my strategy to run in the strategy tester. Is there a way I can send you my strategy privately and have you take a look?


                      Hello Jeff,

                      Thanks for your note.

                      Unfortunately, it is against our policy to debug, modify, or create the logic of a strategy at your request.

                      If you have if (State == State.Historical) return; in your script, this would need to be removed from the script if you want to run a backtest on the strategy in the Strategy Analyzer.

                      If the script is still not behaving as expected, you should add debugging prints to the script to understand how your custom strategy logic is behaving.

                      Below is a link to a forum post that demonstrates how to use prints to understand behavior.

                      It could be that you are using IsFirstTickOfBar within the script to have logic process OnBarClose and OnEachTick. The Strategy Analyzer will only process logic OnBarClose so the IsFirstTickOfBar logic would not be triggered.

                      ​You may use Tick Replay along with an added 1-tick series to have logic processed intra-bar and have orders filled intrabar. Tick Replay would be used to have the logic process OnEachTick or OnPriceChange with historical data, but this does not allow for intra-bar order fills. You would need to add a single tick data series and submit orders to that single tick data series for a strategy that uses Tick Replay.

                      See this forum thread for detailed information about backtesting a strategy that uses IsFirstTickOfBar: ​

                      Please let me know if you have questions about creating a print or analyzing the Output window.
                      Last edited by NinjaTrader_BrandonH; 03-30-2023, 10:23 AM.
                      Brandon H.NinjaTrader Customer Service


                        I have been running my strategy with a new condition that includes checking if the current bar is a doji candle or not. It's not getting triggered when the doji candle appears.

                        Here is my condition below. Current bars are [1], not [0], in my strategy, since I use a mix of calculate 'on each tick' (default setting) and firsttickofbar, defined where needed). It doesnt make sense why when doji candles appear, its not triggering the condition. The condition is being met, only when the other parts that condition line with OR statements are met as well as the rest of the conditions. I've isolated it down to the candlestickpattern condition.

                        if (IsFirstTickOfBar
                        && ((Open[1] == Open[2] && High[1] > High[2] && Low[1] < Low[2]) || (CandlestickPattern(ChartPattern.Doji, 4)[1] == 1) || (Volume[1] >= ExitVolume))

                        I followed the reference guide for using candlestick patterns in my strategy


                          Hello Jeff,

                          Thanks for your note.

                          That would be the correct way to use CandleStickPattern() in a NinjaScript to check if the previous bar is doji pattern.

                          CandleStickPattern() returns a value of 1 if the pattern is found; returns a value of 0 if no pattern was found.

                          Note that if you want the CandleStickPattern() to only detect based on the candles themselves, a trendStrength value of 0 should be used instead of a value of 4.


                          To clarify, have you added prints to your script one line above the condition that prints out each value in your condition to confirm exactly which set of conditions is becoming true in the script?

                          Do you see that the CandleStickPattern condition is returning a value of 1 in the prints or does this condition return a value of 0?

                          The print might look something like this:

                          Print( "IsFirstTickOfBar is " + IsFirstTickOfBar + " the CandleStickPattern(ChartPattern.Doji, 4)[1] is " + CandlestickPattern(ChartPattern.Doji, 4)[1]);

                          If you need assistance with analyzing the prints in the Output window, please share a copy of the Output results by right-clicking on the Output window after running the script, selecting 'Save as', and attaching the file to your reply.

                          I look forward to assisting further.
                          Brandon H.NinjaTrader Customer Service


                            Thanks. I am trying to determine which bar in the past 5 bars from the current bar[1] has the highest high, so I can set my limit order at the highest high of the last 5 bars I tried adding in the code to my strategy

                            highestBarsAgo = HighestBar(High, 5);
                            highestPrice = High[highestBarsAgo];

                            It is not working right and keeps saying bar 1 is the highest with a value that is not found in any of the 5 bars before the previous bar. I added these two lines within the if statement, after the conditions.


                              Hello Jeff,

                              Thanks for your note.

                              I have attached a simple example script demonstrating how to get the highest price of the last 5 bars by using the HighesBar() method.

                              If we compare the prints in the script to a Data Box window and hover the mouse over the last 5 bars, we can see that the prints accurately state what the highest price of the last 5 bars is and the bars ago value the highest price is located. See the attached screenshot.


                              Note that if you added this logic within a condition, you would need to compare the highest price from the CurrentBar value the condition became true on.

                              Within your condition, you could print out the CurrentBar value to see what bar number the condition became true on. Then you could open a Data Box window, hover the mouse over the CurrentBar index the condition became true on, and compare the high price for the prior 5 bars.

                              Let me know if I may assist further.​
                              Attached Files
                              Brandon H.NinjaTrader Customer Service


                                I assume this will work directly in my strategy as well?

                                It is the previous 5 bars before the CurrentBar. I do not want to include the current bars high, so does that change things? Anyway to exclude the current bar from being used?

                                I need the bar # that has the highest high, not the actual high value. I am aware of the Max() function, but this returns the highest value of the input data series (in this case, the High price) within the lookback period, not the bar number of the highest high.

                                Would this work instead using a simple loop? My current bar is at index 1

                                if (IsFirstTickOfBar)
                                int lookbackPeriod = 5;
                                int barWithHighestHigh = 2;

                                for (int i = 3; i <= lookbackPeriod + 1; i++)
                                if (High[i] > High[barWithHighestHigh])
                                barWithHighestHigh = i;
                                Last edited by Jdmtrader; 04-04-2023, 04:12 PM.


                                Latest Posts


                                Topics Statistics Last Post
                                Started by vitaly_p, 05-31-2023, 09:35 AM
                                6 responses
                                Last Post vitaly_p  
                                Started by Trader17, Today, 09:45 AM
                                0 responses
                                1 view
                                Last Post Trader17  
                                Started by ATMtrader0001, 02-10-2021, 01:20 PM
                                8 responses
                                Last Post bltdavid  
                                Started by Trader17, Today, 07:38 AM
                                1 response
                                Last Post NinjaTrader_ChrisL  
                                Started by trader3000a, Today, 07:12 AM
                                1 response
                                Last Post NinjaTrader_Emily