🚀 AI 一键生成 ptrade 策略代码

如何使用 PTrade API 获取股票的实时五档/十档行情?

ptrade | 发布时间: 2025/12/1
以下内容由 EasyQuant 生成。

问题描述

如何获取一只股票实时的买一卖一价格和挂单量?

解决方案

在PTrade中,获取一只股票实时的买一卖一价格和挂单量,主要使用 get_snapshot 函数。该函数返回实时的行情快照数据。

核心步骤

  1. 调用接口:使用 get_snapshot(security) 获取指定标的的行情字典。
  2. 解析数据
    • 买盘信息:位于返回字典的 bid_grp 字段中。Key为档位(1代表买一),Value为列表 [价格, 挂单量, 笔数]
    • 卖盘信息:位于返回字典的 offer_grp 字段中。Key为档位(1代表卖一),Value为列表 [价格, 挂单量, 笔数]

代码实现

以下是一个完整的策略示例,展示如何在盘中每隔3秒获取一次“恒生电子”的买一卖一数据并打印到日志中。

def initialize(context):
    # 设置关注的股票
    g.security = '600570.SS'
    set_universe(g.security)
    
    # 设置定时任务,每3秒运行一次 check_realtime_quote 函数
    # 注意:run_interval 仅在交易模式下有效
    run_interval(context, check_realtime_quote, seconds=3)

def check_realtime_quote(context):
    # 获取行情快照
    snapshot = get_snapshot(g.security)
    
    # 校验数据是否获取成功
    if snapshot and g.security in snapshot:
        tick_data = snapshot[g.security]
        
        # 获取买一档位数据 (bid_grp Key 1)
        # 数据结构: {1: [价格, 量, 笔数], 2: [...], ...}
        bid_grp = tick_data.get('bid_grp', {})
        if 1 in bid_grp:
            bid_1_info = bid_grp[1]
            bid_1_price = bid_1_info[0] # 买一价
            bid_1_vol = bid_1_info[1]   # 买一量
        else:
            bid_1_price, bid_1_vol = 0, 0
            
        # 获取卖一档位数据 (offer_grp Key 1)
        # 数据结构: {1: [价格, 量, 笔数], 2: [...], ...}
        offer_grp = tick_data.get('offer_grp', {})
        if 1 in offer_grp:
            offer_1_info = offer_grp[1]
            offer_1_price = offer_1_info[0] # 卖一价
            offer_1_vol = offer_1_info[1]   # 卖一量
        else:
            offer_1_price, offer_1_vol = 0, 0
            
        # 打印日志
        log.info("股票: %s" % g.security)
        log.info("买一价: %.2f, 买一量: %d" % (bid_1_price, bid_1_vol))
        log.info("卖一价: %.2f, 卖一量: %d" % (offer_1_price, offer_1_vol))
        log.info("-" * 30)

def handle_data(context, data):
    pass

注意事项

  1. 适用环境get_snapshot 函数主要用于**交易(实盘/模拟盘)**环境。在回测环境中,该函数通常不支持或返回空数据(回测建议使用 get_history 获取K线数据,或使用Tick级回测模式下的 tick_data 回调)。
  2. 数据结构
    • bid_grpoffer_grp 是字典类型。
    • Key 是整数 15(或 10,取决于行情权限),代表档位。
    • Value 是列表,索引 0 是价格,索引 1 是数量。
  3. 盘前阶段:在 before_trading_start 或开盘集合竞价前调用时,可能获取到的价格或数量为0,需做好空值判断。

Q&A

Q: 回测模式下如何获取买一卖一数据?
A: 普通的日线或分钟线回测不支持获取盘口挂单数据。如果需要测试基于盘口的策略,必须选择Tick级别的回测频率,并在 tick_data(context, data) 回调函数中通过 data[security]['tick']['bid_grp'] 获取。

Q: get_snapshotget_gear_price 有什么区别?
A: get_snapshot 返回包含最新价、涨跌停、成交量、五档盘口等全量的快照信息;而 get_gear_price 仅返回五档(或十档)盘口的价格和委托量信息。如果只需要盘口数据,两者均可,但 get_snapshot 信息更全面。

Q: 为什么有时候获取到的 bid_grp 是空的?
A: 这通常发生在非交易时间、股票停牌、或者网络连接异常导致行情未推送时。代码中应始终包含 if snapshot 的非空判断以避免报错。