strategy.exit()触发止损后未平仓的Pine Script技术问题
Pine Script 止损未触发问题修复方案
问题根源
你提供的代码存在几处关键问题,导致止损无法正常触发:
- 代码未完成,做空仓位的
strategy.entry()调用被截断,且未添加对应的止损逻辑 - 做多止损错误使用了
low[1](前一根K线低点),而非开仓当前K线的低点 strategy.exit()的参数配置不符合规则,entry_id未正确关联开仓指令
修正后的完整代码
//@version=5 strategy("RSI 带固定止损策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000) oversold = 10 overbought = 90 rsiPlus = ta.rsi(close, 14) // 补充RSI指标定义,原代码未声明 atr = ta.atr(14) // 补充ATR指标定义,原代码未声明 co = ta.crossover(rsiPlus, oversold) cu = ta.crossunder(rsiPlus, overbought) if (not na(rsiPlus)) // 做多逻辑:RSI上穿超卖+收盘价站在20EMA上方 if (co) and (ta.ema(close,20) < close) strategy.entry("RSI_Long", strategy.long, comment="RSI做多") // 用开仓K线的低点减去ATR作为止损(可根据需求调整ATR倍数) strategy.exit("Exit_Long", "RSI_Long", stop=low - atr) // 做空逻辑:RSI下穿超买+收盘价低于20EMA if (cu) and (ta.ema(close,20) > close) strategy.entry("RSI_Short", strategy.short, comment="RSI做空") // 用开仓K线的高点加上ATR作为止损 strategy.exit("Exit_Short", "RSI_Short", stop=high + atr)
关键修改说明
- 指标补全:补充了
rsiPlus和atr的定义,原代码未声明这两个变量会导致编译错误 - 开仓ID区分:做多和做空使用不同的entry_id(
RSI_Long/RSI_Short),避免指令冲突 - 止损价修正:做多止损使用当前开仓K线的
low,做空止损使用当前开仓K线的high,确保是开仓K线的高低点 - 参数关联:
strategy.exit()的第二个参数严格对应开仓的entry_id,保证止损指令绑定正确仓位
额外优化建议
如果需要止损价固定为开仓K线的高低点(不叠加ATR),可直接修改止损参数:
- 做多止损:
stop=low - 做空止损:
stop=high
内容的提问来源于stack exchange,提问作者Dev Oberay
相关产品推荐
相关产品推荐

