🚀 AI 一键生成 ptrade 策略代码
立即体验

ptrade 平台如何解析 Level-2 盘口买卖档位排队委托笔数与委托队列?

ptrade | 发布时间: 2026/8/7
以下内容由 EasyQuant 生成。

问题描述

ptrade Level-2 高频进阶:如何在 tick_data 盘口字典中解析买卖档位的排队委托笔数
在 ptrade 的 tick_data 回调函数中,如何提取并解析买卖五档/十档数据中的委托笔数和委托对列信息?

解决方案

在 ptrade 的高频交易与 tick 级策略中,获取 Level-2 行情数据是核心步骤。通过 tick_data(context, data) 回调函数,我们可以获取到包含买卖档位详细信息的 tick 字典。

一、Level-2 档位数据结构解析

在 ptrade 的 tick_data 中,data[security]['tick'] 包含 bid_grp(买档)和 offer_grp(卖档)两个字典。其结构如下:

  • 普通档位(2-10档)格式[价格, 委托量, 委托笔数]
  • 第一档(买一/卖一)格式[价格, 委托量, 委托笔数, 委托队列{}](仅在开通 Level-2 行情时支持,委托队列字典的 key 为排队序号,value 为该笔委托的数量)

二、核心解析步骤与注意事项

  1. 数据类型转换:在 tick_data 中,bid_grpoffer_grp 往往需要使用 eval()json.loads() 进行解析(视柜台推送格式而定)。
  2. Level-2 权限校验:若无 Level-2 行情权限,委托笔数将返回 0,且第一档的委托队列字典将为空 {}
  3. 下单限制:在 tick_data 事件中,必须使用 order_tick 接口进行下单。

三、Python 示例代码

以下是一个完整的策略示例,展示如何在 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