Angle of Line in Pine Script

11,175

Solution 1

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: enter image description here

Solution 2

You can create an "angle" oscillator to measure line angles.

//@version=4
study("Angle Oscillator", overlay=false)

src = input(title="Source", type=input.source, defval=close)
price2bar_ratio = input(title="Price To Bar Ratio", type=input.float, defval=5.0)

get_degrees(src, price2bar_ratio) => (180.0 / (22.0 / 7.0)) * atan(change(src) / price2bar_ratio)

plot(get_degrees(src, price2bar_ratio))

The price2bar_ratio is the value from Chart settings > Scales > Lock Price To Bar Ratio.


The ratio itself is up to you since you're the one that decides what is a "steep" or "flat" angle. The catch is that to compare angles effectively (the price chart with the angle indicator) you'll have to use the same price to bars ratio for that symbol/timeframe for both chart and indicator.

So if your chart's price scale is set to Auto scaling, you'll get a different chart angle for the same price with every change in zoom (the indicator angle values won't be affected). To get the same chart angle no matter how much you zoom in or out, right click on the scale and make sure Lock Price To Bar Ratio is checked.

To use:

  1. save the above angle oscillator so it appears in Indicators > My scripts
  2. add a MA indicator to the chart
  3. click that indicator's More > Add Indicator on (MA)
  4. select the angle oscillator from My scripts
  5. adjust the angle oscillator's Price To Bar Ratio value

For a more advanced version see https://www.tradingview.com/script/D8RA0UqC-Cosmic-Angle/

Share:
11,175
Phillip
Author by

Phillip

Updated on July 02, 2022

Comments

  • Phillip
    Phillip almost 2 years

    I would like to find price trend for last 200 bars in TradingView Pine Script language.

    I want to draw a line from latest bar (close) to 200 bars older one. Then I want to calculate the angle of the line in degrees to see how much bullish or bearish the trend.

    I can do this by Regression Trend tool in TradingView drawing screen easily. I want to do the same thing programmatically.

    I guess the angle can be found by this formula (Java):

    double rads = Math.Atan((line.Y2 - line.Y1) / (line.X2 - line.X1));
    double degrees = rads * (180f / Math.PI);
    

    Can you give me an example?

    Thanks

  • Phillip
    Phillip over 5 years
    Thank you. I can print the degrees now. The only problem is I still could not determine the direction of trend like the Regression Tool. getAngle(_src, _len) => ((180.0 / (22.0 / 7.0)) * atan((nz(_src[x]) - _src) / _len)) the functions is this one. 22/7 is for PI. So angle = getAngle(close, x) and if I write a condition like tcolor = angle > 3 ? green : angle < (-3) ? red : gray it does not give what I expect. For example, XAUUSD, Weekly chart, 26.01.2009 - 14.11.2011, I use the Trend Angle tool on the left menu, it measures about 23 degrees, but the indicator plots -75 degrees. Idea?
  • vitruvius
    vitruvius over 5 years
    First of all, there was a mistake in code which I fixed now. It should be y = close - nz(close[x]). Now, coming to the real problem, unfortunately, we were mixing apples and oranges. x and y have different units. y is in price, and x is in bar. From 26.01.2009 to 14.11.2011, there are 146 bars, hence x=146, and y=1723.10-926.35, which is 796.75. However, you can't just do atan(y/x), because they have different units - conversion is missing. One is in cm, other is in mm, so to speak. Just draw the triangle yourself and you will see 146 is much longer than 796.75.
  • Phillip
    Phillip over 5 years
    I just want to make programmatical version of Regression Trend Tool. Isn't it possible? Just a straight line and it's slope/angle in degrees for the last 200 bars. - tradingview.com/wiki/Regression_Trend
  • vitruvius
    vitruvius over 5 years
    Seems like it's not possible unfortunately.
  • jaggedsoft
    jaggedsoft over 5 years
    Nice job on this Baris, great work. Yeah, I also have attempted linear regression channels in pinescript. I think it is possible just not feasible because they don't make it where you can draw straight lines from code
  • vitruvius
    vitruvius over 5 years
    @jaggedsoft Thanks. I actually started to think that it might be possible to draw a trend line with some tricks but I’m not sure if it’s worth the effort. Also, whenever I try to be clever and try some tricks out, pine-script fails so bad. So, I really don’t have the motivation. Maybe I will try once I have some free time. But I’m pretty sure that it won’t be feasible as you said.
  • not2qubit
    not2qubit over 5 years
    No effort is wasted, but TBH, because of pine-script missing line drawing support, your life with it will suck! I tried drawing angled lines and it's possible, but really ugly to do. Its a long piece of code, to just "fake" one line. Basically each line consists of n line segments attached one after the other. (Since P-S is using a series for all values.)
  • Phillip
    Phillip over 5 years
    Guys, I'm a bit confused. Is it mixing apples and oranges the method above explained by Baris or not? The line angle formula is OK, but we use there price and constant range values instead of x and y coordinates as expected by the formula.
  • vitruvius
    vitruvius over 5 years
    @Phillip My explanation above is still valid. We were just talking about the posibilities and the effort to do draw the line. I think the end product would be too messy and not very useful as others stated.
  • Phillip
    Phillip almost 5 years
    @BarisYakut, Hello again. Now there is pine script v4 which supports line instruction directly. Do you think that now it is possible to find the angle of a line?
  • vitruvius
    vitruvius almost 5 years
    @Phillip Haha, when I first saw the v4, this question was the first thing that came to my mind. Yes, I believe it is possible now. However, I have not had time to work with v4 yet, so cannot confirm.
  • Phillip
    Phillip almost 5 years
    @BarisYakut, Thanks, please take a look at line.new() instruction if you have time.
  • Tim Pozza
    Tim Pozza over 3 years
    From a long forgotten script example: PI = 2*(asin(1))
  • Pang Ho Ming
    Pang Ho Ming over 3 years
    amazing explanation. thanks so so much :D