🚀 AI 一键生成 qmt 策略代码

QMT 平台如何查询历史委托与成交记录?(附本地存储方案)

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

问题描述

请问get_trade_detail_data()这个函数只能获取当天的委托或成交记录吗?

比如,我昨天有一笔交易,昨天能用 get_trade_detail_data()这个函数查到委托或成交记录,但今天就只能查到今天的交易记录,查不到昨天的交易记录了,那我今天想查询昨天的某笔交易记录,该怎么查呢?

解决方案

是的,您理解得完全正确。在 QMT 平台中,get_trade_detail_data() 函数只能获取当前交易日(当日)的委托(ORDER)和成交(DEAL)记录

这是因为该函数是直接向券商柜台系统发起实时查询,而柜台系统的当日委托和成交列表在每日结算后会进行清空和归档。因此,到了第二个交易日,您无法再通过该 API 直接获取前一交易日的明细。

如何查询历史交易记录?

由于 QMT 的 Python API 目前没有直接提供查询历史实盘成交记录的函数,如果您需要在策略中用到历史交易数据,最标准的解决方案是:在策略运行期间,将每日的交易记录自行持久化存储到本地(如保存为 CSV、TXT 或数据库中)

解决方案:利用 deal_callback 实时保存成交记录

您可以在策略中利用成交主推回调函数 deal_callback(),每当有一笔新成交时,就将其关键信息写入到本地文件中。第二天或以后需要查询时,直接利用 Python 读取该本地文件即可。

示例代码:将成交记录实时保存到本地 CSV 文件

#coding:gbk
import os
import csv

def init(ContextInfo):
    # 设置对应的资金账号
    ContextInfo.account = '6000000248'
    ContextInfo.set_account(ContextInfo.account)
    
    # 定义本地保存路径
    ContextInfo.history_trade_file = 'D:/QMT_Trades/history_trades.csv'
    
    # 如果文件不存在,则初始化表头
    if not os.path.exists(ContextInfo.history_trade_file):
        os.makedirs(os.path.dirname(ContextInfo.history_trade_file), exist_ok=True)
        with open(ContextInfo.history_trade_file, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['TradeDate', 'TradeTime', 'AccountID', 'InstrumentID', 'Direction', 'OffsetFlag', 'Price', 'Volume', 'TradeAmount'])

def handlebar(ContextInfo):
    # 您的策略逻辑
    pass

# 当账号成交状态有变化时,运行这个函数
def deal_callback(ContextInfo, dealInfo):
    # 提取成交对象的关键属性
    trade_date = dealInfo.m_strTradeDate
    trade_time = dealInfo.m_strTradeTime
    account_id = dealInfo.m_strAccountID
    instrument_id = dealInfo.m_strInstrumentID
    direction = dealInfo.m_nDirection
    offset_flag = dealInfo.m_nOffsetFlag
    price = dealInfo.m_dPrice
    volume = dealInfo.m_nVolume
    trade_amount = dealInfo.m_dTradeAmount
    
    # 将成交记录追加写入本地 CSV 文件
    with open(ContextInfo.history_trade_file, 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([trade_date, trade_time, account_id, instrument_id, direction, offset_flag, price, volume, trade_amount])
    
    print(f"已将成交记录保存至本地: {instrument_id}, 数量: {volume}, 价格: {price}")

如何在今天读取昨天的记录?

当您按照上述方法将数据保存后,第二天只需要使用 Python 标准的 csvpandas 库读取 D:/QMT_Trades/history_trades.csv 文件,筛选出 TradeDate 为昨天的日期,即可获取昨天的所有交易记录,供策略逻辑继续使用。