Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy Shows Entry one Bar to Late

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

    Strategy Shows Entry one Bar to Late

    Hello, i have a Big Problem. I Try to Test different (My Own) Strategies but all have the same Problem. It Shows the Entrys on Chart one Bar to late to the right. I donw know why it is so.
    Im getting Crazy here. Simple if(CLose[0]<Close[1]) Dont Work. ist getting enter 1 Bar later.

    And yes its Calculated on Tick and its working right on Playback Mode, means on Replay it enters on the Right bar Live only on Normal Chart Showing Enter one Bar to the Right.
    Im using NQ Chart 30 Seconds.

    Its Frustrating that this simple Thinks not work. As i seer now Exits are One Bar to the Right too. Also wrong too.


    Please Help me out.

    Add<<<

    here are the Simple Block. Than should Show Enter on Bar (0) at Chart but it does not means its enter at bar -1 ;o)

    if(Close[1]>SMA1[1] && Low[1]<SMA1[1] && Open[1]>SMA1[1]){

    EnterLong(1,0, "myEntryLong");
    StopPrice=Low[1]-TickSize;
    EntryPrice=Close[0];
    TargetPrice=Close[0]+((EntryPrice-StopPrice)*2);
    }​

    EDIt: I have now found out if i aktivate the Tick Replay in the Chart Window, than it shows right, but is that the Solution? its need i lot Computing power. why does this not work with the High resolution config?
    Last edited by orbito; 09-09-2023, 08:30 AM.

    #2
    Hello orbito,

    Thanks for your post.

    Are you comparing historically calculated trades?

    If so, you should enable Tick Replay which will ensure that the market data (bid/ask/last) that went into building a bar is loaded in the exact sequence of market data events. This guarantees that your indicators and strategies are historically calculated tick-per-tick exactly as they would have been if the indicator/strategy was running live during a period.

    Tick Replay: https://ninjatrader.com/support/help...ick_replay.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.

    Tick Replay would be used to have the logic process OnEachTick or OnPriceChange with historical data.​
    <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
      Thank you for answere. yes the Tick Replay on Chart resolve the Problem but waht you mean bby "​When in historical data"? there is only ​historical data on the Charts backwards or not? or is there a other way to do that? the Problem is without the Tick Replay all Stats are wrong ionclude the Performance for the Strategy. I think its because the entry are intrabar. So i think there is not way other than Tick Replay to show the Trades correct on Chart

      Comment


        #4
        Hello orbito,

        Thanks for your notes.

        When a strategy is enabled, it processes historical data to determine trades that the strategy would have made on the data that is already on the PC/chart and to determine what position the strategy is in. Historical data refers to prior data on the chart at the time the strategy is enabled. Realtime data would be any data going forward that populates from the time the strategy is enabled.

        If you want your strategy to historically calculate tick-per-tick exactly as it would have been if the strategy was running live during a period, you should enable Tick Replay.

        See this help guide page for further information about how Tick Replay works: https://ninjatrader.com/support/help...ick_replay.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


          #5
          Thank you for your Help. i have one other Problem I try to use my own indicator with 2 Plot use in StrategyBuilder. But the Plots not showing as selectable Values there, only the Plot Colors.

          I have the Follow Code. I dont know how to make a Value Plot to show in the Strategy Builder.

          <<<

          /This namespace holds Indicators in this folder and is required. Do not change it.
          namespace NinjaTrader.NinjaScript.Indicators.Eigene
          {
          public class MyMomo : Indicator
          {

          private Series<double> LongEntry;
          private Series<double> ShortEntry;
          protected override void OnStateChange()
          {


          if (State == State.SetDefaults)
          {
          Description = @"NinjaScript Price Variables Tutorial";
          Name = "MyMomo";
          Calculate = Calculate.OnBarClose;
          IsOverlay = false;
          DisplayInDataBox = true;
          DrawOnPricePanel = true;
          DrawHorizontalGridLines = true;
          DrawVerticalGridLines = true;
          PaintPriceMarkers = true;
          ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
          //Disable this property if your indicator requires custom values that cumulate with each new market data event.
          //See Help Guide for additional information.
          IsSuspendedWhileInactive = true;
          BarsAgo = 1;

          AddPlot(Brushes.Orange, "SmallMomo");
          AddPlot(Brushes.White, "BigMomo");
          AddPlot(Brushes.White, "Middle");
          AddPlot(new Stroke(Brushes.Green), PlotStyle.TriangleUp, "SignalLong");
          }
          else if (State == State.Configure)
          {
          LongEntry = new Series<double>(this);
          ShortEntry = new Series<double>(this);
          }
          }

          protected override void OnBarUpdate()
          {
          if(CurrentBar < BarsAgo + 260)
          return;

          //Values[0][BarsAgo] = (Close[BarsAgo] > Close[(BarsAgo + 1)]) ? (High[BarsAgo] + (5 * TickSize)) : (Low[BarsAgo] - (5 * TickSize));

          Values[0][BarsAgo]=(Close[BarsAgo]/Close[BarsAgo+21])*1000;
          Values[1][BarsAgo]=(Close[BarsAgo]/Close[BarsAgo+252])*1000;
          Values[2][BarsAgo]=1000;
          //

          // Signal Plot Long
          if(Values[0][BarsAgo+4]<1000 && Values[0][BarsAgo]>1000){
          Values[3][BarsAgo]=Values[0][BarsAgo];

          LongEntry[0]=Values[0][BarsAgo];
          //Draw.ArrowUp(this, "SignalLong"+Close[BarsAgo], false, 0, Low[BarsAgo] - TickSize, Brushes.Green,true);
          }
          }

          Comment


            #6
            Hello orbito,

            Thanks for your notes.

            Does your script have public properties defined for the plots?

            If not, you should add public properties for each of the plots being added in your script. The second sample code section on the AddPlot() help guide page demonstrates this.

            For example, the properties might look something like this:
            Code:
            #region Properties
            
            [Browsable(false)]
            [XmlIgnore]
            public Series<double> SmallMomo
            {
            get { return Values[0]; }
            }
            
            [Browsable(false)]
            [XmlIgnore]
            public Series<double> BigMomo
            {
            get { return Values[1]; }
            }
            #endregion​​
            See the help guide documentation below for more information.

            AddPlot(): https://ninjatrader.com/support/help...t8/addplot.htm
            Values: https://ninjatrader.com/support/help.../nt8/value.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


              #7
              Thank its working now. I Try Now to set a Profit Target after EnterShort with on Line for may Short Trades. It Should be 2 Times the stop but the Target not work. Can you tell me whats wrong?

              SetProfitTarget(@"SystemShort", CalculationMode.Price, (Position.AveragePrice-((High[HighestBar(High,2)]-Position.AveragePrice)*2)) - TickSize);

              Comment


                #8
                Hello orbito,

                Thanks for your notes.

                Do you see any error messages in the Log tab of the Control Center when running your strategy? If so what exactly does the error report?

                Did you create the strategy using the Strategy Builder or using the NinjaScript Editor window?

                Are you calling SetProfitTarget() in OnStateChange() when the State == State.Configure?

                Note that you cannot access price values such as High[0] in OnStateChange() when the State == State.Configure.

                You could use Exit methods, such as ExitLongLimit()/ExitShortLimit() within OnBarUpdate() instead of using SetProfitTarget() within your script to submit the exit order to a specific price value.

                Attached is a simple sample strategy demonstrating the use of Exit methods for Profit Target and Stop Loss orders.

                Managed Approach: https://ninjatrader.com/support/help...d_approach.htm

                If the strategy is not be having and placing order as expected, debugging prints should be added to the strategy to understand how it is behaving.

                To understand why the script is behaving as it is, such as placing orders or not placing orders 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 one line above the order method that prints the value being passed into the order method 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​​
                Attached Files
                <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


                  #9
                  I would like to say thank you for all the help​. Great Support. No i Have my First working Strategy with Time Restricted Trading and the Right Stops and Targets.;o) And its maybe Profitable so the Stratregy Performance shows...

                  Comment


                    #10
                    Shameless i have a new Problem ( The Strategy works perfect in history but today i have tested realtime and the strategy close the Position immediately after open it at the same price.

                    I have gone thrue the Code but i can not find any mistake i have made. Maybe you can short look at this. Stop should Last X Bars High for Short ans x Bars Low for Long (x=2)

                    The StopLoss and Target works perfect at the History but not live

                    One More Addition: in the Order History shows that the Profit Target has Close the Trade but i can not find any wrong with that. its a 2:1 from the Stop Price, also the last x Candles High/Low for Long or Short.

                    here are my order set code for OnExecutionUpdate(


                    // Order Execution Positioncheck

                    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                    {

                    // Long Position Check
                    if (execution.Order.Name == "SystemLong" && execution.Order.OrderState == OrderState.Filled){

                    if(Position.AveragePrice>=1){

                    // Set StopLoss under StopBars Low
                    Print(" Stop Loss Long "+ (Low[LowestBar(Low,StopBars)] - TickSize));
                    SetStopLoss("SystemLong", CalculationMode.Price, (Low[LowestBar(Low,StopBars)] - TickSize), false);

                    // If Bar Range kleiner als Average dann Target * 1.5
                    if(RangeValue>(Position.AveragePrice-Low[LowestBar(Low,StopBars)])*1.5){

                    if(TestMode){
                    Print(Time[0] + " OutSide Stop Pips "+ (Position.AveragePrice-Low[LowestBar(Low,StopBars)])+" Range Value " +RangeValue);
                    }

                    FlexTarget=Target_RR*1.5;
                    }else{FlexTarget=Target_RR;}

                    SetProfitTarget("SystemLong", CalculationMode.Price, (Position.AveragePrice+((Position.AveragePrice-Low[LowestBar(Low,StopBars)])*FlexTarget)) + TickSize);

                    if(TestMode){
                    Print (Time[0]+" Stop Pips "+ (Position.AveragePrice-Low[LowestBar(Low,StopBars)])+" Range Value " +RangeValue);
                    }
                    }
                    }


                    // Short Position Check
                    if (execution.Order.Name == "SystemShort" && execution.Order.OrderState == OrderState.Filled){

                    if(Position.AveragePrice>=1){

                    // Set Stop over StopBars High
                    Print(" Stop Loss Short "+ High[HighestBar(High,StopBars)] + TickSize);
                    SetStopLoss("SystemShort", CalculationMode.Price, (High[HighestBar(High,StopBars)] + TickSize), false);

                    // If Bar Range kleiner als Average dann Target * 1.5
                    if(RangeValue>(High[HighestBar(High,StopBars)]-Position.AveragePrice)*1.5){

                    if(TestMode){
                    Print(Time[0] + " Outside Stop Pips "+ (High[HighestBar(High,StopBars)]-Position.AveragePrice)+" Range Value " +RangeValue);
                    }
                    FlexTarget=Target_RR*1.5;
                    }else{FlexTarget=Target_RR;}


                    SetProfitTarget("SystemShort", CalculationMode.Price, (Position.AveragePrice-((High[HighestBar(High,StopBars)]-Position.AveragePrice)*FlexTarget)) - TickSize);

                    if(TestMode){
                    Print (Time[0] + " Stop Pips "+ (High[HighestBar(High,StopBars)]-Position.AveragePrice)+" Range Value " +RangeValue);
                    }
                    }
                    }
                    }

                    Last edited by orbito; 09-13-2023, 09:02 AM.

                    Comment


                      #11
                      Hello orbito,

                      Thanks for your notes.

                      I do not see anything specifically standing out in the code that you shared that would cause the behavior to occur.

                      You would need to further debug your script to understand exactly how the orders are submitted when running the strategy on realtime data.

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

                      You could also enable TraceOrders when debugging the behavior of your orders. With the use of this property, you can track orders placed, amended, and canceled. The traces displayed in the NinjaScript Output window.

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


                        #12
                        Thank you i will try that. I have see now that the Profit Target Close the Position after open. i have set some Prints for the next realtime order.

                        The Strategy is a OnBarClose so ist should be easy to set the stop and profit right.

                        hhhm Can i simulate a realtime with the playback function?
                        Last edited by orbito; 09-13-2023, 09:15 AM.

                        Comment


                          #13
                          Hello orbito,

                          Thanks for your notes.

                          Calculate.OnBarClose means that the strategy code executes once at the end of each bar and will perform calculations on completed bars

                          Yes, you could use the Playback connection with Market Replay data to mimic the strategy running on realtime data.

                          Market Replay data could be downloaded from the Tools > Historical Data window.

                          See the help guide documentation below for more information.

                          Calculate: https://ninjatrader.com/support/help.../calculate.htm
                          Playback: https://ninjatrader.com/support/help...8/playback.htm
                          Downloading Market Replay data: https://ninjatrader.com/support/help...8/set_up12.htm
                          Last edited by NinjaTrader_BrandonH; 09-13-2023, 09:19 AM.
                          <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
                            so i have the first realtim trade and have become 3 error alerts i have attached as image but i dont know what all of this means.
                            In Script Output are nothing. i dont know why my prints are not showing there.
                            I that because i must use the SetStopLoss order With the From Entry with '@"SystemLong"' and not only the "SystemLong" name?

                            Sorry i´am new to this and try to start with the process but i dont know why this work historicel and not realtime
                            Attached Files

                            Comment


                              #15
                              Hello orbito,

                              Thanks for your notes.

                              The error message in the screenshot you shared indicates that a buy stop or buy stop limit order was placed on the wrong side of the market. Since the order was placed on the wrong side of the market, the order was rejected.

                              Since the order was rejected, the second OCO ID error message occurred. This is because the first order was rejected and the two stop/profit orders are tied by OCO.

                              Buy stop orders must be placed above the current ask price. Sell stop orders must be placed below the current bid price.

                              When the order is submitted, is the stop price parameter greater than the GetCurrentAsk() for a buy stop order? Or, is the stop price parameter less than the GetCurrentBid() for a sell stop order?

                              I suggest you add prints to the strategy to determine why the order is being rejected. One line above where the stop order is placed, print the GetCurrentAsk()/GetCurrentBid() and print the price being submitted to the Set order method.

                              ​Below is a link to a forum post that demonstrates using prints to understand behavior.
                              https://ninjatrader.com/support/foru...121#post791121

                              Please see the help guide documentation below for more information about GetCurrentAsk().
                              https://ninjatrader.com/support/help...currentask.htm

                              See this help guide documentation about GetCurrentBid():
                              https://ninjatrader.com/support/help...currentbid.htm

                              Note that if this is due to market volatility then there isn't really a way to 100% avoid this occurring, as in volatile markets the market could move so far and fast that this would occur.

                              You could consider using RealtimeErrorHandling.IgnoreAllErrors to determine the behavior of a strategy when the strategy places an order that is returned "Rejected". The default behavior is to stop the strategy, cancel any remaining working orders, and then close any open positions.

                              Please note that setting this property value to IgnoreAllErrors can have serious adverse affects on a running strategy unless you have programmed your own order rejection handling in the OnOrderUpdate() method. To do this you could trap the rejected order by checking if the OrderState is Rejected within OnOrderUpdate() followed by defining your own order rejection handling behavior for the rejected order.

                              Please see the example in the help guide link below that demonstrates using RealtimeErrorHandling and trapping a rejected order in OnOrderUpdate().

                              RealtimeErrorHandling — https://ninjatrader.com/es/support/h...orhandling.htm
                              Last edited by NinjaTrader_BrandonH; 09-13-2023, 10:31 AM.
                              <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, Yesterday, 05:17 AM
                              0 responses
                              54 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              131 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              73 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