You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pine Script v5指标中添加买卖条件告警?

解决Pine Script v5添加买卖告警的问题

你的问题核心是没有把两条SMA均线赋值为变量,导致后续没法在告警条件里引用它们。按照下面的步骤修改代码就能解决:

步骤1:把两条SMA均线存为变量

在计算出s之后,把原来直接写在plot()里的SMA单独赋值给变量,这样后面的告警条件就能直接调用:

// 新增:将两条SMA均线存为变量
fastSMA = ta.sma(s, fastLength)
slowSMA = ta.sma(s, slowLength)

步骤2:定义买卖触发条件

为了避免行情波动时连续触发告警,我们可以判断首次满足条件的K线(如果不需要限制,直接用简单的比较逻辑即可):

// 买入条件:s首次同时上穿两条SMA均线
buyCondition = s > fastSMA and s > slowSMA and ta.barssince(s <= fastSMA or s <= slowSMA) == 1

// 卖出条件:s首次同时下穿两条SMA均线
sellCondition = s < fastSMA and s < slowSMA and ta.barssince(s >= fastSMA or s >= slowSMA) == 1

如果不需要限制首次触发,只想只要满足条件就告警,可以简化成:

buyCondition = s > fastSMA and s > slowSMA
sellCondition = s < fastSMA and s < slowSMA

步骤3:添加告警条件

用alertcondition()分别为买卖条件设置告警:

// 添加买入告警
alertcondition(buyCondition, title="买入信号", message="s上穿两条SMA均线,触发买入")

// 添加卖出告警
alertcondition(sellCondition, title="卖出信号", message="s下穿两条SMA均线,触发卖出")

完整修改后的代码

indicator(title='TBA Test', shorttitle='TBA')
src = close
rsi_length = input(14, title='RSI Length')
rsi_mom_length = input(30, title='RSI Momentum Length')
rsi_ma_length = input(9, title='RSI MA Length')
ma_length = input(6, title='SMA Length')
fastLength = input(23)
slowLength = input(50)

r = ta.rsi(src, rsi_length)
rsidelta = ta.mom(r, rsi_mom_length)
rsisma = ta.sma(ta.rsi(src, rsi_ma_length), ma_length)
s = rsidelta + rsisma

// 新增:将两条SMA均线存为变量
fastSMA = ta.sma(s, fastLength)
slowSMA = ta.sma(s, slowLength)

// 定义买卖触发条件(首次满足版本)
buyCondition = s > fastSMA and s > slowSMA and ta.barssince(s <= fastSMA or s <= slowSMA) == 1
sellCondition = s < fastSMA and s < slowSMA and ta.barssince(s >= fastSMA or s >= slowSMA) == 1

// 添加告警条件
alertcondition(buyCondition, title="买入信号", message="s上穿两条SMA均线,触发买入")
alertcondition(sellCondition, title="卖出信号", message="s下穿两条SMA均线,触发卖出")

// 绘图部分不变
plot(s, color=color.new(#e7c7e7, 0), linewidth=2)
plot(fastSMA, linewidth=1, color=color.new(#FFFF00, 0))
plot(slowSMA, linewidth=1, color=color.new(#FF0000, 0))

注意事项

  • 若使用首次触发的条件,需确保图表加载的K线数量足够(至少大于fastLength和slowLength),否则ta.barssince可能无法正确计算。
  • 在TradingView的告警设置里,要选择对应指标的“买入信号”或“卖出信号”作为触发源。

内容的提问来源于stack exchange,提问作者ElonWannabe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:07:32