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
bitfinex_api/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Python client for the Bitfinex HTTP API.
|
|
2
|
+
|
|
3
|
+
Import the client from ``bitfinex_api.data``::
|
|
4
|
+
|
|
5
|
+
from bitfinex_api.data import BitfinexAPI
|
|
6
|
+
|
|
7
|
+
client = BitfinexAPI()
|
|
8
|
+
client.get(endpoint="tickers", query_params={"symbols": "ALL"})
|
|
9
|
+
|
|
10
|
+
Optional ``api_key`` and ``api_secret`` are stored for future signed calls;
|
|
11
|
+
``authenticated=True`` raises until v2 signing is implemented.
|
|
12
|
+
Request timeout and retries come from ``bitfinex_api.config``.
|
|
13
|
+
"""
|
|
14
|
+
from bitfinex_api.data import BitfinexAPI
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"BitfinexAPI"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Auxiliary modules for Bitfinex API."""
|
|
2
|
+
|
|
3
|
+
from bitfinex_api.aux.base import BitfinexAPIBaseMixin
|
|
4
|
+
from bitfinex_api.aux.candles import BitfinexAPICandlesMixin
|
|
5
|
+
from bitfinex_api.aux.config import BitfinexAPIConfigMixin
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"BitfinexAPIBaseMixin",
|
|
9
|
+
"BitfinexAPICandlesMixin",
|
|
10
|
+
"BitfinexAPIConfigMixin",
|
|
11
|
+
]
|
bitfinex_api/aux/base.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Bitfinex REST API HTTP client base."""
|
|
2
|
+
import requests
|
|
3
|
+
from typing import Any
|
|
4
|
+
from loguru import logger
|
|
5
|
+
from urllib.parse import urljoin
|
|
6
|
+
from tenacity import (
|
|
7
|
+
RetryCallState, retry, retry_if_exception_type, stop_after_attempt)
|
|
8
|
+
from tenacity.wait import wait_base
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
# Local imports
|
|
12
|
+
from bitfinex_api.config import (
|
|
13
|
+
BITFINEX__PROXY_URL, BITFINEX__REQUEST_MAX_ATTEMPTS,
|
|
14
|
+
BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT, BITFINEX__REQUEST_RETRY_MIN_WAIT,
|
|
15
|
+
BITFINEX__REQUEST_TIMEOUT)
|
|
16
|
+
from bitfinex_api.exceptions import (
|
|
17
|
+
BitfinexAPIAuthenticationError, BitfinexAPIRequestTreatment,
|
|
18
|
+
BitfinexAPITooManyRequestsError)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
RETRY_ERRORS = (
|
|
22
|
+
requests.ConnectionError,
|
|
23
|
+
requests.Timeout,
|
|
24
|
+
BitfinexAPITooManyRequestsError,
|
|
25
|
+
)
|
|
26
|
+
"""Exception types that trigger a retried HTTP call."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _WaitByExceptionType(wait_base):
|
|
30
|
+
"""Network errors use short backoff; rate limits use env wait."""
|
|
31
|
+
|
|
32
|
+
def __call__(self, retry_state: RetryCallState) -> float:
|
|
33
|
+
outcome = retry_state.outcome
|
|
34
|
+
if outcome is not None and outcome.failed:
|
|
35
|
+
exc = outcome.exception()
|
|
36
|
+
if isinstance(exc, BitfinexAPITooManyRequestsError):
|
|
37
|
+
return BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT
|
|
38
|
+
return BITFINEX__REQUEST_RETRY_MIN_WAIT
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _log_retry_before_sleep(retry_state: RetryCallState) -> None:
|
|
42
|
+
"""Log a failure before sleeping for the next attempt."""
|
|
43
|
+
outcome = retry_state.outcome
|
|
44
|
+
if outcome is None or not outcome.failed:
|
|
45
|
+
return
|
|
46
|
+
exc = outcome.exception()
|
|
47
|
+
fn_name = retry_state.fn.__name__
|
|
48
|
+
if isinstance(exc, BitfinexAPITooManyRequestsError):
|
|
49
|
+
wait_s = BITFINEX__REQUEST_RATE_LIMIT_RETRY_WAIT
|
|
50
|
+
reason = "rate limit"
|
|
51
|
+
else:
|
|
52
|
+
wait_s = BITFINEX__REQUEST_RETRY_MIN_WAIT
|
|
53
|
+
reason = "network"
|
|
54
|
+
msg = (
|
|
55
|
+
"Bitfinex API {fn_name} failed ({reason}, {error_type}): {error}. "
|
|
56
|
+
"Attempt {attempt}/{max_attempts}, sleeping {wait_s}s")
|
|
57
|
+
logger.warning(
|
|
58
|
+
msg, fn_name=fn_name, reason=reason, error_type=type(exc).__name__,
|
|
59
|
+
error=exc, attempt=retry_state.attempt_number,
|
|
60
|
+
max_attempts=BITFINEX__REQUEST_MAX_ATTEMPTS, wait_s=wait_s)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
_RETRY_ON_NETWORK = retry(
|
|
64
|
+
retry=retry_if_exception_type(RETRY_ERRORS),
|
|
65
|
+
stop=stop_after_attempt(BITFINEX__REQUEST_MAX_ATTEMPTS),
|
|
66
|
+
wait=_WaitByExceptionType(),
|
|
67
|
+
reraise=True,
|
|
68
|
+
before_sleep=_log_retry_before_sleep,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class BitfinexAPIBaseMixin:
|
|
73
|
+
"""HTTP session and low-level methods for Bitfinex API v2."""
|
|
74
|
+
|
|
75
|
+
PUBLIC_BASE_URL = "https://api-pub.bitfinex.com/v2/"
|
|
76
|
+
"""Base URL for public Bitfinex endpoints."""
|
|
77
|
+
|
|
78
|
+
AUTH_BASE_URL = "https://api.bitfinex.com/v2/"
|
|
79
|
+
"""Base URL for authenticated Bitfinex endpoints."""
|
|
80
|
+
|
|
81
|
+
_api_key = None
|
|
82
|
+
"""Bitfinex API key for authenticated endpoints."""
|
|
83
|
+
|
|
84
|
+
_api_secret = None
|
|
85
|
+
"""Bitfinex API secret for authenticated endpoints."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, api_key: str | None = None,
|
|
88
|
+
api_secret: str | None = None) -> None:
|
|
89
|
+
"""Open a requests session for Bitfinex calls.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
api_key (str | None):
|
|
93
|
+
Bitfinex API key for authenticated endpoints.
|
|
94
|
+
api_secret (str | None):
|
|
95
|
+
Bitfinex API secret for authenticated endpoints.
|
|
96
|
+
"""
|
|
97
|
+
self._api_key = api_key
|
|
98
|
+
self._api_secret = api_secret
|
|
99
|
+
|
|
100
|
+
proxies = None
|
|
101
|
+
if BITFINEX__PROXY_URL is not None:
|
|
102
|
+
proxies = {
|
|
103
|
+
"http": BITFINEX__PROXY_URL,
|
|
104
|
+
"https": BITFINEX__PROXY_URL}
|
|
105
|
+
|
|
106
|
+
self.session = requests.Session()
|
|
107
|
+
if proxies is not None:
|
|
108
|
+
self.session.proxies.update(proxies)
|
|
109
|
+
|
|
110
|
+
def build_headers(self) -> dict[str, str]:
|
|
111
|
+
"""Build default request headers."""
|
|
112
|
+
return {"accept": "application/json"}
|
|
113
|
+
|
|
114
|
+
def get_base_url(self, authenticated: bool) -> str:
|
|
115
|
+
"""Resolve the REST host for public or authenticated calls.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
authenticated (bool):
|
|
119
|
+
When True, credentials must be configured on the client.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
str:
|
|
123
|
+
Base URL ending with ``/v2/``.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
BitfinexAPIAuthenticationError:
|
|
127
|
+
When ``authenticated`` is True and API key or secret is
|
|
128
|
+
missing.
|
|
129
|
+
NotImplementedError:
|
|
130
|
+
When credentials are set but v2 request signing is not
|
|
131
|
+
implemented yet.
|
|
132
|
+
"""
|
|
133
|
+
if not authenticated:
|
|
134
|
+
return self.PUBLIC_BASE_URL
|
|
135
|
+
|
|
136
|
+
is_auth_not_set = (
|
|
137
|
+
self._api_key is None or self._api_secret is None)
|
|
138
|
+
if is_auth_not_set:
|
|
139
|
+
msg = (
|
|
140
|
+
"Authentication is required but API key and secret "
|
|
141
|
+
"are not set.")
|
|
142
|
+
raise BitfinexAPIAuthenticationError(message=msg)
|
|
143
|
+
|
|
144
|
+
msg = (
|
|
145
|
+
"Authenticated Bitfinex API v2 requests are not implemented; "
|
|
146
|
+
"request signing is required.")
|
|
147
|
+
raise NotImplementedError(msg)
|
|
148
|
+
# return self.AUTH_BASE_URL
|
|
149
|
+
|
|
150
|
+
@_RETRY_ON_NETWORK
|
|
151
|
+
def get(self, endpoint: str, query_params: dict | None = None,
|
|
152
|
+
authenticated: bool = False) -> Any:
|
|
153
|
+
"""Send a GET request and return the JSON body.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
endpoint (str):
|
|
157
|
+
Path joined onto the base URL.
|
|
158
|
+
query_params (dict | None):
|
|
159
|
+
Query string parameters.
|
|
160
|
+
authenticated (bool):
|
|
161
|
+
When True, raise until v2 request signing is implemented.
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
Any:
|
|
165
|
+
Parsed JSON body (object or array).
|
|
166
|
+
|
|
167
|
+
Raises:
|
|
168
|
+
BitfinexAPIAuthenticationError:
|
|
169
|
+
When ``authenticated`` is True and credentials are missing.
|
|
170
|
+
NotImplementedError:
|
|
171
|
+
When ``authenticated`` is True and signing is not implemented.
|
|
172
|
+
BitfinexAPIJSONDecodeError:
|
|
173
|
+
Error body is not JSON.
|
|
174
|
+
BitfinexAPITooManyRequestsError:
|
|
175
|
+
Rate limit (HTTP 429 / Bitfinex code 11010).
|
|
176
|
+
BitfinexAPIBitfinexInvalidParametersError:
|
|
177
|
+
Invalid parameters (HTTP 500 / code 10020).
|
|
178
|
+
BitfinexAPIRequestError:
|
|
179
|
+
Other non-success HTTP responses.
|
|
180
|
+
"""
|
|
181
|
+
base = self.get_base_url(authenticated=authenticated)
|
|
182
|
+
request_url = urljoin(base, endpoint)
|
|
183
|
+
headers = self.build_headers()
|
|
184
|
+
|
|
185
|
+
response = self.session.get(
|
|
186
|
+
url=request_url, params=query_params,
|
|
187
|
+
headers=headers, timeout=BITFINEX__REQUEST_TIMEOUT)
|
|
188
|
+
|
|
189
|
+
# Raise an exception if the response status, using the Bitfinex
|
|
190
|
+
# return to raise the appropriate exception
|
|
191
|
+
BitfinexAPIRequestTreatment.raise_by_code(response=response)
|
|
192
|
+
return response.json()
|
|
193
|
+
|
|
194
|
+
@_RETRY_ON_NETWORK
|
|
195
|
+
def post(self, endpoint: str, query_params: dict | None = None,
|
|
196
|
+
data: dict | None = None, authenticated: bool = False) -> Any:
|
|
197
|
+
"""Send a POST request and return the JSON body.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
endpoint (str):
|
|
201
|
+
Path joined onto the base URL.
|
|
202
|
+
query_params (dict | None):
|
|
203
|
+
Query string parameters.
|
|
204
|
+
data (dict | None):
|
|
205
|
+
JSON request body.
|
|
206
|
+
authenticated (bool):
|
|
207
|
+
When True, raise until v2 request signing is implemented.
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
Any:
|
|
211
|
+
Parsed JSON body (object or array).
|
|
212
|
+
|
|
213
|
+
Raises:
|
|
214
|
+
BitfinexAPIAuthenticationError:
|
|
215
|
+
When ``authenticated`` is True and credentials are missing.
|
|
216
|
+
NotImplementedError:
|
|
217
|
+
When ``authenticated`` is True and signing is not implemented.
|
|
218
|
+
BitfinexAPIJSONDecodeError:
|
|
219
|
+
Error body is not JSON.
|
|
220
|
+
BitfinexAPITooManyRequestsError:
|
|
221
|
+
Rate limit (HTTP 429 / Bitfinex code 11010).
|
|
222
|
+
BitfinexAPIBitfinexInvalidParametersError:
|
|
223
|
+
Invalid parameters (HTTP 500 / code 10020).
|
|
224
|
+
BitfinexAPIRequestError:
|
|
225
|
+
Other non-success HTTP responses.
|
|
226
|
+
"""
|
|
227
|
+
base = self.get_base_url(authenticated=authenticated)
|
|
228
|
+
request_url = urljoin(base, endpoint)
|
|
229
|
+
headers = self.build_headers()
|
|
230
|
+
|
|
231
|
+
response = self.session.post(
|
|
232
|
+
url=request_url,
|
|
233
|
+
params=query_params,
|
|
234
|
+
json=data,
|
|
235
|
+
headers=headers,
|
|
236
|
+
timeout=BITFINEX__REQUEST_TIMEOUT)
|
|
237
|
+
|
|
238
|
+
# Raise an exception if the response status, using the Bitfinex
|
|
239
|
+
# return to raise the appropriate exception
|
|
240
|
+
BitfinexAPIRequestTreatment.raise_by_code(response=response)
|
|
241
|
+
return response.json()
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
"""Bitfinex public candle history endpoints."""
|
|
2
|
+
import datetime
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from pandas import Timestamp
|
|
5
|
+
from operator import itemgetter
|
|
6
|
+
from loguru import logger
|
|
7
|
+
|
|
8
|
+
# Local imports
|
|
9
|
+
from bitfinex_api.aux.misc import (
|
|
10
|
+
datetime_to_epoch_ms, epoch_ms_to_timestamp)
|
|
11
|
+
from bitfinex_api.exceptions import (
|
|
12
|
+
BitfinexAPIInvalidParametersError)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BitfinexAPICandlesMixin:
|
|
16
|
+
"""Fetch trade candles from Bitfinex REST API v2."""
|
|
17
|
+
|
|
18
|
+
TRADING_PAIR_SYMBOL_TEMPLATE = "t{base_symbol}{quote_symbol}"
|
|
19
|
+
"""REST pair prefix for candle ``trade:{period}:{symbol}`` paths."""
|
|
20
|
+
|
|
21
|
+
AVAILABLE_CANDLE_PERIODS = [
|
|
22
|
+
"1m", "5m", "15m", "30m", "1h", "3h", "6h", "12h", "1D", "1W",
|
|
23
|
+
"14D", "1M"]
|
|
24
|
+
"""Available candle aggregation periods."""
|
|
25
|
+
|
|
26
|
+
CANDLE_RESPONSE_COLUMNS = [
|
|
27
|
+
"mts", "open", "close", "high", "low", "volume",]
|
|
28
|
+
"""Columns in the candle response."""
|
|
29
|
+
|
|
30
|
+
CANDLE_COLUMNS = [
|
|
31
|
+
"time", "open", "close", "high", "low", "volume",]
|
|
32
|
+
"""Columns in the candle response."""
|
|
33
|
+
|
|
34
|
+
def validate_time_args(self, start_delta: datetime.timedelta | None,
|
|
35
|
+
start_datetime: Timestamp | datetime.datetime | str | None, # NOQA
|
|
36
|
+
end_datetime: Timestamp | datetime.datetime | str | None
|
|
37
|
+
) -> dict[str, int]: # NOQA
|
|
38
|
+
"""Resolve candle window bounds as UTC epoch milliseconds.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
start_delta (datetime.timedelta | None):
|
|
42
|
+
Window length ending at ``end_datetime`` or now (UTC).
|
|
43
|
+
start_datetime (Timestamp | datetime.datetime | str | None):
|
|
44
|
+
Inclusive range start; mutually exclusive with
|
|
45
|
+
``start_delta``.
|
|
46
|
+
end_datetime (Timestamp | datetime.datetime | str | None):
|
|
47
|
+
Inclusive range end; defaults to current UTC time.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
dict[str, int]:
|
|
51
|
+
``start_ms`` and ``end_ms`` for Bitfinex ``start`` /
|
|
52
|
+
``end`` query params.
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
BitfinexAPIInvalidParametersError:
|
|
56
|
+
When ``start_delta`` and ``start_datetime`` conflict or
|
|
57
|
+
both are omitted.
|
|
58
|
+
"""
|
|
59
|
+
# Validate the time arguments
|
|
60
|
+
if start_delta is not None and start_datetime is not None:
|
|
61
|
+
message = (
|
|
62
|
+
"Only one of start_delta or start_datetime can be provided. "
|
|
63
|
+
"start_delta [{start_delta}]; "
|
|
64
|
+
"start_datetime [{start_datetime}]")
|
|
65
|
+
raise BitfinexAPIInvalidParametersError(
|
|
66
|
+
message=message,
|
|
67
|
+
payload={
|
|
68
|
+
"start_delta": start_delta,
|
|
69
|
+
"start_datetime": start_datetime})
|
|
70
|
+
if start_delta is None and start_datetime is None:
|
|
71
|
+
message = (
|
|
72
|
+
"One of start_delta or start_datetime must be provided.")
|
|
73
|
+
raise BitfinexAPIInvalidParametersError(message=message)
|
|
74
|
+
|
|
75
|
+
# If time are passed as strings, convert them to pandas Timestamps
|
|
76
|
+
if isinstance(start_datetime, str):
|
|
77
|
+
start_datetime = pd.to_datetime(start_datetime)
|
|
78
|
+
if isinstance(end_datetime, str):
|
|
79
|
+
end_datetime = pd.to_datetime(end_datetime)
|
|
80
|
+
|
|
81
|
+
if start_datetime is None:
|
|
82
|
+
start_datetime = (
|
|
83
|
+
datetime.datetime.now(datetime.timezone.utc) - start_delta)
|
|
84
|
+
if end_datetime is None:
|
|
85
|
+
end_datetime = datetime.datetime.now(datetime.timezone.utc)
|
|
86
|
+
|
|
87
|
+
# Convert the time arguments to epoch milliseconds, as it is
|
|
88
|
+
# used by Bitfinex API.
|
|
89
|
+
return {
|
|
90
|
+
"start_ms": datetime_to_epoch_ms(start_datetime),
|
|
91
|
+
"end_ms": datetime_to_epoch_ms(end_datetime),
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
def validate_period(self, period: str) -> str:
|
|
95
|
+
"""Validate a Bitfinex candle aggregation period.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
period (str):
|
|
99
|
+
Period string (e.g. ``1h``, ``1D``).
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
str:
|
|
103
|
+
The same ``period`` when valid.
|
|
104
|
+
|
|
105
|
+
Raises:
|
|
106
|
+
BitfinexAPIInvalidParametersError:
|
|
107
|
+
When ``period`` is not in ``AVAILABLE_CANDLE_PERIODS``.
|
|
108
|
+
"""
|
|
109
|
+
if period not in self.AVAILABLE_CANDLE_PERIODS:
|
|
110
|
+
message = (
|
|
111
|
+
"Invalid candle period [{period}]. Must be one of: "
|
|
112
|
+
"{available_periods}")
|
|
113
|
+
raise BitfinexAPIInvalidParametersError(
|
|
114
|
+
message=message,
|
|
115
|
+
payload={
|
|
116
|
+
"period": period,
|
|
117
|
+
"available_periods": self.AVAILABLE_CANDLE_PERIODS})
|
|
118
|
+
return period
|
|
119
|
+
|
|
120
|
+
def get_trade_candles(self, base_symbol: str, quote_symbol: str,
|
|
121
|
+
period: str = "1h",
|
|
122
|
+
start_delta: datetime.timedelta | None = None,
|
|
123
|
+
start_datetime: datetime.datetime | str | None = None, # NOQA
|
|
124
|
+
end_datetime: datetime.datetime | str | None = None,
|
|
125
|
+
limit: int = 10000) -> pd.DataFrame:
|
|
126
|
+
"""Fetch trade candles for a trading pair over a time window.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
base_symbol (str):
|
|
130
|
+
Base asset code (e.g. ``BTC``).
|
|
131
|
+
quote_symbol (str):
|
|
132
|
+
Quote asset code (e.g. ``USD``).
|
|
133
|
+
period (str):
|
|
134
|
+
Candle size; see ``AVAILABLE_CANDLE_PERIODS``.
|
|
135
|
+
start_delta (datetime.timedelta | None):
|
|
136
|
+
Window length when ``start_datetime`` is omitted.
|
|
137
|
+
start_datetime (datetime.datetime | str | None):
|
|
138
|
+
Inclusive start; mutually exclusive with ``start_delta``.
|
|
139
|
+
end_datetime (datetime.datetime | str | None):
|
|
140
|
+
Inclusive end in UTC; defaults to now.
|
|
141
|
+
limit (int):
|
|
142
|
+
Maximum rows per HTTP page (Bitfinex cap applies).
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
pd.DataFrame:
|
|
146
|
+
Columns ``CANDLE_COLUMNS``; empty schema when no bars.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
BitfinexAPIInvalidParametersError:
|
|
150
|
+
Invalid period or time arguments (client-side).
|
|
151
|
+
BitfinexAPIRequestError:
|
|
152
|
+
HTTP or Bitfinex API errors (including invalid time range).
|
|
153
|
+
"""
|
|
154
|
+
path_template = "candles/trade:{period}:{symbol}/hist"
|
|
155
|
+
|
|
156
|
+
# Validate and correct the time arguments
|
|
157
|
+
time_args = self.validate_time_args(
|
|
158
|
+
start_delta=start_delta,
|
|
159
|
+
start_datetime=start_datetime,
|
|
160
|
+
end_datetime=end_datetime)
|
|
161
|
+
start_ms, end_ms = \
|
|
162
|
+
itemgetter("start_ms", "end_ms")(time_args)
|
|
163
|
+
period = self.validate_period(period=period)
|
|
164
|
+
|
|
165
|
+
# Build the request parameters
|
|
166
|
+
trading_symbol = self.TRADING_PAIR_SYMBOL_TEMPLATE\
|
|
167
|
+
.format(base_symbol=base_symbol, quote_symbol=quote_symbol)
|
|
168
|
+
path = path_template.format(
|
|
169
|
+
period=period, symbol=trading_symbol)
|
|
170
|
+
|
|
171
|
+
return self._fetch_candles_paginated(
|
|
172
|
+
path=path, start_ms=start_ms,
|
|
173
|
+
end_ms=end_ms, limit=limit)
|
|
174
|
+
|
|
175
|
+
def _fetch_candles_paginated(self, path: str,
|
|
176
|
+
start_ms: int, end_ms: int, limit: int,
|
|
177
|
+
) -> pd.DataFrame:
|
|
178
|
+
"""Fetch all candle bars between ``start_ms`` and ``end_ms``.
|
|
179
|
+
|
|
180
|
+
Stops when the API returns an empty page, the window end is reached,
|
|
181
|
+
or ``max(mts)`` fails to advance the pagination cursor.
|
|
182
|
+
"""
|
|
183
|
+
all_candles: list = []
|
|
184
|
+
cursor = start_ms
|
|
185
|
+
i_pages = 0
|
|
186
|
+
while cursor <= end_ms:
|
|
187
|
+
body = self.get(
|
|
188
|
+
endpoint=path,
|
|
189
|
+
query_params={
|
|
190
|
+
"sort": 1, "start": cursor,
|
|
191
|
+
"end": end_ms, "limit": limit})
|
|
192
|
+
|
|
193
|
+
# If the body is empty, break the loop
|
|
194
|
+
if len(body) == 0:
|
|
195
|
+
break
|
|
196
|
+
|
|
197
|
+
pd_body = pd.DataFrame(
|
|
198
|
+
body, columns=self.CANDLE_RESPONSE_COLUMNS)
|
|
199
|
+
all_candles.append(pd_body)
|
|
200
|
+
|
|
201
|
+
page_cursor = cursor
|
|
202
|
+
next_cursor = int(pd_body["mts"].max() + 1)
|
|
203
|
+
if next_cursor <= page_cursor:
|
|
204
|
+
msg = (
|
|
205
|
+
"Candle pagination stalled for {path}: cursor did not "
|
|
206
|
+
"advance (page_cursor={page_cursor}, "
|
|
207
|
+
"next_cursor={next_cursor})")
|
|
208
|
+
logger.warning(
|
|
209
|
+
msg, path=path, page_cursor=page_cursor,
|
|
210
|
+
next_cursor=next_cursor)
|
|
211
|
+
break
|
|
212
|
+
|
|
213
|
+
# If the next cursor is after the end_ms, break the loop
|
|
214
|
+
if end_ms < next_cursor:
|
|
215
|
+
break
|
|
216
|
+
|
|
217
|
+
# Keep the loop until the next cursor is after the end_ms
|
|
218
|
+
last_call_dt = datetime.datetime.fromtimestamp(
|
|
219
|
+
next_cursor / 1000, tz=datetime.timezone.utc).isoformat()
|
|
220
|
+
msg = (
|
|
221
|
+
"Page [{i_pages}] of [{path}]: last time [{last_call_dt}] "
|
|
222
|
+
"collected [{n}] candles")
|
|
223
|
+
logger.info(
|
|
224
|
+
msg, i_pages=i_pages, path=path, last_call_dt=last_call_dt,
|
|
225
|
+
n=len(pd_body))
|
|
226
|
+
cursor = next_cursor
|
|
227
|
+
i_pages = i_pages + 1
|
|
228
|
+
|
|
229
|
+
frames = [frame for frame in all_candles if not frame.empty]
|
|
230
|
+
if len(frames) == 0:
|
|
231
|
+
return pd.DataFrame(columns=self.CANDLE_COLUMNS)
|
|
232
|
+
|
|
233
|
+
# Remove candles after the end_ms
|
|
234
|
+
all_data = pd.concat(frames, ignore_index=True)
|
|
235
|
+
is_after_end_ms = end_ms < all_data["mts"]
|
|
236
|
+
all_data = all_data.loc[~is_after_end_ms, :].reset_index(drop=True)
|
|
237
|
+
|
|
238
|
+
# Convert the mts to a timestamp
|
|
239
|
+
all_data["time"] = epoch_ms_to_timestamp(all_data["mts"])
|
|
240
|
+
|
|
241
|
+
# Return the data in the correct columns
|
|
242
|
+
return all_data.loc[:, self.CANDLE_COLUMNS]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Bitfinex ``conf`` pair and currency metadata."""
|
|
2
|
+
from bitfinex_api.aux.config.config import BitfinexAPIConfigMixin
|
|
3
|
+
from bitfinex_api.aux.config.config_base import BitfinexAPIConfigBaseMixin
|
|
4
|
+
from bitfinex_api.aux.config.config_info import BitfinexAPIConfigInfoMixin
|
|
5
|
+
from bitfinex_api.aux.config.config_list import BitfinexAPIConfigListMixin
|
|
6
|
+
from bitfinex_api.aux.config.config_map import (
|
|
7
|
+
CURRENCY_NAME_OVERRIDES,
|
|
8
|
+
apply_currency_name_overrides,
|
|
9
|
+
BitfinexAPIConfigMapMixin,
|
|
10
|
+
)
|
|
11
|
+
from bitfinex_api.aux.config.treatment import TreatmentPairSymbols
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"BitfinexAPIConfigBaseMixin",
|
|
16
|
+
"BitfinexAPIConfigInfoMixin",
|
|
17
|
+
"BitfinexAPIConfigListMixin",
|
|
18
|
+
"BitfinexAPIConfigMapMixin",
|
|
19
|
+
"BitfinexAPIConfigMixin",
|
|
20
|
+
"CURRENCY_NAME_OVERRIDES",
|
|
21
|
+
"TreatmentPairSymbols",
|
|
22
|
+
"apply_currency_name_overrides",
|
|
23
|
+
]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Aggregate Bitfinex ``conf`` mixins for the HTTP client."""
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from bitfinex_api.aux.config.config_info import BitfinexAPIConfigInfoMixin
|
|
4
|
+
from bitfinex_api.aux.config.config_list import BitfinexAPIConfigListMixin
|
|
5
|
+
from bitfinex_api.aux.config.config_map import BitfinexAPIConfigMapMixin
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BitfinexAPIConfigMixin(
|
|
9
|
+
BitfinexAPIConfigMapMixin,
|
|
10
|
+
BitfinexAPIConfigListMixin,
|
|
11
|
+
BitfinexAPIConfigInfoMixin):
|
|
12
|
+
"""All config endpoint mixins composed for ``BitfinexAPI``."""
|
|
13
|
+
|
|
14
|
+
def list_pair_with_info(self) -> pd.DataFrame:
|
|
15
|
+
"""List pairs with information from the map tables."""
|
|
16
|
+
pairs = self.list_api_pairs()
|
|
17
|
+
api_symbol_info = self.map_api_symbol_all()
|
|
18
|
+
|
|
19
|
+
base_symbol_info = api_symbol_info.add_prefix("base_")
|
|
20
|
+
quote_symbol_info = api_symbol_info.add_prefix("quote_")
|
|
21
|
+
|
|
22
|
+
return pairs\
|
|
23
|
+
.merge(
|
|
24
|
+
base_symbol_info, on="base_api_symbol",
|
|
25
|
+
how="left")\
|
|
26
|
+
.merge(
|
|
27
|
+
quote_symbol_info, on="quote_api_symbol",
|
|
28
|
+
how="left")
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Shared helpers for Bitfinex ``conf`` endpoints."""
|
|
2
|
+
import datetime
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from bitfinex_api.exceptions import BitfinexAPIInvalidParametersError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BitfinexAPIConfigBaseMixin:
|
|
9
|
+
"""``unwrap_response``, market validation, platform status."""
|
|
10
|
+
|
|
11
|
+
VALID_MARKETS: tuple[str, ...] = (
|
|
12
|
+
"exchange", "margin", "futures", "securities")
|
|
13
|
+
"""Valid markets for ``pub:list:pair`` segments."""
|
|
14
|
+
|
|
15
|
+
def validate_market(self, market: str) -> None:
|
|
16
|
+
"""Validate a ``pub:list:pair`` market segment.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
market (str):
|
|
20
|
+
One of ``VALID_MARKETS``.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
BitfinexAPIInvalidParametersError:
|
|
24
|
+
When ``market`` is not supported.
|
|
25
|
+
"""
|
|
26
|
+
if market not in self.VALID_MARKETS:
|
|
27
|
+
raise BitfinexAPIInvalidParametersError(
|
|
28
|
+
message="Invalid market: {market}. Expected one of {choices}.",
|
|
29
|
+
payload={"market": market, "choices": self.VALID_MARKETS})
|
|
30
|
+
|
|
31
|
+
def unwrap_response(self, body: Any) -> Any:
|
|
32
|
+
"""Unwrap the response body from a Bitfinex API call."""
|
|
33
|
+
if not isinstance(body, list) or len(body) == 0:
|
|
34
|
+
return None
|
|
35
|
+
return body[0]
|
|
36
|
+
|
|
37
|
+
def platform_status(self) -> dict[str, Any]:
|
|
38
|
+
"""Fetch ``GET /v2/platform/status``."""
|
|
39
|
+
path = "platform/status"
|
|
40
|
+
collected_at = datetime.datetime.now(datetime.timezone.utc)
|
|
41
|
+
body = self.unwrap_response(self.get(endpoint=path))
|
|
42
|
+
return {
|
|
43
|
+
"collected_at": collected_at,
|
|
44
|
+
"body": body,
|
|
45
|
+
}
|