新建NewBarGenerator类,继承BarGenerator类,然后修改 update_bar_minute_window 函数。写cta策略时,使用NewBarGenerator可以定义一些奇奇怪怪的K线,例如7分钟、9分钟、11分钟等。
代码如下:
`
from typing import Callable
from vnpy.trader.constant import Interval
from vnpy_ctastrategy import BarData, BarGenerator
class NewBarGenerator(BarGenerator):
def init(
self,
on_bar: Callable,
window: int = 0,
on_window_bar: Callable = None,
interval: Interval = Interval.MINUTE
):
super().init(on_bar, window, on_window_bar, interval)
def update_bar_minute_window(self, bar: BarData) -> None:
# If not inited, create window bar object
if not self.window_bar:
dt = bar.datetime.replace(second=0, microsecond=0)
self.window_bar = BarData(
symbol=bar.symbol,
exchange=bar.exchange,
datetime=dt,
gateway_name=bar.gateway_name,
open_price=bar.open_price,
high_price=bar.high_price,
low_price=bar.low_price
)
# Otherwise, update high/low price into window bar
else:
self.window_bar.high_price = max(
self.window_bar.high_price,
bar.high_price
)
self.window_bar.low_price = min(
self.window_bar.low_price,
bar.low_price
)
# Update close price/volume/turnover into window bar
self.window_bar.close_price = bar.close_price
self.window_bar.volume += bar.volume
self.window_bar.turnover += bar.turnover
self.window_bar.open_interest = bar.open_interest
# Check if window bar completed
self.interval_count += 1
if not self.interval_count % self.window:
self.interval_count = 0
self.on_window_bar(self.window_bar)
self.window_bar = None
`