背景
由于大家按分钟整点下单,造成分钟整点下单高峰,造成抢单、下单成本变高,所以想改造一下VNPY,每个bar 提前5秒钟形成,错开下单高峰。
实现
修改BarGenerator
- 每个分钟bar在tick时间秒数字 每分钟第一次大于55时刻,触发 on_bar
- 记录一个标志 self.minute_change_flag 来保证每分钟只有第一次大于等于55才触发
- flag标志位默认是True
- 当tick时间秒 大于等于 55时, 触发on_bar, 并且 flag改为 False
- 当tick时间进入下一分钟时,flag重置为 True
def update_tick(self, tick: TickData) -> None:
"""
Update new tick data into generator.
"""
new_minute = False
# Filter tick data with 0 last price
if not tick.last_price:
return
# Filter tick data with older timestamp
if self.last_tick and tick.datetime < self.last_tick.datetime:
# 日盘开盘区间,郑商所会把昨天收盘时间错改成今天收盘时间,导致盘前启动开盘后bar无法更新
# tick.datetime: 2021-06-22 09:00:00+08:00
# last_tick.datetime: 2021-06-22 22:59:59+08:00
if self.last_tick.datetime > datetime.now(tz=local_zone):
pass
else:
return
if not self.bar:
new_minute = True
# 逻辑开始 #####################################################
elif tick.datetime.second >= 55 and self.minute_change_flag:
self.bar.datetime = self.bar.datetime.replace(
second=0, microsecond=0
)
print(tick.datetime)
self.minute_change_flag = False
self.on_bar(self.bar)
new_minute = True
elif (self.bar.datetime.minute != tick.datetime.minute) or \
(self.bar.datetime.hour != tick.datetime.hour):
self.minute_change_flag = True
# 结束 #####################################################
if new_minute:
self.bar = BarData(
symbol=tick.symbol,
exchange=tick.exchange,
interval=Interval.MINUTE,
datetime=tick.datetime,
gateway_name=tick.gateway_name,
open_price=tick.last_price,
high_price=tick.last_price,
low_price=tick.last_price,
close_price=tick.last_price,
open_interest=tick.open_interest
)
else:
self.bar.high_price = max(self.bar.high_price, tick.last_price)
if tick.high_price > self.last_tick.high_price:
self.bar.high_price = max(self.bar.high_price, tick.high_price)
self.bar.low_price = min(self.bar.low_price, tick.last_price)
if tick.low_price < self.last_tick.low_price:
self.bar.low_price = min(self.bar.low_price, tick.low_price)
self.bar.close_price = tick.last_price
self.bar.open_interest = tick.open_interest
self.bar.datetime = tick.datetime
if self.last_tick:
volume_change = tick.volume - self.last_tick.volume
self.bar.volume += max(volume_change, 0)
self.last_tick = tick