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

Define Slope of EMA(20)

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

    Define Slope of EMA(20)

    Hi Everybody,

    I try to code Slope of last 10 Bars to last 5 Bars of SMA(20),
    Can I just type Slope(SMA(20), 10, 5)>30 ?

    Please instruct me to right way, thanks a lot.

    Arthur
    Last edited by ArthurMFTse; 08-10-2014, 12:26 AM.

    #2
    You cannot do that for many reasons:

    (1) Such a Slope function is not defined. Please refer to the NinjaScript Manual to learn about the methods defined in NinjaScript.

    (2) The slope is not an angle, but the slope is related to the angle via the formula slope = tan (angle). You would therefore need to replace the value 30 with tan(30), if you wish to get a signal when the angle exceeds 30 degrees. However, angles do not make sense, if you use a software package with scalable x and y axis. You need to use an abstract slope not representing any angles on your screens.

    (3) Slope is a geometrical concept, typically a ratio that is obtained by dividing the difference taken from two prices by the distance between the referenced bars. Such a slope indicator does not comply with Eckhardt's coherency test, as it would take different values depending on instrument and timeframe chosen. Therefore you should normalize the slope by dividing the geometrical slope by either average range, average true range or the standard deviation.

    A normalized slope which has been adjusted to the average bar size would be an appropriate tool to identify strong uptrends and downtrends.

    Comment


      #3
      Thanks a lot Harry!

      Can I code as below?

      //int
      private int _sma20slope

      // OnBarsUpdate()

      _sma20slope=(int)(180/Math.PI*(Math.Atan((SMA(20)[5]-(SMA(20)[5]+SMA(20)[5])/5/TickSize))));

      if (_sma20slope>30){do something;}

      Arthur
      Last edited by ArthurMFTse; 08-10-2014, 04:12 AM.

      Comment


        #4
        Hello Arthur,

        Thank you for your post.

        Your use of the Slope() method has the correct syntax, however, as Harry mentioned it would not be a degree value returned from the slope. So 30 would not be a fair comparison. The angle here would not be appropriate as the angle of the data points on the chart will change based on the highest and lowest bars on the visible area of the chart. Slope() is used to provide the steepness of a line, and not the angle.

        Are you looking for the angle? Can you provide details on what you are looking for when comparing the SMA() 10 bars ago to 5 bars ago?

        The code you provided as a test of Math.Atan() does not appear to be valid. Why would you add the 5 bars ago value to it self and then subtract it? Can you provide information on what you are attempting here with Math.Atan?

        I look forward to your response.

        Comment


          #5
          Originally posted by ArthurMFTse View Post
          Thanks a lot Harry!

          Can I code as below?

          //int
          private int _sma20slope

          // OnBarsUpdate()

          _sma20slope=(int)(180/Math.PI*(Math.Atan((SMA(20)[5]-(SMA(20)[5]+SMA(20)[5])/5/TickSize))));

          if (_sma20slope>30){do something;}

          Arthur
          You may be overcomplicating it here. Slope has a very simple definition. Why not go back to basics? Slope is simply rise/run, so for the slope of the last 10 bars to 5 bars
          Code:
          double slope = (SMA(20)[5] - SMA(20)[10]) / 5;
          Note that the slope is independent of angle; angle is a trigonometric concept related to the slope, but they are not the same. IOW, a slope can be represented by an angle, but unless that slope is a dimensionless quantity, the relationship is essentially meaningless.

          Comment


            #6
            Originally posted by koganam View Post
            You may be overcomplicating it here. Slope has a very simple definition. Why not go back to basics? Slope is simply rise/run, so for the slope of the last 10 bars to 5 bars
            Code:
            double slope = (SMA(20)[5] - SMA(20)[10]) / 5;
            Note that the slope is independent of angle; angle is a trigonometric concept related to the slope, but they are not the same. IOW, a slope can be represented by an angle, but unless that slope is a dimensionless quantity, the relationship is essentially meaningless.
            Would divide that result by the average range or standard deviation to have the slope normalized. Would make a provision to avoid division by zero though.

            Comment


              #7
              Originally posted by Harry View Post
              Would divide that result by the average range or standard deviation to have the slope normalized. Would make a provision to avoid division by zero though.
              That is the last point that I made, more or less. Dividing by any measure of price would make the result dimensionless. Which then translated into an angle would make mathematical sense.
              Last edited by koganam; 08-11-2014, 04:39 AM.

              Comment


                #8
                Thanks very much Everybody!


                So can I code as below?

                //int
                private int _sma20slope

                // OnBarsUpdate()

                _sma20slope=(int)(180/Math.PI*(Math.Atan((SMA(20)[5]-(SMA(20)[10])/5/TickSize)));

                if (_sma20slope>30){do something;}

                I would like to test the slope momentum of SMA(20) before the price pullback to SMA(20), so I assuming slope of bar10 to bar5 may work better.

                Any other suggestion to test the momentum of move upward again after price pullback to SMA(20).

                Thanks a lot,

                Arthur

                Comment


                  #9
                  Originally posted by ArthurMFTse View Post
                  Thanks very much Everybody!


                  So can I code as below?

                  //int
                  private int _sma20slope

                  // OnBarsUpdate()

                  _sma20slope=(int)(180/Math.PI*(Math.Atan((SMA(20)[5]-(SMA(20)[10])/5/TickSize)));

                  if (_sma20slope>30){do something;}

                  I would like to test the slope momentum of SMA(20) before the price pullback to SMA(20), so I assuming slope of bar10 to bar5 may work better.

                  Any other suggestion to test the momentum of move upward again after price pullback to SMA(20).

                  Thanks a lot,

                  Arthur
                  If I may ask, why are you so enamored of using an angle, when you can just use the slope directly? After all, you intend to do comparisons. What does conversion to an angle give you that using the slope does not?

                  IMHO, when coding, one should use Occam's Razor, cutting code to its simplest that does the job, and avoiding unnecessary operations.
                  Last edited by koganam; 08-11-2014, 06:35 AM.

                  Comment


                    #10
                    Originally posted by koganam View Post
                    If I may ask, why are you so enamored of using and angle, when you can just use the slope directly? After all, you intend to do comparisons. What does conversion to an angle give you that using the slope does not?

                    IMHO, when coding, one should use Occam's Razor, cutting code to its simplest that does the job, and avoiding unnecessary operations.

                    I would also use the slope (rise over run). Slope is just a variation of the first derivative of price, you may consider it as an average momentum that can be used to gauge the trend strength.

                    In case that you only trade one instrument and one time frame, it is good enough to divide the rise (price difference) by the number of bars of the lookback period.

                    However, in case that you wish to use the concept for several instruments and timeframes, you should definitely compare the rise to the intrabar volatility. The easiest way to do this, is to divide the rise over run by the average range over the lookback period.

                    Now the slope will be shown as a percentage of bar size. The trend strength is compared to intra-bar volatility, which is crucial if you wish to have a common measure for the trend strength across various instruments and timeframes.


                    How to determine the slope:

                    Mathematically the slope is the first derivative of a curve. Therefore, if you wish to determine the normalized slope of an SMA(20), it is sufficient to have a look at the rise of the SMA from the previous to the current bar. You took 5 bars, but this is not necessary, as the SMA is already sufficiently smooth due to the longer lookback period of 20. Here are the formulae:

                    rise over run = (SMA(20)[0] - SMA(20)[1])/1

                    case ATR(20) > 0:

                    normalized slope = (SMA(20)[0] - SMA(20)[1]/(ATR(20)[0]

                    case ATR(20) = 0:

                    normalized slope = 0

                    Nota: I prefer to use the ATR instead of the average range, as it has a lesser probability to have a value of zero. And if it takes the value of zero, than you may consider the slope as being zero as well, which would not necessarily be the case for the average range.

                    I agree with @koganam that one should use the simplest solution available. Basically the formula above shows the rise of the SMA over 1 single bar. The normalization has only been added to make the outcome of the formula comparable over multiple instruments and timeframes. Angles are not needed and would only confuse the matter.

                    Comment


                      #11
                      Thanks a lot Everybody,

                      I need sometimes to digest the Slope concepts presents from yours.

                      Will comeback later if need more help.

                      Thanks again for you all.

                      Arthur

                      Comment


                        #12
                        How would it work with MACD?

                        Many thanks indeed, Harry and Koganam, for a great explanation of slope/Slope!

                        I can see how the elegantly simple code you provided, Harry, would work with a "simple" indicator such as a MA, but what about with something like MACD?

                        The rise over run is straightforward enough (just use the values at bars 0 and 1), but what about the ATR and consequentially the normalized slope?

                        If one is using MACD(12, 26, 9), for example, and the slopes of both MACD and MACD.Avg are required, what value would one use for the ATR in each case? Fast (12), slow (26) or smooth (9)?

                        Many thanks.
                        Multi-Dimensional Managed Trading
                        jeronymite
                        NinjaTrader Ecosystem Vendor - Mizpah Software

                        Comment


                          #13
                          Originally posted by jeronymite View Post
                          Many thanks indeed, Harry and Koganam, for a great explanation of slope/Slope!

                          I can see how the elegantly simple code you provided, Harry, would work with a "simple" indicator such as a MA, but what about with something like MACD?

                          The rise over run is straightforward enough (just use the values at bars 0 and 1), but what about the ATR and consequentially the normalized slope?

                          If one is using MACD(12, 26, 9), for example, and the slopes of both MACD and MACD.Avg are required, what value would one use for the ATR in each case? Fast (12), slow (26) or smooth (9)?

                          Many thanks.
                          For the MACD there is no average true range, but there is only the difference between the current value of the MACD and the prior value of the MACD. This difference can be used as a substitute for the ATR.

                          You would therefore replace the ATR with an average of the absolute amount of the one bar momentum. The code would look like this.

                          Code:
                          #region variables
                          ....
                          private Momentum slopeMACD;
                          private DataSeries absSlopeMACD; 
                          ...
                          #endregion
                          
                          protected override void OnStartUp()
                          {
                               slopeMACD = Momentum( MACD(12,26,9), 1);
                               absSlopeAverage = SMA(absSlopeMACD, normPeriod);
                          }
                          
                          protected override void OnBarUpdate()
                          {
                               ....
                               absSlopeMACD.Set(Math.Abs(slopeMACD[0]);
                               double divisor = absSlopeAverage[0];
                               if (divisor > 0) 
                                   normalizedSlope = slopeMACD[0] / divisor;
                               else
                                   normalizedSlope = 0;
                               ...
                          }
                          Last edited by Harry; 09-15-2014, 02:10 PM.

                          Comment


                            #14
                            Thanks!

                            Many thanks, Harry! Very much appreciated.
                            Multi-Dimensional Managed Trading
                            jeronymite
                            NinjaTrader Ecosystem Vendor - Mizpah Software

                            Comment


                              #15
                              Code:
                              private [B]DataSeries (absSlopeMACD)[/B];
                              
                              private override void [B]OnStartUp()[/B] {     ...
                              absSlopeAverage = SMA(absSlopeMACD, normPeriod); }
                              Hi Harry

                              I've been fascinated to read this thread, as much for the approaches to coding as for the ideas about 'slope'.

                              I have a couple of questions, if you have a spare moment, about the coding you've used.

                              I notice that you define the data series by

                              Code:
                              private DataSeries (absSlopeMACD);
                              whereas when I've done this myself, I've used this approach:

                              In Variables (without parentheses):

                              Code:
                              private DataSeries testseries;
                              and in Initialize

                              Code:
                              testseries =  new DataSeries(this);
                              Would you possibly be able to explain why you chose the approach you have, esp. the placing the name of the series in parentheses and how this differs from the other approach? Also, does this approach mean you don't have to state anything in Initialize?

                              Moreover, I'd appreciate it if you could explain in a few words what the OnStartUp method does and how it differs from OnBarUpdate. I've seen this only once or twice in indicators and have never really grasped its purpose.

                              Thanks very much in advance.
                              Last edited by arbuthnot; 09-15-2014, 06:08 AM. Reason: edit

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by judysamnt7, 03-13-2023, 09:11 AM
                              4 responses
                              59 views
                              0 likes
                              Last Post DynamicTest  
                              Started by ScottWalsh, Today, 06:52 PM
                              4 responses
                              36 views
                              0 likes
                              Last Post ScottWalsh  
                              Started by olisav57, Today, 07:39 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post olisav57  
                              Started by trilliantrader, Today, 03:01 PM
                              2 responses
                              21 views
                              0 likes
                              Last Post helpwanted  
                              Started by cre8able, Today, 07:24 PM
                              0 responses
                              10 views
                              0 likes
                              Last Post cre8able  
                              Working...
                              X