Calculate SMA's Slope in pine script

Viewed 3044

I'm want to calculate the slope for the Simple Moving Average's (SMA). I have already tried the following code which is mathematically correct.

rad2degree = 180/3.14159265359  //pi
sma2sample = sma(close,50) 
slopeD = rad2degree*atan( (sma2sample[0] - nz(sma2sample[1]))/1 )

However, the problem is that the value for each stock differs, so the slopeD value is not in a fixed rang, between [-90 to 90] degrees. Which would be more logical.

I believe that I would need to normalize the date in order to have this variable in a fixed range, but I do not know how.

How can I normalize the range of the slopeD?

1 Answers

With the version 5 of pinescript there is a way to get the slope of a function :

sma2sample = sma(close,50)
slope = ta.linreg(sma2sample, 4, 1) - ta.linreg(sma2sample, 4, 0)

You can see the ta.linreg function here : pinescript ta.linreg

Related