I normally use the python-binance library, however, it is not up to date for a particular call I need to make.
I'm therefore attempting to use the standard requests.get
function as follows:
import requests
TakerRatio = requests.get('https://www.binance.com/futures/data/takerlongshortRatio','symbol=BTCUSDT&period=5m&limit=30')
TakerRatio = TakerRatio.text
This returns me all the data I need, however as one string:
[{"buySellRatio":"0.8314","sellVol":"418.6670","buyVol":"348.0720","timestamp":1591194900000},{"buySellRatio":"1.1938","sellVol":"284.8710","buyVol":"340.0660","timestamp":1591195200000},{"buySellRatio":"1.1901","sellVol":"377.4750","buyVol":"449.2250","timestamp":1591195500000}]
Could you guys help me with the simplest way to turn this string into an indexed list? I need to be able to reference the sellVol and buyVol values like you normally would, e.g. querying TakerRatio[0]['sellVol'] to return 418.6670.
It seems that what you get is already what you want, with the only difference that you are getting the numbers as strings. All you need to do is to convert them back to numbers. Also, the timestamp looks like a POSIX timestamp, but with milliseconds. We can use datetime.fromtimestamp
to convert it to a proper date and time.
import requests
import datetime
TakerRatio = requests.get('https://www.binance.com/futures/data/takerlongshortRatio','symbol=BTCUSDT&period=5m&limit=30')
data = TakerRatio.json()
for i in data:
i["buySellRatio"] = float(i["buySellRatio"])
i["sellVol"] = float(i["sellVol"])
i["buyVol"] = float(i["sellVol"])
# The timestamp looks like a POSIX timestamp, but POSIX timestamps are in
# seconds and the one returned looks like it is in milliseconds
i["timestamp"] = datetime.datetime.fromtimestamp(i["timestamp"]/1000)
# This will print a number and not a string representation of the number
print(data[0]['sellVol'])
You can also use pandas for an even easier way to work with this data. The previously converted data be easily turned into a pandas DataFrame
.
import pandas as pd
df = pd.DataFrame(data)
# Print the first 5 rows in a nice tabular way
print(df.head(5))
This will show something like
buySellRatio sellVol buyVol timestamp
0 1.6940 406.295 406.295 2020-06-03 11:55:00
1 1.0489 333.205 333.205 2020-06-03 12:00:00
2 1.0623 209.696 209.696 2020-06-03 12:05:00
3 1.3297 240.111 240.111 2020-06-03 12:10:00
4 2.1152 272.227 272.227 2020-06-03 12:15:00
From this, you can do all kinds of manipulations very easily.