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

Is it possible to do Intra bar order generation in a strategy

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

    Is it possible to do Intra bar order generation in a strategy

    Hi all,

    I have a strategy that I wrote in EasyLanguage and I want to convert it to run using Ninja Script.

    I run it on a daily chart and look for a certain pattern to set up and when it does I set a limit order to place a trade. It checks for the pattern to setup at every tick throughout the day.

    In EasyLanguage I set the following at the very top of the file to make this work.

    [Intrabarordergeneration=True]

    I noticed that there is an enum -
    Calculate.OnEachTick

    Will this do the trick?
    Last edited by NeverDownMoney; 09-11-2020, 11:13 PM.

    #2
    Hello NeverDownMoney,

    Thanks for your post.

    Yes. intrabar logical processing can be achieved with Calculate.OnPriceChange or OnEachTick. This would be used for realtime data processing only.

    Tick Replay can used for Calculate.OnEachTick and Calculate.OnPriceChange modes in historical processing/backtesting, but we should note that orders will still be filled based on the Open High Low and Close values of the data series we submit the orders to. To overcome this, the strategy may be unlocked and orders can be submitted to a single tick data series. This is essentially doing the same thing as using High Order Fill Resolution, but submitting orders to the single tick data series on our own will work with Tick Replay.

    Please note that we can use the Playback Connection to simulate realtime data processing.

    Tick Replay - https://ninjatrader.com/support/help...ick_replay.htm

    Developing for Tick Replay - https://ninjatrader.com/support/help...ick_replay.htm

    Understanding Historical Fill Processing - https://ninjatrader.com/support/help...ical_fill_.htm

    Backtesting with intrabar granularity (can be used in place of High Order Fill Resolution) — https://ninjatrader.com/support/help...ipt_strate.htm

    We look forward to assisting.
    JimNinjaTrader Customer Service

    Comment


      #3
      Hello,
      the strategy is running on the primary feed 5Min. There is a second feed added (1Tick) on which the order should be executed. In the screen you can see that the signal does not come intrabar. It should already come at the red marked bar when touching the green horizontal indicator line. Somehow it calculates on the primary feed. How can I change this? Thanks!

      My code in OnBarUpdate():

      Code:
      if (BarsInProgress == 0)
      {
           if (CrossAbove(Closes[1], greenLine, 1))
           {
                EnterLong(1, Lots, "L01");
           }
      }​​
      Click image for larger version

