'How to create alert for line.new function in Pine Script?

I have created a pine script in TradingView to draw line from pivot to pivot like a trendline which has slope and is not horizontal. Now i want to add alert to these lines so that when price crosses the last line i can get an alert. Here is the sample code:

line upper = line.new(x1, y1, x2, y2, extend=extend.right, color=color1, width=width1)
line lower = line.new(x1, y1, x2, y2, extend=extend.right, color=color2, width=width1)

So how is it possible to add alert to this line?



Solution 1:[1]

You can get the values of the line using line.get_*() function. If you wish to get the line price value at a specific bar, you'll need to get the y2 value that was calculated using line.get_y2() function.

Here is an example code:

//@version=5

indicator("My script", overlay=true)

upperY = high[1] * 1.01
lowerY = low[1] * 0.99

line upper = line.new(bar_index - 1, upperY[1], bar_index, upperY)
line lower = line.new(bar_index - 1, lowerY[1], bar_index, lowerY)

upperYvalue = line.get_y2(upper)
lowerYvalue = line.get_y2(lower)

if ta.crossover(close, upperYvalue)
    label.new(x=bar_index, y=high * 1.07, text=str.tostring(upperYvalue), color=color.green)


if ta.crossunder(close, lowerYvalue)
    label.new(x=bar_index, y=low * 0.93, text=str.tostring(upperYvalue), color=color.red, style=label.style_label_up)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mr_statler