问题描述
解决方案
这是一个基于PTrade API实现的策略,主要利用 on_trade_response 回调函数来实现接收到成交回报时立即打印详情的功能。
策略说明
- 核心函数:
on_trade_response(context, trade_list)。这是PTrade提供的交易主推回调接口,仅在交易模块(实盘或模拟盘)中可用。当账户有成交发生时,系统会立即调用该函数。 - 数据解析:
trade_list是一个列表,包含一个或多个成交记录(字典格式)。策略遍历该列表并打印关键字段,如股票代码、成交价格、成交数量、成交方向等。 - 触发测试:为了演示效果,在
handle_data中设置了一个简单的买入逻辑,以便产生交易触发回调。
策略代码
def initialize(context):
"""
初始化函数
"""
# 设置要操作的股票,这里以恒生电子为例
g.security = '600570.SS'
set_universe(g.security)
# 设置一个标志位,防止重复下单,仅用于演示
g.has_ordered = False
def handle_data(context, data):
"""
盘中运行函数
"""
# 仅在第一次运行时下单,用于触发成交回报
if not g.has_ordered:
log.info("尝试买入 %s 100股..." % g.security)
# 下单买入100股
order(g.security, 100)
g.has_ordered = True
def on_trade_response(context, trade_list):
"""
成交主推回调函数
当有成交发生时,该函数会被立即触发
"""
log.info("【接收到成交回报】")
# 遍历成交列表
for trade in trade_list:
# 获取成交详情字段
stock_code = trade.get('stock_code') # 股票代码
price = trade.get('business_price') # 成交价格
amount = trade.get('business_amount') # 成交数量
direction = trade.get('entrust_bs') # 成交方向 (1-买, 2-卖)
trade_time = trade.get('business_time') # 成交时间
business_id = trade.get('business_id') # 成交编号
# 转换方向描述
dir_str = "买入"
if str(direction) == '2':
dir_str = "卖出"
# 打印详细日志
log.info("--------------------------------")
log.info("时间: %s" % trade_time)
log.info("代码: %s" % stock_code)
log.info("方向: %s" % dir_str)
log.info("价格: %f" % float(price))
log.info("数量: %d" % int(amount))
log.info("成交编号: %s" % business_id)
log.info("--------------------------------")
注意事项
- 运行环境:
on_trade_response函数通常仅在交易模式(模拟盘或实盘)下生效。在普通的回测模式中,成交通常是基于K线撮合的,可能不会触发此实时主推接口(具体取决于券商服务器的回测引擎配置,但标准文档指出该函数仅在交易模块可用)。 - 数据类型:返回的
trade_list中的字段值可能是字符串或数字,代码中使用了float()和int()进行转换以确保格式化输出正确。 - Python版本:代码采用了兼容 Python 3.5 的字符串格式化方式(
%s),未使用 f-string。
Q&A
Q: on_trade_response 和 get_trades 有什么区别?
A: on_trade_response 是事件驱动的,只有在成交发生的瞬间会被系统主动调用,实时性最高,适合做高频策略或实时风控;get_trades 是主动查询接口,需要你在 handle_data 或定时任务中主动调用来获取当天的成交记录。
Q: 为什么我在回测中没有看到 on_trade_response 的日志?
A: 根据PTrade API文档,on_trade_response 仅在交易模块(实盘/模拟交易)可用。回测引擎通常是基于历史数据的静态撮合,不具备实时推送机制。如果在回测中需要查看成交,请查看回测结果详情或在 handle_data 中使用 get_trades() 查询。
Q: trade_list 中的 entrust_bs 字段返回值代表什么?
A: entrust_bs 代表成交方向。通常情况下,'1' 代表买入,'2' 代表卖出。具体定义可参考PTrade的数据字典。