🚀 AI 一键生成 qmt 策略代码
立即体验

QMT 平台如何实时获取回测持仓明细?(附 get_result_records 代码示例)

qmt | 发布时间: 2026/8/6
以下内容由 EasyQuant 生成。

问题描述

qmt 盘中持仓监控:使用 get_result_records 实时获取回测持仓状态
如何在qmt策略运行中通过代码获取当前回测面板的实时持仓明细?

解决方案

QMT 盘中持仓监控:使用 get_result_records 实时获取回测持仓状态

在 QMT 平台进行策略回测时,开发者往往需要实时监控当前的持仓状态、买卖明细或历史汇总信息,以便进行动态的仓位控制或策略逻辑判断。QMT 提供了内置函数 get_result_records,允许我们在 handlebar 运行过程中,直接获取回测面板上的实时记录。


1. get_result_records 函数详解

get_result_records 专门用于在模型回测时获取回测面板中的记录结果。

函数原型

get_result_records(recordtype, index, ContextInfo)

参数说明

  • recordtype (string):需要获取的面板记录类型,可选值包括:
    • 'holdings':当前持仓
    • 'buys':买入持仓
    • 'sells':卖出持仓
    • 'historysums':历史汇总
    • 'dealdetails':交易明细
  • index (number):当前主图对应的 K 线索引,通常传入 ContextInfo.barpos
  • ContextInfo:Python 策略运行环境对象。

返回值属性

函数返回一个 list,其中包含 0 个或多个 Python 对象。每个对象内含以下常用属性:

  • market (string):市场代码
  • stockcode (string):合约代码
  • position (number):仓位数量
  • trade_price (number):持仓成本/成交价
  • current_price (number):最新价
  • profit (number):持仓盈亏
  • trade_balance (number):成交额或市值
  • trade_date (number):交易日期(毫秒时间戳)

2. 实时获取回测持仓的 Python 代码示例

以下是一个完整的策略示例,展示了如何在每根 K 线(Bar)结束时,实时获取并打印当前的持仓明细和持仓盈亏:

#coding:gbk

def init(ContextInfo):
    # 设定初始资金与股票池
    ContextInfo.capital = 1000000
    ContextInfo.set_universe(['600000.SH', '000001.SZ'])

def handlebar(ContextInfo):
    index = ContextInfo.barpos
    
    # 仅在最后一根 K 线或特定逻辑下获取,避免回测时输出过多日志
    if ContextInfo.is_last_bar():
        # 获取当前持仓明细
        holdings = get_result_records('holdings', index, ContextInfo)
        
        print(f"=== 当前 K 线索引 {index} 实时持仓明细 ===")
        if not holdings:
            print("当前无持仓")
        else:
            for position_obj in holdings:
                print(f"代码: {position_obj.stockcode}.{position_obj.market} | "
                      f"持仓数量: {position_obj.position} | "
                      f"持仓成本: {position_obj.trade_price:.2f} | "
                      f"当前价格: {position_obj.current_price:.2f} | "
                      f"持仓盈亏: {position_obj.profit:.2f}")

3. 注意事项

  1. 模式限制get_result_records 仅在回测模式下有效。如果是实盘或模拟盘交易,请使用 get_trade_detail_data 函数来获取真实的资金账号持仓。
  2. 索引匹配:参数 index 决定了获取的是哪一个历史时刻的持仓状态。若要获取当前 Bar 的最新状态,务必传入 ContextInfo.barpos