如何在Pine Script中为RSI超买超卖条件设置可调回溯周期
Pine Script RSI策略回溯周期参数配置问题解决
错误原因
原代码编写做多触发条件时错误使用逗号分隔变量,语法不符合Pine Script规范,导致触发"and"相关语法报错:
// 错误写法 long = rsiOversold, lookback and open > close[1] and high*1 - low*1 >= 24 * syminfo.mintick
修正方案
要实现可调节的回溯周期检查,需要用方括号[]引用历史K线的RSI超卖状态,核心正确写法如下:
// 定义可调节回溯周期参数,默认值为4,支持回测时修改 lookback = input(4, "Lookback") // 修正后的做多条件:回溯lookback根K线内出现过RSI超卖,同时满足其他开仓条件 long = rsiOversold[lookback] and open > close[1] and high - low >= 24 * syminfo.mintick
额外优化说明:原代码中high*1 - low*1可直接简化为high - low,计算结果完全一致,代码可读性更高。
完整可运行代码
//@version=4 strategy(title="相对强弱指数策略", shorttitle="RSI", format=format.price, precision=2, overlay = false, process_orders_on_close = true) // 获取参数值 len = input(10, minval=1, title="RSI周期长度") src = input(close, "计算源", type = input.source) up = rma(max(change(src), 0), len) down = rma(-min(change(src), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) overbought = input(title="超买阈值",defval=70) oversold = input(title="超卖阈值",defval=30) lookback = input(4, "超卖信号回溯周期") // RSI状态判断 rsiValue = rsi(src, len) rsiOverbought = barssince(rsiValue > overbought) ==1 rsiOversold = barssince(rsiValue < oversold) ==1 // 开平仓条件 long = rsiOversold[lookback] and open > close[1] and high - low >= 24 * syminfo.mintick exitLong = close < low[1] short = rsiOverbought and open < close[1] and high - low >= 24 * syminfo.mintick exitShort = high > high[1] // 背景色标记 bgcolor(barssince(rsiValue > overbought) == 1 ? color.red : na) bgcolor(barssince(rsiValue < oversold) == 1 ? color.green : na) // 预警设置 alertcondition(rsiOverbought, title = "超买预警", message = "{{close}}") alertcondition(rsiOversold, title = "超卖预警", message = "{{close}}") // 指标绘制 plot(rsi, "RSI", color=#7E57C2) band1 = hline(70, "超买线", color=#787B86) bandm = hline(50, "中间线", color=color.new(#787B86, 50)) band0 = hline(30, "超卖线", color=#787B86) fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="RSI背景填充") // 交易执行 strategy.entry("多单", strategy.long, 1, when = long) strategy.close("多单", when = exitLong) strategy.entry("空单", strategy.short, 1, when = short) strategy.close("空单", when = exitShort)
内容的提问来源于stack exchange,提问作者Paul Cas
相关产品推荐
相关产品推荐

