【问题标题】:How to detect BinanceSocketManager websocket disconnect in Python?如何在 Python 中检测 BinanceSocketManager websocket 断开连接?
【发布时间】:2021-08-07 15:06:59
【问题描述】:

Binance API 和python-binance 提供async 功能以实现Async basics for Binance 中讨论的非阻塞执行。

我正在使用BinanceSocketManager 通过 websocket 监听(异步非阻塞)实时数据。

在网络间歇性连接丢失等情况下,我希望在我的项目中添加自动重新连接功能。但我似乎无法找到BinanceSocketManager 的任何信息。我只能找到一个使用ThreadedWebsocketManagerguide,但它不是异步实现。

有人知道如何实现 Binance websocket 断开检测和自动重新连接机制吗?

这是我目前所拥有的一些代码:

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    await kline_listener(client)

async def kline_listener(client):
    bm = BinanceSocketManager(client)
    async with bm.kline_socket(symbol='BTCUSDT') as stream:
        while True:
            res = await stream.recv()
            print(res)
    # a way detect websocket error/disconnect, callback 'disconnect_callback'

async def disconnect_callback():
    await client.close_connection()
    await main()  # restart client and kline socket

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

【问题讨论】:

    标签: python websocket python-asyncio binance


    【解决方案1】:

    如果其他人正在查看此内容,您应该查看 BinanceAPIException。代码可能看起来像这样:

    from binance import AsyncClient, BinanceSocketManager
    from binance.exceptions import BinanceAPIException
    
    async def main():
    
        client = await AsyncClient.create()
        bm = BinanceSocketManager(client, user_timeout=60)
    
        # start any sockets here, i.e a trade socket
        kline_candles = bm.kline_socket('BNBUSDT', interval=client.KLINE_INTERVAL_1MINUTE)
    
        # start receiving messages
        try:
            status = await client.get_system_status()
            print(status['msg'])
    
            async with kline_candles as stream:
                for _ in range(5):
                    res = await stream.recv()  # create/await response
                    await process_message(msg=res, client=client)  # process message
                
        except BinanceAPIException as e:
            print(e)
            await disconnect_callback(client=client)
    
    async def disconnect_callback(client):
        await client.close_connection()  # close connection
        time.sleep(60)  # wait a minute before restarting
        await main()  # restart client and kline socket
    
    async def process_message(msg, client):
        if msg['e'] == 'error':
            await disconnect_callback(client=client)
    
            print('ERROR OCCURED')
            
        else:
            candle = msg['k']  # get only the candle info within the general dict
    
            start_time = datetime.utcfromtimestamp(candle['t']/1000).strftime('%Y-%m-%d %H:%M:%S')
            close_time = datetime.utcfromtimestamp(candle['T']/1000).strftime('%Y-%m-%d %H:%M:%S')
    
            print(f'__ start: {start_time}, close: {close_time}')
            print(msg)
    
    if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
    

    尚未测试断开连接,但我认为这会起作用。如果有人有任何其他说明,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      相关资源
      最近更新 更多