Lines are very useful in technical analysis. Lines can be use to draw support, resistance, highs, lows, trends, you name it.
Many of us use the line tool in TradingView to manually draw lines between two points or along a set of highs or lows.
But what if we could draw this lines automatically? What if we could write a Pine Script indicator to draw them for us?
The good news is, we can! And this article will show you how. However, this article will NOT show you how to determine which points you want to draw the lines between. That should come from your strategy. That will be up to you.
As an example, you could use highs, lows, pivots, or other calculated points such as from a linear regression. But which highs, lows, or pivots, is up to you and depends on exactly what you’re trying to accomplish.
Let’s get into it.
Drawing Lines in Pine Script
New in Pine Script v4 is the line.new()
function:
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) → series[line]
Remembering back to middle school algebra, its fairly simple, you give it two (x, y) points, and TradingView will connect the dots for you.
- The x points can be either the bar index or a UNIX time (they both need to be the same type), and is specified using the
xloc
parameter. - The y points need to be price values.
For example, here is a simple script that draws a line between the low of 7 candles ago and the current low.
Let’s move on to something more interesting…
Drawing Multiple Lines
Here, I’ve edited the script to connect the lows of the first and last trading day of the week for forex, which don’t trade on the weekends:
In this example, we don’t actually use the reference to the line (the l
variable) for anything…but we will in the next example!
Updating a Line in Pine Script
What about updating the line after you drew it? One thing that’s cool about line.new
is you can actually update the line after its been drawn by setting an x or y point to some new value:
This time, the script does exactly the same thing as the first script (connects the lows of today and 7 candles ago). However, the WAY it does it is slightly different.
Instead of using if barstate.is_last ...
, this time we instantiate the line object once at the first candle (that’s what the var
keyword does) and then we update the x and y points every candle. So, naturally, we only see the line as if it was only drawn from today.
We’re Done
Need help with Pine Script? Did this article not mention something you’re looking for? Just reach out in our Discord server.