问题描述
只是想通过一些简单的例子来了解asyncio
:
import asyncio
from binance import Asyncclient,BinanceSocketManager
async def main():
# initialise the client
client = await Asyncclient.create()
bsm = BinanceSocketManager(client)
# create listener using async with
# this will exit and close the connection after 5 messages
async with bsm.Trade_socket('BTCUSDT') as ts:
for _ in range(5):
res = await ts.recv()
print(f'{_} recv {res}')
print('Hello')
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出:
0 recv {'e': 'Trade','E': 1620125896291,'s': 'BTCUSDT','t': 807604863,'p': '56336.87000000','q': '0.00044900','b': 5772457377,'a': 5772457449,'T': 1620125896291,'m': True,'M': True}
1 recv {'e': 'Trade','E': 1620125896345,'t': 807604864,'p': '56336.88000000','q': '0.00099900','b': 5772457451,'a': 5772457310,'T': 1620125896345,'m': False,'M': True}
2 recv {'e': 'Trade','E': 1620125896556,'t': 807604865,'q': '0.01220300','a': 5772457460,'T': 1620125896555,'M': True}
3 recv {'e': 'Trade','E': 1620125896579,'t': 807604866,'q': '0.01037100','b': 5772457461,'T': 1620125896579,'M': True}
4 recv {'e': 'Trade','E': 1620125896583,'t': 807604867,'q': '0.00091100','b': 5772457462,'T': 1620125896583,'M': True}
Hello
每当收到交易事件时,以 0、1、2、3 和 4 开头的行几乎立即出现。但是,在打印 Hello
之前有一段很长的暂停(大约 1-5 秒,每次运行都会有所不同)。暂停的原因是什么?
解决方法
这将在 5 条消息后退出并关闭连接
对于范围内的 _(5):
将 5 改为 > 数字。
如果我的理解对您的问题是正确的。