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

Strategy doesn't execute all entries

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

    #31
    Hello Jim,
    I've created a new trading hours template. When defining Early Close in holidays tab Strategy Analyzer calculates indicators and open positions as if the day had normal trading hours. When defining Full Day, indicators ignore data from holidays but still open positions. In image attached you can see 2016 Thanksgiving day long position (BTO 1@2204,50) but indicator is well calculated. Is this as expected?
    Attached Files
    Last edited by esborsa; 05-16-2017, 02:06 PM.

    Comment


      #32
      Hello esborsa,

      After a few tests, this would be expected.

      Please reload the historical data for that interval from a chart that has a data series of that same interval and Trading Hour template. Once the data is reloaded, click Run on the Strategy Analyzer and check your results.

      The newly defined Trading Hour template should now be followed in the Strategy Analyzer.

      Please let me know if I may be of further assistance.
      JimNinjaTrader Customer Service

      Comment


        #33
        Hello Jim,
        Thanks for your reply. Is this a bug that will be solved in future versions?

        Comment


          #34
          Hello esborsa,

          Sorry for any delayed response.

          I am asking the development team if this is a bug of something that should be happening or a limitation of logic that is not implemented. I will update this post when I hear back.

          Thanks in advance for your patience.
          JimNinjaTrader Customer Service

          Comment


            #35
            Hello Jim,
            I'm trying to plot a 200 period daily SMA in a 5 minute chart in Strategy Analizer. I've read some comments saying it's not possible. Is it still that way in NT8?
            My code to do this is:
            Code:
            else if (State == State.DataLoaded)
                        {    
                            SMA1                = SMA(Closes[1], Convert.ToInt32(length));
                            SMA2                = SMA(Closes[1], Convert.ToInt32(length));
                            SMA1.Plots[0].Brush = Brushes.RoyalBlue;
                            AddChartIndicator(SMA1);
                        }
            I also want to get the values of this SMA in output window, so I've added the following line in OnBarUpdate()
            Code:
            Print(string.Format("{0} / SMA = {1}", Time[0], SMA1[0].ToString()));
            but I get this error:
            Error on calling 'OnBarUpdate' method on bar 0: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.
            Could you please tell me what I'm doing wrong?

            Comment


              #36
              Hello esborsa,

              Thanks for writing back.

              I am not aware of any limitation that would not allow you to plot an SMA for a different data series on a chart or through NinjaScript.

              As long as the daily data series is what you are adding with AddDataSeries(), what you have looks correct.

              The error you are reporting is an indexing issue, likely to do with there not being enough bars available for one of the additional data series. Please consider the scenario: The primary data series is 1 minute and the secondary data series is 1 day. OnBarUpdate() will be called for the minute series numerous times before the daily bar iterates through OnBarUpdate(). Therefore, any reference to the daily data series before the daily bar gets iterated would not have a valid reference and would throw that error.

              Please make sure you have enough bars for your additional data series in OnBarUpdate() and not just for the primary data series.

              You may reference CurrentBars for syntax when setting up a return condition for enough bars for multiple data series: https://ninjatrader.com/support/help...urrentbars.htm

              Indexing issues can be troubleshooted with the tips listed here: http://ninjatrader.com/support/forum...ead.php?t=3170

              Please let me know if I may be of further help.

              EDIT: The issue reported for holiday hours not taking affect until after you reload a data series does not appear to be reproducible in the latest continuous build. Once R7 is released, please let me know if you are able to reproduce the Trading hours issue.
              Last edited by NinjaTrader_Jim; 06-02-2017, 03:25 PM.
              JimNinjaTrader Customer Service

              Comment


                #37
                Hello Jim,

                I've updated to NT 8.0.7.1 and session template issue seems to be solved.

                On the other hand, I'm trying to code a kind of intraday breakout strategy using unmanaged order methods and I want my opened orders to be closed X min. before market close.
                In State.SetDefaults I've set IsExitOnSessionCloseStrategy = true and ExitOnSessionCloseSeconds = 300. Using 5 min. charts, this means that all my opened positions should be closed 5 minutes before closing time, but it doesn't work, as you can see in image attached. Does ExitOnSessionClose work with unmanaged approach?
                I've also tried it with this code but no position is opened:

                Code:
                if (Times[0][0].TimeOfDay >= TimeClose.TimeOfDay)
                            {
                                if (longStopEntry != null && execution.Order == longStopEntry)
                                {
                                    SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Market, 1, 0, 0, entryString, @"STC");
                                }
                                else if (shortStopEntry != null && execution.Order == shortStopEntry)
                                {
                                    SubmitOrderUnmanaged(0, OrderAction.BuyToCover, OrderType.Market, 1, 0, 0, entryString, @"BTC");
                                }
                            }
                
                            //when SL o TP executed, set orders to null to enter again
                            else if (execution.Name == "Long SL" || execution.Name == "Long TP" || execution.Name == "STC")
                            {
                                longStopEntry = null;
                            }
                            else if (execution.Name == "Short SL" || execution.Name == "Short TP" || execution.Name == "BTC")
                            {
                                shortStopEntry = null;
                            }
                Would you tell me what's wrong whith this code?
                Attached Files

                Comment


                  #38
                  Hello esborsa,

                  ExitOnSessionClose does work with the unmanaged approach. I have attached a modified version of the Unmanaged Template for NinjaTrader 8 that uses a Session Iterator to limit entries that occur after the ExitOnSessionCloseSeconds. You can use this example to model your logic using ExitOnSessionClose.

                  I have enabled Trace Orders to monitor the orders, and here are my results on the ES 09-17 for yesterday. I used the Playback connection to simulate real time data.

                  6/21/2017 2:59:01 PM CancelAllOrders: BarsInProgress=0
                  6/21/2017 2:59:01 PM CancelAllOrders: BarsInProgress=1
                  6/21/2017 2:59:01 PM Strategy 'UnmanagedTemplate NT8/109459613': Entered internal SubmitOrderManaged() method at 6/21/2017 2:59:01 PM: BarsInProgress=0 Action=BuyToCover OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='Exit on session close' FromEntrySignal=''
                  6/21/2017 4:01:01 PM Strategy 'UnmanagedTemplate NT8/109459613': Entered internal SubmitOrderUnmanaged() method at 6/21/2017 4:01:01 PM: BarsInProgress=1 Action=SellShort OrderType=Limit Quantity=1 LimitPrice=2433.25 StopPrice=0 SignalName='Short limit entry'
                  As you can see, CancelAllOrders() is noted in the output window at 60 seconds before the end of the session, and there is a SubmitOrderManaged() with the SignalName "Exit on session close" noted as well that closes the open position

                  Additional orders are not placed until the beginning of the next session because of the entry condition that uses the session close received from the added Session Iterator.

                  Code:
                  if (longEntry == null && shortEntry == null
                                  && Position.MarketPosition == MarketPosition.Flat
                  				&& Time[0] <= endTime.Subtract(TimeSpan.FromSeconds(ExitOnSessionCloseSeconds)))
                  Here is our documentation on using a Session Iterator - https://ninjatrader.com/support/help...oniterator.htm

                  If you have any additional question, please don't hesitate to ask.
                  Attached Files
                  JimNinjaTrader Customer Service

                  Comment


                    #39
                    Hello Jim,
                    Thank you for your answer. Unfortunately, I cannot reproduce your results with your code.
                    Just for clarification purposes, here's the process to get my results:
                    1. I've imported your code though Tools>Import>NinjaScript Add-On
                    2. I've changed ExitOnSessionCloseSeconds = 300 in State == State.SetDefaults
                    3. I've connected to Playback connection
                    4. I've set settings in SA window as shown in image below and runned strategy
                    I get in at 8:35 and exits at 15:15 (but should exit at 10:10). I've also attached NinjaScript Output.
                    I get similar results setting Trading hours to <Use Instrument settings> or CME US Index Futures ETH.
                    Would you point me what I'm doing wrong?
                    Attached Files

                    Comment


                      #40
                      Hello esborsa,

                      ExitOnSessionCloseSeconds is only used for realtime data. It would not work with historical fill processing in the Strategy Analyzer.

                      From the help guide:
                      Note: This is a real-time only property, it will not have any effect on your ExitOnSessionClose time in backtesting processing historical data.
                      https://ninjatrader.com/support/help...oseseconds.htm

                      Please test the strategy using Market Replay data in the Playback Connection. Market Replay data is treated like real time data in NinjaTrader, and does not use historical fill processing.

                      You can reference using the Playback Connection below.

                      Playback Connection - https://ninjatrader.com/support/help...connection.htm

                      There are significant differences between historical fill processing and using realtime data. I will provide some material that covers these discrepancies and how historical
                      fill processing works.

                      Discrepancies between Realtime and backtest - https://ninjatrader.com/support/help...ime_vs_bac.htm

                      Historical Fill processing - https://ninjatrader.com/support/help...ical_fill_.htm
                      JimNinjaTrader Customer Service

                      Comment


                        #41
                        Hello Jim,

                        ExitOnSessionCloseSeconds is only used for realtime data. It would not work with historical fill processing in the Strategy Analyzer.
                        Does this mean that I cannot close my positions at a specified time using historical data and SA?
                        Isn't there any way to test an intraday strategy and set a closing condition by time using historical data and SA?

                        Comment


                          #42
                          Hi esborsa,

                          It is still possible to close your positions at a certain time before the market close. You are only limited in not using ExitOnSessionCloseSeconds to ExitOnSessionClose.

                          To do this in a context that would work with backtesting, I would create a time based condition to cancel pending/working orders and exit any open positions. You would need to use Order objects to keep track of your orders and you can check the OrderState of those orders to determine if you need to cancel them or close them.

                          The SampleOnOrderUpdate() reference sample is a good example for creating a strategy that uses Order objects. You can find it here: http://ninjatrader.com/support/forum...ead.php?t=7499

                          CancelOrder() - https://ninjatrader.com/support/help...ancelorder.htm

                          Order objects and OrderStates - https://ninjatrader.com/support/help...n-us/order.htm

                          I look forward to assisting further.
                          JimNinjaTrader Customer Service

                          Comment


                            #43
                            Hello Jim,
                            This is what I was trying to do with my code attached in commentary #37
                            In OnExecutionUpdate(), I've coded this to close the opening position at a specified time:
                            Code:
                            if (Times[0][0].TimeOfDay >= TimeClose.TimeOfDay)
                            {
                                if (longEntry != null && execution.Order == longEntry)
                                {
                                    timeExitLong = SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Market, 1, 0, 0, entryString, @"STC");
                                }
                                else if (shortEntry != null && execution.Order == shortEntry)
                                {
                                     timeExitShort = SubmitOrderUnmanaged(0,  OrderAction.BuyToCover, OrderType.Market, 1, 0, 0, entryString, @"BTC");
                                 }
                            }
                            But it doesn't close it.
                            In image attached you can see a position closed in the last candle of day at 15:00h (it should be closed at 14.30h due to this code) because price hits stop and no new position is opened the rest of testing period. It seems that strategy terminates. This doesn't happen without this code snippet.
                            Any idea of what's going wrong with this code?
                            Attached Files

                            Comment


                              #44
                              Hello esborsa,

                              As OnExecutionUpdate() is an event driven method which fires when an execution occurs, your code will have the following result:

                              1. OnExecutionUpdate() occurs when one of your entries gets filled.
                              2. If the current time is greater than the TimeOfClose, an exit it order placed for a long or short entry, depending on the execution that passes through OnExecutionUpdate()

                              I would not advise to place a time check to close your open positions and cancel any pending or working orders within OnExecutionUpdate(). The OnBarUpdate() method would be a proper place to place the time check to then cancel orders and close positions.

                              I would advise to instead do this in OnBarUpdate() before any trading logic, and then to call return so further entries cannot be made for that day.

                              I also suggest to review the documentation for OnExecutionUpdate() to fully understand when this method is called.

                              OnExecutionUpdate() - https://ninjatrader.com/support/help...tionupdate.htm

                              Please let me know if I may be of further assistance.
                              JimNinjaTrader Customer Service

                              Comment


                                #45
                                Jim, thanks for your time. It seems to work now.

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Kaledus, Today, 01:29 PM
                                0 responses
                                0 views
                                0 likes
                                Last Post Kaledus
                                by Kaledus
                                 
                                Started by PaulMohn, Today, 12:36 PM
                                1 response
                                14 views
                                0 likes
                                Last Post NinjaTrader_Gaby  
                                Started by yertle, Yesterday, 08:38 AM
                                8 responses
                                36 views
                                0 likes
                                Last Post ryjoga
                                by ryjoga
                                 
                                Started by rdtdale, Today, 01:02 PM
                                1 response
                                6 views
                                0 likes
                                Last Post NinjaTrader_LuisH  
                                Started by alifarahani, Today, 09:40 AM
                                3 responses
                                17 views
                                0 likes
                                Last Post NinjaTrader_Jesse  
                                Working...
                                X