Pine Script: boolean to indicate line crossing

Viewed 29

I would like to have a boolean indicate whether two series have ever crossed in their entire histories. If I use boolCross = ta.cross(series1, series2), this only tells me whether the latest values of the two series have crossed. How do I get boolCross to indicate whether there ever have been crosses over the entire histories of series1 and series2?

2 Answers

I'm thinking you could count the total number of crosses for each series, and then return a boolean true if the total is above one.

So for instance:

//Get the data you'll be assessing for crosses

ema1 = ta.ema(close, 50)                                                   
ema2 = ta.ema(close, 100)

//Establish a 'var' - a variable that doesn't update with every bar - you can use this to store a cumulative total. 

var cross_count = 0

//Give the instruction to add 1 to it with every crossover

if ta.crossover(ema1, ema2)
    cross_count := cross_count[1] + 1

//Link a boolean to the condition '> 0'

cross_test = cross_count > 0 ? true : false

//And (if you like) plot the output to the data window to check it works.

plot(cross_count, title="cross_count", display=display.data_window -display.pane)
plot(cross_test ? 1 : 0, title="1 Cross or More?", display=display.data_window -display.pane)

Hope that helps.

Actually, I figured it out myself after a bit of digging around.

boolCross = not na(ta.valuewhen(ta.cross(series1, series2), series1, 0))
Related