unicex 0.1.15__py3-none-any.whl → 0.1.18__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.
unicex/_abc/adapter.py CHANGED
@@ -1,3 +1,5 @@
1
+ __all__ = ["IAdapter"]
2
+
1
3
  from abc import ABC, abstractmethod
2
4
  from typing import Any
3
5
 
@@ -1,6 +1,7 @@
1
1
  __all__ = ["BaseClient"]
2
2
 
3
3
  import asyncio
4
+ import json
4
5
  from itertools import cycle
5
6
  from typing import Any, Self
6
7
 
@@ -169,27 +170,45 @@ class BaseClient:
169
170
  Возвращает:
170
171
  `dict | list`: Ответ API в формате JSON.
171
172
  """
173
+ response_text = await response.text()
174
+ status_code = response.status
175
+
176
+ # Парсинг JSON
172
177
  try:
173
- response.raise_for_status()
174
- except Exception as e:
175
- response_text = await response.text()
178
+ response_json = json.loads(response_text)
179
+ except json.JSONDecodeError as e:
176
180
  raise ResponseError(
177
- f"HTTP error: {e}. Response: {response_text}. Status code: {response.status}"
178
- ) from e
181
+ f"JSONDecodeError: {e}. Response: {response_text}. Status code: {response.status}",
182
+ status_code=status_code,
183
+ response_text=response_text,
184
+ ) from None
179
185
 
186
+ # Проверка HTTP-статуса
180
187
  try:
181
- result = await response.json()
188
+ response.raise_for_status()
182
189
  except Exception as e:
190
+ error_code = next(
191
+ (
192
+ response_json[k]
193
+ for k in ("code", "err_code", "errCode", "status")
194
+ if k in response_json
195
+ ),
196
+ "",
197
+ )
183
198
  raise ResponseError(
184
- f"JSONDecodeError error: {e}. Response: {response.text}. Status code: {response.status}"
185
- ) from e
186
-
199
+ f"HTTP error: {e}. Response: {response_json}. Status code: {response.status}",
200
+ status_code=status_code,
201
+ code=error_code,
202
+ response_text=response_text,
203
+ response_json=response_json,
204
+ ) from None
205
+
206
+ # Логирование ответа
187
207
  try:
188
- result_str: str = str(result)
189
208
  self._logger.debug(
190
- f"Response: {result_str[:100]}{'...' if len(result_str) > 100 else ''}"
209
+ f"Response: {response_text[:300]}{'...' if len(response_text) > 300 else ''}"
191
210
  )
192
211
  except Exception as e:
193
- self._logger.error(f"Error while log response: {e}")
212
+ self._logger.error(f"Error while logging response: {e}")
194
213
 
195
- return result
214
+ return response_json
@@ -183,7 +183,12 @@ class Websocket:
183
183
  break
184
184
  except Exception as e:
185
185
  self._logger.error(f"{self} Error({type(e)}) while processing message: {e}")
186
- self._queue.task_done()
186
+
187
+ try:
188
+ self._queue.task_done()
189
+ except Exception as e:
190
+ if self._running:
191
+ self._logger.error(f"{self} Error({type(e)}) while marking task done: {e}")
187
192
 
188
193
  def _generate_ws_kwargs(self) -> dict:
189
194
  """Генерирует аргументы для запуска вебсокета."""
@@ -1,5 +1,6 @@
1
1
  __all__ = ["BaseClient"]
2
2
 
3
+ import json
3
4
  import time
4
5
  from itertools import cycle
5
6
  from typing import Any, Self
@@ -133,37 +134,53 @@ class BaseClient:
133
134
  ) from errors[-1]
134
135
 
135
136
  def _handle_response(self, response: requests.Response) -> Any:
136
- """Обрабатывает HTTP‑ответ.
137
+ """Обрабатывает HTTP-ответ.
137
138
 
138
139
  Параметры:
139
- response (`requests.Response`): Ответ HTTP‑запроса.
140
+ response (`requests.Response`): Ответ HTTP-запроса.
140
141
 
141
142
  Возвращает:
142
143
  `dict | list`: Ответ API в формате JSON.
143
144
  """
145
+ response_text = response.text
146
+ status_code = response.status_code
147
+
148
+ # Парсинг JSON
144
149
  try:
