3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 的高频交易与 tick 级策略中,获取 Level-2 行情数据是核心步骤。通过 tick_data(context, data) 回调函数,我们可以获取到包含买卖档位详细信息的 tick 字典。
在 ptrade 的 tick_data 中,data[security]['tick'] 包含 bid_grp(买档)和 offer_grp(卖档)两个字典。其结构如下:
[价格, 委托量, 委托笔数][价格, 委托量, 委托笔数, 委托队列{}](仅在开通 Level-2 行情时支持,委托队列字典的 key 为排队序号,value 为该笔委托的数量)tick_data 中,bid_grp 和 offer_grp 往往需要使用 eval() 或 json.loads() 进行解析(视柜台推送格式而定)。0,且第一档的委托队列字典将为空 {}。tick_data 事件中,必须使用 order_tick 接口进行下单。以下是一个完整的策略示例,展示如何在 tick_data 中提取买一档的委托笔数、委托队列,以及买二档的委托笔数:
def initialize(context):
g.security = '600570.SS' # 恒生电子
set_universe(g.security)
def tick_data(context, data):
security = g.security
if security not in data:
return
try:
# 1. 获取 tick 数据中的买档信息
# 注意:部分环境推送的数据可能需要 eval 解析
bid_grp_raw = data[security]['tick']['bid_grp']
bid_grp = eval(bid_grp_raw) if isinstance(bid_grp_raw, str) else bid_grp_raw
# 2. 解析买一档 (包含价格、委托量、委托笔数、委托队列)
buy_1_info = bid_grp.get(1) or bid_grp.get('1')
if buy_1_info:
buy_1_px = buy_1_info[0] # 买一价格
buy_1_vol = buy_1_info[1] # 买一总委托量
buy_1_count = buy_1_info[2] # 买一总委托笔数 (L2 特有)
buy_1_queue = buy_1_info[3] # 买一排队委托队列 dict (L2 特有)
log.info(f"【买一档】价格: {buy_1_px}, 总委托量: {buy_1_vol}, 总笔数: {buy_1_count}")
if buy_1_queue:
# 打印前3笔排队委托的单笔数量
top_3_orders = list(buy_1_queue.items())[:3]
log.info(f"【买一排队前三笔】: {top_3_orders}")
# 3. 解析买二档 (不含委托队列)
buy_2_info = bid_grp.get(2) or bid_grp.get('2')
if buy_2_info:
buy_2_px = buy_2_info[0]
buy_2_count = buy_2_info[2] # 买二委托笔数
log.info(f"【买二档】价格: {buy_2_px}, 委托笔数: {buy_2_count}")
# 4. 盘口逻辑触发:例如当买一档排队大单(第一笔)大于 10000 股时尝试跟单
if buy_1_queue and buy_1_queue.get(1, 0) > 10000:
log.info("检测到买一排队首笔超大单,尝试以买一档价格跟单买入")
order_tick(security, 100, '1')
except Exception as e:
log.error(f"解析盘口 L2 数据异常: {e}")
def handle_data(context, data):
pass