如何用Pine Script实现买卖信号的交替循环编号
实现交替编号的买卖信号(Long1→Short1→Long2→Short2)
完全可以实现你需要的交替编号信号逻辑。下面是修改后的完整脚本,以及关键改动的说明:
修改后的完整脚本
// Smooth Average Range source = input(close, title="Source") per1 = input(defval=27, minval=1, title="Fast period") mult1 = input(defval=1.6, minval=0.1, title="Fast range") per2 = input(defval=55, minval=1, title="Slow period") mult2 = input(defval=2, minval=0.1, title="Slow range") smoothrng(x, t, m) => wper = t * 2 - 1 avrng = ema(abs(x - x[1]), t) smoothrng = ema(avrng, wper) * m smoothrng smrng1 = smoothrng(source, per1, mult1) smrng2 = smoothrng(source, per2, mult2) smrng = (smrng1 + smrng2) / 2 // Range Filter rngfilt(x, r) => rngfilt = x rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r rngfilt filt = rngfilt(source, smrng) upward = 0.0 upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1]) downward = 0.0 downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1]) hband = filt + smrng lband = filt - smrng longCond = bool(na) shortCond = bool(na) longCond := source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0 shortCond := source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0 CondIni = 0 CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1] long = longCond and CondIni[1] == -1 short = shortCond and CondIni[1] == 1 // 新增:跟踪信号编号,实现1→2→1的交替循环 signalNumber = 1 signalNumber := short ? (signalNumber[1] == 1 ? 2 : 1) : nz(signalNumber[1], 1) // Plotting - 显示带编号的信号 plotshape(long, title="Long", text="Long" + str.tostring(signalNumber), style=shape.labelup, textcolor=color.black, size=size.tiny, location=location.belowbar, color=color.lime, transp=0) plotshape(short, title="Short", text="Short" + str.tostring(signalNumber), style=shape.labeldown, textcolor=color.white, size=size.tiny, location=location.abovebar, color=color.red, transp=0) // Alerts - 带编号的预警信息 alertcondition(long, title="Long " + str.tostring(signalNumber), message="Long " + str.tostring(signalNumber)) alertcondition(short, title="Short " + str.tostring(signalNumber), message="Short " + str.tostring(signalNumber))
关键改动说明
新增信号编号跟踪变量
- 添加了
signalNumber变量,初始值为1 - 每次触发空单(
short)信号时,自动切换编号:1→2→1循环 - 保证多单和对应的空单使用相同编号(Long1对应Short1,Long2对应Short2)
- 添加了
修改信号显示文本
- 将
plotshape的text参数修改为"Long" + str.tostring(signalNumber)和"Short" + str.tostring(signalNumber),实现编号显示
- 将
更新预警信息
- 预警的标题和消息也添加了编号,方便接收预警时区分信号序列
修复原脚本小问题
- 补充了原脚本缺失的
source输入变量,避免运行报错
- 补充了原脚本缺失的
内容的提问来源于stack exchange,提问作者Jimmy Lee
相关产品推荐
相关产品推荐

