Metadata-Version: 2.4
Name: bitfinex-api
Version: 0.0.2
Summary: Python API to interact with Bitfinex endpoints
License: BSD-3-Clause License
License-File: LICENSE
Author: Murabei Data Science
Author-email: a.baceti@murabei.com
Requires-Python: >=3.12
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Dist: loguru
Requires-Dist: pandas (>=2.2.0,<3.0.0)
Requires-Dist: pydantic (>=2.10.0,<3.0.0)
Requires-Dist: requests (>=2.32.5,<3.0.0)
Requires-Dist: tenacity (>=9.1.4,<10.0.0)
Description-Content-Type: text/markdown

# bitfinex-api

Python client for [Bitfinex REST API v2](https://docs.bitfinex.com/docs/rest-general)
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:

```bash
pip install dist/*.whl
```

From source (Poetry):

```bash
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

```python
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:

```python
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:

```python
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

```python
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

```python
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

```python
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

```python
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):

```bash
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:

```bash
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

```bash
ruff check src/
```

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

```bash
./build.sh
```

Package history: [CHANGELOG.md](CHANGELOG.md).

## License

BSD-3-Clause — see [LICENSE](LICENSE).
