首页 > 解决方案 > How to read json format from binance api using pandas?

问题描述

I want to get live prices of concurrency from rest api of binance.

I am using:

def inCoin(coin):
    url = 'https://api.binance.com/api/v3/ticker/price?symbol='+coin+'USDT'
    df = pd.read_json(url)
    df.columns = ["symbol","price"]
    return df

It gives the following error when this function is called:

    Traceback (most recent call last):
  File "ee2.py", line 201, in <module>
    aa = inCoin('BTC')
  File "ee2.py", line 145, in inCoin
    df = pd.read_json(url, orient='index')
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/io/json/json.py", line 422, in read_json
    result = json_reader.read()
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/io/json/json.py", line 529, in read
    obj = self._get_object_parser(self.data)
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/io/json/json.py", line 546, in _get_object_parser
    obj = FrameParser(json, **kwargs).parse()
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/io/json/json.py", line 638, in parse
    self._parse_no_numpy()
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/io/json/json.py", line 861, in _parse_no_numpy
    loads(json, precise_float=self.precise_float), dtype=None).T
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 348, in __init__
    mgr = self._init_dict(data, index, columns, dtype=dtype)
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 459, in _init_dict
    return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 7356, in _arrays_to_mgr
    index = extract_index(arrays)
  File "/home/hspace/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 7393, in extract_index
    raise ValueError('If using all scalar values, you must pass'
ValueError: If using all scalar values, you must pass an index

Previously, I used this function to call historical data from binance api:

def Cryptodata2(symbol,tick_interval='1m'):
    url = 'https://api.binance.com/api/v1/klines?symbol='+symbol+'&interval='+tick_interval
    df = pd.read_json(url)
    df.columns = [ "date","open","high","low","close","volume",
        "close time","quote asset volume","number of trades","taker buy base asset volume",
        "Taker buy quote asset volume","ignore"]
    df['date'] =  pd.to_datetime(df['date'],dayfirst=True, unit = 'ms')
    df.set_index('date',inplace=True)
    del df['ignore']
    return df

And this works fluently.

I just want price of that coin and show it as an integer or dataframe from this url:

https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT

Thanks for helping me.

Also, it would be great if you could provide more detail on debugging such "value" errors.

标签: pythonjsonpython-3.xdataframebinance

解决方案


推荐阅读