Ilja
Ilja

Reputation: 46479

Check if crossover occurred in the period of last 10 candles

I am working on a strategy that requires me to check if there was a certain crossover few candles back in time when I get my signal on current candle close.

Right now I am basically creating 10 variables for each candle, because I want to check back 10 candles and see if crossover happened (any kind of crossover works for this example).

This works, but leads to a bit of a messy and verbose code, so I was wondering if I can somehow create a "one liner" solution to check this for the whole period?

Upvotes: 0

Views: 4612

Answers (3)

Robert Lash
Robert Lash

Reputation: 1

I can't comment under the other answer because I don't have over 50 reputation, but this worked for me:

if (bar_index - ta.valuewhen(crossover(sma20, sma50), bar_index, 0)) <= 10

//do whatever it is you want to do after the if condition

Upvotes: 0

Samaara
Samaara

Reputation: 51

Or you can just use this condition:

if ta.valuewhen(crossover(sma20, sma50), bar_index, 0) <= 10

//do whatever it is you want to do after the if condition

Upvotes: 3

e2e4
e2e4

Reputation: 3818

This might help

//@version=4
study("Sma cross during last n candles", overlay=true)

sma20 = sma(close, 20)
sma50 = sma(close, 50)

plot(sma20)
plot(sma50)

cross = cross(sma20, sma50)

// Highligh cross on the chart
bgcolor(cross ? color.red : na)

// Function looking for a happened condition during lookback period
f_somethingHappened(_cond, _lookback) =>
    bool _crossed = false
    for i = 1 to _lookback
        if _cond[i]
            _crossed := true
    _crossed

// The function could be called multiple times on different conditions, that should reduce the code
crossed10 = f_somethingHappened(cross, 10)

// Highligh background if cross happened during last 10 bars
bgcolor(crossed10 ? color.green : na)

Upvotes: 11

Related Questions