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

Taking trader on the start of the next candle

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

    Taking trader on the start of the next candle

    Hello,

    I am trying to build a strategy which enters a long position when the price crosses above the Bollinger band. I want to take the tread on the start of next candle/bar from when the condition is met.
    I used the strategy builder and wrote the following condition:

    Code:
    if ((CrossAbove(Close, Bollinger1.Upper, 1))
    && (Times[0][0].TimeOfDay >= TimeStart.TimeOfDay)
    && (Times[0][0].TimeOfDay <= TimeEnd.TimeOfDay))
    {
    BackBrush = Brushes.CornflowerBlue;
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    }


    Click image for larger version

Name:	image.png
Views:	143
Size:	17.5 KB
ID:	1244003

    ​This works fine when back testing. It takes trade on the next candle after the cross over as it should:
    Click image for larger version

Name:	image.png
Views:	176
Size:	19.3 KB
ID:	1244004
    As seen in the image above, the trade is taken on the start of next candle once the cross over condition is met. But, this is not the case during live trading.
    During live trading it enters the trade on the same candle after the cross over and it does this every time.
    Click image for larger version

Name:	image.png
Views:	167
Size:	14.7 KB
ID:	1244005Click image for larger version

Name:	image.png
Views:	176
Size:	14.9 KB
ID:	1244007

    So, what should I be doing differently to ensure it takes trade on the start of the following candle once the cross over condition is met.
    Please guide me. Thank you for your time and help!​
    Attached Files

    #2
    Hello arp101,

    Use Calculate.OnBarClose to run the logic in OnBarUpdate() after a bar closes to submit an order after the submission bar closes.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_ChelseaB View Post
      Hello arp101,

      Use Calculate.OnBarClose to run the logic in OnBarUpdate() after a bar closes to submit an order after the submission bar closes.
      Hi Chelsea B.​

      Just to make sure that my understanding is correct, when we use Calculate.OnBarClose :

      All the logic and comparisons that exist in the "Conditions" segment are based on the fully formed completed bar, and this calculation
      is done on the very last tick of the "old" bar
      but
      all the actions in the "Actions" segment are executed on the very first tick of the new (yet unshaped) bar.

      For example if we set the Condition: Close[0]>Open[0] ---> Action: Enter Long
      we don't know the "close" price of the bar until the very last tick of the bar, so we can only make this comparison on that specific time point.
      Thus the [0] represent the previous (just completed) bar on the exact time of its closing, and not the newly-born bar that is going to be the new [0] !

      Is that correct ?
      Last edited by KonstantinosNT; 04-03-2023, 05:54 AM.

      Comment


        #4
        What happens is that it waits for the first tick of the new (incomplete bar) to arrive, because until then, it doesn't know that the old bar is complete. When the first tick of the new (incomplete) bar arrives, it runs the conditions but withholds the information about the new tick so the code only sees the completed bars as index [0 back]. So yes and no - it waits until the first tick of the next bar arrives (in terms of sequence of events), but it does not show this to the code when you're looking at the prices or timestamps etc.

        It's important to understand that, speaking generally and without getting into any specific bar type's particulars, you can't know in general that a bar is closed until the first tick of the next bar. Any rules to the contrary would be specific to some particular type of bar, and the platform has to be written to work with all types of bars.

        So, distinguish carefully between WHEN the code runs, and WHAT it shows as Close[0] and Time[0] etc... it runs after the first tick of the next bar arrives, but it shows Close[0] and Time[0] etc. as the last tick of the closed bar.
        Last edited by QuantKey_Bruce; 04-03-2023, 06:02 AM.
        Bruce DeVault
        QuantKey Trading Vendor Services
        NinjaTrader Ecosystem Vendor - QuantKey

        Comment


          #5
          Thank you Bruce !

          Comment


            #6
            Hello KonstantinosNT,

            Bruce is providing good information.

            I wanted to confirm yes, a bar does not close until there is a tick to open the new bar.

            The conditions and actions for the completed bar are not evaluated or triggered until after the bar has fully closed (meaning the first tick of the new bar was received).
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by QuantKey_Bruce View Post
              ...So, distinguish carefully between WHEN the code runs, and WHAT it shows as Close[0] and Time[0] etc... it runs after the first tick of the next bar arrives, but it shows Close[0] and Time[0] etc. as the last tick of the closed bar.
              The following is taken from NinjaTrader Help under the Topic "IsFirstTickOfBar​"

              " Tip:

              In NinjaTrader's event driven framework, bar closures are signaled by the tick that opens the next bar. The price of the last tick of a bar can be referenced by checking Close[1] on IsFirstTickOfBar. .... "


              It says there that on the exact time when "IsFirstTickOfBar​=True" the just complete bar's close price is referenced by [1] bar index.
              It says Close[1] not Close[0].

              Excuse me for insisting on this, but I need to understand exactly when the bar index [0] becomes [1].
              Last edited by KonstantinosNT; 04-04-2023, 11:09 AM.

              Comment


                #8
                Hello KonstantinosNT,

                This is when using Calculate.OnEachTick or .OnPriceChange in real-time or with TickReplay in historical.

                When the bar updates after has fully closed, the most recently updated bar [0], is the fully closed bar.
                When the bar updates before the bar has closed, the most recently updated bar [0], is the currently building bar. To reference the most recent fully closed bar, that would be the previous bar [1].

                Below is a link to the help guide.
                https://ninjatrader.com/support/help...taIsReferenced

                IsFirstTickOfBar can only be false when using .OnEachTick or .OnPriceChange in real-time or with TickReplay in historical.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Yes NinjaTrader_ChelseaB you are right of course. I should have noticed the critical difference between the calculation modes.
                  This picture is also consistent with my own experience when running a strategy in "Calculate.OnBarClose" mode.

                  Comment


                    #10
                    Thank you everyone for your input. I am using Heiken Ashi candle chart for this strategy and need to calculate on each tick. I did some research and found to use the idea of using multi instrument and IsFirstTickOfBar function.

                    I have added
                    Code:
                    else if (State == State.Configure)
                                {
                                    AddHeikenAshi("NQ 06-23", BarsPeriodType.Tick, 150, MarketDataType.Last);
                                }​
                    My on bar update is as follows:
                    Code:
                                protected override void OnBarUpdate()
                        {
                    
                        if (CurrentBars[0] < 1 || CurrentBars[1] < 1)
                            return;
                    
                           // Set 1
                          if (BarsInProgress == 1)
                          {
                    
                              if (IsFirstTickOfBar)
                              {
                    
                    
                                 if ((CrossAbove(Closes[1], Bollinger1.Upper, 1))
                                && (Closes[1][0] > VWMA1[0])
                                && (Times[1][0].TimeOfDay >= TimeStart.TimeOfDay)
                                && (Times[1][0].TimeOfDay <= TimeEnd.TimeOfDay)
                                )
                            {
                                BackBrush = Brushes.CornflowerBlue;
                                EnterLong(Convert.ToInt32(DefaultQuantity), "");
                    
                            }
                              }
                          }
                        }​
                    I expect this to take trade on the start of next candle (first tick) once the conditions are met. This look fine when i back test the data. But in tick replay and in realtime it does not take any trades. What am I doing wrong? Thank you very much for your time and help!

                    Comment


                      #11
                      Hello arp101,

                      If the strategy is getting data and the strategy is enabled or a backtest is run with no errors in the Log tab of the Control Center, then would likely indicate the logic conditions did not evaluate as true or orders are being ignored or cancelled.

                      In order to better understand how the code is working, it will be necessary to use Print to see how the conditions are evaluating and enable TraceOrders to see if orders are being submitted, ignored, rejected, or cancelled.

                      Below is a link to a forum post that demonstrates using prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.
                      https://ninjatrader.com/support/foru...121#post791121

                      Enable TraceOrders, print the time of the bar and all values used in the conditions that submit entry orders. Include labels for all values and comparison operators.

                      Let me know if you need any assistance creating a print or enabling TraceOrders.

                      Save the output from the output window to a text file and provide this with your reply.

                      I'll be happy to assist with analyzing the output.


                      That said, the CrossAbove() condition would be comparing the close of the most recently closed bar [1] with the first tick of this new bar [0]. Are you sure this is what you are wanting? Do you actually want to compare [2] barsAgo with [1] barAgo?​
                      Chelsea B.NinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by Tim-c, Today, 02:10 PM
                      1 response
                      6 views
                      0 likes
                      Last Post NinjaTrader_ChelseaB  
                      Started by Taddypole, Today, 02:47 PM
                      0 responses
                      1 view
                      0 likes
                      Last Post Taddypole  
                      Started by chbruno, 04-24-2024, 04:10 PM
                      4 responses
                      50 views
                      0 likes
                      Last Post chbruno
                      by chbruno
                       
                      Started by TraderG23, 12-08-2023, 07:56 AM
                      10 responses
                      399 views
                      1 like
                      Last Post beobast
                      by beobast
                       
                      Started by lorem, Yesterday, 09:18 AM
                      5 responses
                      23 views
                      0 likes
                      Last Post NinjaTrader_ChelseaB  
                      Working...
                      X