How to set alert when close cross my line.new

Viewed 315

I created a simple script in tradingview which create a line using building function line.new(). Now I want to set alert when a price crossed below my line.

In case this is not possible. I also tried to paint my line using plot(). My line is based on pivotlow() and I know how to get x,y. Since pivotlow is based on past events I need to extend it. I'm not sure how to do it.

line.new(plx1,ply1,plx2,ply2, xloc.bar_time, style=line.style_dotted, width=1)

I'm using code version 4.

2 Answers

Use line.get_price to find the value of a line ID at a given bar_index, it will not work on time based lines. You will need to determine if using your time based line u can index with get_price using bar_index or change your line.new to use bar_index for x coordinate.

Yes, it can be done. You can use something like this, which uses an array to save the IDs of lines created for each pivot. The crosses detect up and down crosses of the lines; you may choose to detect only up or down crosses by modifying the conditions setting the cross variable in the loop.

In this code, the x2 position of the lines is only updated on the last bar.

Also, you will see crosses on historical bars that occurred on lines that have since been deleted:

//@version=5
indicator("Pivot crosses", "", true)
int activeLevelsInput = input(10)
int pivotLegsInput = input(5)

// When a pivot occurs, create a line and save it.
float pLo = ta.pivotlow(pivotLegsInput, pivotLegsInput)
var pivotLines = array.new<line>(activeLevelsInput)
if not na(pLo)
    line newPivotLine = line.new(bar_index - pivotLegsInput, pLo, bar_index, pLo)
    array.push(pivotLines, newPivotLine)
    // Delete the oldest line.
    line.delete(array.shift(pivotLines))

// Extend the lines.
if barstate.islast and barstate.isnew
    for pivotLine in pivotLines
        line.set_x2(pivotLine, bar_index)

// Check for crosses.
bool cross = false
for pivotLine in pivotLines
    float linePrice = line.get_y1(pivotLine)
    bool newCrossUp = close[1] < linePrice and close > linePrice
    bool newCrossDn = close[1] > linePrice and close < linePrice
    cross := cross or newCrossUp or newCrossDn

// Alert.
if cross
    alert("A cross has occurred")

plotchar(cross, "Cross", "X")

enter image description here

Related