Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

What is wrong with this code?

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

    What is wrong with this code?

    I am trying out to exit at 10 PT even before the bar close.
    My entry is at the bar close but exit it at 10 PT profit.(40 ticks).

    I have this code but it exists at the close of the candle. Why?

    First entry is correct : 17542.50 but exit should have been at 17552.50. Instead it exited at 15557.75. Why?

    Here is the code:

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    // Set 1
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    MoveToBE = false;
    }

    if (CurrentBars[0] < 1)
    return;

    // Set 2
    if ((CONDITION FOR LONG)
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), @"L");
    MoveToBE = false;
    }

    // Set 3
    if ((Position.MarketPosition == MarketPosition.Long)
    && (Close[0] >= (Position.AveragePrice + (40 * TickSize)) ))
    {
    ExitLong(Convert.ToInt32(DefaultQuantity), @"LPT", @"L");
    }

    }​


    Click image for larger version

Name:	image.png
Views:	210
Size:	51.1 KB
ID:	1287639

    #2
    I'm quite new to creating strats and I can't see why you're having the issue with the code you've provided .... but that said.... are you sure you don't have some check in the code that's waiting for the previous bar close before you go into this logic to exit? also, is there any reason why you aren't using SetProfitTarget for your exit?

    Comment


      #3
      Originally posted by ravvles View Post
      I'm quite new to creating strats and I can't see why you're having the issue with the code you've provided .... but that said.... are you sure you don't have some check in the code that's waiting for the previous bar close before you go into this logic to exit? also, is there any reason why you aren't using SetProfitTarget for your exit?
      Yes, i am sure that there is no additional logic to exit. Set-2 is entry. Set-3 is exit. (which seems pretty straightforward) but it isn't working. May i am missing something which i can't see it :-(

      Good question on why i am not using SetProfitTarget. Reason is that i have additional logic that i need to implement to move the SL to Break Even(BE), which is only possible in condition builder and not in set target & stops.

      Comment


        #4
        Hello psangram,

        Thanks for your notes.

        Are you running your script using Calculate.OnBarClose?

        If so, the strategy's OnBarUpdate() will only process logic at the close of each bar. This means that conditions would be evaluated and actions would only happen at the close of the bar.

        To have the strategy's OnBarUpdate() logic process intrabar, you could set the Calculate mode to Calculate.OnPriceChange or Calculate.OnEachTick. This could be set in the UI when adding the strategy to a chart or in the Default Properties screen of the Strategy Builder.

        See this help guide documentation about Calculate: https://ninjatrader.com/support/help.../calculate.htm

        Further, to understand exactly how your strategy's logic is evaluating, it is necessary to add debugging prints to the strategy. In the strategy, add prints (outside the conditions) the prints out all the values being used for the condition to place the order along with the time of the 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 and a publicly available video demonstrating using prints in a Strategy Builder strategy.


        I see you noted you are trying to implement a BreakEven function in the Strategy Builder. My colleague Chelsea has created educational examples of strategy builder breakeven and trailing stop in the strategy builder here which you might find helpful:https://ninjatrader.com/support/forum/forum/suggestions-and-feedback/suggestions-and-feedback-aa/103992-request-breakeven-functions-in-strategy-builder#post806596​​
        <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
          Hello Brandon, i am running the strategy on "onPriceChange" and also, i tried it on "OnPriceChange".
          Do you think code is right for the above Calculation type?

          Comment


            #6
            Hello psangram,

            Thanks for your notes.

            I do not see anything standing out as incorrect in the code you shared and the information provided.

            To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects when expected, 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.

            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).

            Also, enable TraceOrders which is a useful property when debugging the behavior of your orders. With the use of this property, you can track orders placed, amended, and canceled. This will provide meaningful information for diagnosis when NinjaTrader ignores, changes or cancels orders when various strategy order methods are called.

            TraceOrders: https://ninjatrader.com/support/help...aceorders2.htm

            ​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


              #7
              Sure, i will give it a try and reach out to you.

              Comment


                #8
                Hi Brandon, i tried to print and its printing every minute instead of every tick change. Not sure why?

                I have the code as follows:

                protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = @"TestingOnPriceChangeLogic";
                Name = "TestingOnPriceChangeLogic";
                Calculate = Calculate.OnEachTick;
                EntriesPerDirection = 1;
                EntryHandling = EntryHandling.AllEntries;
                IsExitOnSessionCloseStrategy = true;
                ExitOnSessionCloseSeconds = 30;
                IsFillLimitOnTouch = false;
                MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
                OrderFillResolution = OrderFillResolution.Standard;
                Slippage = 0;
                StartBehavior = StartBehavior.WaitUntilFlat;
                TimeInForce = TimeInForce.Gtc;
                TraceOrders = true;
                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;
                LongBreakEvenTrigger = 20;
                LongProfitTarget = 40;
                LongStop = 80;
                ShortBreakEvenTrigger = 20;
                ShortProfitTarget = 40;
                ShortStop = 80;
                EntryTimeFrom = DateTime.Parse("09:30", System.Globalization.CultureInfo.InvariantCulture) ;
                EntryTimeTo = DateTime.Parse("10:30", System.Globalization.CultureInfo.InvariantCulture) ;
                MaxDailyProfit = 500;
                MaxDailyLoss = -500;
                MoveToBE = false;
                DayIsOK = true;
                Accumulated = 0;
                NoShort = true;
                }
                else if (State == State.Configure)
                {
                }​

                Comment


                  #9
                  Here is the NS output:

                  Click image for larger version

