3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在量化高频交易中,主力资金经常通过“闪撤单”(Spoofing)在盘口挂出大单制造买卖压力假象(诱多或诱空),随后迅速撤单。通过监测 Level-2 的买入撤单总量与卖出撤单总量,并计算其占总委托量的比例,可以有效识别这种欺骗性行为。
QMT 平台提供了强大的 Level-2 数据接口,支持获取行情快照指标。以下是具体实现方法及 Python 源码。
要获取 Level-2 撤单数据,需要使用 ContextInfo.get_market_data_ex 接口,并将周期参数 period 设置为 'l2quoteaux'(Level2 行情快照指标)。
withdrawBidQuantity: 买入撤单总量withdrawOffQuantity: 卖出撤单总量totalBidQuantity: 委买总量totalOffQuantity: 委卖总量以下代码展示了如何在 QMT 中订阅并获取指定股票的 Level-2 撤单数据,并实时计算撤单比例因子:
#encoding:gbk
import pandas as pd
def init(ContextInfo):
# 设定需要监测的股票池
ContextInfo.stock_list = ['600000.SH']
ContextInfo.set_universe(ContextInfo.stock_list)
print("Level-2 撤单监控因子初始化成功")
def handlebar(ContextInfo):
# 仅在最后一根 Bar(最新 Tick 驱动)时执行计算
if not ContextInfo.is_last_bar():
return
for stock in ContextInfo.stock_list:
# 获取 Level-2 行情快照指标
l2_data = ContextInfo.get_market_data_ex(
fields=['withdrawBidQuantity', 'withdrawOffQuantity', 'totalBidQuantity', 'totalOffQuantity'],
stock_code=[stock],
period='l2quoteaux',
count=1
)
if stock in l2_data and not l2_data[stock].empty:
df = l2_data[stock]
# 提取最新一笔快照数据
withdraw_bid = df['withdrawBidQuantity'].iloc[-1]
withdraw_off = df['withdrawOffQuantity'].iloc[-1]
total_bid = df['totalBidQuantity'].iloc[-1]
total_off = df['totalOffQuantity'].iloc[-1]
# 计算买入撤单比例
bid_denom = total_bid + withdraw_bid
bid_ratio = (withdraw_bid / bid_denom) if bid_denom > 0 else 0.0
# 计算卖出撤单比例
off_denom = total_off + withdraw_off
off_ratio = (withdraw_off / off_denom) if off_denom > 0 else 0.0
# 打印监控结果
print(f"股票: {stock} | 委买总量: {total_bid} | 买入撤单: {withdraw_bid} | 买入撤单比例: {bid_ratio:.2%}")
print(f"股票: {stock} | 委卖总量: {total_off} | 卖出撤单: {withdraw_off} | 卖出撤单比例: {off_ratio:.2%}")
# 诱多诱空逻辑研判
if bid_ratio > 0.8 and total_bid > 100000:
print(f"【警惕】{stock} 出现高比例买单撤销({bid_ratio:.2%}),可能存在主力诱多后撤单行为!")
elif off_ratio > 0.8 and total_off > 100000:
print(f"【警惕】{stock} 出现高比例卖单撤销({off_ratio:.2%}),可能存在主力诱空后撤单行为!")
total_bid > 100000),避免因小额散户撤单导致因子失真。