You can access the historical values of a series type with the history referencing operator []
. So, for example; close[1]
will give you yesterday's close price, which is also a series.
Your formula to find the angle is correct. Your y2 - y1
is close - close[200]
and your x2 - x1
is 200 - 0
. So, what you need to calculate is atan((close - close[200]) / 200)
.
Here is an indicator that colors the background depending on the value of the angle in radians. You can play with the input to try out different ranges.
//@version=3
study(title="Angle Bg", overlay=true)
x = input(title="Range", minval=1, defval=5)
y = close - nz(close[x])
angle = atan(y/x) // radians
color = angle < 0 ? green : red
bgcolor(color, transp=70)
Below piece of code is for debugging purposes. It plots the angle in radians.
//@version=3
study(title="Angle", overlay=false)
x = input(title="Range", minval=1, defval=5)
y = close - nz(close[x])
angle = atan(y/x) // radians
plot(angle, title="Angle", linewidth=4)
hline(0, color=gray, linestyle=dotted, linewidth=3)
Below code is also for debugging purposes. It plots the current close price and close[x]. So you don't need to go back and forth while calculating the angle manually :)
//@version=3
study("Close")
range = input(title="Range", type=integer, minval=1, defval=5)
plot(close, title="close", linewidth=4, color=orange)
plot(nz(close[range]), title="close[]", linewidth=4, color=green)
Note: I found using radians more useful than degrees. But if you want to use degrees in your indicator, you might as well apply your formula to angle
variable. Please note that pine-script
does NOT have any built-in variables for pi
. So, you are gonna have to type that manually.
If you add those three indicators to your chart, you should get something similar to this:
