简体   繁体   English

如何引用 websocket 数据数组 python-binance

[英]how to reference websocket data array python-binance

I have a script that receives this binance json data array via websocket and prints to console via callback function:我有一个脚本,它通过 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"}]}

I need to be able to reference the BNB balance ["B"]["f"] in the callback function.我需要能够在回调函数中引用 BNB 余额 ["B"]["f"]。 I have tried code like this but does not work.我试过这样的代码,但不起作用。

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

Printing the whole message works fine so I figured I was referencing the data array wrong.打印整个消息工作正常,所以我想我引用的数据数组是错误的。 How to fix?怎么修? Thanks谢谢

You just received a string that contains a JSON structure.您刚刚收到一个包含 JSON 结构的字符串。 Its possible to convert this to a python dict.可以将其转换为 python 字典。

You can use every JSON lib for that, the fastest is ujson:您可以为此使用每个 JSON 库,最快的是 ujson:

import ujson as json

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

A library that does this for you and forms well named dicts is unicorn_fy: https://github.com/oliver-zehentleitner/unicorn_fy为您执行此操作并形成命名良好的字典的库是 unicorn_fy: 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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM