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

Best Practice for Referencing an Indicator on bar close in a Real Time Strategy?

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

    Best Practice for Referencing an Indicator on bar close in a Real Time Strategy?

    Hello!

    What approach do you recommend for referencing an indicator "on bar close" in a real time strategy? I can think of the following two ways.

    1) Adding the indicator to the strategy for calculation update on every tick and then referencing an output series one bar ago on FirstTickOfBar.
    You will have to make sure somehow that the indicator is updated on the last tick of the previous bar if you want to reference the output series on FirstTickOfBar, haven't you?

    2) Shift the entire code of the indicator back one value to be calculated on FirstTickOfBar as decribed in your sample "Separating logic to either calculate once on bar close or on every tick" and then referencing and output series one bar ago. (I use the varibale below to shift between COBC= true and COBC= false.)

    Code:
            protected override void OnBarUpdate()
            {
                if ( FirstTickOfBar )
                {
                    // Shift between RT and COBC
                   int x = (CalculateOnBarClose || Historical) ? 0 : 1;
                }
                else
                {
                    return;
                }
                
                 Values[0][x].Set(x, myOutput);
    
             }


    The first approach means that the indicator has to be calculated for every tick which is computation intense, while the second approach will need more coding for shifting the indexes one bar. Are there other better aproaches?

    // Best Regards
    Poseidon

    #2
    Hello,

    Thanks for the forum post.

    Best approach is to reference the value on FirstTickOfBar. There is no need to look one bar ago.

    Let me know if I can be of further assistance.

    Comment


      #3
      I'm sorry, but I don't think that I have understood your answer correctly. The following code doesn't generate the same output for COBC = true and COBC = false for me, which I thought you meant above. Can you point me in the right direction? Is there a sample/ example somewhere on how to reference an indicators correctly in a real time strategy?

      Strategy
      Code:
              #region VARIABLES
              //Parameters
              private int period            = 5;
      
              //Add Indicator
              private SMA mySMA;
                  
              #endregion
      
              #region OnStartUp()
              protected override void OnStartUp()
              {
                  mySMA = SMA(High, period);
              }
              #endregion
              
              protected override void Initialize()
              {
              }
      
              /// <summary>
              /// Called on each bar update event (incoming tick)
              /// </summary>
              protected override void OnBarUpdate()
              {
                  if ( FirstTickOfBar)
                  {
                      Print("");
                      Print("************************************************************************");
                      Print(Time[0]);
                      Print("CurrentBar: " + CurrentBar);
                      Print("************************************************************************");
                      Print("");
      
                      Print("mySMA.Values[0][0]: " + mySMA.Values[0][0]);
                  }
              }
      
              #region Properties
              // Parameters
              [Description("")]
              [GridCategory("Parameters")]
              public int Period
              {
                  get { return period; }
                  set { period = Math.Max(0, value); }
              }
      
              #endregion

      Comment


        #4
        Please see this sample here Poseidon - http://www.ninjatrader.com/support/f...ad.php?t=19387

        To clarify: you do want to reference one bar back further in your FirstTickOfBar code section as demonstrated in the code above.
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Thank for your prompt replay. I get the expected result in real time when referencing the output series one bar ago on FirstTickOfBar. I now see that the output series of the indicator is properly updated for the previous bar at FirstTickOfBar of the current bar.

          // Best Regards
          Poseidon

          Comment


            #6
            Hello again!

            I have now futher explored how to reference an indicator "on bar close" in a Real Time Strategy. Can you confirm or reject the following findings?

            1) The recomended approach below, to reference an output series of the indicator one bar ago on FirstTickOfBar, requires that the indicator is coded as a real time indicator, by which I mean that the indicator has to return the same output regardless if COBC = true or COBC = false. It's not sufficient to code an indicator that just returns correct output for COBC = true, although you only intend to reference it "on bar close" in a real time strategy.

            2) If the indicator references another indicator and this indicator has the property COBC set to true in the Initialize section, then this property wont be overridden by the calling real time strategy, and thus the calling indicator will return an incorrect value in a real time strategy.

            3) Altough you only call an indicator on FirstTickOfBar, it is uppdated on every tick. Print statments that I put in another indicator that is called by the current indicator are updated and printed in the output window on every tick, although the current indicator is only called on FirstTickOfBar.

            4) The alternative method for referencing the indicator "on bar close" as described in my first post below (that is to shift the entire code of the indicator back one bar to be calculated on FirstTickOfBar as decribed in your sample "Separating logic to either calculate once on bar close or on every tick" ) don't requier one to code a realtime indicator. An indicator that just returns the correct output for COBC = true will also return the correct value when referenced in a real time strategy with this alternative method.

            When you take into consideration the abovementioned, why do think that it is a better practice to reference a real time indicator on FirstTickOfBar than the alternative method to shift the entire indicator one bar?

            /Best Regards
            Poseidon

            Comment


              #7
              Poseidon, all of your points are valid, but it is really a matter of preference. Depending on what exactly you're trying to do, shifting the indicator could be the optimal solution, or it might be better to use FirstTickOfBar. I would have to take a look at your bar-shifting indicator in action to see how it functions, but it does sound like you've figured out a solid solution with the shifting.
              AustinNinjaTrader Customer Service

              Comment


                #8
                Thanks for the reply.
                Could you please provide a scenario where, in your opinion, one of the two methods would be more optimal than the other?

                In my opinion the alternative method for referencing the indicator "on bar close" as described in my first post below (that is to shift the entire code of the indicator back one bar to be calculated on FirstTickOfBar as decribed in your sample "Separating logic to either calculate once on bar close or on every tick" ) has some advantages to the standard method:
                1. It's more computational efficient since the indicator is only calculated on FirstTickOfBar as opposed to the standard method where the indicators is updated and calculated on every tick!!!
                2. You don't need to code a realtime indicator.
                3. You can expose a simple variable in the output from the indicator with the alternative method while you need to expose a series indicator with the standard method since you need to reference a series one bar ago in the real time strategy

                My only concern is if there is a risk that the indicator for some reason is updated later with the alternative method than the standard method and that one has to use the Update() method in the output section. I have yet not seen this situation, but what do you think?

                Best Regards
                Poseidon

                Comment


                  #9
                  Poseidon, in general, I agree with you. The benefits you've outlined here (as well as the other factors you've mentioned) make the shifting method preferable most of the time. The only real drawbacks are the update concern, which you can work around by coding the indicator correctly, and the risk of using the wrong bars ("unshifted bars") in your strategy code, which can also be worked around by thoroughly testing the strategy.

                  I can't think of any scenarios off the top of my head that would make one a better choice, other than something extremely computationally intensive that wouldn't be able to re-calculate on every tick.
                  AustinNinjaTrader Customer Service

                  Comment


                    #10
                    Hi again!

                    I think I now can pinpoint the heart of my issue. It's about the difference between:


                    Case 1:

                    Code:
                            protected override void OnBarUpdate()
                            {
                                if ( !FirstTickOfBar) return;
                                
                                // Write some code
                            }
                    Case 2:

                    Code:
                            protected override void OnBarUpdate()
                            {
                                if ( FirstTickOfBar)
                                {
                                      // Write some code
                                }
                            }
                    In Case 1 the indicator will only update on the first tick of bar due to the return key word while in Case 2
                    ( that is in line with your sample "Separating logic to either calculate once on bar close or on every tick") the indicatoris recalculated and updated on every tick.

                    So this gives ut two alternative approaches to shift an entire indictaor for Referencing on bar close in a Real Time Strategy, where Case 2 is the recomended approach by NT.

                    Do you have any futher thoughts or comments on using Case 1 besides the update concerns that you mentioned in the previous post? In what situations may one risk to encounter the update issue with Case 1?


                    Best Regards

                    /Poseidon

                    Comment


                      #11
                      Poseidon, this will simply depend on your needs in the custom code used and when you seek to get the 'update' - if only a piece of code should be updated 'on the closing bar tick' then this would be more convenient.
                      BertrandNinjaTrader Customer Service

                      Comment


                        #12
                        How should I Reference my Indicator in Real Time to Avoid Unnecessary Recalculations?

                        Hello!
                        My trading strategy only requires indicators to update on bar close, while entry- and exit methods are monitored for every tick. Since some of my indicators are CPU intense, I try to program my startegy and Indicators so that indicators only will be called on FirstTickOfBar. But this seams more complicated than I first thought. I would appreciate some advice on how to proceed.

                        The first problem I discovered is that altough I only call an indicator on FirstTickOfBar from another indicator or strategy, the called indicator still is uppdated on every tick. ( I see that the print statments that I put in another indicator that is called by the current indicator are updated and printed in the output window on every tick, although the current indicator is only called on FirstTickOfBar.) So calling an indicator on FirstTickOfBar doesn't reduce the called indicators impact on the CPU.

                        To prevent the called indicator to recalculate on every tick I tried to put a FirstTickOfBar statement at the beginning of the OnBarUpdate() of the calliee as well (and shift the entire indicator one bar for real time calculations). But this caused an update problem in real time. The called indicator wasn't updateted before the calling indicator on FirstTickOfBar.

                        To solve the update problem I tried to add Update(); in the getter of the called indicators output series. This seems to solve the update problem. But my concern is that the Update() method may cause the called CPU intense indicator to recalculate twice or more on FirstTickOfBar which would be most unsatisfying. Since I expose several output series in the called indicator I have to add Update() to each output series which means that Update(); could be called more then once.

                        Do you have any advice on how I can call my indicator on FirstTickOfBar without unneccessary recalculations?
                        Is there a safe way to check if an indicator is updated or not on the current bar so that one could enter a conditional statment for Update(); in the getter of the called indicator?

                        Code:
                                [Browsable(false)]    // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                                [XmlIgnore()]        // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                                public DataSeries MyOutput
                                {
                                    get { 
                                            if ( [B][COLOR=Red]???[/COLOR][/B]) Update();
                                            return myOutput;
                                        }
                                }
                        Best Regards
                        /Posedon

                        Comment


                          #13
                          poseidon_sthlm, can you please clarify for us: is the FirstTickOfBar logic also inside the indicator you're trying to access externally and then run on COBC = false?
                          BertrandNinjaTrader Customer Service

                          Comment


                            #14
                            Yes. I provide a simplified code example below. (My question regards when COBC = false. In this case my shifting varaible int x = 1.)

                            The Calling Indicator:
                            Code:
                             public class Caller : Indicator
                                {
                                    // Variables
                                    private Callee myCallee;                // Declare Callee indicator
                                    private DataSeries callerOutput;    // Output
                                        
                                    protected override void Initialize()
                                    {
                                        callerOutput = new DataSeries(this);
                                    }
                            
                                    protected override void OnStartUp()
                                    {
                                        myCallee = Callee();   // Instanciate indicator
                                    }
                                    
                                    protected override void OnBarUpdate()
                                    {
                                        if ( !FirstTickOfBar ) return;    // [COLOR=Red]Only FTOB Calc.[/COLOR]
                                        
                                        int x = ( CalculateOnBarClose || Historical ? 0 : 1); // Shift between COBC = true and COBC = false
                                        
                                        if ( CurrentBar < x ) return;
                                        
                                        myCallee.CalleeOutput[x] >= 0 ? callerOutput.Set(x, 1.0) : callerOutput.Set(x, -1.0);
                                    }
                            
                                   //Properties
                                    [Browsable(false)]    // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                                    [XmlIgnore()]        // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                                    public DataSeries CallerOutput
                                    {
                                        get { return callerOutput; }
                                    }
                                }
                            The Called Indicator:
                            Code:
                              public class Callee : Indicator
                                {
                                     // Variables
                                    private DataSeries calleeOutput;// Output
                                    
                                    protected override void Initialize()
                                    {
                                        calleeOutput = new DataSeries(this);
                                    }
                            
                                    protected override void OnBarUpdate()
                                    {
                                        if ( !FirstTickOfBar ) return;    [COLOR=Red]// Only FTOB Calc.[/COLOR]
                                        
                                       int x = ( CalculateOnBarClose || Historical ? 0 : 1); // Shift between COBC = true and COBC = false
                                        
                                        if ( CurrentBar < x ) return;
                                        
                                        double output = "Do some calculations here";
                                        calleeOutput.Set(x, output);
                                    }
                            
                                   //Properties
                                    [Browsable(false)]    // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
                                    [XmlIgnore()]        // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
                                    public DataSeries CalleeOutput
                                    {
                                        //if ([COLOR=Red]???)[/COLOR] Update();
                                        get { return calleeOutput; }
                                    }
                               }
                            Last edited by poseidon_sthlm; 08-22-2011, 02:33 PM.

                            Comment


                              #15
                              poseidon_sthlm, thanks - then this would be as much optimized as you can get here, the calcs are called for every tick on CalculateOnBarClose = false yet nothing is processed except on FirstTickOfBar. There's unfortunately no other CalculateOnBarClose setting that would allow for another timing of the OnBarUpdate() calls (though it's on the list as suggestion already).
                              BertrandNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by DanielTynera, Today, 01:14 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post DanielTynera  
                              Started by yertle, 04-18-2024, 08:38 AM
                              9 responses
                              40 views
                              0 likes
                              Last Post yertle
                              by yertle
                               
                              Started by techgetgame, Yesterday, 11:42 PM
                              0 responses
                              12 views
                              0 likes
                              Last Post techgetgame  
                              Started by sephichapdson, Yesterday, 11:36 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post sephichapdson  
                              Started by bortz, 11-06-2023, 08:04 AM
                              47 responses
                              1,615 views
                              0 likes
                              Last Post aligator  
                              Working...
                              X