Это потому, что вы должны читать полученные данные после каждой отправки.
#!/usr/bin/env python3
import asyncio
import websockets
import json
var = []
async def test():
async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
response = await websocket.recv()
print(response)
await websocket.send("ping")
response = await websocket.recv()
print(response)
var.append(response)
await websocket.send(json.dumps({"op": "subscribe", "args": "test"}))
response = await websocket.recv()
print(response)
asyncio.get_event_loop().run_until_complete(test())
print(var)
Вывод:
{"info":"Welcome to the BitMEX Realtime API.","version":"2019-02-12T19:21:05.000Z","timestamp":"2019-02-17T14:38:32.696Z","docs":"https://www.bitmex.com/app/wsAPI","limit":{"remaining":37}}
pong
{"status":400,"error":"Unknown table: test","meta":{},"request":{"op":"subscribe","args":"test"}}
['pong']
Редактировать - код с обработкой падающих веб-сокетов и несколькими данными:
#!/usr/bin/env python3
import asyncio
import websockets
import json
total = 0
async def test():
async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
response = await websocket.recv()
print(response)
await websocket.send(json.dumps({"op": "subscribe", "args": "trade:TRXH19"}))
response = await websocket.recv()
#resp = await websocket.recv()
#print(json.loads(resp))
global total
while True:
resp = await websocket.recv()
print(resp)
for jj in json.loads(resp)["data"]:
size = jj["size"]
side = jj["side"]
coin = jj["symbol"]
if side == "Buy":
total += size
else:
total -= size
print(coin)
print(size)
print(side)
print("Totale = ", total)
while True:
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(test())
except Exception as e:
print(e)
loop.close()
#finally:
print(total)
print("Ciclo Finito!!!!")