3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT 平台进行策略回测时,开发者往往需要实时监控当前的持仓状态、买卖明细或历史汇总信息,以便进行动态的仓位控制或策略逻辑判断。QMT 提供了内置函数 get_result_records,允许我们在 handlebar 运行过程中,直接获取回测面板上的实时记录。
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):交易日期(毫秒时间戳)以下是一个完整的策略示例,展示了如何在每根 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}")
get_result_records 仅在回测模式下有效。如果是实盘或模拟盘交易,请使用 get_trade_detail_data 函数来获取真实的资金账号持仓。index 决定了获取的是哪一个历史时刻的持仓状态。若要获取当前 Bar 的最新状态,务必传入 ContextInfo.barpos。