veighna-global / vnpy_binance

Binance trading gateway for VeighNa Evo
MIT License
236 stars 100 forks source link

订阅合约会一直重连,“行情Websocket API连接刷新” #11

Closed milkpuff closed 3 years ago

milkpuff commented 3 years ago

BinanceSpotGateway通道订阅合约后会一直断开重连,不断刷“行情Websocket API连接刷新”

怀疑是以下代码的问题

    def on_connected(self) -> None:
        """连接成功回报"""
        self.gateway.write_log("行情Websocket API连接刷新")
        for req in list(self.subscribed.values()):
            self.subscribe(req)

    def subscribe(self, req: SubscribeRequest) -> None:
        """订阅行情"""
        ...
        channels = []
        for ws_symbol in self.ticks.keys():
            channels.append(ws_symbol + "@ticker")
            channels.append(ws_symbol + "@depth5")

假如已经订阅了10个合约,当断线重连时, on_connected 中for req in list(self.subscribed.values()): 会发送10次订阅请求,但在subscribe中,每次都调用了 for ws_symbol in self.ticks.keys(),即每次都订阅了10个合约,所以 on_connected中无需调用10次,只需要运行1次即可。 将上代码改为

    def on_connected(self) -> None:
        """连接成功回报"""
        self.gateway.write_log("行情Websocket API连接刷新")
        for req in list(self.subscribed.values()):
            self.subscribe(req)
            return

就不会出现一直断线重连的问题。但是造成断线的根本原因尚不清楚。

附上测试订阅断线的代码:


import time
from vnpy.event import Event, EventEngine
from vnpy.trader.event import EVENT_TICK, EVENT_CONTRACT, EVENT_LOG
from vnpy.trader.constant import Exchange
from vnpy.trader.object import SubscribeRequest
from vnpy_binance import BinanceSpotGateway

if __name__ == '__main__':

    def process_event(event: Event):
        data = event.data
        print(data)

    setting = {
        "key": "xxx",
        "secret": "xxx",
        "服务器": "REAL",
        "代理地址": "xxx",
        "代理端口": 1080
    }

    event_engine = EventEngine()
    event_engine.register(EVENT_TICK, handler=process_event)
    event_engine.register(EVENT_CONTRACT, handler=process_event)
    event_engine.register(EVENT_LOG, handler=process_event)
    event_engine.start()
    gateway = BinanceSpotGateway(event_engine)
    gateway.connect(setting)
    time.sleep(5)

    for symbol in ['bnbusdt', 'ethusdt', 'btcusdt', 'linkusdt', 'bchusdt', 'eosusdt']:
        sub_req = SubscribeRequest(
            symbol=symbol,
            exchange=Exchange.BINANCE)
        gateway.subscribe(sub_req)
        print(f'subscribe, {symbol}')

    while True:
        time.sleep(3)

运行后一般没有行情推送,只有不停的 “行情Websocket API连接刷新”,如果开始时行情推送正常,等待断线重连时同样出现问题。

vnpy commented 3 years ago

已经修复,感谢反馈