VeighNa量化社区
你的开源社区量化交易平台
Member
avatar
加入于:
帖子: 10
声望: 0

就差最后一步可以交易。救助~~~!

可以正常接收tick,on_tick里能正常print
bg里可以正常运转,bg里可以print,
on_bar里无法pirnt,不知道数据合成后,为什么无法正常返回
`
from vnpy.app.cta_strategy import (
CtaTemplate,
StopOrder,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager,
)

from vnpy.app.cta_strategy.base import StopOrderStatus
from vnpy.trader.constant import Interval
from vnpy.trader.object import BarData, TickData

class s30Strategy(CtaTemplate):
""""""
author = "amber"

# 策略参数
fixedSize = 100
initDays = 0

# 策略变量
posPrice = 0  # 持仓价格
pos = 0  # 持仓数量

def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
    """"""
    super().__init__(cta_engine, strategy_name, vt_symbol, setting)

    self.bg30=newBarGenerator(self.on_30sbar)

    self.vt_orderids = []
    self.am = ArrayManager(size=30)

def on_init(self):
    """
    Callback when strategy is inited.
    """
    self.write_log("策略初始化")
    self.load_bar(30)#,use_database=True

def on_start(self):
    """
    Callback when strategy is started.
    """
    self.write_log("策略启动")

def on_stop(self):
    """
    Callback when strategy is stopped.
    """
    self.write_log("策略停止")


def on_tick(self, tick: TickData):
    """
    Callback of new tick data update.
    """
    self.bg30.update_tick(tick)


def on_30sbar(self, bar: BarData):
    """
    Callback of new tick data update.
    """

    am = self.am
    am.update_bar(bar)
    print(bar)

    if not am.inited:
        return


    self.put_event()

def on_order(self, order: OrderData):
    """
    Callback of new order data update.
    """
    self.put_event()

def on_trade(self, trade: TradeData):
    """
    Callback of new trade data update.
    """
    print(trade.datetime,trade.direction,trade.price)
    # 删掉已经下单的成功的ID
    td_orderid = 'BACKTESTING.'+trade.orderid
    if td_orderid in self.vt_orderids:
        self.vt_orderids.remove(td_orderid)
    self.put_event()


class newBarGenerator(BarGenerator):#继承
"""
30秒tick合成
"""

def __init__(self,
    on_bar: Callable,
    window: int = 0,
    on_window_bar: Callable = None,
    interval: Interval = Interval.TICK
):

    super().__init__(on_bar,window,on_window_bar,interval)

    self.bar: BarData = None
    self.on_bar: Callable = on_bar

    self.interval: Interval = interval
    self.interval_count: int = 0

    self.hour_bar: BarData = None

    self.window: int = window
    self.window_bar: BarData = None
    self.on_window_bar: Callable = on_window_bar

    self.last_tick: TickData = None
    self.last_bar: BarData = None

def update_tick(self, tick: TickData) -> None:
    """收到新的tick
    Update new tick data into generator.
    """
    new_minute = False

    # Filter tick data with 0 last price
    #print(self.last_tick)

    if not tick.last_price:#
        return

    try:#self.last_tick是否存在的代理变量
        if len(self.last_tick)>0:
            lt_exc=True
    except:
            lt_exc=False
    # Filter tick data with older timestamp

    if lt_exc and tick.datetime < self.last_tick.datetime:  #
        return

    if (lt_exc and (tick.datetime.second ==30) & (self.last_tick.datetime.second ==29)) \
            or (lt_exc and (tick.datetime.second ==0) & (self.last_tick.datetime.second ==59)):
        self.bar.datetime = self.bar.datetime.replace(second=0, microsecond=0)
        self.on_bar(self.bar)
        new_minute = True

    elif not self.bar:
        new_minute = True

    if new_minute:
        self.bar = BarData(
            symbol=tick.symbol,
            exchange=tick.exchange,
            interval=Interval.TICK,
            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:#不是新的bar,继续和旧的比较
        self.bar.high_price = max(self.bar.high_price, tick.last_price)
        if tick.last_price > self.last_tick.last_price:
            self.bar.high_price = max(self.bar.high_price, tick.last_price)

        self.bar.low_price = min(self.bar.low_price, tick.last_price)
        if tick.last_price < self.last_tick.last_price:
            self.bar.low_price = min(self.bar.low_price, tick.last_price)

        self.bar.close_price = tick.last_price
        self.bar.open_interest = tick.open_interest
        self.bar.datetime = tick.datetime

    if lt_exc:
        volume_change = tick.volume - self.last_tick.volume
        self.bar.volume += max(volume_change, 0)

    self.last_tick = tick

`

Member
avatar
加入于:
帖子: 337
声望: 28

要在初始化的时候传入Tick数据合成K线来做初始化,应该用load_tick加载历史数据。因为load_bar初始化时会传入bar而不是Tick。

Member
avatar
加入于:
帖子: 10
声望: 0

改成了
def on_init(self):
"""
Callback when strategy is inited.
"""
self.write_log("策略初始化")
self.load_tick(2)

还是原来的问题。能初始化——启动,on_tick能收到,bg能收到。
但在on_bar里收不到数据

Member
avatar
加入于:
帖子: 5078
声望: 306

那就是合成有问题,在bg里打印排查修改应该就行了吧

Member
avatar
加入于:
帖子: 10
声望: 0

好的。感谢两位,
回测生效的地方,在实盘中却不行,可能是因为回测我自己导入的csv

        try:#self.last_tick是否存在的代理变量
            if len(self.last_tick)>0:
                lt_exc=True
        except:
                lt_exc=False

lt_exc会一直为False,
换回 if self.last_tick 就好了。

© 2015-2022 上海韦纳软件科技有限公司
备案服务号:沪ICP备18006526号

沪公网安备 31011502017034号

【用户协议】
【隐私政策】
【免责条款】