
等级: 专业版
- 注册:
- 2021-10-19
- 曾用名:
|
from PythonApi import *
from collections import deque
class OrderFlowPyramid:
def __init__(self):
self.buy_vol = 0
self.sell_vol = 0
self.delta = 0
self.lookback = 50 # 订单流分析周期
self.threshold = 0.6 # 信号阈值
self.tick_buffer = {
'prices': deque(maxlen=self.lookback),
'volumes': deque(maxlen=self.lookback),
'directions': deque(maxlen=self.lookback)
}
def init(self, context):
"""策略初始化"""
# 设置基准合约为螺纹钢主力连续
context.base_book_id = "SQRB00"
# 设置回测参数
context.start_date = "20230101"
context.end_date = "20231231"
context.initial_cash = 1000000
context.open_slippage = 1 # 开仓滑点1跳
context.close_slippage = 1 # 平仓滑点1跳
def handle_bar(self, context):
"""Bar事件驱动处理"""
# 获取最新tick数据
latest_tick = get_dynainf(context.base_book_id, 7) # 7表示最新价
# 订单方向判断
bid_price = get_dynainf(context.base_book_id, 28) # 买一价
ask_price = get_dynainf(context.base_book_id, 34) # 卖一价
direction = self._infer_direction(latest_tick, bid_price, ask_price)
# 更新订单流缓存
self._update_order_flow(latest_tick, get_dynainf(context.base_book_id, 8), direction) # 8表示成交量
# 计算信号指标
imbalance = self._calculate_imbalance()
delta_profile = self.delta / (abs(self.delta) + 1e-6)
# 生成交易信号
if imbalance > self.threshold and delta_profile > 0.5:
self._send_order(context, 1) # 强烈买入信号
elif imbalance < -self.threshold and delta_profile < -0.5:
self._send_order(context, -1) # 强烈卖出信号
def _infer_direction(self, price, bid, ask):
"""买卖方向推断"""
if price >= ask:
return 'S'
elif price <= bid:
return 'B'
return 'N'
def _update_order_flow(self, price, volume, direction):
"""更新订单流数据"""
self.tick_buffer['prices'].append(price)
self.tick_buffer['volumes'].append(volume)
self.tick_buffer['directions'].append(direction)
# 更新累计Delta
if direction == 'B':
self.delta += volume
elif direction == 'S':
self.delta -= volume
def _calculate_imbalance(self):
"""计算订单不平衡度"""
buys = sum(v for d, v in zip(self.tick_buffer['directions'], self.tick_buffer['volumes']) if d == 'B')
sells = sum(v for d, v in zip(self.tick_buffer['directions'], self.tick_buffer['volumes']) if d == 'S')
return (buys - sells) / (buys + sells + 1e-6)
def _send_order(self, context, signal):
"""执行订单"""
position = get_portfolio(context.base_book_id, 2, calc=True)
if signal == 1 and position.buy_quantity == 0:
# 市价开多
buy_open(context.base_book_id, "Market", 0, 1,serial_id = 1)
elif signal == -1 and position.sell_quantity == 0:
# 市价开空
sell_open(context.base_book_id, "Market", 0, 1,serial_id = 2)
def exit(self, context):
"""策略退出清理"""
# 平掉所有持仓
close_all()
# 禁用回测报告自动弹出
test_report_none()
> 开始编译 <MyPython25> ......
>
> 编译错误 : 语法错误
> 错误信息 : handle_bar(context)方法为必须实现的函数。
|
|