pythonbinance

Binance API - Several symbols/pairs in a code


It does work with 1 crypto pair by coding symbol = 'XRPUSDT' but it doesn't work with 2 or more pairs. Ways I tried are:

symbol = ['XRPUSDT', 'DOGEUSDT']

symbol = 'XRPUSDT', 'DOGEUSDT'

symbol = {
    "XRP/USDT": "XRP/USDT", 
    "DOGE/USDT": "DOGE/USDT"
    }

symbol = [(XRP/USDT, 'XRP/USDT'), (DOGE/USDT, 'DOGE/USDT')]

Unfortunately, none of above worked out. Does anyone have any ideas for listing several crypto pairs, please? TIA


Solution

  • You can do it within a loop:

    symbols = ['XRPUSDT', 'DOGEUSDT']
    for symbol in symbols:
        # Binance RESTful API
    

    Here is a snippet code of how to send GET request to Binance API inside a loop:

    for symbol in symbols:
        candles = requests.get("https://api.binance.com/api/v3/klines", params={'symbol': symbol,
                                      'interval': interval,
                                      'startTime': start_time,
                                      'endTime': end_time}).json()
    

    And here is a complete example:

    import requests
    from datetime import datetime
    
    api_address = 'https://api.binance.com/api/v3/klines'
    start_time = int(datetime(2021, 8, 20).timestamp()) * 1000
    end_time = int(datetime(2021, 8, 30).timestamp()) * 1000
    interval='1d'
    symbols = ['XRPUSDT', 'DOGEUSDT']
    for symbol in symbols:
      candles = requests.get(url=api_address,
                          params={'symbol': symbol,
                                  'interval': interval,
                                  'startTime': start_time,
                                  'endTime': end_time})
      print(candles.json())
    

    See documentation for more info https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#klinecandlestick-data