Pine Script中带偏移量的移动平均线交叉判断实现问题
Pine Script 带偏移量均线的交叉判断实现
需求说明
- 使用一条100周期的移动平均线
- 使用另一条100周期、偏移量20的移动平均线
- 基于这两条均线,用
crossover()和crossunder()实现交叉判断,注意直接对均线值加偏移量的写法错误(会得到等效120周期的均线,并非需求的偏移均线)
核心逻辑
Pine Script中plot()函数的offset参数,作用是把当前计算的指标值偏移到指定数量的K线位置显示。比如plot(ma100, offset=20),是把当前K线的ma100值,画在20根K线之后的位置。反过来,当前K线位置显示的“偏移20的均线值”,其实是20根K线之前计算出的ma100值。
因此,要获取这条偏移均线在当前K线的实际值,直接用历史引用ma100[20]即可,也可以用ta.offset()函数实现相同效果。
完整代码示例
//@version=5 indicator("MA Offset Cross", overlay=true) // 计算100周期基础均线 ma100 = ta.sma(close, 100) // 获取偏移20的均线值:取20根K线前的ma100值 ma100_offset20 = ma100[20] // 等价写法:ma100_offset20 = ta.offset(ma100, 20) // 交叉判断 cross_up = ta.crossover(close, ma100_offset20) cross_down = ta.crossunder(close, ma100_offset20) // 可视化验证:红绿线会与带offset的绿点重合 plot(ma100, color=color.blue, title="MA100") plot(ma100_offset20, color=color.red, title="MA100 Offset 20") plot(ma100, offset=20, color=color.green, style=plot.style_circles, title="MA100 Plot Offset 20") // 标记交叉信号 plotshape(cross_up, title="Cross Up", location=location.belowbar, color=color.green, style=shape.labelup, text="金叉") plotshape(cross_down, title="Cross Down", location=location.abovebar, color=color.red, style=shape.labeldown, text="死叉")
代码说明
ma100[20]:直接引用20根K线之前的100周期均线值,这就是plot(ma100, offset=20)在当前K线显示的数值- 交叉判断直接使用
ma100_offset20与价格进行对比,逻辑完全符合需求 - 可视化部分通过三种不同样式的绘图验证了取值的正确性:红色线与带offset的绿色圆点完全重合
内容的提问来源于stack exchange,提问作者Deepu
相关产品推荐
相关产品推荐

