首页 > 解决方案 > 如何引用 websocket 数据数组 python-binance

问题描述

我有一个脚本,它通过 websocket 接收这个 binance json 数据数组并通过回调函数打印到控制台:

{"e":"outboundAccountPosition","E":1600502318390,"u":1600502318389,"B":[{"a":"BTC","f":"0.00000000","l":"0.00000000"},{"a":"BNB","f":"0.00000000","l":"0.00000000"},{"a":"XTZ","f":"0.00000000","l":"0.00000000"}]}

我需要能够在回调函数中引用 BNB 余额 ["B"]["f"]。我试过这样的代码但不起作用。

def callback_function(msg)
    if msg['e'] == 'outboundAccountPosition':
    print(msg["B"]["f"])

打印整条消息效果很好,所以我认为我引用了数据数组错误。怎么修?谢谢

标签: pythonarraysjsonpython-3.xbinance

解决方案


您刚刚收到一个包含 JSON 结构的字符串。可以将其转换为 python dict。

您可以为此使用每个 JSON 库,最快的是 ujson:

import ujson as json

stream_data_dict = json.loads(stream_data_json)
print(stream_data_dict["B"]["f"])

unicorn_fy 是一个为您执行此操作并形成名称良好的 dicts 的库:https ://github.com/oliver-zehentleitner/unicorn_fy

from unicorn_fy.unicorn_fy import UnicornFy

received_stream_data_json = {"stream": "btcusdt@trade",
                             "data": {"e": "trade",
                                      "E": 1556876873656,
                                      "s": "BTCUSDT",
                                      "t": 117727701,
                                      "p": "5786.76000000",
                                      "q": "0.03200500",
                                      "b": 341831847,
                                      "a": 341831876,
                                      "T": 1556876873648,
                                      "m": True,
                                      "M": True}}

unicorn_fied_stream_data = UnicornFy.binance_com_websocket(received_stream_data_json)
print(unicorn_fied_stream_data)
>>>
{'stream_type': 'btcusdt@trade', 'event_type': 'trade', 'event_time': 1556876873656, 'symbol': 'BTCUSDT', 'trade_id': 117727701, 'price': '5786.76000000', 'quantity': '0.03200500', 'buyer_order_id': 341831847, 'seller_order_id': 341831876, 'trade_time': 1556876873648, 'is_market_maker': True, 'ignore': True, 'unicorn_fied': ['binance', '0.1.0']}

推荐阅读