【问题标题】:How can i sort Binance historical candles for multiple pairs across multiple timeframes如何在多个时间范围内对多对的 Binance 历史蜡烛进行排序
【发布时间】:2021-08-01 16:47:50
【问题描述】:

我正在从 binance api 下载不同时间范围内多个加密货币对的历史烛台数据,我想知道如何根据货币对和时间范围对这些数据进行排序,并检查哪个时间范围内的哪个货币对执行我的代码,如下代码是我用来获取历史数据的

import requests

class BinanceFuturesClient:

def __init__(self):
    self.base_url = "https://fapi.binance.com"

def make_requests(self, method, endpoint, data):
    if method=="GET":
        response = requests.get(self.base_url + endpoint, params=data)
    return response.json()

def get_symbols(self):
    symbols = []
    exchange_info = self.make_requests("GET", "/fapi/v1/exchangeInfo", None)
    if exchange_info is not None:
        for symbol in exchange_info['symbols']:
            if symbol['contractType'] == 'PERPETUAL' and symbol['quoteAsset'] == 'USDT':
                symbols.append(symbol['pair'])

    return symbols

def initial_historical_data(self, symbol, interval):
    data = dict()
    data['symbol'] = symbol
    data['interval'] = interval
    data['limit'] = 35
    raw_candle = self.make_requests("GET", "/fapi/v1/klines", data)
    candles = []
    if raw_candle is not None:
        for c in raw_candle:
            candles.append(float(c[4]))
    return candles[:-1]

运行此代码

print(binance.initial_historical_data("BTCUSDT", "5m"))

将其作为输出返回

[55673.63, 55568.0, 55567.89, 55646.19, 55555.0, 55514.53, 55572.46, 55663.91, 55792.83, 55649.43, 
55749.98, 55680.0, 55540.25, 55470.44, 55422.01, 55350.0, 55486.56, 55452.45, 55507.03, 55390.23, 
55401.39, 55478.63, 55466.48, 55584.2, 55690.03, 55760.81, 55515.57, 55698.35, 55709.78, 55760.42, 
55719.71, 55887.0, 55950.0, 55980.47]

这是一个关闭列表

我想以这样一种方式循环代码,以便我可以返回我需要的货币对和时间范围的所有收盘价并相应地对其进行排序,我确实尝试过,但只是停留在这一点上

period = ["1m", "3m", "5m", "15m"]
binance = BinanceFuturesClient()
symbols = binance.get_symbols()
for symbol in symbols:
    for tf in period:
        historical_candles = binance.initial_historical_data(symbol, tf)
        # store values and run through strategy

【问题讨论】:

    标签: python dataframe api algorithmic-trading binance


    【解决方案1】:

    您可以使用我在下面发布的代码。它需要在您的环境中安装 python-binance 包,并从您的 Binance 帐户获取 API 密钥/秘密。方法尝试按周块(参数步骤)加载数据,并支持在超时后重新发送失败请求。当您需要获取大量数据时,它可能会有所帮助。

    import pandas as pd
    import pytz, time, datetime
    from binance.client import Client
    from tqdm.notebook import tqdm
    
    def binance_client(api_key, secret_key):
        return Client(api_key=api_key, api_secret=secret_key)
    
    def load_binance_data(client, symbol, start='1 Jan 2017 00:00:00', timeframe='1M', step='4W', timeout_sec=5):
        tD = pd.Timedelta(timeframe)
        now = (pd.Timestamp(datetime.datetime.now(pytz.UTC).replace(second=0)) - tD).strftime('%d %b %Y %H:%M:%S')
        tlr = pd.DatetimeIndex([start]).append(pd.date_range(start, now, freq=step).append(pd.DatetimeIndex([now])))
    
        print(f' >> Loading {symbol} {timeframe} for [{start}  -> {now}]')
        df = pd.DataFrame()
        s = tlr[0]
        for e in tqdm(tlr[1:]):
            if s + tD < e:
                _start, _stop = (s + tD).strftime('%d %b %Y %H:%M:%S'), e.strftime('%d %b %Y %H:%M:%S')
                nerr = 0
                while nerr < 3:
                    try:
                        chunk = client.get_historical_klines(symbol, timeframe.lower(), _start, _stop)
                        nerr = 100
                    except e as Exception:
                        nerr +=1
                        print(red(str(e)))
                        time.sleep(10)
    
                if chunk:
                    data = pd.DataFrame(chunk, columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_av', 'trades', 'tb_base_av', 'tb_quote_av', 'ignore' ])
                    data.index = pd.to_datetime(data['timestamp'].rename('time'), unit='ms')
                    data = data.drop(columns=['timestamp', 'close_time']).astype(float).astype({
                        'ignore': bool,
                        'trades': int,
                    })
                    df = df.append(data)
                s = e
                time.sleep(timeout_sec)
    
        return df
    

    如何使用

    c = binance_client(<your API code>, <your API secret>)
    # loading daily data from 1/Mar/21 till now (your can use other timerames like 1m, 5m etc)
    data = load_binance_data(c, 'BTCUSDT', '2021-03-01', '1D')
    

    它返回带有加载数据的索引DataFrame:

    time open high low close volume quote_av trades tb_base_av tb_quote_av ignore
    2021-03-02 00:00:00 49595.8 50200 47047.6 48440.7 64221.1 3.12047e+09 1855583 31377 1.52515e+09 False
    2021-03-03 00:00:00 48436.6 52640 48100.7 50349.4 81035.9 4.10952e+09 2242131 40955.4 2.07759e+09 False
    2021-03-04 00:00:00 50349.4 51773.9 47500 48374.1 82649.7 4.07984e+09 2291936 40270 1.98796e+09 False
    2021-03-05 00:00:00 48374.1 49448.9 46300 48751.7 78192.5 3.72713e+09 2054216 38318.3 1.82703e+09 False
    2021-03-06 00:00:00 48746.8 49200 47070 48882.2 44399.2 2.14391e+09 1476474 21500.6 1.03837e+09 False

    接下来的步骤取决于您并取决于您希望如何设计数据结构。在最简单的情况下,您可以将数据存储到字典中:

    from collections import defaultdict
    data = defaultdict(dict)
    
    for symbol in ['BTCUSDT', 'ETHUSDT']:
        for tf in ['1d', '1w']:
            historical_candles = load_binance_data(c, symbol, '2021-05-01', timeframe=tf)
    
            # store values and run through strategy
            data[symbol][tf] = historical_candles
    

    要访问您的 OHLC,您只需要以下内容:data['BTCUSDT']['1d'] 等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2023-03-11
      • 2018-08-02
      • 1970-01-01
      相关资源
      最近更新 更多