10

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

PineCoders-LucF
  • 8,288
  • 2
  • 12
  • 21
Phillip
  • 259
  • 1
  • 2
  • 11
  • Do you really need to draw the line? I think that's currently not possible. You can, however, calculate the angle. – vitruvius Oct 04 '18 at 15:51
  • The angle can be acceptable. I would like to see the line for debugging purposes only. Did you try the Regression Tool in left menu? – Phillip Oct 04 '18 at 17:33
  • Yes, but that calculates a different thing. I believe I got what you are asking. I will prepare an answer for you. – vitruvius Oct 04 '18 at 18:13
  • 1
    the price to bar ratio is key to capturing a proper angle, any other calc with just bars and price will be inaccurate the problem is the price/bar ratio is not a system variable another approach I have used is to normalize the data – John Baron Feb 20 '21 at 11:56

3 Answers3

13

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/

galki
  • 8,149
  • 7
  • 50
  • 62
12

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

vitruvius
  • 15,740
  • 3
  • 16
  • 26
  • 1
    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? – Phillip Oct 04 '18 at 20:05
  • 1
    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`. – vitruvius Oct 05 '18 at 10:09
  • 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. - https://www.tradingview.com/wiki/Regression_Trend – Phillip Oct 05 '18 at 10:53
  • 1
    Seems like it's not possible unfortunately. – vitruvius Oct 05 '18 at 15:45
  • 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 – jaggedsoft Oct 08 '18 at 17:36
  • 1
    @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. – vitruvius Oct 08 '18 at 22:46
  • 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.) – not2qubit Oct 09 '18 at 05:40
  • 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. – Phillip Oct 09 '18 at 12:53
  • 1
    @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. – vitruvius Oct 10 '18 at 14:10
  • @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? – Phillip Sep 18 '19 at 11:35
  • @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. – vitruvius Sep 18 '19 at 12:27
  • @BarisYakut, Thanks, please take a look at line.new() instruction if you have time. – Phillip Sep 18 '19 at 12:36
  • From a long forgotten script example: ```PI = 2*(asin(1))``` – Tim Pozza Sep 25 '20 at 22:33
0

x=146, and y=796.75$

it's still possible to calculate the angle, if you see it on a chart=)

Let's say we have MA100 and we clearly see an up-trend on the chart. Measure how much percentage the price should go for a 100 bars see a screenshot

let's say if price goes roughly 2.5% for 100 bars it's clear an up-trend movement takes place

dist = (sma - sma[100])/sma[100]*100 

actually no need to convert anything to degrees or radians simply build your logic around percentages it gives the same if distance in percentage is enough to make a steep angle than it is a trending movement

Of course for different timeframes the % to make a steep angle is different so you can think how to convert absolute % into relative so it will be universal measurement regardless the timeframe resolution

enter image description here

Artem Vertiy
  • 1,002
  • 15
  • 31