问题
如何将两个或三个异步websocket结果的结果合并,由asyncio
中。
output_dict
>>> {"XRP-BTC" : 0.00023, "ETH-BTC" : 0.04, "LTC-BTC" : 0.001}
。
代码示例
import asyncio
import websockets
import ast
import time
import json
# websocket address for the cryptocurrency exchange OKEx
url = "wss://ws.okex.com:8443/ws/v5/public"
# function to download orderbook data, using websocket asynchronously
async def ws_orderbook5(crypto_pair):
while True:
try:
async with websockets.connect(url) as ws:
channels = [{'channel': 'books5', 'instId': f'{crypto_pair}'}]
sub_param = {"op": "subscribe", "args": channels}
sub_str = json.dumps(sub_param)
await ws.send(sub_str)
print(f"send: {sub_str}")
res = await asyncio.wait_for(ws.recv(), timeout=25)
while True:
try:
res = await asyncio.wait_for(ws.recv(), timeout=25)
res = ast.literal_eval(res)
lowest_ask_price = res['data'][0]['asks'][0][0]
print(f"{crypto-pair} : Lowest ask price is {lowest_ask_price}")
time.sleep(1)
except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e:
try:
await ws.send('ping')
print("")
print("ping")
res = await ws.recv()
continue
except Exception as e:
print("Failure due to an unknown error. Stopped working")
break
except Exception as e:
print("Failure due to an unknown error. Try working again")
continue
res
是从OKEx websocket下载的数据,当参数crypto_pair
= 'XRP-BTC‘.时,如下所示
{'arg': {'channel': 'books5', 'instId': 'XRP-BTC'},
'data': [{'asks': [['0.00002585', '4514.84', '0', '2'],
['0.00002586', '5845.946', '0', '5'],
['0.00002587', '30306.155', '0', '5'],
['0.00002588', '9974.105', '0', '7'],
['0.00002589', '3104.84', '0', '5']],
'bids': [['0.00002582', '3988', '0', '2'],
['0.00002581', '23349.817', '0', '4'],
['0.0000258', '18735.565', '0', '8'],
['0.00002579', '6429.196', '0', '6'],
['0.00002578', '3492.795', '0', '5']],
'instId': 'XRP-BTC',
'ts': '1622805157064'}]
}
因此,在控制台上打印的
。
XRP-BTC : The most favorable ask price is 0.00023
output_dict
>>> {"XRP-BTC" : 0.00023, "ETH-BTC" : 0.04, "LTC-BTC" : 0.001}
发布于 2021-06-04 19:39:34
您需要将您的协同线封装在一个任务中,每个货币对对应一个。
loop = asyncio.get_event_loop()
loop.create_task(ws_orderbook5(pair1))
loop.create_task(ws_orderbook5(pair2))
loop.create_task(ws_orderbook5(pair3))
loop.run_forever()
要合并结果,可以将ws.recv()的结果添加到asyncio.Queue
对象中。
https://stackoverflow.com/questions/67837181
复制相似问题