You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:37:36