How to draw line from condition to current close for all occurences of the condition

Viewed 411
condition = ta.barssince(ta.rsi(close, 14) > 20) == 1

var flag = false

if ta.ema(close, 50) > ta.ema(close, 200)
    flag := true

var theLine = line.new(0, 0, 0, 0)

if flag
    line.set_xy1(theLine, bar_index - ta.barssince(condition), ta.valuewhen(condition, close, 0))
    line.set_xy2(theLine, bar_index, close)

The code above will plot a line from the close of the latest occurence of the condition to the current close. How do I plot a line for every occurence of the condition to the current close?

EDIT: (Here's visual representation of what I'm trying to convey.) enter image description here

2 Answers

You need multiple lines here so I would do this with an array.

Basically, keep track of the last n occurences and update your array accordingly. Then update xy2 of your lines in the array on each bar.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius

//@version=5
indicator("My script", overlay=true, max_lines_count=500)

line_cnt = input.int(5)

var line_arr = array.new_line()

_ema = ta.ema(close, 50)
cond = ta.crossover(close, _ema)

len = array.size(line_arr)

if (cond)
    id = line.new(bar_index, close, bar_index, close, color=color.yellow)
    
    if (len < line_cnt)
        array.push(line_arr, id)
    else
        l = array.get(line_arr, 0)
        line.delete(l)
        array.shift(line_arr)
        array.push(line_arr, id)

if (len > 0)
    for i=0 to len-1
        l = array.get(line_arr, i)
        line.set_xy2(l, bar_index, close)

plotshape(cond, size=size.small)
plot(_ema, "EMA", color.white, 2)

Here I draw lines from the close price of the last five occurences of the condition to the current close price.

enter image description here

Remove line_cnt from the equation if you want to do that for all occurences.

A great answer by Vitruvius, however, I love the recently added for..in structure and would like to demonstrate it, hope this helps as well!

PS: I've also removed the redundant flag, as it becomes true after the very first occurrence of the ema crossover on the chart and doesn't change back.

//@version=5
indicator("Lines to the current close", overlay = true)

condition = ta.barssince(ta.rsi(close, 14) > 20) == 1
    
var line[] lines = array.new<line>()

if condition
    array.unshift(lines, line.new(bar_index, close, bar_index, close))

for line in lines
    line.set_xy2(line, bar_index, close)

enter image description here

Related