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

Pine Script中strategy.exit仅对多单生效,空单止盈止损失效求助

Pine Script策略空单止盈止损失效问题修复

问题根源

你的代码存在两个核心错误:

  • 持仓状态判断错误:inTrade = strategy.position_size > 0仅将多单判定为持仓状态,空单时strategy.position_size为负数,inTrade会返回false,导致空单的strategy.exit逻辑完全不会执行。
  • 空单止盈止损价格逻辑错误:空单盈利源于价格下跌、止损源于价格上涨,你原公式搞反了计算方向,即便触发也会是错误的价格点位。

修正后的代码

//@version=5
strategy("修复空单止盈止损问题", overlay=true)

// 定义可调整参数(将百分比转为实际比例)
longProfitPerc = input.float(1.5, "多单止盈百分比", step=0.1) / 100
longStopPerc = input.float(1, "多单止损百分比", step=0.1) / 100
shortProfitPerc = input.float(1.5, "空单止盈百分比", step=0.1) / 100
shortStopPerc = input.float(1, "空单止损百分比", step=0.1) / 100

// 拆分多空持仓状态判断
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0
inTrade = strategy.position_size != 0
notInTrade = not inTrade

// 修正止盈止损价格计算逻辑
longExitPrice  = strategy.position_avg_price * (1 + longProfitPerc) 
longStopPrice = strategy.position_avg_price * (1 - longStopPerc) 
// 空单止盈:价格下跌至持仓价的(1-盈利比例);止损:价格上涨至持仓价的(1+止损比例)
shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc) 
shortStopPrice = strategy.position_avg_price * (1 + shortStopPerc) 

// 多单入场逻辑
if (GL1 and GL2 == 1 and GL3 == 1 and GL4 == 1 and GL5 == 1 and notInTrade)
    strategy.entry("long_Entry", strategy.long)

// 多单止盈止损:仅在多单持仓时触发
if (isLong)
    strategy.exit("Long_Exit", "long_Entry", limit=longExitPrice, loss=longStopPrice)

// 空单入场逻辑
if (GS1 and GS2 == 0 and GS3 == 0 and GS4 == 0 and GS5 == 0 and notInTrade)
    strategy.entry("short_Entry", strategy.short)

// 空单止盈止损:仅在空单持仓时触发
if (isShort)
    strategy.exit("Short_Exit", "short_Entry", limit=shortExitPrice, loss=shortStopPrice)

关键修改说明

  1. 拆分持仓状态:用isLong和isShort分别判断多空持仓,确保对应止盈止损逻辑只在目标持仓状态下执行。
  2. 修正空单价格计算:匹配空单盈利/止损的价格变动方向,避免逻辑颠倒导致的无效触发。
  3. 参数标准化:将输入的百分比数值除以100,确保1.5代表1.5%而非150%,符合常规参数使用习惯。

内容的提问来源于stack exchange,提问作者kaustubh natu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:15:43