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

Pine Script技术求助:未触发TP/SL时空单被多单自动平仓

问题原因与解决方案

核心问题

你的策略出现空单被多单信号自动平仓的情况,是因为Pine Script的strategy.entry默认支持反向开仓自动平仓:当持有空单时触发多单信号,系统会自动先平掉现有空单,再开新的多单,这个过程和止盈止损无关,是内置的反向开仓逻辑。

代码问题点

  1. 开仓条件未限制持仓状态:没有判断当前是否无仓位,导致反向信号触发时自动平仓现有仓位
  2. 空单止盈止损变量复用错误:用多单的止损(longSL_pc)做空单止盈,多单的止盈(longTP_pc)做空单止损,逻辑完全颠倒,会导致空单的止盈止损失效或错误触发

修正后的代码

pc=input.int(title="tpsl percent",defval=6)/100
adx_val=input.int(title="adx_val",defval=50)
k_val=input.int(title="k_val",defval=20)
d_val=input.int(title="d_val",defval=20)
ordersize=1000/close

// 单独定义多空止盈止损变量,避免混淆
var float longTP = na
var float longSL = na
var float shortTP = na
var float shortSL = na

longCondition = k<=k_val and d<=d_val and ta.crossover(k,d)

// 仅无仓位时开多单
if (longCondition and strategy.position_size == 0)
    strategy.entry("Long", strategy.long, ordersize)
    longTP := strategy.position_avg_price*(1+pc)
    longSL := strategy.position_avg_price*(1-pc)

if strategy.position_size > 0                                               
    strategy.exit(id="close long",limit=longTP, stop=longSL)

shortCondition = k>=(100-k_val) and d>=(100-d_val) and ta.crossunder(k,d)

// 仅无仓位时开空单
if (shortCondition and strategy.position_size == 0)
    strategy.entry("Short", strategy.short,ordersize)
    shortTP := strategy.position_avg_price*(1-pc)
    shortSL := strategy.position_avg_price*(1+pc)

if strategy.position_size < 0 
    strategy.exit(id="close short",limit=shortTP, stop=shortSL)

关键修改说明

  • 在开仓条件中加入strategy.position_size == 0,确保只有当前无任何持仓时才触发开仓,彻底避免反向开仓自动平仓的情况
  • 为多空单分别定义独立的止盈止损变量,开仓时实时更新对应价格,修正原代码中空单止盈止损的逻辑错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:10:18