bitfinex-api 0.0.2__py3-none-any.whl

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.
@@ -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,24 @@
1
+ bitfinex_api/__init__.py,sha256=Tav_3DTX6p0zBfoTqcpRPPV8SBq4ev61ozF6yQ0ED5U,515
2
+ bitfinex_api/aux/__init__.py,sha256=41zDswrA-WHC-VexhrYVd2-LqqIv9vC3DsTF1jvb7jw,321
3
+ bitfinex_api/aux/base.py,sha256=QY-SsYXlrmY7ycDq3ZiA5qwjI1_bqpt9vHwT2vuGSzU,8614
4
+ bitfinex_api/aux/candles/__init__.py,sha256=zgRj5A20oGOngU5aECOw5Pq58funIJ_m8429gvyL0_E,154
5
+ bitfinex_api/aux/candles/candles.py,sha256=H_t9Xi3phmbLBjGhbznlEtxX8vQDm8cYk79awl4Qzpc,9657
6
+ bitfinex_api/aux/config/__init__.py,sha256=_GWXKLPztrSaT9sPgJQttFB79XlI7LX7ehdTBF2ia80,833
7
+ bitfinex_api/aux/config/config.py,sha256=mKGwZPsPAj1d-5iZaFMz7Z4uAxSBi6rxj2fxv-toO_4,1080
8
+ bitfinex_api/aux/config/config_base.py,sha256=HIDVWRYzIx6Rvyky6BK7omWVNC2B02s-vDXA0MAoph8,1564
9
+ bitfinex_api/aux/config/config_info.py,sha256=TTCdrZsNkLxIgI4Pn1B9JOsRoCDd6r2ndB-2b1-RbwE,3881
10
+ bitfinex_api/aux/config/config_list.py,sha256=2Xjp94_k7vdJqqsoq8fKKYb4hJkgfQS3art5nf36gJg,3291
11
+ bitfinex_api/aux/config/config_map.py,sha256=4pd_kUe7Bf8Hv5w_DyNqDf4q8Vwar-JCnwGLETe-tNo,14369
12
+ bitfinex_api/aux/config/contracts.py,sha256=nMjx4PJF1c0JS_ng8Aq29GN7Q8BLOoM3KFpGGSNbTcA,1062
13
+ bitfinex_api/aux/config/treatment/__init__.py,sha256=G1X9kLKTzj8j6LUQ2aYjL4t8lyWxecYC76KJmlpyOdI,185
14
+ bitfinex_api/aux/config/treatment/pair_symbols.py,sha256=zaUsVHN-Qj1zPbxjpxTRec4pbjNJc7pcTr_fbQTFWac,4432
15
+ bitfinex_api/aux/misc/__init__.py,sha256=lYnZrfuFqYSj1KEpS3bg9_IVLjWztGXMseM1UtweRyM,208
16
+ bitfinex_api/aux/misc/datetime_aux.py,sha256=bVSq_CNh3yf3JKgsszEk45luRCCgaw6YHo4jn-7a0b0,1146
17
+ bitfinex_api/config.py,sha256=OYM2p_VEsKzgQHcVNh-NZWCIbBMQeDnlP0a99VOu5Mw,2803
18
+ bitfinex_api/data.py,sha256=etgwL3aYqXMhPSacpb4u_P3Y_OzBlePlclZfuwtvavg,610
19
+ bitfinex_api/exceptions.py,sha256=fnr_2rCVPtCpjqrX9RkBtQD2GVDk3lGtnYXXfGgGFk0,10193
20
+ bitfinex_api/run_tests.bash,sha256=tLu3y4SQKkBF5lR-M4ytNplGuQIBjI-FZXXjld8_jWk,35
21
+ bitfinex_api-0.0.2.dist-info/METADATA,sha256=cAiv3n17jil5jaj7Ko6sgkBs7HVIU8XiFBZw9WzOfF0,10544
22
+ bitfinex_api-0.0.2.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
23
+ bitfinex_api-0.0.2.dist-info/licenses/LICENSE,sha256=k3c5NO7TRJzr7kiHw-EPMO_T0fTw4WTbZtk-rwr7_hA,1506
24
+ bitfinex_api-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.5.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.