Name:	intrabarOrderGeneration.png
Views:	323
Size:	17.0 KB
ID:	1244532

      Comment


        #4
        Hello signalworks,

        Thanks for your post.

        Are you running your strategy on a realtime chart? Or, are you running your strategy in the Strategy Analyzer?

        What Calculate mode is your strategy using? (OnBarClose, OnPriceChange, OnEachTick)

        When Calculate is set to Calculate.OnBarClose, the strategy will process OnBarUpdate() logic at the close of each bar.

        To have the strategy process logic intrabar you could set the Calculate mode to Calculate.OnPriceChange or Calculate.OnEachTick.

        Calculate.OnPriceChange means that OnBarUpdate() logic will process for each change in price. Calculate.OnEachTick means the strategy will process OnBarUpdate() logic for each incoming tick.

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

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

        Comment


          #5
          Thank you, Brandon! The CalculateMode is Calculate.OnEachTick. It's a realtimeChart. is the CrossAbove function suitable for this?

          Comment


            #6
            Hello signalworks,

            Thanks for your note.

            The CrossAbove() method checks if one series crossed above another series or double value within a specified look-back period. The look-back period refers to the number of bars back to check the cross above condition.

            CrossAbove(): https://ninjatrader.com/support/help...crossabove.htm

            Since the strategy is not entering where you are expecting it to, I suggest adding and reviewing print statements in the NinjaScript Output window to get a better understanding of the values used in your conditions and why the conditions are evaluating as true to allow the entries. Below is a link to a forum post that demonstrates how to use prints to understand behavior.
            https://ninjatrader.com/support/foru...121#post791121

            That said, you could store the previous tick's close price into a variable and perform a check to compare the last closed tick's price with your value and the previous tick's price with that value to see if a crossover has occurred intrabar.

            The following forum post contains a snippet that demonstrates CrossAboveFromLastTick and you could use similar logic in your script to achieve the desired result:
            https://forum.ninjatrader.com/forum/...91#post1092491

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

            Comment


              #7
              Hello again,

              I am still on the issue. The implementation would be more precise with limits. However, error messages come up, such as this one:

              An Enter() method to place an entry order was ignored
              and
              Error calling 'OnOrderUpdate' method at bar 89: The object reference was not set to an object instance.
              The Einter-method in OrderBarUpdate looks like this and in addition OnOrderUpdate with Order-handling:
              What else do I have to consider here?
              Thank you!

              Code:
              private Order orderLE = null;
              private Order orderSE = null;​
              
              protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
              {
                          if (order.Name == "LE")
                               orderLE = order;
              
                          if (order.Name == "SE")            
                              orderSE = order;
              
                          #region ORDER.LONG
                          if (orderLE != null && orderLE == order)
                          {
                              if (order.OrderState == OrderState.Filled)
                              {
                                  orderLE = null;
                              }
              
                              if (orderLE.OrderState == OrderState.Cancelled)
                              {
                                  orderLE = null;
                              }
                          }
                          #endregion
              
                          #region ORDER.SHORT
                          if (orderSE != null && orderSE == order)
                          {
                              if (order.OrderState == OrderState.Filled)
                              {
                                  orderSE = null;
                              }
              
                              if (orderSE.OrderState == OrderState.Cancelled)
                              {
                                  orderSE = null;
                              }
                          }
                          #endregion
                      }​
              
              
              protected override void OnBarUpdate()
              {
              ​     if (CurrentBar < BarsRequiredToPlot)
                        return;
              
                   if (BarsInProgress == 1)
                   {                
                        return;
                   }​
              
                  if (TIME_CONDITIONS == true)  //TIME_CONDITIONS => PseudoCode
                  {
                        if (orderLE == null)
                        {
                             orderLE = new Order();
                             orderLE = EnterLongLimit(0, true, Lots, sdHi[0], "LE");
                        }
              
              ​          if (orderSE == null)
                        {
                             orderSE = new Order();
                             orderSE = EnterShortLimit(0, true, Lots, sdLo[0], "SE");
                        }​
                  }
              
                  //......
              
                  if (Position.MarketPosition == MarketPosition.Long
                    && orderSE != null
                     )
                   {
                         CancelOrder(orderSE);
                    }
              
                   if (Position.MarketPosition == MarketPosition.Short
                    && orderLE != null
                     )
                   {
                         CancelOrder(orderLE);
                   }​
              }

              Comment


                #8
                Hello signalworks,

                Thanks for your notes.

                Is this the full error message you are seeing for the error "An Enter() method to place an entry order was ignored"?

                If not, what exactly does the full error message report?

                The error message "Object reference not set to the instance of an object" means that something in the script is returning null at the time you are accessing it. Debugging steps would need to be taken to determine what exactly is returning null in the indicator.

                That said, in the code you shared it seems that you are defining 'orderSE' and 'orderLE' as class-level variables and you are calling "orderLE = new Order()' and 'orderSE = new Order()' in OnBarUpdate.

                Since you are defining those Order objects as class-level variables, you could remove the "orderLE = new Order()' and 'orderSE = new Order()' lines of code in the script and just call ' orderLE = EnterLongLimit(0, true, Lots, sdHi[0], "LE")' and 'orderSE = EnterShortLimit(0, true, Lots, sdLo[0], "SE")'.

                Please see this reference sample demonstrating how OnOrderUpdate() could be used in a NinjaScript: https://ninjatrader.com/support/help...and_onexec.htm

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

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

                Comment


                  #9
                  Hello Brandon,

                  thank you very much.

                  The fully error message is in case of the Enter() Method:

                  An Enter() method for placing an entry order was ignored. Please search for the term 'Internal Order Handling Rules' in the user manual for a detailed explanation.
                  I found out that an Enter() method was ignored: Only one of the two Enter() methods is processed at the same time. I changed the logic to EnterLongStopMarket() or EnterShortStopMarket(). The result is the same - the second Enter() method is ignored. If I deactivate the upper one, the second one is processed and the signal is generated.
                  Now the crucial question;-): Can NinjaTrader set two StopMarket orders in parallel? (which I assume) What would have to be handled differently in the code?​
                  Thank you!

                  Code:
                  protected override void OnBarUpdate()
                  {
                  ​ if (CurrentBar < BarsRequiredToPlot)
                       return;
                  
                  if (BarsInProgress == 1)
                  {
                       return;
                  }​
                  
                  if (TIME_CONDITIONS == true) //TIME_CONDITIONS => PseudoCode
                  {
                       orderLE = EnterLongStopMarket(0, true, Lots, sdHi[0], "LE");     //same result with: EnterLongStopMarket(Lots, sdHi[0], "LE");
                  
                       orderSE = EnterShortStopMarket(0, true, Lots, sdLo[0], "SE");     //same result with: EnterShortStopMarket(Lots, sdLo[0], "SE");
                  }​

                  Comment


                    #10
                    signalworks With the managed order approach, you cannot have pending entry orders both long and short at the same time. You would need to use unmanaged orders for this, or you would need to do something like put one side on (whichever is closer) and as price gets closer to the other side, cancel the first side and put the other side on.

                    You may wish to refer to https://forum.ninjatrader.com/forum/...et-oco-example or the several other unmanaged bracket breakout examples on the forum to save you time understanding the issues with this.
                    Bruce DeVault
                    QuantKey Trading Vendor Services
                    NinjaTrader Ecosystem Vendor - QuantKey

                    Comment


                      #11
                      Hello Bruce,

                      thank you very much! Would the unmanaged solution also be backtestable?​

                      Comment


                        #12
                        Hello signalworks,

                        Yes, unmanaged approach strategies can be backtested as long as they are not using Atm Strategy methods.
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Hello Chelsea,

                          in your example script for unmanaged-OCOBracketExample NT8 it says in the description that the script does not work for historical orders. So a backtest would not be possible in this form. What would have to be adjusted here so that historical orders are also generated? Thanks a lot!

                          Comment


                            #14
                            Hello signalworks,

                            Thanks for your notes.

                            The UnmanagedOCOBracketExampleNT8 script shared by my colleague Chelsea on the forum thread linked below contains a condition in OnMarketData() that checks if (State != State.Realtime || ExitOnCloseWait(marketDataUpdate.Time)) return; which means the strategy will only place orders on realtime data, not on historical data.



                            To backtest the strategy on the Strategy Analyzer, you would need to remove the State != State.Realtime from the condition mentioned above. Further, since OnMarketData() is used, you will need to also enable Tick Replay when running the backtest.

                            OnMarketData: https://ninjatrader.com/support/help...marketdata.htm
                            Tick Replay: https://ninjatrader.com/support/help...ick_replay.htm

                            Brandon H.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello again,
                              I am testing the system with delayed market data. The signals are now accurately generated and displayed in the history.
                              However, the display (thick arrow) of the current running signal is moved to this bar with each new bar instead of remaining on the entry bar. The small arrow remains on the entry level, but is also shifted from bar to bar. How do you make the signal stay on the entry bar? Thanks a lot!

                              Click image for larger version

Name:	position_arrow_changes1.png
Views:	248
Size:	13.8 KB
ID:	1251004
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by kujista, Today, 06:23 AM
                              4 responses
                              14 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by traderqz, Yesterday, 09:06 AM
                              2 responses
                              16 views
                              0 likes
                              Last Post traderqz  
                              Started by traderqz, Today, 12:06 AM
                              3 responses
                              6 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by RideMe, 04-07-2024, 04:54 PM
                              5 responses
                              28 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by f.saeidi, Today, 08:13 AM
                              1 response
                              8 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Working...
                              X