使用Python(最好是请求)从Binance API获取K线图/K线图数据,以获取JSON Dat

66bbxpm5  于 2022-12-01  发布在  Python
关注(0)|答案(3)|浏览(520)

我正在开发一个从Binance API中获取烛台数据的电报机器人。我无法获得JSON数据作为响应。下面的代码是我尝试过的。

import requests 

 import json

 import urllib.request

`url = "https://api.binance.com/api/v1/klines"

response = requests.request("GET", url)
print(response.text)`

所需输出:
[ [ 1499040000000, // Open time "0.01634790", // Open "0.80000000", // High "0.01575800", // Low "0.01577100", // Close "148976.11427815", // Volume 1499644799999, // Close time "2434.19055334", // Quote asset volume 308, // Number of trades "1756.87402397", // Taker buy base asset volume "28.46694368", // Taker buy quote asset volume "17928899.62484339" // Ignore ] ]
问题已编辑:
我得到的输出是:

`{"code":-1102,"msg":"Mandatory parameter 'symbol' was not sent, was empty/null, or malformed."}'
oipij1gg

oipij1gg1#

缺少必需的参数符号和间隔,则查询应如下所示:
https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h
您只需要导入请求:

import requests

market = 'BTCUSDT'
tick_interval = '1h'

url = 'https://api.binance.com/api/v3/klines?symbol='+market+'&interval='+tick_interval
data = requests.get(url).json()

print(data)

请在此处查看官方Binance REST API文档:https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md

hpxqektj

hpxqektj2#

requests python包有一个paramsjson参数,所以你不需要导入任何你要导入的包。

import requests

url = 'https://api.binance.com/api/v3/klines'
params = {
  'symbol': 'BTCUSDT',
  'interval': '1h'
}
response = requests.get(url, params=params)
print(response.json())
2o7dmzc5

2o7dmzc53#

将数据收集到 Dataframe 中

import requests
import datetime
import pandas as pd
import numpy as np

def get_binance_data_request_(ticker, interval='4h', limit=500, start='2018-01-01 00:00:00'):
  """
  interval: str tick interval - 4h/1h/1d ...
  """
  columns = ['open_time','open', 'high', 'low', 'close', 'volume','close_time', 'qav','num_trades','taker_base_vol','taker_quote_vol', 'ignore']
  start = int(datetime.datetime.timestamp(pd.to_datetime(start))*1000)
  url = f'https://www.binance.com/api/v3/klines?symbol={ticker}&interval={interval}&limit={limit}&startTime={start}'
  data = pd.DataFrame(requests.get(url).json(), columns=columns, dtype=np.float)
  data.index = [pd.to_datetime(x, unit='ms').strftime('%Y-%m-%d %H:%M:%S') for x in data.open_time]
  usecols=['open', 'high', 'low', 'close', 'volume', 'qav','num_trades','taker_base_vol','taker_quote_vol']
  data = data[usecols]
  return data

get_binance_data_request_('ETHUSDT', '1h')

结果:

相关问题