Pine Script中基于均线顺序条件的买卖信号编写需求
4SMA 带买卖信号指标
功能说明
- 买入信号触发:当移动平均线首次呈现
SMA200 > SMA100 > SMA50 > SMA20的层级顺序时 - 卖出信号触发:当移动平均线首次呈现
SMA200 < SMA100 < SMA50 < SMA20的层级顺序时
完整代码
study(title="4SMA 带买卖信号", shorttitle="4SMA_Signals", overlay=true) // 定义均线周期参数 SMA1 = input(20, minval=1, title="SMA20") SMA2 = input(50, minval=1, title="SMA50") SMA3 = input(100, minval=1, title="SMA100") SMA4 = input(200, minval=1, title="SMA200") // 计算各周期均线 sma20 = sma(close, SMA1) sma50 = sma(close, SMA2) sma100 = sma(close, SMA3) sma200 = sma(close, SMA4) // 绘制均线 plot(sma20, color=color.new(color.green, 0), linewidth=2) plot(sma50, color=color.new(color.yellow, 0), linewidth=2) plot(sma100, color=color.new(color.orange, 0), linewidth=2) plot(sma200, color=color.new(color.red, 0), linewidth=2) // 定义均线层级条件 buyCondition = sma200 > sma100 and sma100 > sma50 and sma50 > sma20 sellCondition = sma200 < sma100 and sma100 < sma50 and sma50 < sma20 // 判断首次触发(当前满足条件,前一根K线不满足) firstBuy = buyCondition and not buyCondition[1] firstSell = sellCondition and not sellCondition[1] // 绘制买卖信号标记 plotshape(firstBuy, title="买入信号", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY", textcolor=color.white, size=size.small) plotshape(firstSell, title="卖出信号", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL", textcolor=color.white, size=size.small)
关键逻辑解释
- 首次触发判断:通过
buyCondition[1]调用前一根K线的条件状态,确保只有当当前K线刚满足层级顺序时才触发信号,避免连续重复触发。 - 信号标记:使用
plotshape在对应K线的下方/上方绘制标签式信号,直观展示买卖点位置。
内容的提问来源于stack exchange,提问作者ali_he96
相关产品推荐
相关产品推荐