145
- response.raise_for_status()
146
- except Exception as e:
150
+ response_json = json.loads(response_text)
151
+ except json.JSONDecodeError as e:
147
152
  raise ResponseError(
148
- f"HTTP error: {e}. Response: {response.text}. Status code: {response.status_code}"
149
- ) from e
150
-
151
- if not response.content:
152
- raise ResponseError(f"Empty response. Status code: {response.status_code}")
153
+ f"JSONDecodeError: {e}. Response: {response_text}. Status code: {status_code}",
154
+ status_code=status_code,
155
+ response_text=response_text,
156
+ ) from None
153
157
 
158
+ # Проверка HTTP-статуса
154
159
  try:
155
- result = response.json()
156
- except requests.exceptions.JSONDecodeError as e:
160
+ response.raise_for_status()
161
+ except Exception as e:
162
+ error_code = next(
163
+ (
164
+ response_json[k]
165
+ for k in ("code", "err_code", "errCode", "status")
166
+ if k in response_json
167
+ ),
168
+ "",
169
+ )
157
170
  raise ResponseError(
158
- f"JSONDecodeError error: {e}. Response: {response.text}. Status code: {response.status_code}"
159
- ) from e
160
-
171
+ f"HTTP error: {e}. Response: {response_json}. Status code: {status_code}",
172
+ status_code=status_code,
173
+ code=error_code,
174
+ response_text=response_text,
175
+ response_json=response_json,
176
+ ) from None
177
+
178
+ # Логирование ответа
161
179
  try:
162
- result_str: str = str(result)
163
180
  self._logger.debug(
164
- f"Response: {result_str[:100]}{'...' if len(result_str) > 100 else ''}"
181
+ f"Response: {response_text[:300]}{'...' if len(response_text) > 300 else ''}"
165
182
  )
166
183
  except Exception as e:
167
- self._logger.error(f"Error while log response: {e}")
184
+ self._logger.error(f"Error while logging response: {e}")
168
185
 
169
- return result
186
+ return response_json
@@ -2,8 +2,7 @@ __all__ = ["UserWebsocketMixin"]
2
2
 
3
3
 
4
4
  from unicex.exceptions import NotSupported
5
-
6
- from ..types import AccountType
5
+ from unicex.types import AccountType
7
6
 
8
7
 
9
8
  class UserWebsocketMixin:
unicex/binance/adapter.py CHANGED
@@ -2,14 +2,15 @@ __all__ = ["Adapter"]
2
2
 
3
3
 
4
4
  from unicex._abc import IAdapter
5
- from unicex.exceptions import AdapterError
6
5
  from unicex.types import AggTradeDict, KlineDict, TickerDailyDict, TradeDict
6
+ from unicex.utils import catch_adapter_errors
7
7
 
8
8
 
9
9
  class Adapter(IAdapter):
10
10
  """Адаптер для унификации данных с Binance API."""
11
11
 
12
12
  @staticmethod
13
+ @catch_adapter_errors
13
14
  def tickers(raw_data: list[dict], only_usdt: bool = True) -> list[str]:
14
15
  """Преобразует сырой ответ, в котором содержатся данные о тикерах в список тикеров.
15
16
 
@@ -20,18 +21,12 @@ class Adapter(IAdapter):
20
21
  Возвращает:
21
22
  list[str]: Список тикеров.
22
23
  """
23
- try:
24
- return [
25
- item["symbol"]
26
- for item in raw_data
27
- if not only_usdt or item["symbol"].endswith("USDT")
28
- ]
29
- except Exception as e:
30
- raise AdapterError(
31
- f"({type(e)}): {e}. Can not convert {raw_data} to unified tickers."
32
- ) from e
24
+ return [
25
+ item["symbol"] for item in raw_data if not only_usdt or item["symbol"].endswith("USDT")
26
+ ]
33
27
 
34
28
  @staticmethod
29
+ @catch_adapter_errors
35
30
  def futures_tickers(raw_data: list[dict], only_usdt: bool = True) -> list[str]:
