在Pine Script策略中跨时间周期调用RSI背离指标的代码请求
跨时间周期RSI背离交易策略(Pine Script v5)
代码实现
//@version=5 strategy("跨周期RSI背离策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1) // 输入参数 rsiLength = input.int(14, title="RSI周期") rsiSource = input(close, title="RSI计算源") higherTF = input.timeframe("D", title="RSI计算的更高时间周期") overbought = input.int(70, title="超买阈值") oversold = input.int(30, title="超卖阈值") stopLossPips = input.int(50, title="止损点数") takeProfitPips = input.int(100, title="止盈点数") // 获取跨周期数据 [higherTFClose, higherTFRSI] = request.security(syminfo.tickerid, higherTF, [close, ta.rsi(rsiSource, rsiLength)]) // 检测顶背离:价格创新高,RSI未创新高且处于超买区间 topDivergence = ta.highest(close, 5) == close and ta.highest(higherTFRSI, 5) > higherTFRSI and higherTFRSI > overbought // 检测底背离:价格创新低,RSI未创新低且处于超卖区间 bottomDivergence = ta.lowest(close, 5) == close and ta.lowest(higherTFRSI, 5) < higherTFRSI and higherTFRSI < oversold // 绘制背离信号 plotshape(topDivergence, title="顶背离", location=location.belowbar, color=color.red, style=shape.labelup, text="顶背离", textcolor=color.white) plotshape(bottomDivergence, title="底背离", location=location.abovebar, color=color.green, style=shape.labeldown, text="底背离", textcolor=color.white) // 策略交易逻辑 if (bottomDivergence) strategy.entry("做多", strategy.long) strategy.exit("平多", "做多", stop=close - stopLossPips * syminfo.mintick, limit=close + takeProfitPips * syminfo.mintick) if (topDivergence) strategy.entry("做空", strategy.short) strategy.exit("平空", "做空", stop=close + stopLossPips * syminfo.mintick, limit=close - takeProfitPips * syminfo.mintick)
关键逻辑说明
- 跨周期数据获取:通过
request.security()函数拉取指定更高时间周期的收盘价和RSI值,确保背离判断基于大周期的指标趋势 - 背离识别:
- 顶背离:主图价格创5周期新高,但大周期RSI未同步新高且处于超买区,预示上涨动能衰竭
- 底背离:主图价格创5周期新低,但大周期RSI未同步新低且处于超卖区,预示下跌动能衰竭
- 风险控制:内置固定点数的止损止盈,可根据品种特性调整参数,也可替换为ATR动态止损
内容的提问来源于stack exchange,提问作者turkprinting
相关产品推荐
相关产品推荐

