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

PineScript回测历史交易分析:如何获取开仓时指标数值?

在PineScript中获取回测交易开仓时的指标数值

PineScript提供了strategy.closedtrades和strategy.opentrades系列内置函数,专门用于访问回测的交易历史数据,通过这些函数可以轻松提取每笔交易开仓时点的指标数值。

核心思路

  1. 先计算目标指标(如RSI、MACD等)
  2. 通过交易历史函数获取每笔交易的开仓K线索引
  3. 利用K线索引直接调取对应时点的指标数值

代码示例(提取开仓RSI)

//@version=5
strategy("交易历史指标提取示例", overlay=true)

// 1. 计算目标指标(这里以RSI为例)
rsi_length = 14
rsi_value = ta.rsi(close, rsi_length)

// 2. 简单策略生成回测交易(可替换为你的策略)
long_signal = ta.crossover(rsi_value, 30)
short_signal = ta.crossunder(rsi_value, 70)

if (long_signal)
    strategy.entry("多单", strategy.long)
if (short_signal)
    strategy.entry("空单", strategy.short)

// 3. 提取交易历史与对应指标值
if (barstate.islast)
    // 获取已平仓交易总数
    total_closed = strategy.closedtrades
    
    // 遍历所有已平仓交易
    for trade_idx from 0 to total_closed - 1
        // 获取开仓K线的索引
        entry_bar_idx = strategy.closedtrades.entry_bar_index(trade_idx)
        // 获取开仓时点的RSI值
        entry_rsi = rsi_value[entry_bar_idx]
        // 交易基础信息
        direction = strategy.closedtrades.entry_size(trade_idx) > 0 ? "多单" : "空单"
        profit = strategy.closedtrades.profit(trade_idx)
        
        // 在图表上标注信息
        label.new(bar_index, high + ta.atr(14)*0.5, 
             str.format("交易#{0}\n方向: {1}\n开仓RSI: {2:.2f}\n盈亏: {3:.2f}", 
             trade_idx+1, direction, entry_rsi, profit), 
             color=color.new(color.blue, 0), textcolor=color.white)
    
    // 单独提取第一笔已平仓交易的开仓RSI
    if (total_closed > 0)
        first_entry_bar = strategy.closedtrades.entry_bar_index(0)
        first_entry_rsi = rsi_value[first_entry_bar]
        label.new(bar_index, low - ta.atr(14)*0.5, 
             str.format("第一笔交易开仓RSI: {0:.2f}", first_entry_rsi), 
             color=color.new(color.red, 0), textcolor=color.white)

关键函数说明

  • strategy.closedtrades:返回已平仓交易的总数量
  • strategy.closedtrades.entry_bar_index(i):返回第i笔已平仓交易的开仓K线索引(索引从0开始计数)
  • strategy.opentrades:返回当前未平仓交易的总数量,对应未平仓交易的开仓索引用strategy.opentrades.entry_bar_index(i)获取
  • 指标值通过指标变量[开仓K线索引]直接获取,PineScript会保留所有历史K线的指标计算结果,通过索引可直接定位到开仓时点的数值

注意事项

  • 交易历史数据仅在回测完成后(即最后一根K线,barstate.islast条件下)才能完整获取,建议在该条件下执行提取逻辑
  • 上述方法适用于任意自定义或内置指标,只需先计算目标指标,再通过开仓K线索引取值即可
  • 若要提取未平仓交易的开仓指标值,只需将closedtrades相关函数替换为opentrades系列函数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:15:41