36
31
  """Преобразует сырой ответ, в котором содержатся данные о тикерах в список тикеров.
37
32
 
@@ -45,6 +40,7 @@ class Adapter(IAdapter):
45
40
  return Adapter.tickers(raw_data, only_usdt)
46
41
 
47
42
  @staticmethod
43
+ @catch_adapter_errors
48
44
  def ticker_24h(raw_data: list[dict]) -> dict[str, TickerDailyDict]:
49
45
  """Преобразует сырой ответ, в котором содержатся данные о тикере за последние 24 часа в унифицированный формат.
50
46
 
@@ -54,21 +50,17 @@ class Adapter(IAdapter):
54
50
  Возвращает:
55
51
  dict[str, TickerDailyDict]: Словарь, где ключ - тикер, а значение - статистика за последние 24 часа.
56
52
  """
57
- try:
58
- return {
59
- item["symbol"]: TickerDailyDict(
60
- p=float(item["priceChangePercent"]),
61
- q=float(item["quoteVolume"]), # объём в долларах
62
- v=float(item["volume"]), # объём в монетах
63
- )
64
- for item in raw_data
65
- }
66
- except Exception as e:
67
- raise AdapterError(
68
- f"({type(e)}): {e}. Can not convert {raw_data} to unified ticker 24h."
69
- ) from e
53
+ return {
54
+ item["symbol"]: TickerDailyDict(
55
+ p=float(item["priceChangePercent"]),
56
+ q=float(item["quoteVolume"]), # объём в долларах
57
+ v=float(item["volume"]), # объём в монетах
58
+ )
59
+ for item in raw_data
60
+ }
70
61
 
71
62
  @staticmethod
63
+ @catch_adapter_errors
72
64
  def futures_ticker_24h(raw_data: list[dict]) -> dict[str, TickerDailyDict]:
73
65
  """Преобразует сырой ответ, в котором содержатся данные о тикере за последние 24 часа в унифицированный формат.
74
66
 
@@ -81,6 +73,7 @@ class Adapter(IAdapter):
81
73
  return Adapter.ticker_24h(raw_data)
82
74
 
83
75
  @staticmethod
76
+ @catch_adapter_errors
84
77
  def last_price(raw_data: list[dict]) -> dict[str, float]:
85
78
  """Преобразует сырой ответ, в котором содержатся данные о тикере за последние 24 часа в унифицированный формат.
86
79
 
@@ -90,14 +83,10 @@ class Adapter(IAdapter):
90
83
  Возвращает:
91
84
  dict[str, float]: Словарь, где ключ - тикер, а значение - последняя цена.
92
85
  """
93
- try:
94
- return {item["symbol"]: float(item["price"]) for item in raw_data}
95
- except Exception as e:
96
- raise AdapterError(
97
- f"({type(e)}): {e}. Can not convert {raw_data} to unified last price."
98
- ) from e
86
+ return {item["symbol"]: float(item["price"]) for item in raw_data}
99
87
 
100
88
  @staticmethod
89
+ @catch_adapter_errors
101
90
  def futures_last_price(raw_data: list[dict]) -> dict[str, float]:
102
91
  """Преобразует сырой ответ, в котором содержатся данные о тикере за последние 24 часа в унифицированный формат.
103
92
 
@@ -110,6 +99,7 @@ class Adapter(IAdapter):
110
99
  return Adapter.last_price(raw_data)
111
100
 
112
101
  @staticmethod
102
+ @catch_adapter_errors
113
103
  def klines(raw_data: list[list]) -> list[KlineDict]:
114
104
  """Преобразует сырой ответ, в котором содержатся данные о котировках тикеров в унифицированный формат.
115
105
 
@@ -119,28 +109,24 @@ class Adapter(IAdapter):
119
109
  Возвращает:
120
110
  list[KlineDict]: Список словарей, где каждый словарь содержит данные о свече.
121
111
  """
122
- try:
123
- return [
124
- KlineDict(
125
- s="",
126
- t=item[0],
127
- o=float(item[1]),
128
- h=float(item[2]),
129
- l=float(item[3]),
130
- c=float(item[4]),
131
- v=float(item[5]),
132
- q=float(item[7]),
133
- T=item[6],
134
- x=None,
135
- )
136
- for item in raw_data
137
- ]
138
- except Exception as e:
139
- raise AdapterError(
140
- f"({type(e)}): {e}. Can not convert {raw_data} to unified kline."
141
- ) from e
112
+ return [
113
+ KlineDict(
114
+ s="",
115
+ t=item[0],
116
+ o=float(item[1]),
117
+ h=float(item[2]),
118
+ l=float(item[3]),
119
+ c=float(item[4]),
120
+ v=float(item[5]),
121
+ q=float(item[7]),
122
+ T=item[6],
123
+ x=None,
124
+ )
125
+ for item in raw_data
126
+ ]
142
127
 
143
128
  @staticmethod
129
+ @catch_adapter_errors
144
130
  def futures_klines(raw_data: list[list]) -> list[KlineDict]:
145
131
  """Преобразует сырой ответ, в котором содержатся данные о котировках тикеров в унифицированный формат.
146
132
 
@@ -153,6 +139,7 @@ class Adapter(IAdapter):
153
139
  return Adapter.klines(raw_data)
154
140
 
155
141
  @staticmethod
142
+ @catch_adapter_errors
156
143
  def funding_rate(raw_data: list[dict]) -> dict[str, float]:
157
144
  """Преобразует сырой ответ, в котором содержатся данные о ставках финансирования тикеров в унифицированный формат.
158
145
 
@@ -162,14 +149,10 @@ class Adapter(IAdapter):
162
149
  Возвращает:
163
150
  dict[str, float]: Словарь, где ключ - тикер, а значение - ставка финансирования.
164
151
  """
165
- try:
166
- return {item["symbol"]: float(item["lastFundingRate"]) * 100 for item in raw_data}
167
- except Exception as e:
168
- raise AdapterError(
169
- f"({type(e)}): {e}. Can not convert {raw_data} to unified funding rate."
170
- ) from e
152
+ return {item["symbol"]: float(item["lastFundingRate"]) * 100 for item in raw_data}
171
153
 
172
154
  @staticmethod
155
+ @catch_adapter_errors
173
156
  def klines_message(raw_msg: dict) -> list[KlineDict]:
174
157
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
175
158
  свече/свечах в унифицированный вид.
@@ -180,29 +163,25 @@ class Adapter(IAdapter):
180
163
  Возвращает:
181
164
  list[KlineDict]: Список словарей, где каждый словарь содержит данные о свече.
182
165
  """
183
- try:
184
- # Обрабатываем обертку в случае с multiplex stream
185
- kline = raw_msg.get("data", raw_msg)["k"]
186
- return [
187
- KlineDict(
188
- s=kline["s"],
189
- t=kline["t"],
190
- o=float(kline["o"]),
191
- h=float(kline["h"]),
192
- l=float(kline["l"]),
193
- c=float(kline["c"]),
194
- v=float(kline["v"]), # Используем quote volume (в USDT)
195
- q=float(kline["q"]), # Используем quote volume (в USDT)
196
- T=kline["T"],
197
- x=kline["x"],
198
- )
199
- ]
200
- except Exception as e:
201
- raise AdapterError(
202
- f"({type(e)}): {e}. Can not convert {raw_msg} to unified kline."
203
- ) from e
166
+ # Обрабатываем обертку в случае с multiplex stream
167
+ kline = raw_msg.get("data", raw_msg)["k"]
168
+ return [
169
+ KlineDict(
170
+ s=kline["s"],
171
+ t=kline["t"],
172
+ o=float(kline["o"]),
173
+ h=float(kline["h"]),
174
+ l=float(kline["l"]),
175
+ c=float(kline["c"]),
176
+ v=float(kline["v"]), # Используем quote volume (в USDT)
177
+ q=float(kline["q"]), # Используем quote volume (в USDT)
178
+ T=kline["T"],
179
+ x=kline["x"],
180
+ )
181
+ ]
204
182
 
205
183
  @staticmethod
184
+ @catch_adapter_errors
206
185
  def futures_klines_message(raw_msg: dict) -> list[KlineDict]:
207
186
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
208
187
  свече/свечах в унифицированный вид.
@@ -216,6 +195,7 @@ class Adapter(IAdapter):
216
195
  return Adapter.klines_message(raw_msg)
217
196
 
218
197
  @staticmethod
198
+ @catch_adapter_errors
219
199
  def aggtrades_message(raw_msg: dict) -> list[AggTradeDict]:
220
200
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
221
201
  аггрегированных сделке/сделках в унифицированный вид.
@@ -226,23 +206,19 @@ class Adapter(IAdapter):
226
206
  Возвращает:
227
207
  list[KlineDict]: Список словарей, где каждый словарь содержит данные о сделке.
228
208
  """
229
- try:
230
- msg = raw_msg.get("data", raw_msg)
231
- return [
232
- AggTradeDict(
233
- t=int(msg["T"]),
234
- s=str(msg["s"]),
235
- S="SELL" if bool(msg["m"]) else "BUY",
236
- p=float(msg["p"]),
237
- v=float(msg["q"]),
238
- )
239
- ]
240
- except Exception as e:
241
- raise AdapterError(
242
- f"({type(e)}): {e}. Can not convert {raw_msg} to unified aggtrade."
243
- ) from e
209
+ msg = raw_msg.get("data", raw_msg)
210
+ return [
211
+ AggTradeDict(
212
+ t=int(msg["T"]),
213
+ s=str(msg["s"]),
214
+ S="SELL" if bool(msg["m"]) else "BUY",
215
+ p=float(msg["p"]),
216
+ v=float(msg["q"]),
217
+ )
218
+ ]
244
219
 
245
220
  @staticmethod
221
+ @catch_adapter_errors
246
222
  def futures_aggtrades_message(raw_msg: dict) -> list[AggTradeDict]:
247
223
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
248
224
  аггрегированных сделке/сделках в унифицированный вид.
@@ -256,6 +232,7 @@ class Adapter(IAdapter):
256
232
  return Adapter.aggtrades_message(raw_msg)
257
233
 
258
234
  @staticmethod
235
+ @catch_adapter_errors
259
236
  def trades_message(raw_msg: dict) -> list[TradeDict]:
260
237
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
261
238
  сделке/сделках в унифицированный вид.
@@ -266,23 +243,19 @@ class Adapter(IAdapter):
266
243
  Возвращает:
267
244
  list[KlineDict]: Список словарей, где каждый словарь содержит данные о сделке.
268
245
  """
269
- try:
270
- msg = raw_msg.get("data", raw_msg)
271
- return [
272
- TradeDict(
273
- t=int(msg["T"]),
274
- s=str(msg["s"]),
275
- S="SELL" if bool(msg["m"]) else "BUY",
276
- p=float(msg["p"]),
277
- v=float(msg["q"]),
278
- )
279
- ]
280
- except Exception as e:
281
- raise AdapterError(
282
- f"({type(e)}): {e}. Can not convert {raw_msg} to unified trade."
283
- ) from e
246
+ msg = raw_msg.get("data", raw_msg)
247
+ return [
248
+ TradeDict(
249
+ t=int(msg["T"]),
250
+ s=str(msg["s"]),
251
+ S="SELL" if bool(msg["m"]) else "BUY",
252
+ p=float(msg["p"]),
253
+ v=float(msg["q"]),
254
+ )
255
+ ]
284
256
 
285
257
  @staticmethod
258
+ @catch_adapter_errors
286
259
  def futures_trades_message(raw_msg: dict) -> list[TradeDict]:
287
260
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
288
261
  сделке/сделках в унифицированный вид.
@@ -296,6 +269,7 @@ class Adapter(IAdapter):
296
269
  return Adapter.trades_message(raw_msg)
297
270
 
298
271
  @staticmethod
272
+ @catch_adapter_errors
299
273
  def open_interest(raw_data: dict) -> float:
300
274
  """Преобразует сырое сообщение с вебсокета, в котором содержится информация о
301
275
  объеме открытых позиций в унифицированный вид.
@@ -306,9 +280,4 @@ class Adapter(IAdapter):
306
280
  Возвращает:
307
281
  float: Объем открытых позиций в монетах.
308
282
  """
309
- try:
310
- return float(raw_data["openInterest"])
311
- except Exception as e:
312
- raise AdapterError(
313
- f"{type(e)}: {e}. Can not convert {raw_data} to unified open interest."
314
- ) from e
283
+ return float(raw_data["openInterest"])