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.
- bitfinex_api/__init__.py +17 -0
- bitfinex_api/aux/__init__.py +11 -0
- bitfinex_api/aux/base.py +241 -0
- bitfinex_api/aux/candles/__init__.py +7 -0
- bitfinex_api/aux/candles/candles.py +242 -0
- bitfinex_api/aux/config/__init__.py +23 -0
- bitfinex_api/aux/config/config.py +28 -0
- bitfinex_api/aux/config/config_base.py +45 -0
- bitfinex_api/aux/config/config_info.py +98 -0
- bitfinex_api/aux/config/config_list.py +68 -0
- bitfinex_api/aux/config/config_map.py +340 -0
- bitfinex_api/aux/config/contracts.py +31 -0
- bitfinex_api/aux/config/treatment/__init__.py +7 -0
- bitfinex_api/aux/config/treatment/pair_symbols.py +130 -0
- bitfinex_api/aux/misc/__init__.py +5 -0
- bitfinex_api/aux/misc/datetime_aux.py +33 -0
- bitfinex_api/config.py +94 -0
- bitfinex_api/data.py +17 -0
- bitfinex_api/exceptions.py +284 -0
- bitfinex_api/run_tests.bash +1 -0
- bitfinex_api-0.0.2.dist-info/METADATA +343 -0
- bitfinex_api-0.0.2.dist-info/RECORD +24 -0
- bitfinex_api-0.0.2.dist-info/WHEEL +4 -0
- bitfinex_api-0.0.2.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Datetime conversions for Bitfinex API (epoch ms and pandas timestamps)."""
|
|
2
|
+
import datetime
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from pandas import Timestamp
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def datetime_to_epoch_ms(value: datetime.datetime | Timestamp) -> int:
|
|
8
|
+
"""UTC epoch milliseconds for Bitfinex ``start`` / ``end`` query params.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
value (datetime.datetime | Timestamp):
|
|
12
|
+
Instant converted to UTC before scaling to milliseconds.
|
|
13
|
+
|
|
14
|
+
Returns:
|
|
15
|
+
int:
|
|
16
|
+
Epoch milliseconds.
|
|
17
|
+
"""
|
|
18
|
+
# Convert the value to a datetime.datetime object if it is a Timestamp
|
|
19
|
+
# to latter extract the milliseconds.
|
|
20
|
+
if isinstance(value, Timestamp):
|
|
21
|
+
value = value.to_pydatetime()
|
|
22
|
+
|
|
23
|
+
# Convert the value to UTC timezone if it is not already.
|
|
24
|
+
if value.tzinfo is None:
|
|
25
|
+
value = value.replace(tzinfo=datetime.timezone.utc)
|
|
26
|
+
else:
|
|
27
|
+
value = value.astimezone(datetime.timezone.utc)
|
|
28
|
+
return int(value.timestamp() * 1000)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def epoch_ms_to_timestamp(value: int | pd.Series) -> Timestamp | pd.Series:
|
|
32
|
+
"""UTC pandas ``timestamp`` from Bitfinex candle ``mts`` (epoch ms)."""
|
|
33
|
+
return pd.to_datetime(value, unit="ms", utc=True)
|
bitfinex_api/config.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Timeout and retry settings for the Bitfinex client."""
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _positive_int(name: str, default: int) -> int:
|
|
6
|
+
"""Read a positive integer from the environment.
|
|
7
|
+
|
|
8
|
+
A missing or blank value returns ``default``.
|
|
9
|
+
|
|
10
|
+
Args:
|
|
11
|
+
name (str):
|
|
12
|
+
Environment variable name.
|
|
13
|
+
default (int):
|
|
14
|
+
Value used when the variable is missing or blank.
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
int:
|
|
18
|
+
Parsed positive integer.
|
|
19
|
+
|
|
20
|
+
Raises:
|
|
21
|
+
ValueError:
|
|
22
|
+
If the value is not a positive integer.
|
|
23
|
+
"""
|
|
24
|
+
raw = os.getenv(name)
|
|
25
|
+
if raw is None or raw.strip() == "":
|
|
26
|
+
return default
|
|
27
|
+
try:
|
|
28
|
+
value = int(raw)
|
|
29
|
+
except ValueError:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
"{name} must be a positive integer. Got {raw}.".format(
|
|
32
|
+
name=name, raw=raw)) from None
|
|
33
|
+
if value < 1:
|
|
34
|
+
raise ValueError(
|
|
35
|
+
"{name} must be a positive integer. Got {raw}.".format(
|
|
36
|
+
name=name, raw=raw))
|
|
37
|
+
return value
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _positive_float(name: str, default: float) -> float:
|
|
41
|
+
"""Read a positive float from the environment.
|
|
42
|
+
|
|
43
|
+
A missing or blank value returns ``default``.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
name (str):
|
|
47
|
+
Environment variable name.
|
|
48
|
+
default (float):
|
|
49
|
+
Value used when the variable is missing or blank.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
float:
|
|
53
|
+
Parsed positive float.
|
|
54
|
+
|
|
55
|
+
Raises:
|
|
56
|
+
ValueError:
|
|
57
|
+
If the value is not a positive float.
|
|
58
|
+
"""
|
|
59
|
+
raw = os.getenv(name)
|
|
60
|
+
if raw is None or raw.strip() == "":
|
|
61
|
+
return default
|
|
62
|
+
try:
|
|
63
|
+
value = float(raw)
|
|
64
|
+
except ValueError:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"{name} must be a positive number. Got {raw}.".format(
|
|
67
|
+
name=name, raw=raw)) from None
|
|
68
|
+
if value <= 0:
|
|
69
|
+
raise ValueError(
|
|
70
|
+
"{name} must be a positive number. Got {raw}.".format(
|
|
71
|
+
name=name, raw=raw))
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
BITFINEX__REQUEST_TIMEOUT: int = _positive_int(
|
|
76
|
+
"BITFINEX__REQUEST_TIMEOUT", 60)
|
|
77
|
+
"""Seconds to wait for a single Bitfinex HTTP request."""
|
|
78
|
+
|
|
79
|
+
BITFINEX__PROXY_URL: str | None = os.environ.get(
|
|
80
|
+
"BITFINEX__PROXY_URL", None)
|
|
81
|
+
"""URL of the proxy to use for requests to Bitfinex."""
|
|
82
|
+
|
|
83
|
+
BITFINEX__REQUEST_MAX_ATTEMPTS: int = _positive_int(
|
|
84
|
+
"BITFINEX__REQUEST_MAX_ATTEMPTS", 5)
|
|
85
|
+
"""Maximum number of HTTP attempts before giving up on a network error."""
|
|
86
|
+
|
|
87
|
+
BITFINEX__REQUEST_RETRY_MIN_WAIT: float = _positive_float(
|
|
88
|
+
"BITFINEX__REQUEST_RETRY_MIN_WAIT", 0.5)
|
|
89
|
+
"""Minimum wait time between HTTP attempts in seconds."""
|
|
90
|
+
|
|
91
|
+
# Add one second to avoid rate limit, the limit is exactly one minute.
|
|
92
|
+
BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT: float = _positive_float(
|
|
93
|
+
"BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT", 61.0)
|
|
94
|
+
"""Sleep before retry on ``BitfinexAPITooManyRequestsError`` (seconds)."""
|
bitfinex_api/data.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Bitfinex REST API client."""
|
|
2
|
+
from bitfinex_api.aux import (
|
|
3
|
+
BitfinexAPIBaseMixin, BitfinexAPICandlesMixin, BitfinexAPIConfigMixin)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BitfinexAPI(
|
|
7
|
+
BitfinexAPIBaseMixin,
|
|
8
|
+
BitfinexAPICandlesMixin,
|
|
9
|
+
BitfinexAPIConfigMixin):
|
|
10
|
+
"""Bitfinex REST API v2 client (public endpoints and config metadata).
|
|
11
|
+
|
|
12
|
+
Composes HTTP transport (``BitfinexAPIBaseMixin``), trade candles
|
|
13
|
+
(``BitfinexAPICandlesMixin``), and ``conf`` list/map/info helpers
|
|
14
|
+
(``BitfinexAPIConfigMixin``). Public calls need no credentials; signed
|
|
15
|
+
private endpoints are not implemented yet.
|
|
16
|
+
"""
|
|
17
|
+
pass
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Exceptions for Bitfinex HTTP client errors."""
|
|
2
|
+
import requests
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _format_api_error_body(response_payload: Any) -> str:
|
|
7
|
+
"""Human-readable error text from a parsed Bitfinex HTTP error body.
|
|
8
|
+
|
|
9
|
+
Args:
|
|
10
|
+
response_payload (Any):
|
|
11
|
+
JSON body after ``response.json()`` on a failed call.
|
|
12
|
+
|
|
13
|
+
Returns:
|
|
14
|
+
str:
|
|
15
|
+
Message suitable for exception templates keyed by ``error``.
|
|
16
|
+
"""
|
|
17
|
+
if isinstance(response_payload, list) and len(response_payload) == 3:
|
|
18
|
+
return str(response_payload[2])
|
|
19
|
+
return str(response_payload)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BitfinexAPIError(Exception):
|
|
23
|
+
"""Base exception for Bitfinex API client errors.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
message (str):
|
|
27
|
+
Human-readable error description.
|
|
28
|
+
payload (dict):
|
|
29
|
+
Optional context returned by the API or client.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __repr__(self) -> str:
|
|
33
|
+
"""Return the exception representation."""
|
|
34
|
+
template = "{class_name}: {message}"
|
|
35
|
+
message = self.format_message()
|
|
36
|
+
return template.format(
|
|
37
|
+
class_name=self.__class__.__name__,
|
|
38
|
+
message=message)
|
|
39
|
+
|
|
40
|
+
def __str__(self) -> str:
|
|
41
|
+
"""Return the string representation of the exception."""
|
|
42
|
+
return self.__repr__()
|
|
43
|
+
|
|
44
|
+
def __init__(self, message: str, payload: dict | None = None) -> None:
|
|
45
|
+
"""Initialize the exception."""
|
|
46
|
+
self.message = message
|
|
47
|
+
if payload is None:
|
|
48
|
+
payload = {}
|
|
49
|
+
self.payload = payload
|
|
50
|
+
|
|
51
|
+
def format_message(self) -> str:
|
|
52
|
+
"""Fill message placeholders from the payload."""
|
|
53
|
+
try:
|
|
54
|
+
return self.message.format(**self.payload)
|
|
55
|
+
except (KeyError, IndexError, ValueError):
|
|
56
|
+
return self.message
|
|
57
|
+
|
|
58
|
+
def to_dict(self) -> dict[str, object]:
|
|
59
|
+
"""Serialize the exception to a dictionary."""
|
|
60
|
+
message = self.format_message()
|
|
61
|
+
return {
|
|
62
|
+
"payload": self.payload,
|
|
63
|
+
"type": self.__class__.__name__,
|
|
64
|
+
"message": message}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class BitfinexAPIInvalidParametersError(BitfinexAPIError):
|
|
68
|
+
"""Exception for invalid parameters errors."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class BitfinexAPIDataValidationError(BitfinexAPIError):
|
|
72
|
+
"""Exception for data validation errors."""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# Request-related errors
|
|
76
|
+
class BitfinexAPIRequestError(BitfinexAPIError):
|
|
77
|
+
"""Exception for a failed Bitfinex HTTP response."""
|
|
78
|
+
|
|
79
|
+
response_status_code: list[int] | None = None
|
|
80
|
+
"""The HTTP status code of the response."""
|
|
81
|
+
|
|
82
|
+
bitfinex_error_code: list[int] | None = None
|
|
83
|
+
"""The Bitfinex error code of the response."""
|
|
84
|
+
|
|
85
|
+
message_template: str = "Error fetching data from {url}: {error}"
|
|
86
|
+
"""The message template for the exception."""
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def raise_by_code(cls, response: requests.Response,
|
|
90
|
+
response_payload: list | Any | None = None) -> None:
|
|
91
|
+
"""Raise this exception when filters match the HTTP response.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
response (requests.Response):
|
|
95
|
+
Failed HTTP response (``response.ok`` is false).
|
|
96
|
+
response_payload (list | Any | None):
|
|
97
|
+
Parsed JSON body; defaults to empty list when ``None``.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
None:
|
|
101
|
+
When status or Bitfinex code filters do not match.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
NotImplementedError:
|
|
105
|
+
When the subclass has no status or code filters.
|
|
106
|
+
cls:
|
|
107
|
+
When HTTP status and Bitfinex code filters match the payload.
|
|
108
|
+
"""
|
|
109
|
+
is_both_none = (
|
|
110
|
+
cls.response_status_code is None and
|
|
111
|
+
cls.bitfinex_error_code is None)
|
|
112
|
+
if is_both_none:
|
|
113
|
+
msg = (
|
|
114
|
+
"response_status_code and bitfinex_error_code are not set. "
|
|
115
|
+
"It is not possible to use raise_by_code.")
|
|
116
|
+
raise NotImplementedError(msg)
|
|
117
|
+
|
|
118
|
+
response_payload = (
|
|
119
|
+
response_payload
|
|
120
|
+
if response_payload is not None
|
|
121
|
+
else [])
|
|
122
|
+
|
|
123
|
+
# Check if the request status code matches the expected status codes.
|
|
124
|
+
is_request_status_code = (
|
|
125
|
+
(response.status_code in cls.response_status_code) or
|
|
126
|
+
(cls.response_status_code is None))
|
|
127
|
+
|
|
128
|
+
# When Bitfinex code filters are set, require a parsed code to match.
|
|
129
|
+
bitfinex_error_code: int | None = None
|
|
130
|
+
bitfinex_error_message: str | None = None
|
|
131
|
+
is_bitfinex_error_code = cls.bitfinex_error_code is None
|
|
132
|
+
if isinstance(response_payload, list) and len(response_payload) == 3:
|
|
133
|
+
_, bitfinex_error_code, bitfinex_error_message = response_payload
|
|
134
|
+
is_bitfinex_error_code = (
|
|
135
|
+
(bitfinex_error_code in cls.bitfinex_error_code) or
|
|
136
|
+
(cls.bitfinex_error_code is None))
|
|
137
|
+
|
|
138
|
+
if is_request_status_code and is_bitfinex_error_code:
|
|
139
|
+
error_payload = {
|
|
140
|
+
'url': response.url,
|
|
141
|
+
'bitfinex_error_message': bitfinex_error_message,
|
|
142
|
+
'bitfinex_error_code': bitfinex_error_code}
|
|
143
|
+
raise cls(
|
|
144
|
+
message=cls.message_template,
|
|
145
|
+
payload=error_payload)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class BitfinexAPIAuthenticationError(BitfinexAPIRequestError):
|
|
149
|
+
"""Exception for missing or invalid Bitfinex API credentials."""
|
|
150
|
+
|
|
151
|
+
response_status_code = None
|
|
152
|
+
"""The HTTP status code of the response."""
|
|
153
|
+
bitfinex_error_code = None
|
|
154
|
+
"""The Bitfinex error code of the response."""
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class BitfinexAPINoneResponseError(BitfinexAPIRequestError):
|
|
158
|
+
"""Exception for response body containing no data."""
|
|
159
|
+
|
|
160
|
+
response_status_code = None
|
|
161
|
+
"""The HTTP status code of the response."""
|
|
162
|
+
bitfinex_error_code = None
|
|
163
|
+
"""The Bitfinex error code of the response."""
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class BitfinexAPIJSONDecodeError(BitfinexAPIRequestError):
|
|
167
|
+
"""Exception for JSON decode errors."""
|
|
168
|
+
|
|
169
|
+
response_status_code = None
|
|
170
|
+
"""The HTTP status code of the response."""
|
|
171
|
+
bitfinex_error_code = None
|
|
172
|
+
"""The Bitfinex error code of the response."""
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class BitfinexAPIBitfinexInvalidParametersError(BitfinexAPIRequestError):
|
|
176
|
+
"""Exception for Bitfinex invalid-parameter API errors (500 / 10020)."""
|
|
177
|
+
|
|
178
|
+
response_status_code = [500]
|
|
179
|
+
"""The HTTP status code of the response."""
|
|
180
|
+
bitfinex_error_code = [10020]
|
|
181
|
+
"""The Bitfinex error code of the response."""
|
|
182
|
+
|
|
183
|
+
message_template: str = (
|
|
184
|
+
"Invalid parameters for {url}: {bitfinex_error_message}")
|
|
185
|
+
"""The message template for the exception."""
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class BitfinexAPITooManyRequestsError(BitfinexAPIRequestError):
|
|
189
|
+
"""Exception for too many requests errors."""
|
|
190
|
+
|
|
191
|
+
response_status_code = [429]
|
|
192
|
+
"""The HTTP status code of the response."""
|
|
193
|
+
bitfinex_error_code = [11010]
|
|
194
|
+
"""The Bitfinex error code of the response."""
|
|
195
|
+
|
|
196
|
+
message_template: str = (
|
|
197
|
+
"Too many requests for {url}: {bitfinex_error_message}")
|
|
198
|
+
"""The message template for the exception."""
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class BitfinexAPIRequestTreatment:
|
|
202
|
+
"""Translate failed HTTP responses into typed client exceptions.
|
|
203
|
+
|
|
204
|
+
Invoked from ``BitfinexAPIBaseMixin.get`` / ``post`` after the request
|
|
205
|
+
completes and before the JSON body is returned to callers. Successful
|
|
206
|
+
responses (``response.ok``) are left unchanged.
|
|
207
|
+
|
|
208
|
+
Handling order on failure:
|
|
209
|
+
|
|
210
|
+
1. **Fixed rules** on this class — ``401`` / ``403`` → auth; non-JSON body
|
|
211
|
+
→ ``BitfinexAPIJSONDecodeError``.
|
|
212
|
+
2. **Pluggable rules** — ``list_custom_exceptions``: each
|
|
213
|
+
``BitfinexAPIRequestError`` subclass may raise via ``raise_by_code``
|
|
214
|
+
when HTTP status and/or Bitfinex ``error.code`` match.
|
|
215
|
+
3. **Generic fallback** — if nothing matched, ``BitfinexAPIRequestError``
|
|
216
|
+
with the parsed JSON payload (so every non-OK response raises).
|
|
217
|
+
|
|
218
|
+
Prefer specific subclasses in ``list_custom_exceptions`` over relying on
|
|
219
|
+
the generic error when you need distinct handling (e.g. rate limits).
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
list_custom_exceptions = [
|
|
223
|
+
BitfinexAPITooManyRequestsError,
|
|
224
|
+
BitfinexAPIBitfinexInvalidParametersError,
|
|
225
|
+
]
|
|
226
|
+
"""``BitfinexAPIRequestError`` subclasses tried in order after auth.
|
|
227
|
+
|
|
228
|
+
Each class implements ``raise_by_code(response, response_payload)`` and
|
|
229
|
+
raises itself when its status / error-code filters match; otherwise it
|
|
230
|
+
returns without raising so the next entry can run.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def raise_by_code(cls, response: requests.Response) -> None:
|
|
235
|
+
"""Inspect ``response`` and raise when the call failed.
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
response (requests.Response):
|
|
239
|
+
Raw HTTP response from ``requests``.
|
|
240
|
+
|
|
241
|
+
Returns:
|
|
242
|
+
None:
|
|
243
|
+
When ``response.ok`` is true (no exception).
|
|
244
|
+
|
|
245
|
+
Raises:
|
|
246
|
+
BitfinexAPIAuthenticationError:
|
|
247
|
+
HTTP ``401`` or ``403``.
|
|
248
|
+
BitfinexAPIJSONDecodeError:
|
|
249
|
+
Body is not valid JSON on an error status.
|
|
250
|
+
BitfinexAPIRequestError:
|
|
251
|
+
A matching entry in ``list_custom_exceptions``, or the
|
|
252
|
+
generic fallback when the JSON error does not match any
|
|
253
|
+
registered rule.
|
|
254
|
+
"""
|
|
255
|
+
if response.ok:
|
|
256
|
+
return
|
|
257
|
+
|
|
258
|
+
if response.status_code in (401, 403):
|
|
259
|
+
payload = {"url": response.url, "error": response.text}
|
|
260
|
+
raise BitfinexAPIAuthenticationError(
|
|
261
|
+
message="Authentication failed for {url}: {error}",
|
|
262
|
+
payload=payload)
|
|
263
|
+
|
|
264
|
+
try:
|
|
265
|
+
response_payload = response.json()
|
|
266
|
+
except requests.JSONDecodeError:
|
|
267
|
+
response_payload = {
|
|
268
|
+
"json_decode_error": True,
|
|
269
|
+
"error": response.text,
|
|
270
|
+
"url": response.url}
|
|
271
|
+
raise BitfinexAPIJSONDecodeError(
|
|
272
|
+
message="Error fetching data from {url}: {error}",
|
|
273
|
+
payload=response_payload)
|
|
274
|
+
|
|
275
|
+
for temp_exception in cls.list_custom_exceptions:
|
|
276
|
+
temp_exception.raise_by_code(
|
|
277
|
+
response=response, response_payload=response_payload)
|
|
278
|
+
|
|
279
|
+
error_text = _format_api_error_body(response_payload)
|
|
280
|
+
raise BitfinexAPIRequestError(
|
|
281
|
+
message=BitfinexAPIRequestError.message_template,
|
|
282
|
+
payload={
|
|
283
|
+
"url": response.url, "error": error_text,
|
|
284
|
+
"response_body": response_payload})
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pytest --maxfail=1 --last-failed -v
|