如何通过使用Python的binance API获取加密的所有价格历史记录?

2024-06-25 22:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用此脚本使用Binance API和以下脚本从一些加密货币获取价格: https://steemit.com/python/@marketstack/how-to-download-historical-price-data-from-binance-with-python

问题是,使用此脚本,我无法控制日期范围:例如,我想选择2015年12月至2020年12月之间的期间范围,或者我想要任何加密的第一天交易的每日价格…等等

因此,我将与您分享我正在使用的代码(从steemit代码复制并稍加修改) 我怎么做

# https://steemit.com/python/@marketstack/how-to-download-historical-price-data-from-binance-with-python###

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

frequency = input("Please enter the frequency (1m/5m/30m/.../1h/6h/1d/ :  ")

def get_bars(symbol, interval=frequency):
    root_url = 'https://api.binance.com/api/v1/klines'
    url = root_url + '?symbol=' + symbol + '&interval=' + interval
    data = json.loads(requests.get(url).text)
    df = pd.DataFrame(data)
    df.columns = ['open_time',
                  'o', 'h', 'l', 'c', 'v',
                  'close_time', 'qav', 'num_trades',
                  'taker_base_vol', 'taker_quote_vol', 'ignore']
    df.index = [dt.datetime.fromtimestamp(x / 1000.0) for x in df.close_time]
    return df

btcusdt = get_bars('BTCUSDT')
ethusdt = get_bars('ETHUSDT')


df0=pd.DataFrame(btcusdt)
df0.to_csv('_btcusdt.csv')

df1=pd.DataFrame(ethusdt)
df1.to_csv('_ethusdt.csv')

有人能帮我优化一下吗


Tags: csvtohttpsimport脚本comurldf
2条回答

这是我使用的一个函数。 开始和结束是Unix时间戳格式的日期。区间是图的区间

请记住,Binance在2015年12月并不存在:-)

def get_klines_iter(symbol, interval, start, end, limit=5000):
    df = pd.DataFrame()
    startDate = end
    while startDate>start:
        url = 'https://api.binance.com/api/v3/klines?symbol=' + \
            symbol + '&interval=' + interval + '&limit='  + str(iteration)
        if startDate is not None:
            url += '&endTime=' + str(startDate)
        
        df2 = pd.read_json(url)
        df2.columns = ['Opentime', 'Open', 'High', 'Low', 'Close', 'Volume', 'Closetime', 'Quote asset volume', 'Number of trades','Taker by base', 'Taker buy quote', 'Ignore']
        df = pd.concat([df2, df], axis=0, ignore_index=True, keys=None)
        startDate = df.Opentime[0]   
    df.reset_index(drop=True, inplace=True)    
    return df 

我正在使用这个二进制文件:https://python-binance.readthedocs.io/en/latest/binance.html?highlight=get_historical_klines#binance.client.Client.get_historical_klines

import os
from binance.client import Client
import pandas as pd
import datetime, time

def GetHistoricalData(self, howLong):
    self.howLong = howLong
    # Calculate the timestamps for the binance api function
    self.untilThisDate = datetime.datetime.now()
    self.sinceThisDate = self.untilThisDate - datetime.timedelta(days = self.howLong)
    # Execute the query from binance - timestamps must be converted to strings !
    self.candle = self.client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, str(self.sinceThisDate), str(self.untilThisDate))

    # Create a dataframe to label all the columns returned by binance so we work with them later.
    self.df = pd.DataFrame(self.candle, columns=['dateTime', 'open', 'high', 'low', 'close', 'volume', 'closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol', 'takerBuyQuoteVol', 'ignore'])
    # as timestamp is returned in ms, let us convert this back to proper timestamps.
    self.df.dateTime = pd.to_datetime(self.df.dateTime, unit='ms').dt.strftime(Constants.DateTimeFormat)
    self.df.set_index('dateTime', inplace=True)

    # Get rid of columns we do not need
    self.df = self.df.drop(['closeTime', 'quoteAssetVolume', 'numberOfTrades', 'takerBuyBaseVol','takerBuyQuoteVol', 'ignore'], axis=1)

    print(self.df)

我真的希望这能帮助别人

(请注意,此方法是从我拥有的类中裁剪出来的,因此您可以去掉所有的self-s),并且您需要在之前设置您的客户机

client = Client(api_key, api_secret)

当然欢迎任何改进

相关问题 更多 >