问题描述
/
解决方案
在 ptrade 量化平台中,get_price 接口主要用于获取历史 K 线数据,其设计机制决定了返回的数据不包括当天数据。如果您在盘中需要获取实时的行情信息(如最新价、买卖盘口、涨跌停价等),需要使用专门的实时行情接口。
以下是获取实时行情的几种主要方法:
1. 使用 get_snapshot 获取行情快照(最常用)
get_snapshot(security) 是获取实时行情最常用的接口,它返回一个包含最新成交价、开盘价、最高价、最低价、买卖档位、涨跌停价格等丰富信息的字典。
代码示例:
def initialize(context):
g.security = '600570.SS'
set_universe(g.security)
def handle_data(context, data):
# 获取实时行情快照
snapshot = get_snapshot(g.security)
if snapshot:
# 获取最新价
last_price = snapshot[g.security]['last_px']
# 获取涨停价
up_limit = snapshot[g.security]['up_px']
# 获取买一价
bid1_price = snapshot[g.security]['bid_grp'][1][0]
log.info(f"最新价: {last_price}, 涨停价: {up_limit}, 买一价: {bid1_price}")
2. 使用 get_gear_price 获取档位行情
如果您只需要获取买卖盘口的档位数据(如买一到买五,卖一到卖五的价格和委托量),可以使用 get_gear_price(sids) 接口。
代码示例:
def handle_data(context, data):
gear_price = get_gear_price('600570.SS')
if gear_price:
# 获取买一档数据:[价格, 委托量, 委托笔数]
bid1_info = gear_price['bid_grp'].get(1)
if bid1_info:
log.info(f"买一价: {bid1_info[0]}, 买一量: {bid1_info[1]}")
3. 使用 get_history 获取包含当天的 K 线数据
如果您确实需要当天的 K 线数据(例如当天的分钟线,或者盘中计算当天的均线),可以使用 get_history 接口,并将 include 参数设置为 True。
代码示例:
def handle_data(context, data):
# 获取过去5分钟的分钟K线(包含当前未走完的这一分钟)
hist_min = get_history(5, frequency='1m', field=['close', 'volume'], security_list='600570.SS', include=True)
log.info(hist_min)
注意:在日线级别策略中,盘中调用 get_history(..., frequency='1d', include=True) 获取的当天日线数据是截至当前时刻的未完成 K 线。
4. 在 tick_data 中直接从 data 获取(仅限 Tick 级别策略)
如果您编写的是 Tick 级别策略(使用 tick_data 函数),可以直接从传入的 data 参数中获取当前 Tick 的实时数据。
代码示例:
def tick_data(context, data):
security = '600570.SS'
if security in data:
# 获取当前 tick 的最新价
current_price = data[security]['tick']['last_px']
log.info(f"Tick最新价: {current_price}")
总结
- 查历史K线:用
get_price或get_history。 - 查盘中最新价/涨跌停/盘口:用
get_snapshot。 - 查纯盘口档位:用
get_gear_price。