[英]how to reference websocket data array 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"])
打印整個消息工作正常,所以我想我引用的數據數組是錯誤的。 怎么修? 謝謝
您剛剛收到一個包含 JSON 結構的字符串。 可以將其轉換為 python 字典。
您可以為此使用每個 JSON 庫,最快的是 ujson:
import ujson as json
stream_data_dict = json.loads(stream_data_json)
print(stream_data_dict["B"]["f"])
為您執行此操作並形成命名良好的字典的庫是 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.