如何移除除最后一个外的所有Long/Short信号?代码求助
问题解决:保留最后一个Long/Short信号
你的代码问题分析
你尝试的代码存在两个核心错误:
- 错误使用
var声明lastLong和lastShort:var关键字会让变量仅在脚本初始化时赋值一次,后续K线不会更新,导致这两个变量无法跟踪最新的信号条件。 - 逻辑分支与赋值错误:
else if分支会覆盖信号状态,且else na不符合布尔类型变量的赋值规则,Pine Script中布尔变量不能赋值为na。
解决方案
根据需求,提供两种常用实现方式:
方式1:仅显示最后一次触发信号的K线
此方案仅在最后一次触发信号的K线上标记信号,其他K线不显示:
//@version=5 indicator("仅保留最后一个信号", overlay=true) // 替换为你的实际条件 longCond = ta.crossover(ta.sma(close, 5), ta.sma(close, 20)) shortCond = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20)) CondIni = 0 // 替换为你的CondIni变量 // 跟踪最后一次信号的K线索引 var int lastLongBar = na var int lastShortBar = na // 更新信号索引 if (longCond and CondIni[1] == -1) lastLongBar := bar_index if (shortCond and CondIni[1] == 1) lastShortBar := bar_index // 仅在最后一次信号的K线上激活信号 long = bar_index == lastLongBar short = bar_index == lastShortBar // 绘制信号标记(可选) plotshape(long, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small) plotshape(short, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small) // 警报 alertcondition(long, title="Long", message="Long") alertcondition(short, title="Short", message="Short")
方式2:维持最后一次信号的状态
此方案会在触发最后一次信号后,后续所有K线都保持该信号状态,直到出现反向信号:
//@version=5 indicator("维持最后一个信号状态", overlay=true) // 替换为你的实际条件 longCond = ta.crossover(ta.sma(close, 5), ta.sma(close, 20)) shortCond = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20)) CondIni = 0 // 替换为你的CondIni变量 // 初始化信号状态(仅初始化一次) var bool currentLong = false var bool currentShort = false // 更新信号状态 if (longCond and CondIni[1] == -1) currentLong := true currentShort := false else if (shortCond and CondIni[1] == 1) currentShort := true currentLong := false // 输出最终信号 long = currentLong short = currentShort // 绘制信号标记(可选) plotshape(long, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small) plotshape(short, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small) // 警报 alertcondition(long, title="Long", message="Long") alertcondition(short, title="Short", message="Short")
内容的提问来源于stack exchange,提问作者Hamza Ali
相关产品推荐
相关产品推荐

