Skip to main content

bitfinex-api

Python client for Bitfinex REST API v2 public endpoints used in Murabei crawlers and market-data workflows.

Objective and motivation

This library turns Bitfinex public HTTP responses into pandas DataFrames (or JSON for low-level calls), with retries, timeouts, and typed errors suitable for ETL and crawlers.

Why this exists

Crawler workers need stable access to candles, pair lists, and currency metadata without re-implementing Bitfinex URL layout, pagination, rate limits, and error payloads on every project.

How it is used

  • Instantiate BitfinexAPI once per worker run or notebook session.
  • Call high-level methods (get_trade_candles, list_api_pairs, map_api_symbol_all, …) and load the returned DataFrames.
  • Catch bitfinex_api.exceptions types to branch on rate limits, invalid parameters, or validation failures.

Scope

In scope Out of scope
Public api-pub.bitfinex.com paths Private trading (orders, wallets)
conf/pub:* metadata WebSocket feeds
Trade candle /hist pagination v2 request signing (not implemented)

Install

From a built wheel:

pip install dist/*.whl

From source (Poetry):

pip install poetry
export VERSION=$(grep -E '^VERSION=' VERSION | cut -d'=' -f2-)
sed -e 's#{VERSION}#'"${VERSION}"'#g' pyproject_template.toml > pyproject.toml
poetry build
pip install dist/*.whl

Quick start

from bitfinex_api import BitfinexAPI

client = BitfinexAPI()

# Platform status (dict with UTC collected_at + body)
status = client.platform_status()

# One hour BTC/USD candles for the last 7 days
import datetime
candles = client.get_trade_candles(
    base_symbol="BTC",
    quote_symbol="USD",
    period="1h",
    start_delta=datetime.timedelta(days=7),
)
print(candles.head())

Client overview

BitfinexAPI combines three mixins:

Mixin Role
BitfinexAPIBaseMixin Session, get / post, retries
BitfinexAPICandlesMixin Trade candle history
BitfinexAPIConfigMixin conf list, map, info helpers

Import:

from bitfinex_api import BitfinexAPI

Optional constructor arguments api_key and api_secret are stored only for future signed calls. Passing authenticated=True on get / post raises NotImplementedError once credentials are set (signing not shipped).

Low-level HTTP

Use get when no helper exists yet:

body = client.get(
    endpoint="tickers",
    query_params={"symbols": "tBTCUSD"},
)
  • endpoint is joined onto https://api-pub.bitfinex.com/v2/.
  • Returns parsed JSON (list or dict).
  • Non-OK responses raise subclasses of BitfinexAPIRequestError (see Errors and retries).

Trade candles

Method

frame = client.get_trade_candles(
    base_symbol="BTC",
    quote_symbol="USD",
    period="1h",          # see AVAILABLE_CANDLE_PERIODS on the mixin
    start_delta=None,       # or start_datetime=...
    start_datetime=None,
    end_datetime=None,      # default: now (UTC)
    limit=10000,            # per HTTP page
)

Time window: Provide exactly one of:

  • start_delta — length ending at end_datetime or now, or
  • start_datetime — inclusive start (str or datetime; converted to UTC).

Pair path: Built as t{base}{quote} (e.g. tBTCUSD).

Expected result

Column Type (typical) Description
time UTC timestamp Bar open time
open float Open
close float Close
high float High
low float Low
volume float Volume
  • Empty window: DataFrame with these columns and zero rows (schema preserved).
  • Pagination: Long ranges issue multiple /hist calls. Progress is logged at info level.
  • Stall guard: If the API stops advancing mts, the client logs a warning and returns partial data collected so far. Treat logs as the signal that the window may be incomplete.
  • Invalid client args: BitfinexAPIInvalidParametersError (bad period or conflicting time args).
  • Invalid range on API: Often BitfinexAPIBitfinexInvalidParametersError (HTTP 500 / Bitfinex code 10020).

Example

import datetime
import pandas as pd

frame = client.get_trade_candles(
    base_symbol="BTC",
    quote_symbol="USD",
    period="1h",
    start_datetime=datetime.datetime(2025, 12, 1),
    end_datetime=datetime.datetime(2026, 1, 1),
    limit=100,
)
assert list(frame.columns) == [
    "time", "open", "close", "high", "low", "volume"]
assert frame["time"].min() == pd.Timestamp("2025-12-01", tz="UTC")

Config: list endpoints

Methods under BitfinexAPIConfigListMixin return sorted DataFrames.

Method Endpoint (concept) Columns
list_api_currencies pub:list:currency api_symbol
list_api_margin_currencies pub:list:currency:margin api_symbol
list_api_pairs(market="exchange") pub:list:pair:{market} instrument, trading_prefix, pair, base_api_symbol, quote_api_symbol
list_api_competitions pub:list:competitions competition

market must be one of: exchange, margin, futures, securities.

Expected behaviour:

  • Empty or missing unwrap → BitfinexAPINoneResponseError.
  • Unparseable pair string → BitfinexAPIInvalidParametersError from TreatmentPairSymbols.

list_api_pairs performs an extra call to list_api_currencies to split concatenated pair codes.

Config: map endpoints

Each map_* method returns a DataFrame documented on BitfinexAPIConfigMapMixin (column tuples such as API_CURRENCY_SYMBOLS_COLUMNS).

Common entry points:

Method Purpose
map_api_currency_symbol Wallet code → API symbol
map_api_symbol_names Code → display name
map_api_currency_symbol_with_names Merge + name backfill + duplicate check
map_api_symbol_all One row per code with pool, explorer, fees, …

Expected behaviour:

  • Duplicate api_symbol after merge → BitfinexAPIDataValidationError.
  • Row-count mismatch after map_api_symbol_all merge → BitfinexAPIDataValidationError.
  • Missing display names may be filled from CURRENCY_NAME_OVERRIDES; remaining gaps are logged at warning (DataFrame may still contain null name).

Config: info endpoints

Method Columns (summary)
info_api_pair pair, first_trade_ms, sizes, margins, …
info_api_pair_futures Same shape for futures
info_api_tx_status Withdrawal/deposit status per rail

Empty body → BitfinexAPINoneResponseError.

Enriched pair listing

pairs_enriched = client.list_pair_with_info()

Expected result:

  1. list_api_pairs() — one row per tradable pair (exchange market).
  2. Left joins map_api_symbol_all() twice: base_* and quote_* columns prefixed on base_api_symbol / quote_api_symbol.

Operational note: This orchestration triggers many HTTP requests (currencies, pairs, and each map table). Cache or call sparingly in tight loops.

Platform status

payload = client.platform_status()

Expected result: dict with:

  • collected_at — datetime (UTC, naive wall time in object),
  • body — unwrapped JSON from GET platform/status (may be None).

Errors and retries

Exception Typical cause
BitfinexAPIInvalidParametersError Client-side validation
BitfinexAPIDataValidationError Post-processing / merge checks
BitfinexAPINoneResponseError Empty conf response
BitfinexAPITooManyRequestsError Rate limit (retried with long wait)
BitfinexAPIBitfinexInvalidParametersError Bitfinex rejected params
BitfinexAPIRequestError Other HTTP errors
BitfinexAPIAuthenticationError Missing credentials when auth required
NotImplementedError authenticated=True (signing not implemented)

Exceptions expose message, payload, and to_dict() for workers.

Retries (tenacity): Connection errors, timeouts, and rate-limit errors retry up to BITFINEX__REQUEST_MAX_ATTEMPTS. Rate-limit waits use BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT (default 61 seconds).

Configuration (environment)

Variable Default Used for
BITFINEX__REQUEST_TIMEOUT 60 Seconds per HTTP request
BITFINEX__REQUEST_MAX_ATTEMPTS 5 Max retries on network errors
BITFINEX__REQUEST_RETRY_MIN_WAIT 0.5 Seconds between retries
BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT 61 Wait before retry on 429
BITFINEX__PROXY_URL (unset) Optional HTTP(S) proxy

Invalid positive values raise ValueError at import of bitfinex_api.config.

Tests

Unit tests (no network):

PYENV_VERSION=bitfinex-api python -m pytest tests/test__exceptions.py -q

Integration tests (live Bitfinex API):

  1. Copy test_parameters.template to test_parameters.secrets if needed.
  2. Run:
set -a && source test_parameters.secrets && set +a
python -m unittest discover -s tests -v

Candle and config tests call the public API and require network access.

Development and release

ruff check src/

Release build (increments patch in VERSION, renders pyproject.toml, tags, pushes—see build.sh):

./build.sh

Package history: CHANGELOG.md.

License

BSD-3-Clause — see LICENSE.

Metadata

Release files for bitfinex-api 0.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bitfinex-api 0.0.2
File Size Uploaded Provenance Actions
bitfinex_api-0.0.2.tar.gz 23.7 kB Without provenance Details for bitfinex_api-0.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bitfinex-api 0.0.2
File Interpreter ABI Platform Actions
bitfinex_api-0.0.2-py3-none-any.whl Python 3 none any Details for bitfinex_api-0.0.2-py3-none-any.whl

Total release size: 51.3 kB

Release files / bitfinex_api-0.0.2.tar.gz

Download URL bitfinex_api-0.0.2.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
1ad9937781d1e01d11e4ec9600e84f3c49e0c0bce7e4a067780eccb61e0a5b59
BLAKE2b-256 checksum
How to use checksums
786d2d7715622e6d155589ef0a9108d4d00d2550f66bd46b7a451ea5a56335e4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.2 CPython/3.12.16 Linux/7.0.0-1020-azure

Release files / bitfinex_api-0.0.2-py3-none-any.whl

Download URL bitfinex_api-0.0.2-py3-none-any.whl
Size 27.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6687d8260db73dd5ee92729ed5431257ff233e371a2b0ca8ea54fa155b820dd1
BLAKE2b-256 checksum
How to use checksums
b7ce002517ed5784ae8d39271b98ae8f2a3a4137e14a4302ffaa694d42b2fa80
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.2 CPython/3.12.16 Linux/7.0.0-1020-azure

Security for bitfinex-api 0.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page