BinanceDownloader#

API documentation for tradingstrategy.binance.downloader.BinanceDownloader Python class in Trading Strategy framework.

class BinanceDownloader[source]#

Bases: object

Class for downloading Binance candlestick OHLCV data.

Cache loaded data locally, so that subsequent runs do not refetch the data from Binance.

__init__(cache_directory=PosixPath('/home/runner/.cache/trading-strategy/binance-datasets'))[source]#

Initialize BinanceCandleDownloader and create folder for cached data if it does not exist.

Parameters:

cache_directory (Path) –

Methods

__init__([cache_directory])

Initialize BinanceCandleDownloader and create folder for cached data if it does not exist.

fetch_all_lending_symbols()

List of all valid asset symbols for fetching lending data

fetch_all_spot_symbols()

List of all valid pool symbols for fetching candle data

fetch_approx_asset_trading_start_date(symbol)

Get the asset trading start date at Binance.

fetch_assets([market])

Load available assets on binance. Example: # Show all pairs that downloader = BinanceDownloader() pairs = {ticker for ticker in downloader.fetch_assets(market="MARGIN") if ticker.endswith("USDT")} print(f"USDT margin trading pairs: {pairs}") :param market: Are we looking for MARGIN or SPOT or both markets. :return: Iterable of all asset symbols. E.g. "ETHUSDT", "BTCUSDT".

fetch_candlestick_data(symbols, time_bucket)

Get clean candlestick price and volume data from Binance.

fetch_candlestick_data_single_pair(symbol, ...)

Fetch candlestick data for a single pair.

fetch_lending_rates(asset_symbols, ...[, ...])

Get daily lending interest rates for a given asset from Binance, resampled to the given time bucket.

fetch_lending_rates_single_pair(...[, ...])

Fetch lending rates for a single asset.

get_data_parquet(symbol, time_bucket, ...[, ...])

Get parquet file for the candlestick data.

get_parquet_path(symbol, time_bucket, ...[, ...])

Get parquet path for the candlestick data.

load_lending_candle_type_map(...[, ...])

Load lending candles for all assets.

overwrite_cached_data(df, symbol, ...[, ...])

Overwrite specific cached candle data file.

purge_all_cached_data()

Purge all cached candle data.

purge_cached_file(*[, symbol, time_bucket, ...])

Purge specific cached candle data file.

__init__(cache_directory=PosixPath('/home/runner/.cache/trading-strategy/binance-datasets'))[source]#

Initialize BinanceCandleDownloader and create folder for cached data if it does not exist.

Parameters:

cache_directory (Path) –

fetch_candlestick_data(symbols, time_bucket, start_at=None, end_at=None, force_download=False, desc='Downloading Binance data')[source]#

Get clean candlestick price and volume data from Binance. If saved, use saved version, else create saved version.

Download is cached.

Note

If you want to use this data in our framework, you will need to add informational columns to the dataframe and overwrite it. See code below.

Parameters:
  • symbol – Trading pair symbol E.g. ETHUSDC

  • interval – Can be one of 1s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M

  • start_at (datetime) – Start date of the data

  • end_at (datetime) – End date of the data

  • force_download – Force redownload of data from Binance and overwrite cached version

  • symbols (list[str] | str) –

  • time_bucket (TimeBucket) –

Returns:

Pandas dataframe with the OHLCV data for the columns and datetimes as the index

Return type:

DataFrame

fetch_candlestick_data_single_pair(symbol, time_bucket, start_at, end_at, force_download=False, binance_spot_symbols=None, show_individual_progress=False)[source]#

Fetch candlestick data for a single pair.

Download is cached.

Using this function directly will not include progress bars. Use fetch_candlestick_data instead.

Parameters:
Return type:

DataFrame

fetch_lending_rates(asset_symbols, time_bucket, start_at, end_at, force_download=False)[source]#

Get daily lending interest rates for a given asset from Binance, resampled to the given time bucket.

Parameters:
  • asset_symbol – See py:method:tradingstrategy.binance.downloader.get_all_lending_symbols for valid symbols

  • time_bucket (TimeBucket) – Time bucket to resample the data to

  • start_date – Start date for the data. Note this value cannot be eariler than datetime.datetime(2019,4,1) due to Binance data limitations

  • end_date – End date for the data

  • force_download – Force redownload of data from Binance and overwrite cached version

  • asset_symbols (list[str] | str | set[str]) –

  • start_at (datetime) –

  • end_at (datetime) –

