3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 ptrade 量化交易平台中,进行高频交易或盘口分析时,获取买一、卖一档位的具体排队委托明细(即 Level-2 委托队列)是非常核心的需求。通过 tick_data 回调函数,我们可以实时获取到这些高精度数据。
在 tick_data(context, data) 回调中,data 参数是一个字典。对于订阅的股票,其 tick 数据对应的 DataFrame 包含 bid_grp(买档位)和 offer_grp(卖档位)字段。
bid_grp / offer_grp 的结构:[委托价格, 委托数量, 委托笔数]。{1: 价格, 2: 数量, 3: 笔数, 4: {排队序号: 委托量, ...}}tick_data 中提取买一/卖一排队明细以下是完整的策略代码示例,展示了如何在 tick_data 中安全地解析并打印买一和卖一的排队委托明细:
def initialize(context):
# 设置操作的股票池(需要开通 Level-2 行情权限)
g.security = '600570.SS'
set_universe(g.security)
def tick_data(context, data):
security = g.security
if security not in data:
return
# 获取当前 tick 的数据
tick_df = data[security]['tick']
if tick_df is None or tick_df.empty:
return
try:
# 提取买档和卖档信息
# 注意:由于数据传输格式,可能需要使用 eval() 进行解析
bid_grp = eval(tick_df['bid_grp'][0]) if isinstance(tick_df['bid_grp'][0], str) else tick_df['bid_grp'][0]
offer_grp = eval(tick_df['offer_grp'][0]) if isinstance(tick_df['offer_grp'][0], str) else tick_df['offer_grp'][0]
# 获取买一档位数据 [价格, 总委托量, 总笔数, 委托队列]
bid_one = bid_grp.get(1)
if bid_one and len(bid_one) > 3:
bid_one_price = bid_one[0]
bid_one_vol = bid_one[1]
bid_one_count = bid_one[2]
bid_one_queue = bid_one[3] # 委托队列字典 {1: 数量, 2: 数量, ...}
log.info(f"【买一】价格: {bid_one_price}, 总量: {bid_one_vol}, 总笔数: {bid_one_count}")
log.info(f"【买一排队明细】: {bid_one_queue}")
# 获取卖一档位数据
offer_one = offer_grp.get(1)
if offer_one and len(offer_one) > 3:
offer_one_price = offer_one[0]
offer_one_vol = offer_one[1]
offer_one_count = offer_one[2]
offer_one_queue = offer_one[3] # 委托队列字典
log.info(f"【卖一】价格: {offer_one_price}, 总量: {offer_one_vol}, 总笔数: {offer_one_count}")
log.info(f"【卖一排队明细】: {offer_one_queue}")
except Exception as e:
log.error(f"解析 Level-2 委托队列出现异常: {e}")
def handle_data(context, data):
pass
bid_grp 和 offer_grp 中将不包含第四项(委托队列字典),且委托笔数可能返回 0。data[security]['tick'] 中获取的 bid_grp 有时是字符串格式的字典,因此在代码中建议使用 isinstance 判断并配合 eval() 或 json.loads() 进行安全转换。0.0 或为空,解析时需做好空值保护。