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

如何在TradingView回测指标时排除空头头寸盈亏计算

在TradingView Pine Script中仅统计多头头寸盈亏的实现方法

方案一:直接禁用空头交易信号

如果不需要保留空头操作的展示,最简单的方式是直接删除或注释所有空头进场、出场的代码,让策略只执行多头交易,回测统计自然只会计算多头盈亏。

示例代码:

//@version=5
strategy("仅多头盈亏统计策略", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000)

// 多头进场条件(示例:5日均线上穿20日均线)
longCondition = ta.crossover(ta.sma(close, 5), ta.sma(close, 20))
if (longCondition)
    strategy.entry("Long", strategy.long)

// 多头出场条件(示例:5日均线下穿20日均线)
exitLongCondition = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20))
if (exitLongCondition)
    strategy.close("Long")

// 注释或删除所有空头相关代码
// shortCondition = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20))
// if (shortCondition)
//     strategy.entry("Short", strategy.short)
// ...

方案二:保留空头操作但不计入盈亏统计

如果需要保留空头操作的K线展示,同时不让其盈亏影响账户统计,可采用以下两种方法:

方法A:自定义权益跟踪

通过变量单独记录仅多头交易带来的权益变化,忽略空头操作的影响:

//@version=5
strategy("仅多头盈亏统计(保留空头展示)", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000)

// 初始化自定义权益变量
var float customEquity = strategy.initial_capital
var float lastLongExitEquity = strategy.initial_capital

// 多头进场逻辑
longCondition = ta.crossover(ta.sma(close, 5), ta.sma(close, 20))
if (longCondition)
    strategy.entry("Long", strategy.long)

// 多头出场时更新自定义权益
exitLongCondition = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20))
if (exitLongCondition)
    strategy.close("Long")
    lastLongExitEquity = strategy.equity // 记录多头平仓后的权益

// 空头操作(仅展示,不影响自定义权益)
shortCondition = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20))
if (shortCondition)
    strategy.entry("Short", strategy.short)
if (ta.crossover(ta.sma(close, 5), ta.sma(close, 20)))
    strategy.close("Short")

// 自定义权益:持有多头时用实时权益,否则用上次多头平仓后的权益
customEquity = strategy.position_size > 0 ? strategy.equity : lastLongExitEquity

// 绘制仅多头的权益曲线(可选)
plot(customEquity, title="仅多头权益", color=color.green, linewidth=2)

你可以通过自定义的customEquity曲线查看纯多头的盈亏情况,也可在策略设置中关闭默认权益展示,只保留自定义曲线。

方法B:让空头交易盈亏为0

通过让空头平仓价等于进场价,确保空头交易不产生任何盈亏:

//@version=5
strategy("仅多头盈亏统计(空头无盈亏)", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000)

var float shortEntryPrice = na

// 多头逻辑
longCondition = ta.crossover(ta.sma(close, 5), ta.sma(close, 20))
if (longCondition)
    strategy.entry("Long", strategy.long)

exitLongCondition = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20))
if (exitLongCondition)
    strategy.close("Long")

// 空头逻辑:进场记录价格,出场用进场价平仓
shortCondition = ta.crossunder(ta.sma(close, 5), ta.sma(close, 20))
if (shortCondition)
    strategy.entry("Short", strategy.short)
    shortEntryPrice = strategy.position_avg_price

if (ta.crossover(ta.sma(close, 5), ta.sma(close, 20)) and not na(shortEntryPrice))
    strategy.close("Short", limit=shortEntryPrice) // 无盈亏平仓

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:10:04