bitfinex-api 0.0.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bitfinex_api-0.0.2/LICENSE +28 -0
- bitfinex_api-0.0.2/PKG-INFO +343 -0
- bitfinex_api-0.0.2/README.md +325 -0
- bitfinex_api-0.0.2/pyproject.toml +68 -0
- bitfinex_api-0.0.2/src/bitfinex_api/__init__.py +17 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/__init__.py +11 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/base.py +241 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/candles/__init__.py +7 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/candles/candles.py +242 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/__init__.py +23 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/config.py +28 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/config_base.py +45 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/config_info.py +98 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/config_list.py +68 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/config_map.py +340 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/contracts.py +31 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/treatment/__init__.py +7 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/config/treatment/pair_symbols.py +130 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/misc/__init__.py +5 -0
- bitfinex_api-0.0.2/src/bitfinex_api/aux/misc/datetime_aux.py +33 -0
- bitfinex_api-0.0.2/src/bitfinex_api/config.py +94 -0
- bitfinex_api-0.0.2/src/bitfinex_api/data.py +17 -0
- bitfinex_api-0.0.2/src/bitfinex_api/exceptions.py +284 -0
- bitfinex_api-0.0.2/src/bitfinex_api/run_tests.bash +1 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023, Murabei Data Science
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bitfinex-api
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Python API to interact with Bitfinex endpoints
|
|
5
|
+
License: BSD-3-Clause License
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Murabei Data Science
|
|
8
|
+
Author-email: a.baceti@murabei.com
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Dist: loguru
|
|
13
|
+
Requires-Dist: pandas (>=2.2.0,<3.0.0)
|
|
14
|
+
Requires-Dist: pydantic (>=2.10.0,<3.0.0)
|
|
15
|
+
Requires-Dist: requests (>=2.32.5,<3.0.0)
|
|
16
|
+
Requires-Dist: tenacity (>=9.1.4,<10.0.0)
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# bitfinex-api
|
|
20
|
+
|
|
21
|
+
Python client for [Bitfinex REST API v2](https://docs.bitfinex.com/docs/rest-general)
|
|
22
|
+
public endpoints used in Murabei crawlers and market-data workflows.
|
|
23
|
+
|
|
24
|
+
## Objective and motivation
|
|
25
|
+
|
|
26
|
+
This library turns Bitfinex **public** HTTP responses into **pandas**
|
|
27
|
+
DataFrames (or JSON for low-level calls), with retries, timeouts, and typed
|
|
28
|
+
errors suitable for ETL and crawlers.
|
|
29
|
+
|
|
30
|
+
### Why this exists
|
|
31
|
+
|
|
32
|
+
Crawler workers need stable access to **candles**, **pair lists**, and
|
|
33
|
+
**currency metadata** without re-implementing Bitfinex URL layout, pagination,
|
|
34
|
+
rate limits, and error payloads on every project.
|
|
35
|
+
|
|
36
|
+
### How it is used
|
|
37
|
+
|
|
38
|
+
- Instantiate ``BitfinexAPI`` once per worker run or notebook session.
|
|
39
|
+
- Call high-level methods (``get_trade_candles``, ``list_api_pairs``,
|
|
40
|
+
``map_api_symbol_all``, …) and load the returned DataFrames.
|
|
41
|
+
- Catch ``bitfinex_api.exceptions`` types to branch on rate limits, invalid
|
|
42
|
+
parameters, or validation failures.
|
|
43
|
+
|
|
44
|
+
### Scope
|
|
45
|
+
|
|
46
|
+
| In scope | Out of scope |
|
|
47
|
+
|----------|----------------|
|
|
48
|
+
| Public ``api-pub.bitfinex.com`` paths | Private trading (orders, wallets) |
|
|
49
|
+
| ``conf/pub:*`` metadata | WebSocket feeds |
|
|
50
|
+
| Trade candle ``/hist`` pagination | v2 request signing (not implemented) |
|
|
51
|
+
|
|
52
|
+
## Install
|
|
53
|
+
|
|
54
|
+
From a built wheel:
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install dist/*.whl
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
From source (Poetry):
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install poetry
|
|
64
|
+
export VERSION=$(grep -E '^VERSION=' VERSION | cut -d'=' -f2-)
|
|
65
|
+
sed -e 's#{VERSION}#'"${VERSION}"'#g' pyproject_template.toml > pyproject.toml
|
|
66
|
+
poetry build
|
|
67
|
+
pip install dist/*.whl
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Quick start
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from bitfinex_api import BitfinexAPI
|
|
74
|
+
|
|
75
|
+
client = BitfinexAPI()
|
|
76
|
+
|
|
77
|
+
# Platform status (dict with UTC collected_at + body)
|
|
78
|
+
status = client.platform_status()
|
|
79
|
+
|
|
80
|
+
# One hour BTC/USD candles for the last 7 days
|
|
81
|
+
import datetime
|
|
82
|
+
candles = client.get_trade_candles(
|
|
83
|
+
base_symbol="BTC",
|
|
84
|
+
quote_symbol="USD",
|
|
85
|
+
period="1h",
|
|
86
|
+
start_delta=datetime.timedelta(days=7),
|
|
87
|
+
)
|
|
88
|
+
print(candles.head())
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Client overview
|
|
92
|
+
|
|
93
|
+
``BitfinexAPI`` combines three mixins:
|
|
94
|
+
|
|
95
|
+
| Mixin | Role |
|
|
96
|
+
|-------|------|
|
|
97
|
+
| ``BitfinexAPIBaseMixin`` | Session, ``get`` / ``post``, retries |
|
|
98
|
+
| ``BitfinexAPICandlesMixin`` | Trade candle history |
|
|
99
|
+
| ``BitfinexAPIConfigMixin`` | ``conf`` list, map, info helpers |
|
|
100
|
+
|
|
101
|
+
Import:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from bitfinex_api import BitfinexAPI
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Optional constructor arguments ``api_key`` and ``api_secret`` are **stored only**
|
|
108
|
+
for future signed calls. Passing ``authenticated=True`` on ``get`` / ``post``
|
|
109
|
+
raises ``NotImplementedError`` once credentials are set (signing not shipped).
|
|
110
|
+
|
|
111
|
+
## Low-level HTTP
|
|
112
|
+
|
|
113
|
+
Use ``get`` when no helper exists yet:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
body = client.get(
|
|
117
|
+
endpoint="tickers",
|
|
118
|
+
query_params={"symbols": "tBTCUSD"},
|
|
119
|
+
)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
- ``endpoint`` is joined onto ``https://api-pub.bitfinex.com/v2/``.
|
|
123
|
+
- Returns parsed JSON (``list`` or ``dict``).
|
|
124
|
+
- Non-OK responses raise subclasses of ``BitfinexAPIRequestError`` (see
|
|
125
|
+
**Errors and retries**).
|
|
126
|
+
|
|
127
|
+
## Trade candles
|
|
128
|
+
|
|
129
|
+
### Method
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
frame = client.get_trade_candles(
|
|
133
|
+
base_symbol="BTC",
|
|
134
|
+
quote_symbol="USD",
|
|
135
|
+
period="1h", # see AVAILABLE_CANDLE_PERIODS on the mixin
|
|
136
|
+
start_delta=None, # or start_datetime=...
|
|
137
|
+
start_datetime=None,
|
|
138
|
+
end_datetime=None, # default: now (UTC)
|
|
139
|
+
limit=10000, # per HTTP page
|
|
140
|
+
)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
**Time window:** Provide exactly one of:
|
|
144
|
+
|
|
145
|
+
- ``start_delta`` — length ending at ``end_datetime`` or now, or
|
|
146
|
+
- ``start_datetime`` — inclusive start (``str`` or ``datetime``; converted to
|
|
147
|
+
UTC).
|
|
148
|
+
|
|
149
|
+
**Pair path:** Built as ``t{base}{quote}`` (e.g. ``tBTCUSD``).
|
|
150
|
+
|
|
151
|
+
### Expected result
|
|
152
|
+
|
|
153
|
+
| Column | Type (typical) | Description |
|
|
154
|
+
|--------|----------------|-------------|
|
|
155
|
+
| ``time`` | UTC timestamp | Bar open time |
|
|
156
|
+
| ``open`` | float | Open |
|
|
157
|
+
| ``close`` | float | Close |
|
|
158
|
+
| ``high`` | float | High |
|
|
159
|
+
| ``low`` | float | Low |
|
|
160
|
+
| ``volume`` | float | Volume |
|
|
161
|
+
|
|
162
|
+
- **Empty window:** DataFrame with these columns and **zero rows** (schema
|
|
163
|
+
preserved).
|
|
164
|
+
- **Pagination:** Long ranges issue multiple ``/hist`` calls. Progress is
|
|
165
|
+
logged at ``info`` level.
|
|
166
|
+
- **Stall guard:** If the API stops advancing ``mts``, the client logs a
|
|
167
|
+
**warning** and returns **partial** data collected so far. Treat logs as the
|
|
168
|
+
signal that the window may be incomplete.
|
|
169
|
+
- **Invalid client args:** ``BitfinexAPIInvalidParametersError`` (bad period or
|
|
170
|
+
conflicting time args).
|
|
171
|
+
- **Invalid range on API:** Often ``BitfinexAPIBitfinexInvalidParametersError``
|
|
172
|
+
(HTTP 500 / Bitfinex code 10020).
|
|
173
|
+
|
|
174
|
+
### Example
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
import datetime
|
|
178
|
+
import pandas as pd
|
|
179
|
+
|
|
180
|
+
frame = client.get_trade_candles(
|
|
181
|
+
base_symbol="BTC",
|
|
182
|
+
quote_symbol="USD",
|
|
183
|
+
period="1h",
|
|
184
|
+
start_datetime=datetime.datetime(2025, 12, 1),
|
|
185
|
+
end_datetime=datetime.datetime(2026, 1, 1),
|
|
186
|
+
limit=100,
|
|
187
|
+
)
|
|
188
|
+
assert list(frame.columns) == [
|
|
189
|
+
"time", "open", "close", "high", "low", "volume"]
|
|
190
|
+
assert frame["time"].min() == pd.Timestamp("2025-12-01", tz="UTC")
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Config: list endpoints
|
|
194
|
+
|
|
195
|
+
Methods under ``BitfinexAPIConfigListMixin`` return sorted DataFrames.
|
|
196
|
+
|
|
197
|
+
| Method | Endpoint (concept) | Columns |
|
|
198
|
+
|--------|-------------------|---------|
|
|
199
|
+
| ``list_api_currencies`` | ``pub:list:currency`` | ``api_symbol`` |
|
|
200
|
+
| ``list_api_margin_currencies`` | ``pub:list:currency:margin`` | ``api_symbol`` |
|
|
201
|
+
| ``list_api_pairs(market="exchange")`` | ``pub:list:pair:{market}`` | ``instrument``, ``trading_prefix``, ``pair``, ``base_api_symbol``, ``quote_api_symbol`` |
|
|
202
|
+
| ``list_api_competitions`` | ``pub:list:competitions`` | ``competition`` |
|
|
203
|
+
|
|
204
|
+
``market`` must be one of: ``exchange``, ``margin``, ``futures``, ``securities``.
|
|
205
|
+
|
|
206
|
+
**Expected behaviour:**
|
|
207
|
+
|
|
208
|
+
- Empty or missing unwrap → ``BitfinexAPINoneResponseError``.
|
|
209
|
+
- Unparseable pair string → ``BitfinexAPIInvalidParametersError`` from
|
|
210
|
+
``TreatmentPairSymbols``.
|
|
211
|
+
|
|
212
|
+
``list_api_pairs`` performs an extra call to ``list_api_currencies`` to split
|
|
213
|
+
concatenated pair codes.
|
|
214
|
+
|
|
215
|
+
## Config: map endpoints
|
|
216
|
+
|
|
217
|
+
Each ``map_*`` method returns a DataFrame documented on
|
|
218
|
+
``BitfinexAPIConfigMapMixin`` (column tuples such as ``API_CURRENCY_SYMBOLS_COLUMNS``).
|
|
219
|
+
|
|
220
|
+
Common entry points:
|
|
221
|
+
|
|
222
|
+
| Method | Purpose |
|
|
223
|
+
|--------|---------|
|
|
224
|
+
| ``map_api_currency_symbol`` | Wallet code → API symbol |
|
|
225
|
+
| ``map_api_symbol_names`` | Code → display name |
|
|
226
|
+
| ``map_api_currency_symbol_with_names`` | Merge + name backfill + duplicate check |
|
|
227
|
+
| ``map_api_symbol_all`` | One row per code with pool, explorer, fees, … |
|
|
228
|
+
|
|
229
|
+
**Expected behaviour:**
|
|
230
|
+
|
|
231
|
+
- Duplicate ``api_symbol`` after merge → ``BitfinexAPIDataValidationError``.
|
|
232
|
+
- Row-count mismatch after ``map_api_symbol_all`` merge →
|
|
233
|
+
``BitfinexAPIDataValidationError``.
|
|
234
|
+
- Missing display names may be filled from ``CURRENCY_NAME_OVERRIDES``; remaining
|
|
235
|
+
gaps are **logged** at warning (DataFrame may still contain null ``name``).
|
|
236
|
+
|
|
237
|
+
## Config: info endpoints
|
|
238
|
+
|
|
239
|
+
| Method | Columns (summary) |
|
|
240
|
+
|--------|-------------------|
|
|
241
|
+
| ``info_api_pair`` | ``pair``, ``first_trade_ms``, sizes, margins, … |
|
|
242
|
+
| ``info_api_pair_futures`` | Same shape for futures |
|
|
243
|
+
| ``info_api_tx_status`` | Withdrawal/deposit status per rail |
|
|
244
|
+
|
|
245
|
+
Empty body → ``BitfinexAPINoneResponseError``.
|
|
246
|
+
|
|
247
|
+
## Enriched pair listing
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
pairs_enriched = client.list_pair_with_info()
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
**Expected result:**
|
|
254
|
+
|
|
255
|
+
1. ``list_api_pairs()`` — one row per tradable pair (exchange market).
|
|
256
|
+
2. Left joins ``map_api_symbol_all()`` twice: ``base_*`` and ``quote_*``
|
|
257
|
+
columns prefixed on ``base_api_symbol`` / ``quote_api_symbol``.
|
|
258
|
+
|
|
259
|
+
**Operational note:** This orchestration triggers **many** HTTP requests
|
|
260
|
+
(currencies, pairs, and each map table). Cache or call sparingly in tight
|
|
261
|
+
loops.
|
|
262
|
+
|
|
263
|
+
## Platform status
|
|
264
|
+
|
|
265
|
+
```python
|
|
266
|
+
payload = client.platform_status()
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
**Expected result:** ``dict`` with:
|
|
270
|
+
|
|
271
|
+
- ``collected_at`` — ``datetime`` (UTC, naive wall time in object),
|
|
272
|
+
- ``body`` — unwrapped JSON from ``GET platform/status`` (may be ``None``).
|
|
273
|
+
|
|
274
|
+
## Errors and retries
|
|
275
|
+
|
|
276
|
+
| Exception | Typical cause |
|
|
277
|
+
|-----------|----------------|
|
|
278
|
+
| ``BitfinexAPIInvalidParametersError`` | Client-side validation |
|
|
279
|
+
| ``BitfinexAPIDataValidationError`` | Post-processing / merge checks |
|
|
280
|
+
| ``BitfinexAPINoneResponseError`` | Empty conf response |
|
|
281
|
+
| ``BitfinexAPITooManyRequestsError`` | Rate limit (retried with long wait) |
|
|
282
|
+
| ``BitfinexAPIBitfinexInvalidParametersError`` | Bitfinex rejected params |
|
|
283
|
+
| ``BitfinexAPIRequestError`` | Other HTTP errors |
|
|
284
|
+
| ``BitfinexAPIAuthenticationError`` | Missing credentials when auth required |
|
|
285
|
+
| ``NotImplementedError`` | ``authenticated=True`` (signing not implemented) |
|
|
286
|
+
|
|
287
|
+
Exceptions expose ``message``, ``payload``, and ``to_dict()`` for workers.
|
|
288
|
+
|
|
289
|
+
**Retries (tenacity):** Connection errors, timeouts, and rate-limit errors
|
|
290
|
+
retry up to ``BITFINEX__REQUEST_MAX_ATTEMPTS``. Rate-limit waits use
|
|
291
|
+
``BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT`` (default **61** seconds).
|
|
292
|
+
|
|
293
|
+
## Configuration (environment)
|
|
294
|
+
|
|
295
|
+
| Variable | Default | Used for |
|
|
296
|
+
|----------|---------|----------|
|
|
297
|
+
| ``BITFINEX__REQUEST_TIMEOUT`` | `60` | Seconds per HTTP request |
|
|
298
|
+
| ``BITFINEX__REQUEST_MAX_ATTEMPTS`` | `5` | Max retries on network errors |
|
|
299
|
+
| ``BITFINEX__REQUEST_RETRY_MIN_WAIT`` | `0.5` | Seconds between retries |
|
|
300
|
+
| ``BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT`` | `61` | Wait before retry on 429 |
|
|
301
|
+
| ``BITFINEX__PROXY_URL`` | _(unset)_ | Optional HTTP(S) proxy |
|
|
302
|
+
|
|
303
|
+
Invalid positive values raise ``ValueError`` at **import** of
|
|
304
|
+
``bitfinex_api.config``.
|
|
305
|
+
|
|
306
|
+
## Tests
|
|
307
|
+
|
|
308
|
+
Unit tests (no network):
|
|
309
|
+
|
|
310
|
+
```bash
|
|
311
|
+
PYENV_VERSION=bitfinex-api python -m pytest tests/test__exceptions.py -q
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Integration tests (live Bitfinex API):
|
|
315
|
+
|
|
316
|
+
1. Copy ``test_parameters.template`` to ``test_parameters.secrets`` if needed.
|
|
317
|
+
2. Run:
|
|
318
|
+
|
|
319
|
+
```bash
|
|
320
|
+
set -a && source test_parameters.secrets && set +a
|
|
321
|
+
python -m unittest discover -s tests -v
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
Candle and config tests call the public API and require network access.
|
|
325
|
+
|
|
326
|
+
## Development and release
|
|
327
|
+
|
|
328
|
+
```bash
|
|
329
|
+
ruff check src/
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Release build (increments patch in ``VERSION``, renders ``pyproject.toml``,
|
|
333
|
+
tags, pushes—see ``build.sh``):
|
|
334
|
+
|
|
335
|
+
```bash
|
|
336
|
+
./build.sh
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
Package history: [CHANGELOG.md](CHANGELOG.md).
|
|
340
|
+
|
|
341
|
+
## License
|
|
342
|
+
|
|
343
|
+
BSD-3-Clause — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
# bitfinex-api
|
|
2
|
+
|
|
3
|
+
Python client for [Bitfinex REST API v2](https://docs.bitfinex.com/docs/rest-general)
|
|
4
|
+
public endpoints used in Murabei crawlers and market-data workflows.
|
|
5
|
+
|
|
6
|
+
## Objective and motivation
|
|
7
|
+
|
|
8
|
+
This library turns Bitfinex **public** HTTP responses into **pandas**
|
|
9
|
+
DataFrames (or JSON for low-level calls), with retries, timeouts, and typed
|
|
10
|
+
errors suitable for ETL and crawlers.
|
|
11
|
+
|
|
12
|
+
### Why this exists
|
|
13
|
+
|
|
14
|
+
Crawler workers need stable access to **candles**, **pair lists**, and
|
|
15
|
+
**currency metadata** without re-implementing Bitfinex URL layout, pagination,
|
|
16
|
+
rate limits, and error payloads on every project.
|
|
17
|
+
|
|
18
|
+
### How it is used
|
|
19
|
+
|
|
20
|
+
- Instantiate ``BitfinexAPI`` once per worker run or notebook session.
|
|
21
|
+
- Call high-level methods (``get_trade_candles``, ``list_api_pairs``,
|
|
22
|
+
``map_api_symbol_all``, …) and load the returned DataFrames.
|
|
23
|
+
- Catch ``bitfinex_api.exceptions`` types to branch on rate limits, invalid
|
|
24
|
+
parameters, or validation failures.
|
|
25
|
+
|
|
26
|
+
### Scope
|
|
27
|
+
|
|
28
|
+
| In scope | Out of scope |
|
|
29
|
+
|----------|----------------|
|
|
30
|
+
| Public ``api-pub.bitfinex.com`` paths | Private trading (orders, wallets) |
|
|
31
|
+
| ``conf/pub:*`` metadata | WebSocket feeds |
|
|
32
|
+
| Trade candle ``/hist`` pagination | v2 request signing (not implemented) |
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
From a built wheel:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install dist/*.whl
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
From source (Poetry):
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install poetry
|
|
46
|
+
export VERSION=$(grep -E '^VERSION=' VERSION | cut -d'=' -f2-)
|
|
47
|
+
sed -e 's#{VERSION}#'"${VERSION}"'#g' pyproject_template.toml > pyproject.toml
|
|
48
|
+
poetry build
|
|
49
|
+
pip install dist/*.whl
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Quick start
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from bitfinex_api import BitfinexAPI
|
|
56
|
+
|
|
57
|
+
client = BitfinexAPI()
|
|
58
|
+
|
|
59
|
+
# Platform status (dict with UTC collected_at + body)
|
|
60
|
+
status = client.platform_status()
|
|
61
|
+
|
|
62
|
+
# One hour BTC/USD candles for the last 7 days
|
|
63
|
+
import datetime
|
|
64
|
+
candles = client.get_trade_candles(
|
|
65
|
+
base_symbol="BTC",
|
|
66
|
+
quote_symbol="USD",
|
|
67
|
+
period="1h",
|
|
68
|
+
start_delta=datetime.timedelta(days=7),
|
|
69
|
+
)
|
|
70
|
+
print(candles.head())
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Client overview
|
|
74
|
+
|
|
75
|
+
``BitfinexAPI`` combines three mixins:
|
|
76
|
+
|
|
77
|
+
| Mixin | Role |
|
|
78
|
+
|-------|------|
|
|
79
|
+
| ``BitfinexAPIBaseMixin`` | Session, ``get`` / ``post``, retries |
|
|
80
|
+
| ``BitfinexAPICandlesMixin`` | Trade candle history |
|
|
81
|
+
| ``BitfinexAPIConfigMixin`` | ``conf`` list, map, info helpers |
|
|
82
|
+
|
|
83
|
+
Import:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from bitfinex_api import BitfinexAPI
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Optional constructor arguments ``api_key`` and ``api_secret`` are **stored only**
|
|
90
|
+
for future signed calls. Passing ``authenticated=True`` on ``get`` / ``post``
|
|
91
|
+
raises ``NotImplementedError`` once credentials are set (signing not shipped).
|
|
92
|
+
|
|
93
|
+
## Low-level HTTP
|
|
94
|
+
|
|
95
|
+
Use ``get`` when no helper exists yet:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
body = client.get(
|
|
99
|
+
endpoint="tickers",
|
|
100
|
+
query_params={"symbols": "tBTCUSD"},
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
- ``endpoint`` is joined onto ``https://api-pub.bitfinex.com/v2/``.
|
|
105
|
+
- Returns parsed JSON (``list`` or ``dict``).
|
|
106
|
+
- Non-OK responses raise subclasses of ``BitfinexAPIRequestError`` (see
|
|
107
|
+
**Errors and retries**).
|
|
108
|
+
|
|
109
|
+
## Trade candles
|
|
110
|
+
|
|
111
|
+
### Method
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
frame = client.get_trade_candles(
|
|
115
|
+
base_symbol="BTC",
|
|
116
|
+
quote_symbol="USD",
|
|
117
|
+
period="1h", # see AVAILABLE_CANDLE_PERIODS on the mixin
|
|
118
|
+
start_delta=None, # or start_datetime=...
|
|
119
|
+
start_datetime=None,
|
|
120
|
+
end_datetime=None, # default: now (UTC)
|
|
121
|
+
limit=10000, # per HTTP page
|
|
122
|
+
)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
**Time window:** Provide exactly one of:
|
|
126
|
+
|
|
127
|
+
- ``start_delta`` — length ending at ``end_datetime`` or now, or
|
|
128
|
+
- ``start_datetime`` — inclusive start (``str`` or ``datetime``; converted to
|
|
129
|
+
UTC).
|
|
130
|
+
|
|
131
|
+
**Pair path:** Built as ``t{base}{quote}`` (e.g. ``tBTCUSD``).
|
|
132
|
+
|
|
133
|
+
### Expected result
|
|
134
|
+
|
|
135
|
+
| Column | Type (typical) | Description |
|
|
136
|
+
|--------|----------------|-------------|
|
|
137
|
+
| ``time`` | UTC timestamp | Bar open time |
|
|
138
|
+
| ``open`` | float | Open |
|
|
139
|
+
| ``close`` | float | Close |
|
|
140
|
+
| ``high`` | float | High |
|
|
141
|
+
| ``low`` | float | Low |
|
|
142
|
+
| ``volume`` | float | Volume |
|
|
143
|
+
|
|
144
|
+
- **Empty window:** DataFrame with these columns and **zero rows** (schema
|
|
145
|
+
preserved).
|
|
146
|
+
- **Pagination:** Long ranges issue multiple ``/hist`` calls. Progress is
|
|
147
|
+
logged at ``info`` level.
|
|
148
|
+
- **Stall guard:** If the API stops advancing ``mts``, the client logs a
|
|
149
|
+
**warning** and returns **partial** data collected so far. Treat logs as the
|
|
150
|
+
signal that the window may be incomplete.
|
|
151
|
+
- **Invalid client args:** ``BitfinexAPIInvalidParametersError`` (bad period or
|
|
152
|
+
conflicting time args).
|
|
153
|
+
- **Invalid range on API:** Often ``BitfinexAPIBitfinexInvalidParametersError``
|
|
154
|
+
(HTTP 500 / Bitfinex code 10020).
|
|
155
|
+
|
|
156
|
+
### Example
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
import datetime
|
|
160
|
+
import pandas as pd
|
|
161
|
+
|
|
162
|
+
frame = client.get_trade_candles(
|
|
163
|
+
base_symbol="BTC",
|
|
164
|
+
quote_symbol="USD",
|
|
165
|
+
period="1h",
|
|
166
|
+
start_datetime=datetime.datetime(2025, 12, 1),
|
|
167
|
+
end_datetime=datetime.datetime(2026, 1, 1),
|
|
168
|
+
limit=100,
|
|
169
|
+
)
|
|
170
|
+
assert list(frame.columns) == [
|
|
171
|
+
"time", "open", "close", "high", "low", "volume"]
|
|
172
|
+
assert frame["time"].min() == pd.Timestamp("2025-12-01", tz="UTC")
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Config: list endpoints
|
|
176
|
+
|
|
177
|
+
Methods under ``BitfinexAPIConfigListMixin`` return sorted DataFrames.
|
|
178
|
+
|
|
179
|
+
| Method | Endpoint (concept) | Columns |
|
|
180
|
+
|--------|-------------------|---------|
|
|
181
|
+
| ``list_api_currencies`` | ``pub:list:currency`` | ``api_symbol`` |
|
|
182
|
+
| ``list_api_margin_currencies`` | ``pub:list:currency:margin`` | ``api_symbol`` |
|
|
183
|
+
| ``list_api_pairs(market="exchange")`` | ``pub:list:pair:{market}`` | ``instrument``, ``trading_prefix``, ``pair``, ``base_api_symbol``, ``quote_api_symbol`` |
|
|
184
|
+
| ``list_api_competitions`` | ``pub:list:competitions`` | ``competition`` |
|
|
185
|
+
|
|
186
|
+
``market`` must be one of: ``exchange``, ``margin``, ``futures``, ``securities``.
|
|
187
|
+
|
|
188
|
+
**Expected behaviour:**
|
|
189
|
+
|
|
190
|
+
- Empty or missing unwrap → ``BitfinexAPINoneResponseError``.
|
|
191
|
+
- Unparseable pair string → ``BitfinexAPIInvalidParametersError`` from
|
|
192
|
+
``TreatmentPairSymbols``.
|
|
193
|
+
|
|
194
|
+
``list_api_pairs`` performs an extra call to ``list_api_currencies`` to split
|
|
195
|
+
concatenated pair codes.
|
|
196
|
+
|
|
197
|
+
## Config: map endpoints
|
|
198
|
+
|
|
199
|
+
Each ``map_*`` method returns a DataFrame documented on
|
|
200
|
+
``BitfinexAPIConfigMapMixin`` (column tuples such as ``API_CURRENCY_SYMBOLS_COLUMNS``).
|
|
201
|
+
|
|
202
|
+
Common entry points:
|
|
203
|
+
|
|
204
|
+
| Method | Purpose |
|
|
205
|
+
|--------|---------|
|
|
206
|
+
| ``map_api_currency_symbol`` | Wallet code → API symbol |
|
|
207
|
+
| ``map_api_symbol_names`` | Code → display name |
|
|
208
|
+
| ``map_api_currency_symbol_with_names`` | Merge + name backfill + duplicate check |
|
|
209
|
+
| ``map_api_symbol_all`` | One row per code with pool, explorer, fees, … |
|
|
210
|
+
|
|
211
|
+
**Expected behaviour:**
|
|
212
|
+
|
|
213
|
+
- Duplicate ``api_symbol`` after merge → ``BitfinexAPIDataValidationError``.
|
|
214
|
+
- Row-count mismatch after ``map_api_symbol_all`` merge →
|
|
215
|
+
``BitfinexAPIDataValidationError``.
|
|
216
|
+
- Missing display names may be filled from ``CURRENCY_NAME_OVERRIDES``; remaining
|
|
217
|
+
gaps are **logged** at warning (DataFrame may still contain null ``name``).
|
|
218
|
+
|
|
219
|
+
## Config: info endpoints
|
|
220
|
+
|
|
221
|
+
| Method | Columns (summary) |
|
|
222
|
+
|--------|-------------------|
|
|
223
|
+
| ``info_api_pair`` | ``pair``, ``first_trade_ms``, sizes, margins, … |
|
|
224
|
+
| ``info_api_pair_futures`` | Same shape for futures |
|
|
225
|
+
| ``info_api_tx_status`` | Withdrawal/deposit status per rail |
|
|
226
|
+
|
|
227
|
+
Empty body → ``BitfinexAPINoneResponseError``.
|
|
228
|
+
|
|
229
|
+
## Enriched pair listing
|
|
230
|
+
|
|
231
|
+
```python
|
|
232
|
+
pairs_enriched = client.list_pair_with_info()
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
**Expected result:**
|
|
236
|
+
|
|
237
|
+
1. ``list_api_pairs()`` — one row per tradable pair (exchange market).
|
|
238
|
+
2. Left joins ``map_api_symbol_all()`` twice: ``base_*`` and ``quote_*``
|
|
239
|
+
columns prefixed on ``base_api_symbol`` / ``quote_api_symbol``.
|
|
240
|
+
|
|
241
|
+
**Operational note:** This orchestration triggers **many** HTTP requests
|
|
242
|
+
(currencies, pairs, and each map table). Cache or call sparingly in tight
|
|
243
|
+
loops.
|
|
244
|
+
|
|
245
|
+
## Platform status
|
|
246
|
+
|
|
247
|
+
```python
|
|
248
|
+
payload = client.platform_status()
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
**Expected result:** ``dict`` with:
|
|
252
|
+
|
|
253
|
+
- ``collected_at`` — ``datetime`` (UTC, naive wall time in object),
|
|
254
|
+
- ``body`` — unwrapped JSON from ``GET platform/status`` (may be ``None``).
|
|
255
|
+
|
|
256
|
+
## Errors and retries
|
|
257
|
+
|
|
258
|
+
| Exception | Typical cause |
|
|
259
|
+
|-----------|----------------|
|
|
260
|
+
| ``BitfinexAPIInvalidParametersError`` | Client-side validation |
|
|
261
|
+
| ``BitfinexAPIDataValidationError`` | Post-processing / merge checks |
|
|
262
|
+
| ``BitfinexAPINoneResponseError`` | Empty conf response |
|
|
263
|
+
| ``BitfinexAPITooManyRequestsError`` | Rate limit (retried with long wait) |
|
|
264
|
+
| ``BitfinexAPIBitfinexInvalidParametersError`` | Bitfinex rejected params |
|
|
265
|
+
| ``BitfinexAPIRequestError`` | Other HTTP errors |
|
|
266
|
+
| ``BitfinexAPIAuthenticationError`` | Missing credentials when auth required |
|
|
267
|
+
| ``NotImplementedError`` | ``authenticated=True`` (signing not implemented) |
|
|
268
|
+
|
|
269
|
+
Exceptions expose ``message``, ``payload``, and ``to_dict()`` for workers.
|
|
270
|
+
|
|
271
|
+
**Retries (tenacity):** Connection errors, timeouts, and rate-limit errors
|
|
272
|
+
retry up to ``BITFINEX__REQUEST_MAX_ATTEMPTS``. Rate-limit waits use
|
|
273
|
+
``BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT`` (default **61** seconds).
|
|
274
|
+
|
|
275
|
+
## Configuration (environment)
|
|
276
|
+
|
|
277
|
+
| Variable | Default | Used for |
|
|
278
|
+
|----------|---------|----------|
|
|
279
|
+
| ``BITFINEX__REQUEST_TIMEOUT`` | `60` | Seconds per HTTP request |
|
|
280
|
+
| ``BITFINEX__REQUEST_MAX_ATTEMPTS`` | `5` | Max retries on network errors |
|
|
281
|
+
| ``BITFINEX__REQUEST_RETRY_MIN_WAIT`` | `0.5` | Seconds between retries |
|
|
282
|
+
| ``BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT`` | `61` | Wait before retry on 429 |
|
|
283
|
+
| ``BITFINEX__PROXY_URL`` | _(unset)_ | Optional HTTP(S) proxy |
|
|
284
|
+
|
|
285
|
+
Invalid positive values raise ``ValueError`` at **import** of
|
|
286
|
+
``bitfinex_api.config``.
|
|
287
|
+
|
|
288
|
+
## Tests
|
|
289
|
+
|
|
290
|
+
Unit tests (no network):
|
|
291
|
+
|
|
292
|
+
```bash
|
|
293
|
+
PYENV_VERSION=bitfinex-api python -m pytest tests/test__exceptions.py -q
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Integration tests (live Bitfinex API):
|
|
297
|
+
|
|
298
|
+
1. Copy ``test_parameters.template`` to ``test_parameters.secrets`` if needed.
|
|
299
|
+
2. Run:
|
|
300
|
+
|
|
301
|
+
```bash
|
|
302
|
+
set -a && source test_parameters.secrets && set +a
|
|
303
|
+
python -m unittest discover -s tests -v
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Candle and config tests call the public API and require network access.
|
|
307
|
+
|
|
308
|
+
## Development and release
|
|
309
|
+
|
|
310
|
+
```bash
|
|
311
|
+
ruff check src/
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Release build (increments patch in ``VERSION``, renders ``pyproject.toml``,
|
|
315
|
+
tags, pushes—see ``build.sh``):
|
|
316
|
+
|
|
317
|
+
```bash
|
|
318
|
+
./build.sh
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Package history: [CHANGELOG.md](CHANGELOG.md).
|
|
322
|
+
|
|
323
|
+
## License
|
|
324
|
+
|
|
325
|
+
BSD-3-Clause — see [LICENSE](LICENSE).
|