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

PineScript策略无交易结果问题:52周高追踪止损策略无绩效数据

52周新高追踪止损策略无绩效数据的排查与修复

问题背景

编写的PineScript v4策略可在TradingView图表上正常显示52周高线,但绩效窗口无任何交易结果和数据输出。原代码如下:

//@version=4
strategy("52 Weeks High with Trailing Stop", overlay=true)

// Define input variables
trailStopPercent = input(1.0, "Trailing Stop Percentage")

// Calculate the 52-week high
high52Weeks = highest(high, 252)

// Define entry conditions
enterLong = close > high52Weeks

// Define exit conditions
exitLong = close < low[1] * (1 - trailStopPercent / 100)

// Calculate position size based on account capital
accountCapital = strategy.equity
positionSize = accountCapital * 0.01 // 1% of account capital

// Execute long trade
if enterLong and strategy.position_size == 0
    strategy.entry("Long", strategy.long, qty = positionSize)

// Exit long trade
if exitLong
    strategy.close("Long")

// Plotting 52-week high
plot(high52Weeks, "52 Weeks High", color=color.blue, linewidth=2)

核心问题排查

1. 入场条件逻辑错误

原入场条件close > high52Weeks永远无法触发:

  • highest(high, 252)计算的是包含当前K线在内的52周(252根K线)最高价
  • 当前K线的收盘价不可能超过包含自身的52周新高(即使收盘价创历史新高,也只是等于high52Weeks,不满足>的判断条件)

2. 止损条件偏离追踪止损设计

原止损条件close < low[1] * (1 - trailStopPercent / 100)存在两处硬伤:

  • 基于前一根K线的最低价计算止损,而非持仓后的入场价或阶段新高,完全不符合追踪止损的逻辑
  • 该阈值可能远低于当前价格,导致永远无法触发平仓

3. 仓位计算存在异常风险

  • 直接用strategy.equity * 0.01作为仓位数量,未考虑当前标的价格,可能导致仓位极小甚至无法成交(比如高价股,1%资金不足以购买1手)
  • 回测初始阶段strategy.equity可能未完成初始化,导致仓位计算错误

修复后的代码

//@version=4
strategy("52 Weeks High with Trailing Stop", overlay=true, initial_capital=100000, default_qty_type=strategy.cash, default_qty_value=1000)

// 输入参数
trailStopPercent = input(1.0, "追踪止损百分比(%)")

// 计算52周新高(排除当前K线,取前一根K线的52周新高)
high52Weeks = highest(high, 252)[1]

// 入场条件:收盘价突破前一根K线的52周新高且当前无持仓
enterLong = close > high52Weeks and strategy.position_size == 0

// 追踪止损:基于持仓期间的最高价动态调整
var float longStop = na
if (strategy.position_size > 0)
    longStop := max(longStop, close) * (1 - trailStopPercent / 100)
else
    longStop := na

// 执行入场
if (enterLong)
    strategy.entry("Long", strategy.long)

// 执行止损平仓
if (strategy.position_size > 0 and close < longStop)
    strategy.close("Long")

// 绘制52周新高线
plot(high52Weeks, "52周新高", color=color.blue, linewidth=2)

修复说明

  1. 入场条件改为突破前一根K线的52周新高,确保逻辑可触发
  2. 追踪止损改为基于持仓后的阶段最高价动态调整,符合策略设计初衷
  3. 改用default_qty_type=strategy.cash和default_qty_value控制仓位,避免因价格导致的仓位异常
  4. 初始化initial_capital明确回测初始资金

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:45:02