TradingView PineScript:空头移动止损失效问题求助
解决思路及修正代码
原代码核心问题
- 头寸判断错误:空头持仓时
strategy.position_size为负数,原代码用strategy.position_size > 0判断多头,直接导致更新止损的条件永远不触发。 - 变量名混淆:要更新的是空头止损,却误用了
newStopLossLong(多头止损变量),应该改为newStopLossShort。 - 重复Exit ID:使用不同的Exit ID会让策略同时挂多个离场指令,无法覆盖原有止损,必须复用同一个ID来替换。
- 触发条件冗余:
close < BR1会连续触发,改用跌破交叉信号close crosses below BR1更精准,避免重复执行。
修正后的代码
//Short Entry if (shortCondition) and allowedTimes() and close[1] <= BR1 strategy.entry("Enter Short", strategy.short, 1, limit = sessionLowPrice) // 初始化离场指令,固定Exit ID为"Exit Short" strategy.exit("Exit Short", from_entry="Enter Short", stop = initialStopLossShort, limit = BRm34) // 更新空头止损:判断空头持仓 + 价格跌破BR1 if strategy.position_size < 0 and close crosses below BR1 // 复用同一个Exit ID,替换原有止损 strategy.exit("Exit Short", from_entry = "Enter Short", stop = newStopLossShort, limit = BRm34)
额外注意事项
- 确保
newStopLossShort的数值逻辑正确:空头止损应该是比当前价格更高的点位(因为空头止损是价格上涨到止损位平仓),如果你的newStopLossShort设置的是更低的价格,那逻辑完全错误,会导致止损永远无法触发。 - 可以添加
strategy.risk.allow_entry_in()控制同一方向只开一次仓,避免多单干扰。
内容的提问来源于stack exchange,提问作者US1 Trader
相关产品推荐
相关产品推荐

