Bierbaron1920
Bierbaron1920

Reputation: 45

Get bars since pre-last condition

I have the following problem: I want to get the number of days between today and the last time when a condition is true. Relatively easy:

condition = ........
days_since_last_con = barssince(condition)

Is it possible to get get the number of days between today and the pre-last time when a condition is true? And ideally pre-pre-last time?

Thanks for your help!

Upvotes: 1

Views: 2414

Answers (1)

rumpypumpydumpy
rumpypumpydumpy

Reputation: 3833

Yes, we can do it by using a var declared variable to start counting from when a condition occurs and then use valuewhen to obtain how many bars were counted on the bar before an iteration of the condition occurred.

//@version=5
indicator("condition counting with valuewhen", overlay = true)

m1 = ta.ema(close, 30)
m2 = ta.ema(close, 100)

plot(m1, color = color.red)
plot(m2, color = color.yellow)

cond = ta.crossover(m1, m2)

var int count = na

if cond
    count := 0
else
    count += 1

since_last = ta.barssince(cond)
since_prev = ta.valuewhen(cond, count[1], 0)
since_prev2 = ta.valuewhen(cond, count[1], 1)

xo_text = "Bars since last crossover : " + str.tostring(since_last) + "\nBars since previous crossover : " + str.tostring(since_prev + since_last + 1) + "\nBars since 2nd previous crossover : " + str.tostring(since_prev2 + since_prev + since_last + 1)

l = label.new(x = bar_index, y = close, style = label.style_label_left, text = xo_text)
label.delete(l[1])

Upvotes: 2

Related Questions