函数内部简单条件的看似错误的评估

Seemingly wrong evaluation of simple condition inside a function

我想要一个通常 return 为整数 100 的函数,但在满足某些条件时,如果给定的振荡器 (rsi) 低于 20,在我的情况下会偏离该值。以防万一当时的收盘价比最大值更接近 100 日价格最小值 return 值将升至 100 以上,如果接近最大值将跌破。

但奇怪的是,在大多数情况下(但不是全部)值 returned 的行为恰恰相反。

我在以下两个屏幕中绘制了所有相关值(绿色 > 50 表示更接近最高 < 50 更接近最低;蓝绿色是函数的 return 值,红色是 rsi,蓝色函数应该只改变,当它低于 20 - 它确实如此)。我突出显示蓝线增加条件满足绿色背景的条形(示例中不满足上升条件),这是正确完成的,因此在相同条件的函数评估之外确实按预期工作..

青色线错落画面

如您所见,背景颜色为绿色,因此表达式 rsi <= 20 and closeRelativeToHighestLowest() <= 50 在 bgcolor() 函数中被正确计算。

正确上升青色线的屏幕

这里的背景也是绿色的,所以与比较的评估没有什么不同——至少在 bgcolor() 函数中是这样。

这是我的代码:

//@version=4
study("My lookback minimum example")

closeRelativeToHighestLowest() =>
    ret = (close - lowest(low,100)) * 100 / (highest(high,100) - lowest(low,100))
    ret

myOptimalLookback(oscillator) => // will increase currentLength if oscillator is low and above optimalLevelForLow (relative to highest/lowest)
    ret = 100
    if oscillator <= 20
        if (closeRelativeToHighestLowest() > 50) //same condition as outside of function
            ret := round(ret[1] * 0.9)
        else
            ret := round(ret[1] * 1.12)
    ret := max(min(ret, 200), 10) // cap ret at 10 and 200


rsi = rsi(close, 10)
var lookback = 100
lookback := myOptimalLookback(rsi)

plot(lookback)
plot(closeRelativeToHighestLowest(), color = color.green)
plot(rsi, color = color.red)
hline(20)
hline(50)
bgcolor(rsi <= 20 and closeRelativeToHighestLowest() > 50 ? color.red : na)
bgcolor(rsi <= 20 and closeRelativeToHighestLowest() <= 50 ? color.green : na)

有什么可以尝试缩小问题范围的想法吗?

条件分支的计算在 v4 中发生了变化。与之前的版本相反,所有分支不再一直被评估,因此在进入条件分支之前预评估函数调用更安全(并且通常是必要的)。见 Release Notes:

myOptimalLookback(oscillator) => // will increase currentLength if oscillator is low and above optimalLevelForLow (relative to highest/lowest)
    ret = 100
    c = closeRelativeToHighestLowest()
    if oscillator <= 20
        if (c > 50) //same condition as outside of function
            ret := round(ret[1] * 0.9)
        else
            ret := round(ret[1] * 1.12)
    ret := max(min(ret, 200), 10) // cap ret at 10 and 200