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 enters and exits positions 1 bar to late

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

    Strategy enters and exits positions 1 bar to late

    Hi!
    I have managed to create my first custom indicator and stratgeies. Everything seams to work fine except that my custom strategies enter positions one bar to late. I have spent a lot of time trying to solve this on my own, but I'm stuck and would appreciate some help. I suspect that this is just a simple misstake on my side.

    To illustrate the problem I have created a simple as possible strategy that enters and exits a position when EMA(18) crossabove/ crossbelow EMA(55). You can see in the attached pic that entries and exits lag 1 bar comapred to the "cross". I'v also created a custom indicator that writes a gray triangle above/ below the bar where the entries and exits should be. This indicator displays the correct bars for exits and entries and contains the same logic as the strategy, but as mentioned the entries and exits of the strategy lags 1 bar behind the indicator. I can't figure out what the reason for this may be. I have set the option OnBarsClose = false in the strategy.

    I have attcahed my strategy settings below.

    The code of the stratgey is:

    Code:
     protected override void Initialize()
            {
                CalculateOnBarClose = false;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
                if (CrossAbove(EMA(FAST), EMA(SLOW), 1))
                {
                    EnterLong();
                }
                if (CrossBelow(EMA(FAST), EMA(SLOW), 1))
                {
                    EnterShort();
                }
            }
    The code of the corresponding indicator is:
    Code:
            protected override void Initialize()
            {
                Long = new BoolSeries(this);
                Short = new BoolSeries(this);
                
                Overlay                = true;
                PriceTypeSupported    = false;
                
    
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
                // Use this method for calculating your indicator values. Assign a value to each
                
                if (CurrentBar < sLOW) return;
                
                bool EnterLong = false;
                bool EnterShort = false;
                
                if (CrossAbove(EMA(fAST), EMA(sLOW), 1))
                {
                    EnterLong = true;
                }
                
                if (CrossBelow(EMA(fAST), EMA(sLOW), 1))
                {
                    EnterShort = true;
                }
                
                Long.Set(EnterLong);
                
                if (Long[0] == true)
                {
                    DrawTriangleUp( "Long" + CurrentBar.ToString(), false, 0, Low[0] - 100*TickSize, Color.LightSlateGray);
                }
                
                Short.Set(EnterShort);
                
                if (Short[0] == true)
                {
                    DrawTriangleDown( "Short" + CurrentBar.ToString(), false, 0, High[0] + 100*TickSize, Color.LightSlateGray);
                }
            
            }
    Attached Files

    #2
    It enters corectly. In reality when you say enter at the bar close, actualy means enter on the next bar open. Thats exactly what it does.

    Baruch

    Comment


      #3
      Baruch is correct. This is expected behavior. If you'd like more resolution, you could add intrabar granularity to your backtest.
      AustinNinjaTrader Customer Service

      Comment


        #4
        Thanks both of you for your quick replies.

        I read in another thread that you only will get intrabar executions with "OnBarClose = false" if you use real time data. If I got it right the reason that I didn't get intrabar executions in my strategi was that I used historical data in a chart. But then how come that I can get "intarbar signals" from the indicator with historical data but not from the strategy?

        Comment


          #5
          Poseidon, you are correct that you can and will get intrabar executions during a real-time test if CalculateOnBarClose is set to false. You are also correct that you don't get intrabar trades (without adding intrabar granularity) during a backtest with historical data. I'm not sure I follow you on that last question; it is possible to get intrabar signals for both historical and real-time backtests.
          AustinNinjaTrader Customer Service

          Comment


            #6
            What I mean is that there seams to be a difference between an indicator and a strategy when it comes to intrabar calculations on historical data. The indicator below that I applied to the chart did point to the correct entry and exit bars in the chart, whilst the same logic in a strategy does point on the next bar. Why this difference between indicators and strategies?

            Comment


              #7
              Poseidon, there shouldn't be a difference. Perhaps you could show us what you mean with some screenshots?

              The only thing that can be "intrabar" is an entry/exit during a real-time test, or the smaller dataseries for a multi-instrument strategy during a backtest.

              This is copy + paste from another post of mine:
              In general, if you're doing a simple backtest without any added detail, orders will execute one bar 'late'.

              CalculateOnBarClose always is true during a backtest, so that means all calculations are done only once at the end of the bar (which is also the beginning of the next bar--the open of a bar isn't known until the bar before it closes). Then, once the conditions are true, an order is submitted (at the close). This order is then executed at the beginning of the next bar.
              AustinNinjaTrader Customer Service

              Comment


                #8
                I have attached a screenshot in my first post below that displays the entries and exits of the strategy as well as the bars that the indicator points on. The code of the strategy and the indicator contains the same logic as you can see from the code in the first post. Nevertheless the strategy is always one bar behind the indicator. The indicator is displayed as gray triangles above/ below the bar.

                It's also obvious from a visual check of the attached chart that the indicator points to the first bar after the crossabove/ crossbelow has occured whilts the strategy lags one bar compared to the indicator.

                Comment


                  #9
                  Originally posted by poseidon_sthlm View Post
                  I have attached a screenshot in my first post below that displays the entries and exits of the strategy as well as the bars that the indicator points on. The code of the strategy and the indicator contains the same logic as you can see from the code in the first post. Nevertheless the strategy is always one bar behind the indicator. The indicator is displayed as gray triangles above/ below the bar.

                  It's also obvious from a visual check of the attached chart that the indicator points to the first bar after the crossabove/ crossbelow has occured whilts the strategy lags one bar compared to the indicator.
                  poseidon_sthlm,

                  Once you referenced EMA for your entry and exit, you activated NT's late order placement issue.

                  Its the 800 pound gorilla in the software!!! They also deny it exists!!!

                  The work around for this problem is that you cannot reference any indicator on the chart your placing the orders on.

                  You will need multiple charts.

                  Define your trading criteria on one chart and place the trade orders on a second chart using only bar references. (High, Low, Open, and Close).

                  We have all been where you are now.

                  Good Luck,

                  RJay
                  RJay
                  NinjaTrader Ecosystem Vendor - Innovative Trading Solutions

                  Comment


                    #10
                    Your screenshot has nowhere showing an indicator ahead of a strategy as there are no arrow up/downs being drawn. When using the same logic there should never be a difference.
                    Josh P.NinjaTrader Customer Service

                    Comment


                      #11
                      But there is an indicator in the screenshot in my first post displayed as GRAY TRIANGLES one bar in front of the exits and entries of strategy! I'm sorry that the gray triangles above/ below the bars were somewhat difficult to see. Therefore I have attached two new screenshots to this post that hopfully will be more clear .

                      The first screenshot shows soley the the indicator (You can find the code for this indicator in post #1) displayed this time as BLUE TRIANGLES above/ belowe the bar where the cross above or cross below condition is true.

                      The seccond screenshot shows the indicator and the stratgey in the same chart. (You can find the code for the indicator and the strategy in post #1. In my opinion booth contain the same logic.) What I see in this chart is that the Indicator points on the first bar after the crossabove/ crossbelow has occured whilts the strategy lags one bar compared to the indicator.

                      I'm rather new to NT. Please help me to understand what the reasons for this phenomenon is. I'v have this problem with all strategies with custom indicators. At firts I thought that this had something to do with that the option "OnBarClose = false" doesn't work with historical data. But now when I see the one-bar-lag between a strategy and a indicator with identical logic, I'm confused.
                      Attached Files

                      Comment


                        #12
                        Look its like this. NT knows that a bar closes only when it receives a tick for the new bar. At that time it runs the OnBarUpdate() in indicator and strategy. In indicator it sees that it has to draw a triangle so it draws it. If you asked NT to draw it 10 bars ago it would do it too, but remember NT all ready received a tick for a new bar. Do you rely think that it can enter a trade on a close of previous bar which could happen 20 secs ago or more? Thats why it enters on an open of a new bar and even this is not correct. NT already got the first tick, which is the open and now it enters a trade, but theoretically the next ticks price can be 10 or 20 ticks above!!!

                        Baruch

                        Comment


                          #13
                          Thanks for your explanation, Baruch.
                          If I got you right you are saying that the visual representation of an indicator in a chart with historical data is compensated for the required first tick of the next bar to run OnBarUpdate(), whilst a strategy isn't. I can accept that, although I don't think it's self-explaining to a newbe since the arrows that a stratgy draws in a chart also are based on historical data. Why isn't the visual representation of a strategy in a chart with historical data compensated for the required first tick of the next bar like an indicator? If this is the case I'm sure there is a good reason for this (Is it the possibility that both entery and exit conditions can be met on the same bar and that NT can't know which came first?) but it deservs an explanation in the documentation. I'm sure that a lot of newbes like me start to explore NT with a free Yahoo feed and program their first custom indicator and then compare the expected entries of the indicator with their custom strategy based on the same indicator. What they will see is that their strategy lags one bar compared to the indicator which is very confusing.

                          To sum up:
                          1) The (self coded) visual representation of entry- and exit signals from an indicator in a chart with hitorical data corresponds to the default visual representation of a real time stratgy run with the condition "OnBarsClose = false".

                          2) The default visual representation of entry- and exit signals from a strategy in a chart with hitorical data will lag 1 bar compared to a real time stratgy run with the condition "OnBarsClose = false" as well as your custom indicator.
                          Last edited by poseidon_sthlm; 12-23-2009, 05:18 AM.

                          Comment


                            #14
                            Hi,
                            Please stop calling it a lag of 1 bar. I explained that it "lags" 1 tick, instead of showing an entry on the bar close, which is impossible it enters and shows the entry on next bar open. (OPEN <> CLOSE) Lag of a bar would be entry on the close of next bar!!!!

                            Baruch

                            Comment


                              #15
                              Originally posted by poseidon_sthlm View Post
                              Thanks for your explanation, Baruch.
                              If I got you right you are saying that the visual representation of an indicator in a chart with historical data is compensated for the required first tick of the next bar to run OnBarUpdate(), whilst a strategy isn't. I can accept that, although I don't think it's self-explaining to a newbe since the arrows that a stratgy draws in a chart also are based on historical data. Why isn't the visual representation of a strategy in a chart with historical data compensated for the required first tick of the next bar like an indicator? If this is the case I'm sure there is a good reason for this (Is it the possibility that both entery and exit conditions can be met on the same bar and that NT can't know which came first?) but it deservs an explanation in the documentation. I'm sure that a lot of newbes like me start to explore NT with a free Yahoo feed and program their first custom indicator and then compare the expected entries of the indicator with their custom strategy based on the same indicator. What they will see is that their strategy lags one bar compared to the indicator which is very confusing.

                              To sum up:
                              1) The (self coded) visual representation of entry- and exit signals from an indicator in a chart with hitorical data corresponds to the default visual representation of a real time stratgy run with the condition "OnBarsClose = false".

                              2) The default visual representation of entry- and exit signals from a strategy in a chart with hitorical data will lag 1 bar compared to a real time stratgy run with the condition "OnBarsClose = false" as well as your custom indicator.
                              You guys have missed my point entirely!!!

                              Your Code

                              protected override void OnBarUpdate()
                              {
                              if (CrossAbove(EMA(FAST), EMA(SLOW), 1))
                              {
                              EnterLong();
                              }
                              if (CrossBelow(EMA(FAST), EMA(SLOW), 1))
                              {
                              EnterShort();
                              }
                              }

                              You are using an EMA to define your conditions to enter and exit trades.

                              If you define your conditions without referencing an indicator, not only will the extra bar problem disappear, you can now execute immediately without having to wait for first tick of next bar if you choose.

                              Code like the following can execute immediately when conditions are met.

                              protected override void OnBarUpdate()
                              {
                              // Condition set 1
                              if (Close[0] > Open[0] + PlusBarRange * TickSize)
                              {
                              EnterShort(DefaultQuantity, "");
                              }

                              // Condition set 2
                              if (Close[0] < Open[0] + MinusBarRange * TickSize)
                              {
                              EnterLong(DefaultQuantity, "");
                              }

                              Your Choice,

                              RJay
                              RJay
                              NinjaTrader Ecosystem Vendor - Innovative Trading Solutions

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by ETFVoyageur, Today, 02:15 AM
                              0 responses
                              7 views
                              0 likes
                              Last Post ETFVoyageur  
                              Started by Board game geek, Today, 01:34 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post Board game geek  
                              Started by morrnel, 05-12-2024, 06:07 PM
                              3 responses
                              40 views
                              0 likes
                              Last Post wzgy0920  
                              Started by FishTrade, Yesterday, 11:11 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post FishTrade  
                              Started by Austiner87, Yesterday, 03:42 PM
                              1 response
                              22 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Working...
                              X