首页 > 解决方案 > 订阅 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}]}

如果我使用的是其余 api 并且这是一次性请求,我可以毫无问题地提取例如“side”和“size”值,但是当我不断获得新的订阅时,我对如何通过订阅来做到这一点有点困惑来自 websocket 的数据。谢谢你的帮助。

标签: pythonsocketswebsocket

解决方案


推荐阅读