Name:	image.png
Views:	158
Size:	253.9 KB
ID:	1287720

                  Comment


                    #10
                    Hello psangram,

                    Thanks for your notes.

                    Are you testing the script using the Strategy Analyzer, Playback connection, or running the script on a real-time chart?

                    What instrument symbol (and expiry if applicable) have you selected? For example, ES 03-24, AAPL, EURUSD, etc.

                    What interval are you running the strategy on? For example, 1 minute, 1 day, 2000 volume, 4 Renko, etc.

                    Ensure that the Calculate mode is set to OnEachTick in the Strategies window UI when testing the strategy on a real-time chart.
                    <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


                      #11
                      I am testing the script using using the Strategy Analyzer. Is it the right way to test the strategy?
                      Click image for larger version

Name:	image.png
Views:	150
Size:	12.2 KB
ID:	1287726

                      Comment


                        #12
                        Also, how to test the strategy using Playback connection.
                        any insight on how to use playback connection. I never tried this before.

                        Comment


                          #13
                          Hello psangram,

                          Thanks for your notes.

                          The Strategy Analyzer is only able to Calculate.OnBarClose as it does not have intrabar information available to process OnEachTick or OnPriceChange. This is why you are seeing prints occur for each 1-Minute bar instead of for each tick that occurs.

                          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.
                          https://ninjatrader.com/support/help.../calculate.htm

                          Please review the help guide document on the differences on real-time vs backtest (historical).
                          https://ninjatrader.com/support/helpGuides/nt8/discrepancies_real-time_vs_bac.htm​

                          Additional information may be found in this NinjaTrader Forum post:
                          https://ninjatrader.com/support/forum/forum/ninjatrader-8/strategy-development/100192-comparing-real-time-historical-and-replay-performance?t=102504

                          You may consider using the Playback Connection with Market Replay data to test and debug your strategy or run the strategy on a chart while connected to a real-time data feed connection.

                          See this help guide page for information about how to use the Playback Connection: https://ninjatrader.com/support/help...connection.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


                            #14
                            Thanks Brandon. In this case, how can we backtest the strategies that depend on on price change or ontickchange calculation?

                            Comment


                              #15
                              Hello psangram,

                              Thanks for your notes.

                              You would need to add intrabar granularity to your script and enable Tick Replay when running the backtest.

                              See more about intra-bar granularity on the forum thread below.
                              https://ninjatrader.com/support/forum/forum/ninjatrader-8/strategy-development/94098-isfirsttickofbar-vs-onbarclose-for-backtest-live?p=773377#post773377
                              <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 NullPointStrategies, Today, 05:17 AM
                              0 responses
                              52 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              130 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              70 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              44 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              49 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X