【发布时间】:2021-08-07 15:06:59
【问题描述】:
Binance API 和python-binance 提供async 功能以实现Async basics for Binance 中讨论的非阻塞执行。
我正在使用BinanceSocketManager 通过 websocket 监听(异步非阻塞)实时数据。
在网络间歇性连接丢失等情况下,我希望在我的项目中添加自动重新连接功能。但我似乎无法找到BinanceSocketManager 的任何信息。我只能找到一个使用ThreadedWebsocketManager 的guide,但它不是异步实现。
有人知道如何实现 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