3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 QMT 中,要在每一笔新的分笔成交数据(Tick)到来时执行判断逻辑,最推荐的方式是使用 ContextInfo.subscribe_quote 函数进行行情订阅。
通过将订阅周期设置为 'tick' 并指定一个回调函数,每当有新的 Tick 数据推送时,系统会自动触发该回调函数。
以下是具体的实现代码示例和说明:
# -*- coding: gbk -*-
def init(ContextInfo):
# 1. 设定要订阅的股票代码
stock_code = '600000.SH'
# 2. 调用订阅函数
# 参数说明:
# stock_code: 股票代码
# period='tick': 指定订阅周期为分笔数据
# dividend_type='none': 分笔数据通常不复权
# callback=on_tick_callback: 指定数据推送时触发的回调函数
ContextInfo.subscribe_quote(stock_code, period='tick', dividend_type='none', callback=on_tick_callback)
print(f"已订阅 {stock_code} 的Tick数据")
def on_tick_callback(datas):
"""
这是回调函数,每当有新的Tick数据到来时会被调用
datas: 字典类型 {code: dataframe}
"""
# 遍历推送来的数据(通常只有订阅的那一只,但也可能多只)
for stock_code, df in datas.items():
# df 是一个 pandas DataFrame,包含该 tick 的详细信息
# 获取最新价
last_price = df['lastPrice'][0]
# 获取时间
time_str = df.index[0]
# 获取成交量
volume = df['volume'][0]
# --- 在此处编写你的判断逻辑 ---
print(f"收到Tick推送 - 代码: {stock_code}, 时间: {time_str}, 最新价: {last_price}, 成交量: {volume}")
# 示例逻辑:如果价格大于某值则打印日志
if last_price > 10.0:
print(f"{stock_code} 价格突破 10.0 元")
def handlebar(ContextInfo):
# handlebar 是 K 线驱动的,如果主要逻辑在 on_tick_callback 中处理,这里可以留空
pass
subscribe_quote 函数:
init 中调用。period 参数必须设置为 'tick'。回调函数 (callback):
on_tick_callback),并将其函数名作为参数传给 subscribe_quote。datas 是一个字典,Key 是股票代码,Value 是包含 Tick 数据的 pandas.DataFrame。数据结构:
lastPrice (最新价), amount (成交额), volume (成交量), askPrice (卖价), bidPrice (买价) 等。运行模式: