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,98 @@
1
+ """Bitfinex ``conf/pub:info:*`` endpoints."""
2
+ import pandas as pd
3
+
4
+ from bitfinex_api.aux.config.config_base import BitfinexAPIConfigBaseMixin
5
+ from bitfinex_api.exceptions import BitfinexAPINoneResponseError
6
+
7
+
8
+ class BitfinexAPIConfigInfoMixin(BitfinexAPIConfigBaseMixin):
9
+ """One HTTP call per ``pub:info`` config key."""
10
+
11
+ API_PAIR_INFO_COLUMNS: tuple[str, ...] = (
12
+ "pair",
13
+ "first_trade_ms",
14
+ "min_order_size",
15
+ "max_order_size",
16
+ "initial_margin",
17
+ "min_margin",
18
+ )
19
+ """DataFrame columns for ``conf/pub:info:pair`` and ``pair:futures``."""
20
+
21
+ API_TX_STATUS_COLUMNS: tuple[str, ...] = (
22
+ "withdrawal_method",
23
+ "deposit_status",
24
+ "withdrawal_status",
25
+ "payment_id_deposit_allowed",
26
+ "payment_id_withdrawal_allowed",
27
+ "deposit_confirmations_required",
28
+ )
29
+ """DataFrame columns for ``conf/pub:info:tx:status``."""
30
+
31
+ def info_api_pair(self) -> pd.DataFrame:
32
+ """``pub:info:pair`` — limits and margin metadata per spot pair."""
33
+ endpoint = "conf/pub:info:pair"
34
+ body = self.unwrap_response(self.get(endpoint=endpoint))
35
+ if body is None:
36
+ raise BitfinexAPINoneResponseError(
37
+ message="No response body from {endpoint}.",
38
+ payload={"endpoint": endpoint})
39
+ rows = [
40
+ {
41
+ "pair": pair,
42
+ "first_trade_ms": fields[0],
43
+ "min_order_size": fields[3],
44
+ "max_order_size": fields[4],
45
+ "initial_margin": fields[8] if len(fields) > 8 else None,
46
+ "min_margin": fields[9] if len(fields) > 9 else None,
47
+ }
48
+ for pair, fields in body
49
+ if isinstance(fields, list)
50
+ ]
51
+ frame = pd.DataFrame(rows, columns=self.API_PAIR_INFO_COLUMNS)
52
+ return frame.sort_values("pair").reset_index(drop=True)
53
+
54
+ def info_api_pair_futures(self) -> pd.DataFrame:
55
+ """``pub:info:pair:futures`` — derivative pair limits and margin."""
56
+ endpoint = "conf/pub:info:pair:futures"
57
+ body = self.unwrap_response(self.get(endpoint=endpoint))
58
+ if body is None:
59
+ raise BitfinexAPINoneResponseError(
60
+ message="No response body from {endpoint}.",
61
+ payload={"endpoint": endpoint})
62
+ rows = [
63
+ {
64
+ "pair": pair,
65
+ "first_trade_ms": fields[0],
66
+ "min_order_size": fields[3],
67
+ "max_order_size": fields[4],
68
+ "initial_margin": fields[8],
69
+ "min_margin": fields[9],
70
+ }
71
+ for pair, fields in body
72
+ if isinstance(fields, list) and len(fields) >= 10
73
+ ]
74
+ frame = pd.DataFrame(rows, columns=self.API_PAIR_INFO_COLUMNS)
75
+ return frame.sort_values("pair").reset_index(drop=True)
76
+
77
+ def info_api_tx_status(self) -> pd.DataFrame:
78
+ """``pub:info:tx:status`` — deposit/withdrawal status per rail."""
79
+ endpoint = "conf/pub:info:tx:status"
80
+ body = self.unwrap_response(self.get(endpoint=endpoint))
81
+ if body is None:
82
+ raise BitfinexAPINoneResponseError(
83
+ message="No response body from {endpoint}.",
84
+ payload={"endpoint": endpoint})
85
+ rows = [
86
+ {
87
+ "withdrawal_method": row[0],
88
+ "deposit_status": row[1],
89
+ "withdrawal_status": row[2],
90
+ "payment_id_deposit_allowed": row[7],
91
+ "payment_id_withdrawal_allowed": row[8],
92
+ "deposit_confirmations_required": row[11],
93
+ }
94
+ for row in body
95
+ if isinstance(row, list) and len(row) >= 12
96
+ ]
97
+ frame = pd.DataFrame(rows, columns=self.API_TX_STATUS_COLUMNS)
98
+ return frame.sort_values("withdrawal_method").reset_index(drop=True)
@@ -0,0 +1,68 @@
1
+ """Bitfinex ``conf/pub:list:*`` endpoints (pairs, currencies)."""
2
+ import pandas as pd
3
+
4
+ from bitfinex_api.aux.config.config_base import BitfinexAPIConfigBaseMixin
5
+ from bitfinex_api.aux.config.treatment import TreatmentPairSymbols
6
+ from bitfinex_api.exceptions import BitfinexAPINoneResponseError
7
+
8
+
9
+ class BitfinexAPIConfigListMixin(BitfinexAPIConfigBaseMixin):
10
+ """One HTTP call per ``pub:list`` config key."""
11
+
12
+ API_CURRENCY_LIST_COLUMNS: tuple[str, ...] = ("api_symbol",)
13
+ """DataFrame column for ``conf/pub:list:currency`` codes."""
14
+
15
+ API_PAIR_LIST_COLUMNS: tuple[str, ...] = (
16
+ "instrument", "trading_prefix", "pair",
17
+ "base_api_symbol", "quote_api_symbol",
18
+ )
19
+ """Columns for ``conf/pub:list:pair:*`` (``PairSymbolsContract``)."""
20
+
21
+ API_COMPETITION_LIST_COLUMNS: tuple[str, ...] = ("competition",)
22
+ """DataFrame column for ``conf/pub:list:competitions``."""
23
+
24
+ def list_api_currencies(self) -> pd.DataFrame:
25
+ """``pub:list:currency`` — platform wallet codes."""
26
+ endpoint = "conf/pub:list:currency"
27
+ body = self.unwrap_response(self.get(endpoint=endpoint))
28
+ if body is None:
29
+ raise BitfinexAPINoneResponseError(
30
+ message="No response body from {endpoint}.",
31
+ payload={"endpoint": endpoint})
32
+ frame = pd.DataFrame(body, columns=self.API_CURRENCY_LIST_COLUMNS)
33
+ return frame.sort_values("api_symbol").reset_index(drop=True)
34
+
35
+ def list_api_margin_currencies(self) -> pd.DataFrame:
36
+ """``pub:list:currency:margin`` — margin collateral codes."""
37
+ endpoint = "conf/pub:list:currency:margin"
38
+ body = self.unwrap_response(self.get(endpoint=endpoint))
39
+ if body is None:
40
+ raise BitfinexAPINoneResponseError(
41
+ message="No response body from {endpoint}.",
42
+ payload={"endpoint": endpoint})
43
+ frame = pd.DataFrame(body, columns=self.API_CURRENCY_LIST_COLUMNS)
44
+ return frame.sort_values("api_symbol").reset_index(drop=True)
45
+
46
+ def list_api_pairs(self, market: str = "exchange") -> pd.DataFrame:
47
+ """``pub:list:pair:{market}`` — tradable pairs for a market."""
48
+ self.validate_market(market)
49
+ endpoint = f"conf/pub:list:pair:{market}"
50
+ body = self.unwrap_response(self.get(endpoint=endpoint))
51
+ if body is None:
52
+ raise BitfinexAPINoneResponseError(
53
+ message="No response body from {endpoint}.",
54
+ payload={"endpoint": endpoint})
55
+ currency_codes = self.list_api_currencies()["api_symbol"].tolist()
56
+ legs = TreatmentPairSymbols.split_pair_list(body, currency_codes)
57
+ return legs.sort_values("pair").reset_index(drop=True)
58
+
59
+ def list_api_competitions(self) -> pd.DataFrame:
60
+ """``pub:list:competitions`` — active leaderboard competitions."""
61
+ endpoint = "conf/pub:list:competitions"
62
+ body = self.unwrap_response(self.get(endpoint=endpoint))
63
+ if body is None:
64
+ raise BitfinexAPINoneResponseError(
65
+ message="No response body from {endpoint}.",
66
+ payload={"endpoint": endpoint})
67
+ frame = pd.DataFrame(body, columns=self.API_COMPETITION_LIST_COLUMNS)
68
+ return frame.sort_values("competition").reset_index(drop=True)
@@ -0,0 +1,340 @@
1
+ """Bitfinex ``conf/pub:map:*`` currency map endpoints."""
2
+ import pandas as pd
3
+ from loguru import logger
4
+ from bitfinex_api.aux.config.config_base import BitfinexAPIConfigBaseMixin
5
+ from bitfinex_api.exceptions import (
6
+ BitfinexAPINoneResponseError,
7
+ BitfinexAPIDataValidationError)
8
+
9
+
10
+ CURRENCY_NAME_OVERRIDES: dict[str, str] = {
11
+ "ETH2P": "Ethereum 2.0 Pending",
12
+ "ETH2R": "Ethereum 2.0 Rewards",
13
+ "ETH2U": "Ethereum 2.0 Unstaking",
14
+ "ETH2X": "Ethereum 2.0",
15
+ "EUTF0": "Tether EURt (derivative)",
16
+ "HBARF0": "Hedera (derivative)",
17
+ "ONDOF0": "Ondo (derivative)",
18
+ "TAOF0": "Bittensor (derivative)",
19
+ "TESTALGO": "Algorand (test)",
20
+ "TESTALGOF0": "Algorand (test derivative)",
21
+ "TESTEOS": "EOS (test)",
22
+ "TESTXTZF0": "Tezos (test derivative)",
23
+ "TONF0": "Toncoin (derivative)",
24
+ }
25
+ """Labels for platform codes absent from ``pub:map:currency:label``."""
26
+
27
+
28
+ def apply_currency_name_overrides(
29
+ frame: pd.DataFrame,
30
+ *,
31
+ code_column: str = "api_symbol",
32
+ name_column: str = "name",
33
+ overrides: dict[str, str] | None = None,
34
+ ) -> pd.DataFrame:
35
+ """Fill blank ``name`` values from ``CURRENCY_NAME_OVERRIDES``."""
36
+ if not isinstance(frame, pd.DataFrame):
37
+ msg = "frame must be a pandas DataFrame."
38
+ raise TypeError(msg)
39
+ lookup = overrides if overrides is not None else CURRENCY_NAME_OVERRIDES
40
+ if name_column not in frame.columns:
41
+ return frame
42
+ out = frame.copy()
43
+ codes = out[code_column].astype(str).str.upper()
44
+ missing = out[name_column].isna()
45
+ out.loc[missing, name_column] = codes.map(lookup)
46
+ return out
47
+
48
+
49
+ class BitfinexAPIConfigMapMixin(BitfinexAPIConfigBaseMixin):
50
+ """One HTTP call per ``pub:map`` config key."""
51
+
52
+ API_CURRENCY_SYMBOLS_COLUMNS: tuple[str, ...] = (
53
+ "api_symbol", "currency_symbol")
54
+ """DataFrame columns for ``conf/pub:map:currency:sym``.
55
+
56
+ ``api_symbol`` is the platform wallet code (e.g. ``DSH``).
57
+ ``currency_symbol`` is the symbol Bitfinex uses in APIs (e.g. ``DASH``).
58
+ """
59
+
60
+ API_SYMBOL_NAMES_COLUMNS: tuple[str, ...] = (
61
+ "api_symbol", "name")
62
+ """DataFrame columns for ``conf/pub:map:currency:label``.
63
+
64
+ ``api_symbol`` is the wallet code; ``name`` is the display label
65
+ (e.g. ``BTC`` → ``Bitcoin``).
66
+ """
67
+
68
+ API_SYMBOL_UNDERLYING_COLUMNS: tuple[str, ...] = (
69
+ "derivative_api_symbol", "underlying_api_symbol")
70
+ """DataFrame columns for ``conf/pub:map:currency:undl``.
71
+
72
+ Maps a derivative code (e.g. ``BTCF0``) to its underlying (e.g. ``BTC``).
73
+ """
74
+
75
+ API_SYMBOL_CURRENCY_POOL_COLUMNS: tuple[str, ...] = (
76
+ "api_symbol", "currency_pool")
77
+ """DataFrame columns for ``conf/pub:map:currency:pool``.
78
+
79
+ ``currency_pool`` is the parent network for the asset (e.g. ``BAT``
80
+ → ``ETH``).
81
+ """
82
+
83
+ API_SYMBOL_CURRENCY_EXPLORER_COLUMNS: tuple[str, ...] = (
84
+ "api_symbol", "currency_explorer_url_list")
85
+ """DataFrame columns for ``conf/pub:map:currency:explorer``.
86
+
87
+ ``currency_explorer_url_list`` is a list of block explorer URLs.
88
+ """
89
+
90
+ API_SYMBOL_CURRENCY_TX_FEE_COLUMNS: tuple[str, ...] = (
91
+ "api_symbol", "withdrawal_fee")
92
+ """DataFrame columns for ``conf/pub:map:currency:tx:fee``.
93
+
94
+ ``withdrawal_fee`` is taken from the second value in each fee pair
95
+ (amount charged in units of ``api_symbol``).
96
+ """
97
+
98
+ API_SYMBOL_CURRENCY_WITHDRAWAL_METHOD_COLUMNS: tuple[str, ...] = (
99
+ "api_symbol", "currency_withdrawal_methods")
100
+ """DataFrame columns built from ``conf/pub:map:tx:method``.
101
+
102
+ Bitfinex returns method → codes; we invert to one row per
103
+ ``api_symbol`` with a list of withdrawal ``method`` ids (rails).
104
+ """
105
+
106
+ API_SYMBOL_ALL_COLUMNS: tuple[str, ...] = (
107
+ 'api_symbol', 'is_derivative', 'underlying_api_symbol',
108
+ 'currency_symbol', 'name', 'currency_pool',
109
+ 'currency_explorer_url_list', 'withdrawal_fee',
110
+ 'currency_withdrawal_methods')
111
+ """DataFrame columns for all the maps."""
112
+
113
+ def map_api_currency_symbol(self) -> pd.DataFrame:
114
+ """``pub:map:currency:sym`` — platform code → wallet symbol."""
115
+ endpoint = "conf/pub:map:currency:sym"
116
+ body = self.unwrap_response(self.get(endpoint=endpoint))
117
+ if body is None:
118
+ raise BitfinexAPINoneResponseError(
119
+ message="No response body from {endpoint}.",
120
+ payload={"endpoint": endpoint})
121
+ frame = pd.DataFrame(
122
+ body, columns=self.API_CURRENCY_SYMBOLS_COLUMNS)
123
+ return frame.sort_values("api_symbol").reset_index(drop=True)
124
+
125
+ def map_api_symbol_names(self) -> pd.DataFrame:
126
+ """``pub:map:currency:label`` — platform code → display name."""
127
+ endpoint = "conf/pub:map:currency:label"
128
+ body = self.unwrap_response(self.get(endpoint=endpoint))
129
+ if body is None:
130
+ raise BitfinexAPINoneResponseError(
131
+ message="No response body from {endpoint}.",
132
+ payload={"endpoint": endpoint})
133
+ frame = pd.DataFrame(
134
+ body, columns=self.API_SYMBOL_NAMES_COLUMNS)
135
+ return frame.sort_values("api_symbol").reset_index(drop=True)
136
+
137
+ def map_api_currency_symbol_with_names(self) -> pd.DataFrame:
138
+ """``map_api_currency_symbol`` plus label backfill for sym-only."""
139
+ symbol_name_map = self.map_api_symbol_names()
140
+ currency_symbol_map = self.map_api_currency_symbol()
141
+
142
+ # Use the currency symbol to join the symbol name map
143
+ # some api are not normalized or are derivatives.
144
+ merged = currency_symbol_map.merge(
145
+ symbol_name_map, on="api_symbol", how="left")
146
+ is_na_name = merged.loc[:, "name"].isna()
147
+ missing_names = merged.loc[is_na_name, :].drop(columns=["name"])
148
+ to_merge_missing = symbol_name_map.rename(
149
+ columns={"api_symbol": "currency_symbol"})
150
+ missing_with_names = missing_names.merge(
151
+ to_merge_missing, on="currency_symbol", how="left")
152
+
153
+ missing_with_names = apply_currency_name_overrides(missing_with_names)
154
+
155
+ # Join both results and validate if eventually there are duplicates
156
+ # or missing names. The missing name will be logged to futter
157
+ # adjust of the package.
158
+ all_data = pd.concat([
159
+ merged.loc[~is_na_name, :], missing_with_names])
160
+ value_count_api_symbol = all_data["api_symbol"].value_counts()
161
+ if not (value_count_api_symbol == 1).all():
162
+ duplicates = value_count_api_symbol[
163
+ value_count_api_symbol != 1].index.tolist()
164
+ msg = "Duplicate API symbols: {duplicates}"
165
+ raise BitfinexAPIDataValidationError(
166
+ message=msg, payload={"duplicates": duplicates})
167
+
168
+ missing_name_codes = all_data.loc[
169
+ all_data["name"].isna(), "api_symbol"].tolist()
170
+ if missing_name_codes:
171
+ msg = "Missing names for API symbols: {missing_names}"
172
+ logger.warning(msg, missing_names=missing_name_codes)
173
+ return all_data
174
+
175
+ def map_api_symbol_derivative_underlyings(self) -> pd.DataFrame:
176
+ """``pub:map:currency:undl`` — derivative → underlying."""
177
+ endpoint = "conf/pub:map:currency:undl"
178
+ body = self.unwrap_response(self.get(endpoint=endpoint))
179
+ if body is None:
180
+ raise BitfinexAPINoneResponseError(
181
+ message="No response body from {endpoint}.",
182
+ payload={"endpoint": endpoint})
183
+ return pd.DataFrame(
184
+ body, columns=self.API_SYMBOL_UNDERLYING_COLUMNS)
185
+
186
+ def map_api_symbol_currency_pool(self) -> pd.DataFrame:
187
+ """``pub:map:currency:pool`` — token → parent network code."""
188
+ endpoint = "conf/pub:map:currency:pool"
189
+ body = self.unwrap_response(self.get(endpoint=endpoint))
190
+ if body is None:
191
+ raise BitfinexAPINoneResponseError(
192
+ message="No response body from {endpoint}.",
193
+ payload={"endpoint": endpoint})
194
+ return pd.DataFrame(
195
+ body, columns=self.API_SYMBOL_CURRENCY_POOL_COLUMNS)
196
+
197
+ def map_api_symbol_currency_explorer(self) -> pd.DataFrame:
198
+ """``pub:map:currency:explorer`` — code → explorer URL list."""
199
+ endpoint = "conf/pub:map:currency:explorer"
200
+ body = self.unwrap_response(self.get(endpoint=endpoint))
201
+ if body is None:
202
+ raise BitfinexAPINoneResponseError(
203
+ message="No response body from {endpoint}.",
204
+ payload={"endpoint": endpoint})
205
+ return pd.DataFrame(
206
+ body, columns=self.API_SYMBOL_CURRENCY_EXPLORER_COLUMNS)
207
+
208
+ def map_api_symbol_withdrawal_fee(self) -> pd.DataFrame:
209
+ """``pub:map:currency:tx:fee`` — code → withdrawal fee."""
210
+ endpoint = "conf/pub:map:currency:tx:fee"
211
+ body = self.unwrap_response(self.get(endpoint=endpoint))
212
+ if body is None:
213
+ raise BitfinexAPINoneResponseError(
214
+ message="No response body from {endpoint}.",
215
+ payload={"endpoint": endpoint})
216
+ rows = [
217
+ {"api_symbol": row[0], "withdrawal_fee": row[1][1]}
218
+ for row in body
219
+ if isinstance(row, list) and len(row) >= 2
220
+ ]
221
+ return pd.DataFrame(
222
+ rows, columns=self.API_SYMBOL_CURRENCY_TX_FEE_COLUMNS)
223
+
224
+ def map_api_symbol_withdrawal_method(self) -> pd.DataFrame:
225
+ """``pub:map:tx:method`` inverted to code → method ids."""
226
+ endpoint = "conf/pub:map:tx:method"
227
+ body = self.unwrap_response(self.get(endpoint=endpoint))
228
+ if body is None:
229
+ raise BitfinexAPINoneResponseError(
230
+ message="No response body from {endpoint}.",
231
+ payload={"endpoint": endpoint})
232
+ symbol_to_methods: dict[str, list[str]] = {}
233
+ for method, api_symbols in body:
234
+ for api_symbol in api_symbols:
235
+ bucket = symbol_to_methods.setdefault(api_symbol, [])
236
+ bucket.append(method)
237
+ rows = [
238
+ {
239
+ "api_symbol": api_symbol,
240
+ "currency_withdrawal_methods": methods,
241
+ }
242
+ for api_symbol, methods in symbol_to_methods.items()
243
+ ]
244
+ return pd.DataFrame(
245
+ rows, columns=self.API_SYMBOL_CURRENCY_WITHDRAWAL_METHOD_COLUMNS)
246
+
247
+ def _attach_map_columns(self, frame: pd.DataFrame, map_df: pd.DataFrame,
248
+ sym_df: pd.DataFrame,
249
+ value_columns: tuple[str, ...],
250
+ ) -> pd.DataFrame:
251
+ """Attach map cols by wallet code, then underlying / canon sym."""
252
+ if map_df.empty:
253
+ out = frame.copy()
254
+ for col in value_columns:
255
+ out[col] = pd.NA
256
+ return out
257
+ lookup = map_df.set_index("api_symbol")
258
+ in_maps = sym_df["api_symbol"].isin(lookup.index)
259
+ canonical = (
260
+ sym_df.loc[in_maps]
261
+ .sort_values("api_symbol")
262
+ .groupby("currency_symbol", as_index=False)["api_symbol"]
263
+ .first()
264
+ .set_index("currency_symbol")["api_symbol"])
265
+ out = frame.copy()
266
+ for col in value_columns:
267
+ values = out["api_symbol"].map(lookup[col])
268
+ is_deriv = out.get("is_derivative", False).fillna(False)
269
+ undl = out["underlying_api_symbol"]
270
+ deriv_mask = is_deriv & undl.notna()
271
+ if deriv_mask.any():
272
+ undl_mapped = undl.loc[deriv_mask].map(lookup[col])
273
+ values = values.copy()
274
+ values.loc[deriv_mask] = values.loc[deriv_mask].fillna(
275
+ undl_mapped)
276
+ canon_vals = out["currency_symbol"].map(canonical).map(lookup[col])
277
+ out[col] = values.fillna(canon_vals)
278
+ return out
279
+
280
+ def map_api_symbol_all(self) -> pd.DataFrame:
281
+ """Left-join every map table on ``api_symbol`` (one row per code)."""
282
+ currency_symbol = self.map_api_currency_symbol_with_names()
283
+ symbol_underlying = self.map_api_symbol_derivative_underlyings()
284
+ sym_lookup = currency_symbol[
285
+ ["api_symbol", "currency_symbol"]]
286
+
287
+ merged = currency_symbol.merge(
288
+ symbol_underlying,
289
+ left_on="api_symbol",
290
+ right_on="derivative_api_symbol",
291
+ how="left",
292
+ )
293
+ merged["is_derivative"] = merged["derivative_api_symbol"].notna()
294
+ merged = merged.drop(columns=["derivative_api_symbol"])
295
+
296
+ merged = self._attach_map_columns(
297
+ merged,
298
+ self.map_api_symbol_currency_pool(),
299
+ sym_lookup,
300
+ ("currency_pool",))
301
+ merged = self._attach_map_columns(
302
+ merged,
303
+ self.map_api_symbol_currency_explorer(),
304
+ sym_lookup,
305
+ ("currency_explorer_url_list",))
306
+ merged = self._attach_map_columns(
307
+ merged,
308
+ self.map_api_symbol_withdrawal_fee(),
309
+ sym_lookup,
310
+ ("withdrawal_fee",))
311
+ merged = self._attach_map_columns(
312
+ merged,
313
+ self.map_api_symbol_withdrawal_method(),
314
+ sym_lookup,
315
+ ("currency_withdrawal_methods",))
316
+
317
+ return_df = merged
318
+
319
+ # Validate all symbols are present in the return dataframe.
320
+ if len(return_df) != len(currency_symbol):
321
+ message = (
322
+ "Information merge from the map tables is not correct. "
323
+ "Currency symbol count [{n_currency_symbol}], "
324
+ "return df count [{n_return_df}].")
325
+ raise BitfinexAPIDataValidationError(
326
+ message=message,
327
+ payload={
328
+ "n_currency_symbol": len(currency_symbol),
329
+ "n_return_df": len(return_df)})
330
+
331
+ # Validate if eventually there are duplicates or missing names.
332
+ value_count_api_symbol = return_df["api_symbol"]\
333
+ .value_counts()
334
+ if not (value_count_api_symbol == 1).all():
335
+ duplicates = value_count_api_symbol[
336
+ value_count_api_symbol != 1].index.tolist()
337
+ msg = "Duplicate api_symbols: {duplicates}"
338
+ raise BitfinexAPIDataValidationError(
339
+ message=msg, payload={"duplicates": duplicates})
340
+ return return_df.sort_values("currency_symbol").reset_index(drop=True)
@@ -0,0 +1,31 @@
1
+ """Pydantic contracts for Bitfinex config payloads."""
2
+ from pydantic import BaseModel, ConfigDict, Field
3
+
4
+
5
+ class PairSymbolsContract(BaseModel):
6
+ """Contract for pair symbols."""
7
+
8
+ model_config = ConfigDict(str_strip_whitespace=True)
9
+
10
+ instrument: str = Field(
11
+ description=(
12
+ "The instrument used to identify the pair on Bitfinex "
13
+ "trading endpoints."))
14
+ """The instrument used to identify the pair on Bitfinex trading
15
+ endpoints."""
16
+ trading_prefix: str | None = Field(
17
+ description=(
18
+ "The trading prefix of the pair. Either ``t`` or ``f``."))
19
+ """The trading prefix of the pair. Either ``t`` or ``f``."""
20
+ pair: str = Field(
21
+ description=(
22
+ "The pair symbol of the pair."))
23
+ """The pair symbol of the pair."""
24
+ base_api_symbol: str = Field(
25
+ description=(
26
+ "The base asset of the pair."))
27
+ """The base asset of the pair."""
28
+ quote_api_symbol: str = Field(
29
+ description=(
30
+ "The quote asset of the pair."))
31
+ """The quote asset of the pair."""
@@ -0,0 +1,7 @@
1
+ """Module to define treatment of Bitfinex config payloads."""
2
+ from bitfinex_api.aux.config.treatment.pair_symbols import TreatmentPairSymbols
3
+
4
+
5
+ __all__ = [
6
+ "TreatmentPairSymbols",
7
+ ]
@@ -0,0 +1,130 @@
1
+ """Split Bitfinex pair codes into base and quote legs."""
2
+ import pandas as pd
3
+ from loguru import logger
4
+
5
+ from bitfinex_api.aux.config.contracts import PairSymbolsContract
6
+ from bitfinex_api.exceptions import BitfinexAPIInvalidParametersError
7
+
8
+
9
+ class TreatmentPairSymbols:
10
+ """Treatment of pair symbols."""
11
+
12
+ QUOTE_PAIR_COLUMNS: tuple[str, ...] = tuple(
13
+ PairSymbolsContract.model_fields.keys())
14
+ """DataFrame columns aligned with ``PairSymbolsContract``."""
15
+
16
+ @staticmethod
17
+ def split_trading_prefix(symbol: str) -> tuple[str | None, str]:
18
+ """Split leading ``t`` or ``f`` from a REST pair symbol.
19
+
20
+ Args:
21
+ symbol (str):
22
+ Value from ``pub:list:pair`` or candle ``par``.
23
+
24
+ Returns:
25
+ tuple[str | None, str]:
26
+ Trading prefix (``t`` or ``f``) and legs without prefix.
27
+ """
28
+ text = (symbol or "").strip()
29
+ if len(text) > 1 and text[0] in ("t", "f"):
30
+ return text[0], text[1:]
31
+ return None, text
32
+
33
+ @classmethod
34
+ def split_pair_list(
35
+ cls,
36
+ currency_pair_list: list[str],
37
+ currency_codes: list[str]) -> pd.DataFrame:
38
+ """Split pair codes into base and quote assets.
39
+
40
+ Args:
41
+ currency_pair_list (list[str]):
42
+ Symbols from ``pub:list:pair``.
43
+ currency_codes (list[str]):
44
+ Platform currencies from ``pub:list:currency``.
45
+
46
+ Returns:
47
+ pd.DataFrame:
48
+ One row per pair; columns match ``PairSymbolsContract``.
49
+ """
50
+ rows = [
51
+ cls.split_pair(pair, currency_codes).model_dump()
52
+ for pair in currency_pair_list
53
+ ]
54
+ return pd.DataFrame(rows, columns=list(cls.QUOTE_PAIR_COLUMNS))
55
+
56
+ @classmethod
57
+ def split_pair(
58
+ cls,
59
+ pair: str,
60
+ currency_codes: list[str]) -> PairSymbolsContract:
61
+ """Parse base and quote assets from one pair code.
62
+
63
+ Colon notation (``DOGE:USD``) splits on the first colon. Concatenated
64
+ notation (``BTCUSD``) matches the longest known quote suffix from
65
+ ``currency_codes``.
66
+
67
+ Args:
68
+ pair (str):
69
+ Bitfinex pair (with or without leading ``t``/``f``).
70
+ currency_codes (list[str]):
71
+ Platform currencies from ``pub:list:currency``.
72
+
73
+ Returns:
74
+ PairSymbolsContract:
75
+ Validated instrument and leg fields.
76
+
77
+ Raises:
78
+ BitfinexAPIInvalidParametersError:
79
+ When the pair cannot be split.
80
+ """
81
+ instrument = (pair or "").strip()
82
+ if instrument == "":
83
+ msg = "Empty Bitfinex pair symbol."
84
+ raise BitfinexAPIInvalidParametersError(message=msg)
85
+
86
+ trading_prefix, legs = cls.split_trading_prefix(symbol=instrument)
87
+ if ":" in legs:
88
+ base, quote = legs.split(":", 1)
89
+ if base == "" or quote == "":
90
+ msg = "Invalid colon pair symbol: {pair}"
91
+ raise BitfinexAPIInvalidParametersError(
92
+ message=msg,
93
+ payload={"pair": instrument})
94
+ return PairSymbolsContract(
95
+ instrument=instrument,
96
+ trading_prefix=trading_prefix,
97
+ pair=legs,
98
+ base_api_symbol=base,
99
+ quote_api_symbol=quote)
100
+
101
+ quotes = sorted({
102
+ code.strip().upper()
103
+ for code in currency_codes
104
+ if code.strip()},
105
+ key=len,
106
+ reverse=True)
107
+
108
+ legs_upper = legs.upper()
109
+ for quote_upper in quotes:
110
+ q_len = len(quote_upper)
111
+ if q_len == 0 or len(legs_upper) <= q_len:
112
+ continue
113
+
114
+ if legs_upper.endswith(quote_upper):
115
+ base = legs[:-q_len]
116
+ quote = legs[-q_len:]
117
+ if base == "":
118
+ continue
119
+ return PairSymbolsContract(
120
+ instrument=instrument,
121
+ trading_prefix=trading_prefix,
122
+ pair=legs,
123
+ base_api_symbol=base,
124
+ quote_api_symbol=quote)
125
+
126
+ msg = "Could not split pair into base and quote: {pair}"
127
+ logger.warning(msg, pair=instrument)
128
+ raise BitfinexAPIInvalidParametersError(
129
+ message=msg,
130
+ payload={"pair": instrument})
@@ -0,0 +1,5 @@
1
+ """Shared auxiliary helpers (datetime, etc.)."""
2
+ from bitfinex_api.aux.misc.datetime_aux import (
3
+ datetime_to_epoch_ms, epoch_ms_to_timestamp,)
4
+
5
+ __all__ = ["datetime_to_epoch_ms", "epoch_ms_to_timestamp"]