订阅网络套接字后如何解析数据

时间:2019-11-27 03:09:05

标签: python sockets websocket

这是我用来订阅WebSocket的代码。

for i in range(3):
    try:
        ws = create_connection('wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD')
    except Exception as error:
        print('Error')
        time.sleep(3)
    else:
        break

while True:
    try:
        result = ws.recv()
        result = json.loads(result)
        print(f"{result}")
    except Exception as error:
        print("Error")
        time.sleep(3)

ws.close()

这里有一个我得到回报的例子

{'success': True, 'subscribe': 'trade:XBTUSD', 'request': {'op': 'subscribe', 'args': 'trade:XBTUSD'}}        
{'table': 'trade', 'action': 'partial', 'keys': [], 'types': {'timestamp': 'timestamp', 'symbol': 'symbol', 'side': 'symbol', 'size': 'long', 'price': 'float', 'tickDirection': 'symbol', 'trdMatchID': 'guid', 'grossValue': 'long', 'homeNotional': 'float', 'foreignNotional': 'float'}, 'foreignKeys': {'symbol': 'instrument', 'side': 'side'}, 'attributes': {'timestamp': 'sorted', 'symbol': 'grouped'}, 'filter': {'symbol': 'XBTUSD'}, 'data': [{'timestamp': '2019-11-27T03:04:30.081Z', 'symbol': 'XBTUSD', 'side': 'Buy', 'size': 1000, 'price': 7149, 'tickDirection': 'ZeroPlusTick', 'trdMatchID': 'e235b829-dde5-1eda-dc51-d66de2fbd0e7', 'grossValue': 13988000, 
'homeNotional': 0.13988, 'foreignNotional': 1000}]}

如果我正在使用rest api,并且这是一次请求,那么我拿出例如“ side”和“ size”值就不会有问题,但是我对在im时如何使用订阅进行操作有点困惑不断从websocket获取新数据。谢谢你的帮助。

0 个答案:

没有答案