3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化交易中,高频交易和盘口分析离不开十档盘口以及挂单明细(Level 2 数据)。在 QMT 平台中,获取盘口数据主要有两种方式:
get_full_tick 接口(默认提供五档盘口)。get_market_data_ex 或 subscribe_quote 接口获取 Level 2 增强行情(包含十档盘口、委买委卖均价、撤单总量等明细)。本文将为您详细介绍这两种方法的实现方式,并附带完整的 Python 代码示例。
get_full_tick 接口get_full_tick 是 QMT 中获取最新分笔数据的标准接口。需要注意的是,标准行情下该接口默认返回五档盘口数据(askPrice/bidPrice 列表长度为 5)。
ContextInfo.get_full_tick(stock_code=[])askPrice: 卖价五档列表bidPrice: 买价五档列表askVol: 卖量五档列表bidVol: 买量五档列表lastPrice: 最新价、volume: 成交总量等。#coding:gbk
def init(ContextInfo):
ContextInfo.set_universe(['600000.SH'])
def handlebar(ContextInfo):
# 获取最新分笔数据
tick_data = ContextInfo.get_full_tick(['600000.SH'])
if '600000.SH' in tick_data:
sh_data = tick_data['600000.SH']
print("最新价:", sh_data['lastPrice'])
print("卖五档价格:", sh_data['askPrice']) # 默认返回5档
print("买五档数量:", sh_data['bidVol'])
如果您需要获取十档盘口、委买委卖均价、撤单明细等深度数据,必须开通 Level 2 增强版权限,并使用 get_market_data_ex 或 subscribe_quote 接口订阅 l2quoteaux(Level2 行情快照指标)或 l2transactioncount(Level2 大单统计)。
l2quoteaux) 包含的明细字段avgBidPrice: 委买均价totalBidQuantity: 委买总量avgOffPrice: 委卖均价totalOffQuantity: 委卖总量withdrawBidQuantity/withdrawBidAmount: 买入撤单总量/总额withdrawOffQuantity/withdrawOffAmount: 卖出撤单总量/总额#coding:gbk
def on_l2_quote(datas):
# Level 2 数据回调函数
for code, df in datas.items():
print(f"代码: {code} 收到 Level 2 实时数据:")
print(df.tail(1)) # 打印最新的一条 L2 快照指标
def init(ContextInfo):
# 订阅 Level 2 行情快照指标 (l2quoteaux)
# 注意:此接口需要额外开通 Level 2 增强版权限
sub_id = ContextInfo.subscribe_quote(
'600000.SH',
period='l2quoteaux',
dividend_type='none',
callback=on_l2_quote
)
print(f"成功订阅 Level 2 数据,订阅号: {sub_id}")
def handlebar(ContextInfo):
# 也可以在 handlebar 中主动获取历史 Level 2 数据
if ContextInfo.is_last_bar():
l2_data = ContextInfo.get_market_data_ex(
fields=[],
stock_code=['600000.SH'],
period='l2quoteaux',
count=5
)
print("主动获取的历史 Level 2 数据:")
print(l2_data['600000.SH'])
get_full_tick 仅支持五档行情。若要获取真实的十档盘口及详细的撤单、大单统计等 Level 2 数据,请联系您的开户券商确认是否开通了 QMT Level 2 增强版行情权限。ContextInfo.subscribe_quote 配合回调函数,以确保在盘口数据更新时能够第一时间触发策略逻辑,避免因 handlebar 驱动延迟导致错过最佳交易时机。