TradingView自定义指标求助:修复GoLong与ExitLong信号重复触发问题
TradingView Pine Script 5 过滤重复信号解决方案
原始问题与代码
我在TradingView中制作了一个自定义指标,当满足买入或卖出条件时会绘制箭头。原始代码如下:
//@version=5 indicator("RSI + EMA Strategy", overlay=true) //RSI Calculation rsiValue = ta.rsi(close,14) //Variables for storing RSI condition rsiBuy = (rsiValue > 30) ? 1 : 0 rsiSell = (ta.crossunder(rsiValue, 70)) ? 1 : 0 //Exponential MA Code EMA10 = ta.ema(close,10) GoLong = (ta.crossover(close, EMA10)) or (rsiBuy > 0) ? 1 : 0 plotshape(GoLong, "Long", shape.arrowup, location.belowbar, color.green, size = size.normal) ExitLong = ta.crossunder(close, EMA10) or (rsiSell > 0) ? 1 : 0 plotshape(ExitLong, "ExitLong", shape.arrowdown, location.abovebar, color.orange, size = size.normal)
遇到的问题:
- GoLong会在每根满足条件的K线重复绘制箭头,未检查之前的多头信号是否已触发ExitLong;
- ExitLong同样会在每根满足条件的K线重复绘制箭头,未检查是否先触发过GoLong。
解决方案
核心思路是用持久化状态变量跟踪当前持仓状态,无需循环即可实现信号互斥。修改后的代码如下:
//@version=5 indicator("RSI + EMA Filtered Signals", overlay=true) // RSI计算 rsiValue = ta.rsi(close, 14) // EMA计算 EMA10 = ta.ema(close, 10) // 持久化变量:记录当前是否持有多头仓位(仅初始化一次) var inLongPosition = false // 买入条件:EMA上穿 或 RSI回到30以上 goLongCondition = ta.crossover(close, EMA10) or (rsiValue > 30) // 过滤买入信号:仅在未持仓时触发 goLongSignal = goLongCondition and not inLongPosition // 卖出条件:EMA下穿 或 RSI下穿70 exitLongCondition = ta.crossunder(close, EMA10) or ta.crossunder(rsiValue, 70) // 过滤卖出信号:仅在已持仓时触发 exitLongSignal = exitLongCondition and inLongPosition // 更新持仓状态 if goLongSignal inLongPosition := true if exitLongSignal inLongPosition := false // 绘制过滤后的信号箭头 plotshape(goLongSignal, "Long", shape.arrowup, location.belowbar, color.green, size=size.normal) plotshape(exitLongSignal, "ExitLong", shape.arrowdown, location.abovebar, color.orange, size=size.normal)
关键改动说明
var关键字的使用:var inLongPosition = false创建了一个跨K线持久化的变量,初始为false(未持仓),后续仅在信号触发时更新值,确保状态连续。- 信号过滤逻辑:
- 买入信号仅在未持仓且满足买入条件时触发,避免同一持仓周期内重复出买入箭头;
- 卖出信号仅在已持仓且满足卖出条件时触发,避免无持仓时出现卖出箭头。
- 状态同步更新:在信号触发时立即更新持仓状态,保证下一根K线能正确判断是否可以生成新信号。
- 简化原代码逻辑:将原有的三元表达式转换为直接的布尔判断,代码更易读。
内容的提问来源于stack exchange,提问作者samir7399
相关产品推荐
相关产品推荐

