Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the value of 2 lines line.new crossing each other – pinescript

I have 2 lines:

line1 = line.new(bar_index[25], high[25], bar_index, low)
line2 = line.new(bar_index[25], low, bar_index, high[25])

Now you can see that 2 lines will cross each other. The crossing point may be somewhere between them and maybe between 2 consecutive bars in the history.

How to get the value of the crossing point ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This surely helps:

https://www.wolframalpha.com/input/?i=%28×2-x1%29%28y-y1%29%3D%28y2-y1%29%28x-x1%29%2C%28u2-u1%29%28y-v1%29%3D%28v2-v1%29%28x-u1%29+for+x%2C+y

Pine script snippet:

//@version=4
study(title="intersection point", overlay=true)

var float   last_intersect_x    = na
var float   last_intersect_y    = na

// Gets intersection point of two line segments [(x1, y1), (x2, y2)] and [(u1, v1), (u2, v2)].
f_get_intersect_coordinates(x1, y1, x2, y2, u1, v1, u2, v2) =>
    x = -1 * ((x1 - x2) * (u1 * v2 - u2 * v1) - (u2 - u1) * (x2 * y1 - x1 * y2)) / ((v1 - v2) * (x1 - x2) - (u2 - u1) * (y2 - y1))
    y = -1 * (u1 * v2 * y1 - u1 * v2 * y2 - u2 * v1 * y1 + u2 * v1 * y2 - v1 * x1 * y2 + v1 * x2 * y1 + v2 * x1 * y2 - v2 * x2 * y1) / (-1 * u1 * y1 + u1 * y2 + u2 * y1 - u2 * y2 + v1 * x1 - v1 * x2 - v2 * x1 + v2 * x2)
    [x,y]

sma10 = sma(close, 10)
sma50 = sma(close, 50)

if cross(sma10, sma50)
    x1 = bar_index[1]
    y1 = sma10[1]
    x2 = bar_index
    y2 = sma10
    u1 = bar_index[1]
    v1 = sma50[1]
    u2 = bar_index
    v2 = sma50
    
    [x,y] = f_get_intersect_coordinates(x1, y1, x2, y2, u1, v1, u2, v2)
    
    last_intersect_x := x
    last_intersect_y := y

    line.new(bar_index-1, last_intersect_y, bar_index, last_intersect_y, extend=extend.right, color=color.yellow, style=line.style_dashed)
    label.new(bar_index, last_intersect_y, "x = " + tostring(last_intersect_x, "#.##") + "\ny = " + tostring(last_intersect_y, "#.##"), yloc=yloc.abovebar)


plot(sma10, "sma10", color.green)
plot(sma50, "sma50", color.blue)

// Debug
// plotchar(last_intersect_x, "lix", "")
// plotchar(last_intersect_y, "liy", "")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading