检查在最后 10 根蜡烛期间是否发生交叉

Ilj*_*lja 0 pine-script

我正在制定一种策略,该策略要求我在收到当前蜡烛关闭信号时检查是否有特定的交叉几根蜡烛回到过去。

现在我基本上为每根蜡烛创建 10 个变量,因为我想检查 10 根蜡烛,看看是否发生了交叉(任何类型的交叉都适用于这个例子)。

这有效,但会导致一些混乱和冗长的代码,所以我想知道我是否可以以某种方式创建一个“单行”解决方案来检查整个期间的情况?

e2e*_*2e4 5

这可能有帮助

//@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)
Run Code Online (Sandbox Code Playgroud)