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

    #16
    Hello esborsa,

    Thanks for the reply.

    You can use tags to control which Stop Loss is attached to each entry.

    The tag string can be based off of the current bar, so that can be used to create unique entries that have a unique stop loss associated.

    Please consider the following as an example:

    Code:
    if ((Low[0] >= Low[1])
    	 && (High[0] <= High[1]))
    {
    	EnterLong(Convert.ToInt32(DefaultQuantity), @"LongEntry" + CurrentBar.ToString());
    	SetStopLoss( @"LongEntry" + CurrentBar.ToString(), CalculationMode.Price, Low[0], false);
    }
    The code checks the entry conditions and attaches a stop loss to the tagged entry order. Since the tag is "@"LongEntry" + CurrentBar.ToString()" these will be unique with each iteration of OnBarUpdate().

    You may wish to reference the SetStopLoss() documentation for syntax when specifying an entry signal: https://ninjatrader.com/support/help...etstoploss.htm

    Please let me know if you have any additional questions.
    JimNinjaTrader Customer Service

    Comment


      #17
      Hello Jim,

      This solution doesn't work for me. I need to create 2 entry orders to scale out half of the position at a multiple of initial risk (as described in http://ninjatrader.com/support/forum...ead.php?t=3751 ), and don't want to open a new position if scale out of previous entry hasn't been filled. I want to avoid situations like the one shown in image.

      In the image attached EntriesPerDirection is set to 1 and EntryHandling is set to EntryHandling.UniqueEntries, which I understand I can open 1 position long (or short) with unique name simultaneously but behaves the same with EntryHandling.AllEntries and EntriesPerDirection is set to >2.

      The problem is that I don't know how many opened positions I can achieve. The strategy opens 2 long positions every time conditions are met and scale out 1 position at a multiple of risk and let the other position run. The idea is get as much positions as possible.

      Code:
      Entry orders, stop loss and take profit are coded as follows:
      SetStopLoss(@"BTO1-" + CurrentBar.ToString(), CalculationMode.Price, (Low[0] + (SpreadOffsetDown * (TickSize * 10))) , false);
      SetStopLoss(@"BTO2-" + CurrentBar.ToString(), CalculationMode.Price, (Low[0] + (SpreadOffsetDown * (TickSize * 10))) , false);
      SetProfitTarget(@"BTO1-" + CurrentBar.ToString(), CalculationMode.Price, (High[0] + (SpreadOffsetUp * (TickSize * 10)) + InitialRisk ));
      EnterLongStopMarket(Convert.ToInt32(PosQty), (High[0] + (SpreadOffsetUp * (TickSize * 10))) , @"BTO1-" + CurrentBar.ToString());
      EnterLongStopMarket(Convert.ToInt32(PosQty), (High[0] + (SpreadOffsetUp * (TickSize * 10))) , @"BTO2-" + CurrentBar.ToString());
      Is there a solution for this?
      Attached Files

      Comment


        #18
        Hello esborsa,

        Thanks for the reply.

        Using EntryHandling.UniqueEntries will allow multiple entries to be placed for each unique entry tag. Since you are creating unique tags on each entry, EntriesPerDirection will not have an effect on limiting the number of entries.

        I would suggest to use EntryHandling.AllEntries so the EntriesPerDirection applies to all entries. As long as you are using orders in one direction, you should not have issue managing how many entries you would like your strategy to make.

        You may also wish to use your own logic to manage how many times the strategy will re-enter its positions.

        For the thread's reference, Entry Handling documentation can be found here - https://ninjatrader.com/support/help...ryhandling.htm

        Please let me know if you have any questions.
        JimNinjaTrader Customer Service

        Comment


          #19
          Hello Jim,

          This doesn't work either. Setting EntryHandling.AllEntries and EntriesPerDirection to 2, if I have a position running and try to enter 2 new positions, just opens one position to complete 2 entries (as shown in image 1). If setting EntryHandling.AllEntries and EntriesPerDirection to 3, if I have 2 positions running and conditions to enter again are met, opens 1 position to a total of 3 (as shown in image 2).

          The point here is that I need to open positions twice because of scalling out and don't want to open new positions while previous entry hasn't scaled out to take profit. Is this possible?
          Attached Files

          Comment


            #20
            Hello esborsa,

            This will likely best be done by writing your own logic to enter and re-enter positions.

            For example, you can check when an order gets filled, and then you can then set a value to a boolean variable that would allow you to re-enter your positions.

            This kind of order management would involve using Order objects to manage each order, using an override for OnOrderUpdate() to identify when a an order gets filled, and your own boolean variables to further control when your entries should trigger. You may also wish to keep track of the names for your entry signals so you can reference them within OnOrderUpdate(). A List would would be a good type to keep track of entry signal names.

            Here is some documentation and sample code for using OnOrderUpdate() and Order objects that should get you started:

            Using OnOrderUpdate and OnExecutionUpdate() - http://ninjatrader.com/support/forum...ead.php?t=7499

            List - https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx

            Order - http://www.ninjatrader.com/support/h...lightsub=Order

            OnOrderUpdate() - http://www.ninjatrader.com/support/h...=OnOrderUpdate

            In the support department at NinjaTrader we do not create, debug, or modify code for our clients. This is so that we can maintain a high level of service for all of our clients. However if you’d like I could have someone from our business development team pass over a list of third party developers that you could contact about developing your code. If that is the case, please write in to platformsupport[at]ninjatrader[dot]com with the text "Attention Jim" and a copy of the thread's URL.

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

            Comment


              #21
              Hello Jim,

              I'm completing my strategy adding short conditions and positions. But it seems that Strategy Analyzer prioritizes the order in which code is written other than in which price moves.

              This is the way my code is written:

              if ( conditions to long position)
              {
              EnterLongStopMarket();
              }
              if ( conditions to short position)
              {
              EnterShortStopMarket();
              }

              And always enters long and, if doesn't trigger, enters short. But, if I write conditions and orders to short position before conditions and orders to long position, always enters short and, if doesn't trigger, enters long.

              Attached is an example from Strategy Analizer with a long position (60 minute 8h candle). But if I look at a 1 minute chart, I can see that the price moved downside and should have triggered a short position instead long position shown in SA. In this second image the rectangle represents 60 minute 8h candle.

              Is this as expected? Can it be changed the way it triggers orders as price moves?
              Attached Files

              Comment


                #22
                Hello esborsa,

                Thanks for writing back.

                The strategy logic will follow how it is written within the strategy. There is not a way you can tell NinjaTrader to prioritize logic in an out-of-order fashion. The logic must be written to accommodate your needs.

                You are observing that once the first set of conditions are met, then the second conditions cannot be fulfilled. This is happening do to how the logic is written and you would need to debug the strategy with TraceOrders and Print() statements to observe why the second set of conditions do not get filled.

                But if I look at a 1 minute chart, I can see that the price moved downside and should have triggered a short position instead long position shown in SA.
                If the Strategy Analyzer is running a backtest on hourly bars, you will not be able to get intra bar order submissions unless you have added an additional data series for the intra-bar granularity. For example, you can use AddDataSeries() to add an additional data series. If you add a data series with minute data or tick data, you can submit your orders as often as the data series with the finest granularity iterates an OnBarUpdate().

                When using AddDataSeries() to add additional data series, you will have to use BarsInProgress to specify the data series that is being used. 0 is the primary, and each addition data series will be 1, 2, 3, etc.

                Code:
                protected override void OnBarUpdate() 
                { 
                    // Check which Bars object is calling the OnBarUpdate() method 
                    if (BarsInProgress == 0) 
                    { 
                        // A value of zero represents the primary Bars which is the ES 09-14 
                        // 1 minute chart. 
                        // Do something within the context of the 1 minute Bars here 
                    } 
                    else if (BarsInProgress == 1) 
                    { 
                        // A value of 1 represents the secondary 5 minute bars added in the Initialize() 
                        // Do something within the context of the 5 minute Bars 
                    } 
                }
                There is a sample strategy on our forums that outlines using additional data series which may be of use to you:
                You can submit orders to different Bars objects. This allows you the flexibility of submitting orders to different timeframes. Like in live trading, taking entry conditions from a 5min chart means executing your order as soon as possible instead of waiting until the next 5min bar starts building. You can achieve this by


                Please also take the time to read the documentation on creating NinjaScripts for Multi-Time Frame & Instruments: http://ninjatrader.com/support/helpG...nstruments.htm

                Here are the relevant sections of the help guide that the sample sample uses. These sections can be used to reference the components used to reference additional data series.


                Please let me know if I can be of further help.
                JimNinjaTrader Customer Service

                Comment


                  #23
                  Hello Jim,

                  I get a wrong output from time filter you explained me in your post nr.8. I've applied my conditions to emini SP intraday data. Code is as follows:

                  Code:
                              if (((Times[0][0].TimeOfDay > TimeMax.TimeOfDay)
                                   || (Times[0][0].TimeOfDay < TimeMin.TimeOfDay)))
                              {
                                  InTimeFrame = false;
                              }
                                          if (((Times[0][0].TimeOfDay >= TimeMin.TimeOfDay)
                                   && (Times[0][0].TimeOfDay <= TimeMax.TimeOfDay)))
                              {
                                  InTimeFrame = true;
                              }
                              // Daily OpenPrice
                              if (Times[0][0].TimeOfDay == TimeOpen.TimeOfDay)
                              {
                                  OpenPrice = Open[0];
                              }
                  TimeMin = 8:30
                  TimeMax=10:30
                  TimeOpen=8:30

                  I'm expecting to get InTimeFrame = True in my 8:35 candle (which includes data from 8:30 to 8:35) but I get InTimeFrame = False as you can see in image attached and changes to True in 8:40 candle. I also get a wrong OpenPrice, which should be the opening sesion price. InTimeFrame also would change to false at 10:35 candle but changes at 10:40

                  Is there any way to correct this?
                  Attached Files

                  Comment


                    #24
                    Hello esborsa,

                    Thanks for the additional question.

                    Keep in mind when a strategy is set to Calculate.OnBarClose, the bar time will match the closing of that bar.

                    If you want to catch the opening of the bar you will want to reference the opening of the next bar that closes. To be able to capture the opening price of the bar after that time and before the next close of a bar, you will have to utilize Calculate.OnEachTick or use an additional data series to detect when the opening after the bar has closed.

                    Using Calculate.OnEachTick, you can also use IsFirstTickOfBar to tell you that OnBarUpdate() is getting iterated for the first tick after a new bar. Here would be an ideal moment to capture the opening price before the bar completes.

                    Please take note of the tips and notes within the Calculate documentation for complete understanding of its intricacies: https://ninjatrader.com/support/help...?calculate.htm

                    IsFirstTickOfBar: https://ninjatrader.com/support/help...ttickofbar.htm

                    Using intrabar granularity, you can use a separate data series, for example a 1 tick data series, to detect when a tick has occurred after the main bar has closed. Below is an example of how you can use a bool NewOpen and a secondary data series to capture the open on the next tick after the bar closes. Keep in mind you will have to have a 1 tick data series as the first data series added in State == State.Configure for this technique to work.
                    Code:
                    if (BarsInProgress == 0 && Times[0][0].TimeOfDay >= TimeOpen.TimeOfDay)
                    {
                    	NewOpen = true;
                    }
                    
                    if (BarsInProgress == 1 && NewOpen = true)
                    {
                    	OpenPrice = Open[1][0];
                    	NewOpen = false;
                    }
                    There is a sample strategy on our forums that outlines this which may be of use to you:
                    You can submit orders to different Bars objects. This allows you the flexibility of submitting orders to different timeframes. Like in live trading, taking entry conditions from a 5min chart means executing your order as soon as possible instead of waiting until the next 5min bar starts building. You can achieve this by


                    Associated documentation for all components used in that sample are linked in that forum post.

                    Please also take the time to read the documentation on creating NinjaScripts for Multi-Time Frame & Instruments: http://ninjatrader.com/support/helpG...nstruments.htm

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

                    Comment


                      #25
                      Hello Jim,

                      Thank you for your reply.

                      So, as I understand, i should use Calculate.OnEachTick() (which means testing in real time) or have a tick data serie to get opening price (which I don't have). As I'm backtesting historical 1 minute data, is there any other option to get opening price?

                      Comment


                        #26
                        Hello esborsa,

                        Yes, your understanding of using Calculate is correct.

                        Calculate.OnEachTick would be valid for real-time data, and as the help guide states, it will behave like Calculate.OnBarClose for historical data. Back testing uses historical data so Calculate.OnEachTick would behave like Calculate.OnBarClose.

                        To capture the opening price in a way that would work for both historical and real-time data, I would suggest to add intra-bar granularity to your strategy.

                        Additional information regarding the discrepancies between historical and realtime data can be noted here: https://ninjatrader.com/support/help...ime_vs_bac.htm

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

                        Comment


                          #27
                          Hello Jim,
                          I'm trying to understand Multi-timeframe objects. I'm coding a kind of breakout strategy which goes long or short depending on a level touched.
                          As you can see in image attached, in some cases position is opened the next bar it should (5 min chart), so I decided to add a secondary 1 minute serie through
                          Code:
                          else if (State == State.Configure)
                                      {
                                          AddDataSeries(Data.BarsPeriodType.Minute, 1);
                                      }
                          and then,
                          Code:
                          protected override void OnBarUpdate()
                          if (BarsInProgress == 0)
                          {Conditions to open position
                                 longEntry         = SubmitOrderUnmanaged(1, OrderAction.Buy, OrderType.StopMarket, OrderQuantity, 0, LCPoints().R1[0], "entry", "BTO");
                                              
                                 shortEntry         = SubmitOrderUnmanaged(1, OrderAction.SellShort, OrderType.StopMarket, OrderQuantity, 0, LCPoints().S1[0], "entry", "STO");
                          }
                          But I get short at second bar instead when it touches short level. Is this as expected? Should I set primary serie to 1 minute and secondary serie to 5 minutes to be able to get short at right time?

                          On the other hand, is it possible to avoid entries in early close days?
                          Attached Files
                          Last edited by esborsa; 05-16-2017, 09:15 AM.

                          Comment


                            #28
                            Hello esborsa,

                            Thanks for writing back.

                            What you are seeing would be expected.

                            Since the primary data series is set to 5 minutes, even if the order gets filled on the 1 minute data series, the order will be display for the current primary bar that is developing or has not been closed yet.

                            If you consider that when the bar closes, then the order is submitted to the 1 minute data series. Since the minute on the secondary series takes place after the bar close of the primary series, it will display for the next bar that is forming.

                            You could use a 1 minute data series as the primary series if you would like to see plots showing up every minute, but since the orders are submitted on the bar close, you would have to expect them to become filled on the next bar when using Calculate.OnBarClose.

                            If you have nay additional questions, please don't hesitate to ask.
                            JimNinjaTrader Customer Service

                            Comment


                              #29
                              Hello Jim,
                              Thanks for your reply.
                              You probably haven't seen my last question. Is there a way to prevent calculations in indicators and entries in early close days, like Independence or Thanksgiving days?

                              Comment


                                #30
                                Hello esborsa,

                                Thanks for pointing that out.

                                This can be done by creating a return condition for that particular date. As an example:

                                Code:
                                if (Times[0][0] == new DateTime(DateTime.Now.Year, 10, 31)) return;
                                This would prevent execution when the time of the current bar of the primary data series has a date equivalent to Halloween.

                                You could also define a Trading Hours template in which your data series will not parse when it is a holiday defined in the Trading Hours template. The indicators and strategies will have to be assigned to a data series with the specific Trading Hours Template defined.

                                Trading Hours - https://ninjatrader.com/support/help...urs_window.htm

                                You could use the example function overload for AddDataSeries() to add a data series with a specific Trading Hours Template. This Data Series can then be used for you indicators and strategy to calculate on. (The BarsInProgress for this Data Series will reference the Data Series with the Trading Hour template applied.)

                                Code:
                                AddDataSeries(string instrumentName, BarsPeriod barsPeriod, string tradingHoursName)
                                AddDataSeries() - https://ninjatrader.com/support/help...dataseries.htm
                                JimNinjaTrader Customer Service

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by jclose, Today, 09:37 PM
                                0 responses
                                5 views
                                0 likes
                                Last Post jclose
                                by jclose
                                 
                                Started by WeyldFalcon, 08-07-2020, 06:13 AM
                                10 responses
                                1,413 views
                                0 likes
                                Last Post Traderontheroad  
                                Started by firefoxforum12, Today, 08:53 PM
                                0 responses
                                11 views
                                0 likes
                                Last Post firefoxforum12  
                                Started by stafe, Today, 08:34 PM
                                0 responses
                                11 views
                                0 likes
                                Last Post stafe
                                by stafe
                                 
                                Started by sastrades, 01-31-2024, 10:19 PM
                                11 responses
                                169 views
                                0 likes
                                Last Post NinjaTrader_Manfred  
                                Working...
                                X