我正试图向服务器发送消息以获得答案。
我试着从网站上使用官方的websocket,但是我不理解它们,或者不能让它们按我的意愿工作,所以我尝试构建它。
import asyncio
import websockets
async def test():
async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
await websocket.send("ping")
#OR await websocket.send({"op": "subscribe", "args": [<SubscriptionTopic>]})
response = await websocket.recv()
print(response)
asyncio.get_event_loop().run_until_complete(test())我收到连接,但我没有收到“乒乓”的回答“平”,也没有“好你订阅了这个主题”,因为我收到的命令时,在回声网站。
#!/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(json.dumps({"op": "subscribe", "args": "trade:TRXH19"}))
response = await websocket.recv()
resp = await websocket.recv()
print(json.loads(resp))
sum=0
while True:
resp = await websocket.recv()
jj = json.loads(resp)["data"][0]
var.append(jj)
size = jj["size"]
side = jj["side"]
coin = jj["symbol"]
if side=="Buy":
sum+=size
else:
sum-=size
print(coin)
print(size)
print(side)
print("Totale = ", sum )
while True:
asyncio.get_event_loop().run_until_complete(test())
print(var)
print("Ciclo Finito!!!!")发布于 2019-02-17 12:18:35
这是因为你必须在每次发送后读取接收到的数据。
#!/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']编辑-处理websockets和多个数据的代码:
#!/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!!!!")https://stackoverflow.com/questions/54702415
复制相似问题