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

如何将ATR设为止盈(TP)和止损(SL)?回测未平仓问题求助

问题分析与解决方案

你代码的核心问题是误解了strategy.entry()中stop和limit参数的作用:这两个参数是用来设置入场挂单的触发条件(比如做多时,stop是止损入场价、limit是限价入场价),而非持仓后的止盈止损平仓条件。因此当反向信号触发时,strategy.entry()会直接反手开仓,原持仓没有被自动平仓,导致出现多空切换的现象。

修复方案

使用strategy.exit()函数为已开仓的订单绑定止盈止损条件,或手动跟踪入场价格触发平仓。以下是两种可行的实现方式:

方式1:用strategy.exit()绑定止盈止损(推荐)

//@version=5
strategy("ATR TP/SL Strategy", overlay=true)

// 补全原代码缺失的EMA定义
ema10 = ta.ema(close, 10)
ema30 = ta.ema(close, 30)

// ATR计算
atrLength = 14
atr = ta.atr(atrLength)

// 入场条件
longCondition = ema10 > ema30 and ta.crossover(close, ema30)
shortCondition = ema10 < ema30 and ta.crossunder(close, ema30)

// 多单入场+绑定止盈止损
if (longCondition)
    strategy.entry("Long", strategy.long)
    // 绑定到Long订单,设置止损(入场价-2*ATR)、止盈(入场价+4*ATR)
    strategy.exit("Long Exit", "Long", stop=close - atr*2, limit=close + atr*4)

// 空单入场+绑定止盈止损(注意空单的止损/止盈方向与多单相反)
if (shortCondition)
    strategy.entry("Short", strategy.short)
    strategy.exit("Short Exit", "Short", stop=close + atr*2, limit=close - atr*4)

方式2:手动跟踪入场价触发平仓

//@version=5
strategy("ATR TP/SL Strategy", overlay=true)

// 补全EMA定义
ema10 = ta.ema(close, 10)
ema30 = ta.ema(close, 30)

// ATR计算
atrLength = 14
atr = ta.atr(atrLength)

// 入场条件
longCondition = ema10 > ema30 and ta.crossover(close, ema30)
shortCondition = ema10 < ema30 and ta.crossunder(close, ema30)

// 跟踪持仓状态与入场价格
var float longEntryPrice = na
var float shortEntryPrice = na
isLong = strategy.position_size > 0
isShort = strategy.position_size < 0

// 多单入场
if (longCondition)
    strategy.entry("Long", strategy.long)
    longEntryPrice := close
    shortEntryPrice := na

// 空单入场
if (shortCondition)
    strategy.entry("Short", strategy.short)
    shortEntryPrice := close
    longEntryPrice := na

// 多单止盈止损平仓
if (isLong)
    longSL = longEntryPrice - atr*2
    longTP = longEntryPrice + atr*4
    if (close <= longSL or close >= longTP)
        strategy.close("Long")

// 空单止盈止损平仓
if (isShort)
    shortSL = shortEntryPrice + atr*2
    shortTP = shortEntryPrice - atr*4
    if (close >= shortSL or close <= shortTP)
        strategy.close("Short")

关键说明

  1. 空单的止盈止损方向必须与多单相反:空单止损在入场价上方,止盈在入场价下方,避免逻辑错误。
  2. strategy.exit()会自动绑定到指定的入场订单,确保平仓操作仅针对目标持仓,不会出现误平仓。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:55:42