Returns:

Pandas dataframe with the interest rates for the column and datetimes as the index

Return type:

DataFrame

fetch_lending_rates_single_pair(asset_symbol, time_bucket, start_at, end_at, force_download=False, show_individual_progress=False, lending_symbols=None)[source]#

Fetch lending rates for a single asset.

Using this function directly will not include progress bars. Use fetch_lending_rates instead.

Parameters:
Return type:

DataFrame

fetch_approx_asset_trading_start_date(symbol)[source]#

Get the asset trading start date at Binance.

Binance was launched around 2017-08-01.

Raises:

BinanceDataFetchError – If the asset does not exist.

Return type:

datetime

get_data_parquet(symbol, time_bucket, start_at, end_at, is_lending=False)[source]#

Get parquet file for the candlestick data.

Parameters:
  • symbol (str) – Trading pair symbol E.g. ETHUSDC

  • time_bucket (TimeBucket) – TimeBucket instance

  • start_at (datetime) – Start date of the data

  • end_at (datetime) – End date of the data

  • is_lending (bool) –

Returns:

Path to the parquet file

Return type:

DataFrame

get_parquet_path(symbol, time_bucket, start_at, end_at, is_lending=False)[source]#

Get parquet path for the candlestick data.

Parameters:
  • symbol (str) – Trading pair symbol E.g. ETHUSDC

  • time_bucket (TimeBucket) – TimeBucket instance

  • start_at (datetime) – Start date of the data

  • end_at (datetime) – End date of the data

  • is_lending (bool) –

Returns:

Path to the parquet file

Return type:

Path

overwrite_cached_data(df, symbol, STOP_LOSS_TIME_BUCKET, START_AT_DATA, END_AT, is_lending=False)[source]#

Overwrite specific cached candle data file.

Parameters:
  • symbol – Trading pair symbol E.g. ETHUSDC

  • time_bucket – TimeBucket instance

  • start_at – Start date of the data

  • end_at – End date of the data

  • path – Path to the parquet file. If not specified, it will be generated from the other parameters.

  • df (DataFrame) –

  • is_lending (bool) –

Return type:

None

purge_cached_file(*, symbol=None, time_bucket=None, start_at=None, end_at=None, path=None)[source]#

Purge specific cached candle data file.

Parameters:
  • symbol (str) – Trading pair symbol E.g. ETHUSDC

  • time_bucket (TimeBucket) – TimeBucket instance

  • start_at (datetime) – Start date of the data

  • end_at (datetime) – End date of the data

  • path (Path) – Path to the parquet file. If not specified, it will be generated from the other parameters.

Return type:

None

purge_all_cached_data()[source]#

Purge all cached candle data. This delete all contents of a cache directory, but not the directory itself. I.e. the cache directory will be left empty

Parameters:

path – Path to the parquet file

Return type:

None

load_lending_candle_type_map(asset_symbols_dict, time_bucket, start_at, end_at, force_download=False)[source]#

Load lending candles for all assets.

See py:method:tradingstrategy.binance.downloader.fetch_lending_rates for valid symbols

Parameters:
  • symbols – Dictionary of reserve_id to token symbol. The token symbol should be a valid symbol that can be used in .. py:method:tradingstrategy.binance.downloader.fetch_lending_rates.

  • asset_symbols_dict (dict[int, str]) –

  • time_bucket (TimeBucket) –

  • start_at (datetime) –

  • end_at (datetime) –

Returns:

LendingCandleUniverse

Return type:

Dict[LendingCandleType, DataFrame]

fetch_assets(market='MARGIN')[source]#

Load available assets on binance. Example:

# Show all pairs that downloader = BinanceDownloader() pairs = {ticker for ticker in downloader.fetch_assets(market=”MARGIN”) if ticker.endswith(“USDT”)} print(f”USDT margin trading pairs: {pairs}”)

Parameters:

market (Optional[Union[Literal['SPOT'], ~typing.Literal['MARGIN']]]) – Are we looking for MARGIN or SPOT or both markets.

Returns:

Iterable of all asset symbols. E.g. “ETHUSDT”, “BTCUSDT”

Return type:

Iterable[str]

fetch_all_lending_symbols()[source]#

List of all valid asset symbols for fetching lending data

fetch_all_spot_symbols()[source]#

List of all valid pool symbols for fetching candle data