unicex 0.13.17__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.
Files changed (93) hide show
  1. unicex/__init__.py +200 -0
  2. unicex/_abc/__init__.py +11 -0
  3. unicex/_abc/exchange_info.py +216 -0
  4. unicex/_abc/uni_client.py +329 -0
  5. unicex/_abc/uni_websocket_manager.py +294 -0
  6. unicex/_base/__init__.py +9 -0
  7. unicex/_base/client.py +214 -0
  8. unicex/_base/websocket.py +261 -0
  9. unicex/binance/__init__.py +27 -0
  10. unicex/binance/adapter.py +202 -0
  11. unicex/binance/client.py +1577 -0
  12. unicex/binance/exchange_info.py +62 -0
  13. unicex/binance/uni_client.py +188 -0
  14. unicex/binance/uni_websocket_manager.py +166 -0
  15. unicex/binance/user_websocket.py +186 -0
  16. unicex/binance/websocket_manager.py +912 -0
  17. unicex/bitget/__init__.py +27 -0
  18. unicex/bitget/adapter.py +188 -0
  19. unicex/bitget/client.py +2514 -0
  20. unicex/bitget/exchange_info.py +48 -0
  21. unicex/bitget/uni_client.py +198 -0
  22. unicex/bitget/uni_websocket_manager.py +275 -0
  23. unicex/bitget/user_websocket.py +7 -0
  24. unicex/bitget/websocket_manager.py +232 -0
  25. unicex/bybit/__init__.py +27 -0
  26. unicex/bybit/adapter.py +208 -0
  27. unicex/bybit/client.py +1876 -0
  28. unicex/bybit/exchange_info.py +53 -0
  29. unicex/bybit/uni_client.py +200 -0
  30. unicex/bybit/uni_websocket_manager.py +291 -0
  31. unicex/bybit/user_websocket.py +7 -0
  32. unicex/bybit/websocket_manager.py +339 -0
  33. unicex/enums.py +273 -0
  34. unicex/exceptions.py +64 -0
  35. unicex/extra.py +335 -0
  36. unicex/gate/__init__.py +27 -0
  37. unicex/gate/adapter.py +178 -0
  38. unicex/gate/client.py +1667 -0
  39. unicex/gate/exchange_info.py +55 -0
  40. unicex/gate/uni_client.py +214 -0
  41. unicex/gate/uni_websocket_manager.py +269 -0
  42. unicex/gate/user_websocket.py +7 -0
  43. unicex/gate/websocket_manager.py +513 -0
  44. unicex/hyperliquid/__init__.py +27 -0
  45. unicex/hyperliquid/adapter.py +261 -0
  46. unicex/hyperliquid/client.py +2315 -0
  47. unicex/hyperliquid/exchange_info.py +119 -0
  48. unicex/hyperliquid/uni_client.py +325 -0
  49. unicex/hyperliquid/uni_websocket_manager.py +269 -0
  50. unicex/hyperliquid/user_websocket.py +7 -0
  51. unicex/hyperliquid/websocket_manager.py +393 -0
  52. unicex/mapper.py +111 -0
  53. unicex/mexc/__init__.py +27 -0
  54. unicex/mexc/_spot_ws_proto/PrivateAccountV3Api_pb2.py +38 -0
  55. unicex/mexc/_spot_ws_proto/PrivateDealsV3Api_pb2.py +38 -0
  56. unicex/mexc/_spot_ws_proto/PrivateOrdersV3Api_pb2.py +38 -0
  57. unicex/mexc/_spot_ws_proto/PublicAggreBookTickerV3Api_pb2.py +38 -0
  58. unicex/mexc/_spot_ws_proto/PublicAggreDealsV3Api_pb2.py +40 -0
  59. unicex/mexc/_spot_ws_proto/PublicAggreDepthsV3Api_pb2.py +40 -0
  60. unicex/mexc/_spot_ws_proto/PublicBookTickerBatchV3Api_pb2.py +38 -0
  61. unicex/mexc/_spot_ws_proto/PublicBookTickerV3Api_pb2.py +38 -0
  62. unicex/mexc/_spot_ws_proto/PublicDealsV3Api_pb2.py +40 -0
  63. unicex/mexc/_spot_ws_proto/PublicFuture_pb2.py +103 -0
  64. unicex/mexc/_spot_ws_proto/PublicIncreaseDepthsBatchV3Api_pb2.py +38 -0
  65. unicex/mexc/_spot_ws_proto/PublicIncreaseDepthsV3Api_pb2.py +40 -0
  66. unicex/mexc/_spot_ws_proto/PublicLimitDepthsV3Api_pb2.py +40 -0
  67. unicex/mexc/_spot_ws_proto/PublicMiniTickerV3Api_pb2.py +38 -0
  68. unicex/mexc/_spot_ws_proto/PublicMiniTickersV3Api_pb2.py +38 -0
  69. unicex/mexc/_spot_ws_proto/PublicSpotKlineV3Api_pb2.py +38 -0
  70. unicex/mexc/_spot_ws_proto/PushDataV3ApiWrapper_pb2.py +38 -0
  71. unicex/mexc/_spot_ws_proto/__init__.py +335 -0
  72. unicex/mexc/adapter.py +239 -0
  73. unicex/mexc/client.py +846 -0
  74. unicex/mexc/exchange_info.py +47 -0
  75. unicex/mexc/uni_client.py +211 -0
  76. unicex/mexc/uni_websocket_manager.py +269 -0
  77. unicex/mexc/user_websocket.py +7 -0
  78. unicex/mexc/websocket_manager.py +456 -0
  79. unicex/okx/__init__.py +27 -0
  80. unicex/okx/adapter.py +150 -0
  81. unicex/okx/client.py +2864 -0
  82. unicex/okx/exchange_info.py +47 -0
  83. unicex/okx/uni_client.py +202 -0
  84. unicex/okx/uni_websocket_manager.py +269 -0
  85. unicex/okx/user_websocket.py +7 -0
  86. unicex/okx/websocket_manager.py +743 -0
  87. unicex/types.py +164 -0
  88. unicex/utils.py +218 -0
  89. unicex-0.13.17.dist-info/METADATA +243 -0
  90. unicex-0.13.17.dist-info/RECORD +93 -0
  91. unicex-0.13.17.dist-info/WHEEL +5 -0
  92. unicex-0.13.17.dist-info/licenses/LICENSE +28 -0
  93. unicex-0.13.17.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1577 @@
1
+ __all__ = ["Client"]
2
+
3
+ import json
4
+ import time
5
+ import warnings
6
+ from typing import Any
7
+
8
+ from unicex._base import BaseClient
9
+ from unicex.exceptions import NotAuthorized
10
+ from unicex.types import RequestMethod
11
+ from unicex.utils import dict_to_query_string, filter_params, generate_hmac_sha256_signature
12
+
13
+
14
+ class Client(BaseClient):
15
+ """Клиент для работы с Binance API."""
16
+
17
+ _BASE_SPOT_URL: str = "https://api.binance.com"
18
+ """Базовый URL для REST API Binance Spot."""
19
+
20
+ _BASE_FUTURES_URL: str = "https://fapi.binance.com"
21
+ """Базовый URL для REST API Binance Futures."""
22
+
23
+ _RECV_WINDOW: int = 5000
24
+ """Стандартный интервал времени для получения ответа от сервера."""
25
+
26
+ def _get_headers(self, method: RequestMethod) -> dict:
27
+ """Возвращает заголовки для запросов к Binance API."""
28
+ headers = {"Accept": "application/json"}
29
+ if self._api_key: # type: ignore[attr-defined]
30
+ headers["X-MBX-APIKEY"] = self._api_key # type: ignore[attr-defined]
31
+ if method in ["POST", "PUT", "DELETE"]:
32
+ headers.update({"Content-Type": "application/x-www-form-urlencoded"})
33
+ return headers
34
+
35
+ def _prepare_payload(
36
+ self,
37
+ *,
38
+ method: RequestMethod,
39
+ signed: bool,
40
+ params: dict[str, Any] | None,
41
+ ) -> tuple[dict[str, Any], dict[str, Any] | None]:
42
+ """Подготавливает payload и заголовки для запроса.
43
+
44
+ Если signed=True:
45
+ - добавляет подпись и все обязательные параметры в заголовки
46
+
47
+ Если signed=False:
48
+ - возвращает только отфильтрованные params.
49
+
50
+ Параметры:
51
+ method (`RequestMethod`): Метод запроса.
52
+ signed (`bool`): Нужно ли подписывать запрос.
53
+ params (`dict | None`): Параметры для query string.
54
+
55
+ Возвращает:
56
+ tuple:
57
+ - payload (`dict`): Параметры/тело запроса с подписью (если нужно).
58
+ - headers (`dict | None`): Заголовки для запроса или None.
59
+ """
60
+ # Фильтруем параметры от None значений
61
+ params = filter_params(params) if params else {}
62
+
63
+ # Получаем заголовки для запроса
64
+ headers = self._get_headers(method)
65
+
66
+ if not signed:
67
+ return {"params": params}, headers
68
+
69
+ if not self.is_authorized():
70
+ raise NotAuthorized("Api key and api secret is required to private endpoints")
71
+
72
+ # Объединяем все параметры в payload
73
+ payload = {**params}
74
+ payload["timestamp"] = int(time.time() * 1000)
75
+ payload["recvWindow"] = self._RECV_WINDOW
76
+
77
+ # Генерируем подпись
78
+ query_string = dict_to_query_string(payload)
79
+ payload["signature"] = generate_hmac_sha256_signature(
80
+ self._api_secret, # type: ignore[attr-defined]
81
+ query_string,
82
+ "hex",
83
+ )
84
+
85
+ return payload, headers
86
+
87
+ async def _make_request(
88
+ self,
89
+ method: RequestMethod,
90
+ url: str,
91
+ signed: bool = False,
92
+ *,
93
+ params: dict[str, Any] | None = None,
94
+ ) -> Any:
95
+ """Выполняет HTTP-запрос к эндпоинтам Binance API.
96
+
97
+ Если signed=True, формируется подпись для приватных endpoint'ов:
98
+ - Если метод запроса "GET" — подпись добавляется в параметры запроса.
99
+ - Если метод запроса "POST" | "PUT" | "DELETE" — подпись добавляется в тело запроса.
100
+
101
+ Если signed=False, запрос отправляется как публичный.
102
+
103
+ Параметры:
104
+ method (`str`): HTTP метод ("GET", "POST", "DELETE" и т.д.).
105
+ url (`str`): Полный URL эндпоинта Binance API.
106
+ signed (`bool`): Нужно ли подписывать запрос.
107
+ params (`dict | None`): Query-параметры.
108
+
109
+ Возвращает:
110
+ `dict`: Ответ в формате JSON.
111
+ """
112
+ payload, headers = self._prepare_payload(method=method, signed=signed, params=params)
113
+
114
+ if not signed:
115
+ return await super()._make_request(method=method, url=url, **payload)
116
+
117
+ return await super()._make_request(method=method, url=url, params=payload, headers=headers)
118
+
119
+ async def request(
120
+ self, method: RequestMethod, url: str, params: dict, data: dict, signed: bool
121
+ ) -> dict:
122
+ """Специальный метод для выполнения запросов на эндпоинты, которые не обернуты в клиенте.
123
+
124
+ Параметры:
125
+ method (`str`): HTTP метод ("GET", "POST", "DELETE" и т.д.).
126
+ url (`str`): Полный URL эндпоинта Binance API.
127
+ signed (`bool`): Нужно ли подписывать запрос.
128
+ params (`dict | None`): Query-параметры.
129
+ data (`dict | None`): Тело запроса.
130
+
131
+ Возвращает:
132
+ `dict`: Ответ в формате JSON.
133
+ """
134
+ return await self._make_request(method=method, url=url, params=params, signed=signed)
135
+
136
+ # topic: general endpoints
137
+
138
+ async def ping(self) -> dict:
139
+ """Проверка подключения к REST API.
140
+
141
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#test-connectivity
142
+ """
143
+ url = self._BASE_SPOT_URL + "/api/v3/ping"
144
+
145
+ return await self._make_request("GET", url)
146
+
147
+ async def server_time(self) -> dict:
148
+ """Получение серверного времени.
149
+
150
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#check-server-time
151
+ """
152
+ url = self._BASE_SPOT_URL + "/api/v3/time"
153
+
154
+ return await self._make_request("GET", url)
155
+
156
+ async def exchange_info(self) -> dict:
157
+ """Получение информации о символах рынка и текущих правилах биржевой торговли.
158
+
159
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#exchange-information
160
+ """
161
+ url = self._BASE_SPOT_URL + "/api/v3/exchangeInfo"
162
+
163
+ return await self._make_request("GET", url)
164
+
165
+ # topic: market data endpoints
166
+
167
+ async def depth(self, symbol: str, limit: int | None = None) -> dict:
168
+ """Получение книги ордеров.
169
+
170
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#order-book
171
+ """
172
+ url = self._BASE_SPOT_URL + "/api/v3/depth"
173
+ params = {"symbol": symbol, "limit": limit}
174
+
175
+ return await self._make_request("GET", url, params=params)
176
+
177
+ async def trades(self, symbol: str, limit: int | None = None) -> list[dict]:
178
+ """Получение последних сделок.
179
+
180
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#recent-trades-list
181
+ """
182
+ url = self._BASE_SPOT_URL + "/api/v3/trades"
183
+ params = {"symbol": symbol, "limit": limit}
184
+
185
+ return await self._make_request("GET", url, params=params)
186
+
187
+ async def historical_trades(
188
+ self, symbol: str, limit: int | None = None, from_id: int | None = None
189
+ ) -> list[dict]:
190
+ """Исторические сделки.
191
+
192
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#old-trade-lookup
193
+ """
194
+ url = self._BASE_SPOT_URL + "/api/v3/historicalTrades"
195
+ params = {"symbol": symbol, "limit": limit, "fromId": from_id}
196
+
197
+ return await self._make_request("GET", url, params=params)
198
+
199
+ async def agg_trades(
200
+ self,
201
+ symbol: str,
202
+ from_id: int | None = None,
203
+ start_time: int | None = None,
204
+ end_time: int | None = None,
205
+ limit: int | None = None,
206
+ ) -> list[dict]:
207
+ """Получение агрегированных сделок.
208
+
209
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#compressedaggregate-trades-list
210
+ """
211
+ url = self._BASE_SPOT_URL + "/api/v3/aggTrades"
212
+ params = {
213
+ "symbol": symbol,
214
+ "fromId": from_id,
215
+ "startTime": start_time,
216
+ "endTime": end_time,
217
+ "limit": limit,
218
+ }
219
+
220
+ return await self._make_request("GET", url, params=params)
221
+
222
+ async def klines(
223
+ self,
224
+ symbol: str,
225
+ interval: str,
226
+ start_time: int | None = None,
227
+ end_time: int | None = None,
228
+ time_zone: str | None = None,
229
+ limit: int | None = None,
230
+ ) -> list[list]:
231
+ """Получение исторических свечей.
232
+
233
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#klinecandlestick-data
234
+ """
235
+ url = self._BASE_SPOT_URL + "/api/v3/klines"
236
+ params = {
237
+ "symbol": symbol,
238
+ "interval": interval,
239
+ "startTime": start_time,
240
+ "endTime": end_time,
241
+ "timeZone": time_zone,
242
+ "limit": limit,
243
+ }
244
+
245
+ return await self._make_request("GET", url, params=params)
246
+
247
+ async def ui_klines(
248
+ self,
249
+ symbol: str,
250
+ interval: str,
251
+ start_time: int | None = None,
252
+ end_time: int | None = None,
253
+ time_zone: str | None = None,
254
+ limit: int | None = None,
255
+ ) -> list[list]:
256
+ """Получение UI свечей (оптимизированы для отображения).
257
+
258
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#uiklines
259
+ """
260
+ url = self._BASE_SPOT_URL + "/api/v3/uiKlines"
261
+ params = {
262
+ "symbol": symbol,
263
+ "interval": interval,
264
+ "startTime": start_time,
265
+ "endTime": end_time,
266
+ "timeZone": time_zone,
267
+ "limit": limit,
268
+ }
269
+
270
+ return await self._make_request("GET", url, params=params)
271
+
272
+ async def avg_price(self, symbol: str) -> dict:
273
+ """Получение текущей средней цены символа.
274
+
275
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#current-average-price
276
+ """
277
+ url = self._BASE_SPOT_URL + "/api/v3/avgPrice"
278
+ params = {"symbol": symbol}
279
+
280
+ return await self._make_request("GET", url, params=params)
281
+
282
+ async def ticker_24hr(
283
+ self,
284
+ symbol: str | None = None,
285
+ symbols: list[str] | None = None,
286
+ type: str | None = None,
287
+ ) -> dict | list[dict]:
288
+ """Получение статистики изменения цен и объема за 24 часа.
289
+
290
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#24hr-ticker-price-change-statistics
291
+ """
292
+ url = self._BASE_SPOT_URL + "/api/v3/ticker/24hr"
293
+ params = {"symbol": symbol, "type": type, "symbols": symbols}
294
+
295
+ return await self._make_request("GET", url, params=params)
296
+
297
+ async def ticker_trading_day(
298
+ self,
299
+ symbol: str | None = None,
300
+ symbols: list[str] | None = None,
301
+ time_zone: str | None = None,
302
+ type: str | None = None,
303
+ ) -> dict | list[dict]:
304
+ """Статистика изменения цен за торговый день.
305
+
306
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#trading-day-ticker
307
+ """
308
+ url = self._BASE_SPOT_URL + "/api/v3/ticker/tradingDay"
309
+ params = {
310
+ "symbol": symbol,
311
+ "symbols": symbols,
312
+ "timeZone": time_zone,
313
+ "type": type,
314
+ }
315
+
316
+ return await self._make_request("GET", url, params=params)
317
+
318
+ async def ticker_price(
319
+ self, symbol: str | None = None, symbols: list[str] | None = None
320
+ ) -> dict | list[dict]:
321
+ """Получение последней цены тикера(ов).
322
+
323
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#symbol-price-ticker
324
+ """
325
+ url = self._BASE_SPOT_URL + "/api/v3/ticker/price"
326
+ params = {"symbol": symbol, "symbols": symbols}
327
+
328
+ return await self._make_request("GET", url, params=params)
329
+
330
+ async def ticker_book_ticker(
331
+ self, symbol: str | None = None, symbols: list[str] | None = None
332
+ ) -> dict | list[dict]:
333
+ """Получение лучших цен bid/ask в книге ордеров.
334
+
335
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#symbol-order-book-ticker
336
+ """
337
+ url = self._BASE_SPOT_URL + "/api/v3/ticker/bookTicker"
338
+ params = {"symbol": symbol, "symbols": symbols}
339
+
340
+ return await self._make_request("GET", url, params=params)
341
+
342
+ async def ticker(
343
+ self,
344
+ symbol: str | None = None,
345
+ symbols: list[str] | None = None,
346
+ window_size: str | None = None,
347
+ type: str | None = None,
348
+ ) -> dict | list[dict]:
349
+ """Статистика изменения цен в скользящем окне.
350
+
351
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#rolling-window-price-change-statistics
352
+ """
353
+ url = self._BASE_SPOT_URL + "/api/v3/ticker"
354
+ params = {
355
+ "symbol": symbol,
356
+ "symbols": symbols,
357
+ "windowSize": window_size,
358
+ "type": type,
359
+ }
360
+
361
+ return await self._make_request("GET", url, params=params)
362
+
363
+ # topic: trading endpoints
364
+
365
+ async def order_create(
366
+ self,
367
+ symbol: str,
368
+ side: str,
369
+ type: str,
370
+ quantity: float | None = None,
371
+ quote_order_qty: float | None = None,
372
+ price: float | None = None,
373
+ stop_price: float | None = None,
374
+ time_in_force: str | None = None,
375
+ new_client_order_id: str | None = None,
376
+ iceberg_qty: float | None = None,
377
+ new_order_resp_type: str | None = None,
378
+ self_trade_prevention_mode: str | None = None,
379
+ ) -> dict:
380
+ """Создание нового ордера на спот-рынке.
381
+
382
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#new-order-trade
383
+ """
384
+ url = self._BASE_SPOT_URL + "/api/v3/order"
385
+ params = {
386
+ "symbol": symbol,
387
+ "side": side,
388
+ "type": type,
389
+ "quantity": quantity,
390
+ "quoteOrderQty": quote_order_qty,
391
+ "price": price,
392
+ "stopPrice": stop_price,
393
+ "timeInForce": time_in_force,
394
+ "newClientOrderId": new_client_order_id,
395
+ "icebergQty": iceberg_qty,
396
+ "newOrderRespType": new_order_resp_type,
397
+ "selfTradePreventionMode": self_trade_prevention_mode,
398
+ }
399
+
400
+ # return await self._make_request("POST", url, True, params=params)
401
+ return await self._make_request("POST", url, True, params=params)
402
+
403
+ async def order_test(
404
+ self,
405
+ symbol: str,
406
+ side: str,
407
+ type: str,
408
+ quantity: float | None = None,
409
+ quote_order_qty: float | None = None,
410
+ price: float | None = None,
411
+ stop_price: float | None = None,
412
+ time_in_force: str | None = None,
413
+ new_client_order_id: str | None = None,
414
+ iceberg_qty: float | None = None,
415
+ new_order_resp_type: str | None = None,
416
+ self_trade_prevention_mode: str | None = None,
417
+ ) -> dict:
418
+ """Тестирование нового ордера (не выполняется реально).
419
+
420
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#test-new-order-trade
421
+ """
422
+ url = self._BASE_SPOT_URL + "/api/v3/order/test"
423
+ params = {
424
+ "symbol": symbol,
425
+ "side": side,
426
+ "type": type,
427
+ "quantity": quantity,
428
+ "quoteOrderQty": quote_order_qty,
429
+ "price": price,
430
+ "stopPrice": stop_price,
431
+ "timeInForce": time_in_force,
432
+ "newClientOrderId": new_client_order_id,
433
+ "icebergQty": iceberg_qty,
434
+ "newOrderRespType": new_order_resp_type,
435
+ "selfTradePreventionMode": self_trade_prevention_mode,
436
+ }
437
+
438
+ return await self._make_request("POST", url, True, params=params)
439
+
440
+ async def order_cancel(
441
+ self,
442
+ symbol: str,
443
+ order_id: int | None = None,
444
+ orig_client_order_id: str | None = None,
445
+ new_client_order_id: str | None = None,
446
+ ) -> dict:
447
+ """Отмена активного ордера на спот-рынке.
448
+
449
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#cancel-order-trade
450
+ """
451
+ url = self._BASE_SPOT_URL + "/api/v3/order"
452
+ params = {
453
+ "symbol": symbol,
454
+ "orderId": order_id,
455
+ "origClientOrderId": orig_client_order_id,
456
+ "newClientOrderId": new_client_order_id,
457
+ }
458
+
459
+ return await self._make_request("DELETE", url, True, params=params)
460
+
461
+ async def orders_cancel_all(self, symbol: str) -> list[dict]:
462
+ """Отмена всех активных ордеров по символу.
463
+
464
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#cancel-all-open-orders-on-a-symbol-trade
465
+ """
466
+ url = self._BASE_SPOT_URL + "/api/v3/openOrders"
467
+ params = {"symbol": symbol}
468
+
469
+ return await self._make_request("DELETE", url, True, params=params)
470
+
471
+ async def orders_open(self, symbol: str | None = None) -> list[dict]:
472
+ """Получение всех активных ордеров.
473
+
474
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#current-open-orders-user_data
475
+ """
476
+ url = self._BASE_SPOT_URL + "/api/v3/openOrders"
477
+ params = {"symbol": symbol}
478
+
479
+ return await self._make_request("GET", url, True, params=params)
480
+
481
+ async def oco_order_create(
482
+ self,
483
+ symbol: str,
484
+ side: str,
485
+ quantity: str,
486
+ list_client_order_id: str | None = None,
487
+ # ABOVE ORDER
488
+ above_type: str = "TAKE_PROFIT_LIMIT",
489
+ above_client_order_id: str | None = None,
490
+ above_price: str | None = None,
491
+ above_stop_price: str | None = None,
492
+ above_trailing_delta: int | None = None,
493
+ above_time_in_force: str | None = None,
494
+ above_iceberg_qty: str | None = None,
495
+ above_strategy_id: int | None = None,
496
+ above_strategy_type: int | None = None,
497
+ # BELOW ORDER
498
+ below_type: str = "STOP_LOSS_LIMIT",
499
+ below_client_order_id: str | None = None,
500
+ below_price: str | None = None,
501
+ below_stop_price: str | None = None,
502
+ below_trailing_delta: int | None = None,
503
+ below_time_in_force: str | None = None,
504
+ below_iceberg_qty: str | None = None,
505
+ below_strategy_id: int | None = None,
506
+ below_strategy_type: int | None = None,
507
+ # EXTRA
508
+ new_order_resp_type: str | None = None,
509
+ self_trade_prevention_mode: str | None = None,
510
+ ) -> dict:
511
+ """Создание OCO ордера (новая версия).
512
+
513
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade
514
+ """
515
+ url = self._BASE_SPOT_URL + "/api/v3/orderList/oco"
516
+
517
+ params = {
518
+ "symbol": symbol,
519
+ "side": side,
520
+ "quantity": quantity,
521
+ "listClientOrderId": list_client_order_id,
522
+ # ABOVE
523
+ "aboveType": above_type,
524
+ "aboveClientOrderId": above_client_order_id,
525
+ "abovePrice": above_price,
526
+ "aboveStopPrice": above_stop_price,
527
+ "aboveTrailingDelta": above_trailing_delta,
528
+ "aboveTimeInForce": above_time_in_force,
529
+ "aboveIcebergQty": above_iceberg_qty,
530
+ "aboveStrategyId": above_strategy_id,
531
+ "aboveStrategyType": above_strategy_type,
532
+ # BELOW
533
+ "belowType": below_type,
534
+ "belowClientOrderId": below_client_order_id,
535
+ "belowPrice": below_price,
536
+ "belowStopPrice": below_stop_price,
537
+ "belowTrailingDelta": below_trailing_delta,
538
+ "belowTimeInForce": below_time_in_force,
539
+ "belowIcebergQty": below_iceberg_qty,
540
+ "belowStrategyId": below_strategy_id,
541
+ "belowStrategyType": below_strategy_type,
542
+ # EXTRA
543
+ "newOrderRespType": new_order_resp_type,
544
+ "selfTradePreventionMode": self_trade_prevention_mode,
545
+ }
546
+
547
+ return await self._make_request("POST", url, True, params=params)
548
+
549
+ async def oco_order_cancel(
550
+ self,
551
+ symbol: str,
552
+ order_list_id: int | None = None,
553
+ list_client_order_id: str | None = None,
554
+ new_client_order_id: str | None = None,
555
+ ) -> dict:
556
+ """Отмена OCO ордера.
557
+
558
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#cancel-oco-trade
559
+ """
560
+ url = self._BASE_SPOT_URL + "/api/v3/orderList"
561
+ params = {
562
+ "symbol": symbol,
563
+ "orderListId": order_list_id,
564
+ "listClientOrderId": list_client_order_id,
565
+ "newClientOrderId": new_client_order_id,
566
+ }
567
+
568
+ return await self._make_request("DELETE", url, True, params=params)
569
+
570
+ async def oco_order_get(
571
+ self, order_list_id: int | None = None, orig_client_order_id: str | None = None
572
+ ) -> dict:
573
+ """Получение информации об OCO ордере.
574
+
575
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-oco-user_data
576
+ """
577
+ url = self._BASE_SPOT_URL + "/api/v3/orderList"
578
+ params = {
579
+ "orderListId": order_list_id,
580
+ "origClientOrderId": orig_client_order_id,
581
+ }
582
+
583
+ return await self._make_request("GET", url, True, params=params)
584
+
585
+ async def oco_orders_all(
586
+ self,
587
+ from_id: int | None = None,
588
+ start_time: int | None = None,
589
+ end_time: int | None = None,
590
+ limit: int | None = None,
591
+ ) -> list[dict]:
592
+ """Получение всех OCO ордеров.
593
+
594
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-all-oco-user_data
595
+ """
596
+ url = self._BASE_SPOT_URL + "/api/v3/allOrderList"
597
+ params = {
598
+ "fromId": from_id,
599
+ "startTime": start_time,
600
+ "endTime": end_time,
601
+ "limit": limit,
602
+ }
603
+
604
+ return await self._make_request("GET", url, True, params=params)
605
+
606
+ async def oco_orders_open(self) -> list[dict]:
607
+ """Получение активных OCO ордеров.
608
+
609
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-open-oco-user_data
610
+ """
611
+ url = self._BASE_SPOT_URL + "/api/v3/openOrderList"
612
+
613
+ return await self._make_request("GET", url, True)
614
+
615
+ # topic: account endpoints
616
+
617
+ async def account(self) -> dict:
618
+ """Получение информации об аккаунте (балансы, комиссии и т.д.).
619
+
620
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#account-information-user_data
621
+ """
622
+ url = self._BASE_SPOT_URL + "/api/v3/account"
623
+
624
+ return await self._make_request("GET", url, True)
625
+
626
+ async def order_get(
627
+ self,
628
+ symbol: str,
629
+ order_id: int | None = None,
630
+ orig_client_order_id: str | None = None,
631
+ ) -> dict:
632
+ """Получение информации об ордере.
633
+
634
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-order-user_data
635
+ """
636
+ url = self._BASE_SPOT_URL + "/api/v3/order"
637
+ params = {
638
+ "symbol": symbol,
639
+ "orderId": order_id,
640
+ "origClientOrderId": orig_client_order_id,
641
+ }
642
+
643
+ return await self._make_request("GET", url, True, params=params)
644
+
645
+ async def all_orders(
646
+ self,
647
+ symbol: str,
648
+ order_id: int | None = None,
649
+ start_time: int | None = None,
650
+ end_time: int | None = None,
651
+ limit: int | None = None,
652
+ ) -> list[dict]:
653
+ """Получение всех ордеров (активных, отмененных, исполненных) для символа.
654
+
655
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#all-orders-user_data
656
+ """
657
+ url = self._BASE_SPOT_URL + "/api/v3/allOrders"
658
+ params = {
659
+ "symbol": symbol,
660
+ "orderId": order_id,
661
+ "startTime": start_time,
662
+ "endTime": end_time,
663
+ "limit": limit,
664
+ }
665
+
666
+ return await self._make_request("GET", url, True, params=params)
667
+
668
+ async def all_open_orders(
669
+ self,
670
+ symbol: str | None = None,
671
+ ) -> list[dict]:
672
+ """Получение всех ордеров активных ордеров.
673
+
674
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#current-open-orders-user_data
675
+ """
676
+ url = self._BASE_SPOT_URL + "/api/v3/allOrders"
677
+ params = {"symbol": symbol}
678
+
679
+ return await self._make_request("GET", url, True, params=params)
680
+
681
+ async def my_trades(
682
+ self,
683
+ symbol: str,
684
+ order_id: int | None = None,
685
+ start_time: int | None = None,
686
+ end_time: int | None = None,
687
+ from_id: int | None = None,
688
+ limit: int | None = None,
689
+ ) -> list[dict]:
690
+ """Получение торговой истории аккаунта.
691
+
692
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#account-trade-list-user_data
693
+ """
694
+ url = self._BASE_SPOT_URL + "/api/v3/myTrades"
695
+ params = {
696
+ "symbol": symbol,
697
+ "orderId": order_id,
698
+ "startTime": start_time,
699
+ "endTime": end_time,
700
+ "fromId": from_id,
701
+ "limit": limit,
702
+ }
703
+
704
+ return await self._make_request("GET", url, True, params=params)
705
+
706
+ async def order_count_usage(self) -> list[dict]:
707
+ """Получение текущего использования лимитов ордеров.
708
+
709
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-current-order-count-usage-trade
710
+ """
711
+ url = self._BASE_SPOT_URL + "/api/v3/rateLimit/order"
712
+
713
+ return await self._make_request("GET", url, True)
714
+
715
+ async def prevented_matches(
716
+ self,
717
+ symbol: str,
718
+ prevented_match_id: int | None = None,
719
+ order_id: int | None = None,
720
+ from_prevented_match_id: int | None = None,
721
+ limit: int | None = None,
722
+ ) -> list[dict]:
723
+ """Получение предотвращенных совпадений.
724
+
725
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-prevented-matches-user_data
726
+ """
727
+ url = self._BASE_SPOT_URL + "/api/v3/myPreventedMatches"
728
+ params = {
729
+ "symbol": symbol,
730
+ "preventedMatchId": prevented_match_id,
731
+ "orderId": order_id,
732
+ "fromPreventedMatchId": from_prevented_match_id,
733
+ "limit": limit,
734
+ }
735
+
736
+ return await self._make_request("GET", url, True, params=params)
737
+
738
+ async def allocations(
739
+ self,
740
+ symbol: str,
741
+ start_time: int | None = None,
742
+ end_time: int | None = None,
743
+ from_allocation_id: int | None = None,
744
+ limit: int | None = None,
745
+ order_id: int | None = None,
746
+ ) -> list[dict]:
747
+ """Получение распределений.
748
+
749
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/spot-trading-endpoints#query-allocations-user_data
750
+ """
751
+ url = self._BASE_SPOT_URL + "/api/v3/myAllocations"
752
+ params = {
753
+ "symbol": symbol,
754
+ "startTime": start_time,
755
+ "endTime": end_time,
756
+ "fromAllocationId": from_allocation_id,
757
+ "limit": limit,
758
+ "orderId": order_id,
759
+ }
760
+
761
+ return await self._make_request("GET", url, True, params=params)
762
+
763
+ async def commission_rates(self, symbol: str) -> dict:
764
+ """Получение комиссионных ставок.
765
+
766
+ https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#query-commission-rates-user_data
767
+ """
768
+ url = self._BASE_SPOT_URL + "/api/v3/account/commission"
769
+ params = {"symbol": symbol}
770
+
771
+ return await self._make_request("GET", url, True, params=params)
772
+
773
+ # topic: futures market data
774
+
775
+ async def futures_ping(self) -> dict:
776
+ """Проверка подключения к REST API.
777
+
778
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api#api-description
779
+ """
780
+ url = self._BASE_FUTURES_URL + "/fapi/v1/ping"
781
+
782
+ return await self._make_request("GET", url)
783
+
784
+ async def futures_server_time(self) -> dict:
785
+ """Получение текущего времени сервера.
786
+
787
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Check-Server-Time#api-description
788
+ """
789
+ url = self._BASE_FUTURES_URL + "/fapi/v1/time"
790
+
791
+ return await self._make_request("GET", url)
792
+
793
+ async def futures_exchange_info(self) -> dict:
794
+ """Получение информации о символах рынка и текущих правилах биржевой торговли.
795
+
796
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Exchange-Information#api-description
797
+ """
798
+ url = self._BASE_FUTURES_URL + "/fapi/v1/exchangeInfo"
799
+
800
+ return await self._make_request("GET", url)
801
+
802
+ async def futures_depth(self, symbol: str, limit: int | None = None) -> dict:
803
+ """Получение книги ордеров.
804
+
805
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Order-Book#request-parameters
806
+ """
807
+ url = self._BASE_FUTURES_URL + "/fapi/v1/depth"
808
+ params = {"symbol": symbol, "limit": limit}
809
+
810
+ return await self._make_request("GET", url, params=params)
811
+
812
+ async def futures_trades(self, symbol: str, limit: int | None = None) -> list[dict]:
813
+ """Получение последних сделок.
814
+
815
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Recent-Trades-List
816
+ """
817
+ url = self._BASE_FUTURES_URL + "/fapi/v1/trades"
818
+ params = {"symbol": symbol, "limit": limit}
819
+
820
+ return await self._make_request("GET", url, params=params)
821
+
822
+ async def futures_historical_trades(
823
+ self, symbol: str, limit: int | None = None, from_id: int | None = None
824
+ ) -> list[dict]:
825
+ """Получение исторических сделок.
826
+
827
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Old-Trades-Lookup
828
+ """
829
+ url = self._BASE_FUTURES_URL + "/fapi/v1/historicalTrades"
830
+ params = {"symbol": symbol, "limit": limit, "fromId": from_id}
831
+
832
+ return await self._make_request("GET", url, params=params)
833
+
834
+ async def futures_agg_trades(
835
+ self,
836
+ symbol: str,
837
+ from_id: int | None = None,
838
+ start_time: int | None = None,
839
+ end_time: int | None = None,
840
+ limit: int | None = None,
841
+ ) -> list[dict]:
842
+ """Получение агрегированных сделок на фьючерсах.
843
+
844
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Aggregate-Trades-List
845
+ """
846
+ url = self._BASE_FUTURES_URL + "/fapi/v1/aggTrades"
847
+ params = {
848
+ "symbol": symbol,
849
+ "fromId": from_id,
850
+ "startTime": start_time,
851
+ "endTime": end_time,
852
+ "limit": limit,
853
+ }
854
+
855
+ return await self._make_request("GET", url, params=params)
856
+
857
+ async def futures_ticker_24hr(self, symbol: str | None = None) -> dict | list[dict]:
858
+ """Получение статистики изменения цен и объема за 24 часа.
859
+
860
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/24hr-Ticker-Price-Change-Statistics
861
+ """
862
+ url = self._BASE_FUTURES_URL + "/fapi/v1/ticker/24hr"
863
+ params = {"symbol": symbol}
864
+
865
+ return await self._make_request("GET", url, params=params)
866
+
867
+ async def futures_ticker_price(self, symbol: str | None = None) -> dict | list[dict]:
868
+ """Получение последней цены тикера(ов).
869
+
870
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Price-Ticker-v2
871
+ """
872
+ url = self._BASE_FUTURES_URL + "/fapi/v2/ticker/price"
873
+ params = {"symbol": symbol}
874
+
875
+ return await self._make_request("GET", url, params=params)
876
+
877
+ async def futures_klines(
878
+ self,
879
+ symbol: str,
880
+ interval: str,
881
+ start_time: int | None = None,
882
+ end_time: int | None = None,
883
+ limit: int | None = None,
884
+ ) -> list[list]:
885
+ """Получение исторических свечей.
886
+
887
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data
888
+ """
889
+ url = self._BASE_FUTURES_URL + "/fapi/v1/klines"
890
+ params = {
891
+ "symbol": symbol,
892
+ "interval": interval,
893
+ "startTime": start_time,
894
+ "endTime": end_time,
895
+ "limit": limit,
896
+ }
897
+
898
+ return await self._make_request("GET", url, params=params)
899
+
900
+ async def open_interest(self, symbol: str) -> dict:
901
+ """Получение открытого интереса тикера.
902
+
903
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest
904
+ """
905
+ url = self._BASE_FUTURES_URL + "/fapi/v1/openInterest"
906
+ params = {"symbol": symbol}
907
+
908
+ return await self._make_request(method="GET", url=url, params=params)
909
+
910
+ async def futures_mark_price(self, symbol: str | None = None) -> dict | list[dict]:
911
+ """Получение ставки финансирования и цены маркировки.
912
+
913
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price
914
+ """
915
+ url = self._BASE_FUTURES_URL + "/fapi/v1/premiumIndex"
916
+ params = {"symbol": symbol}
917
+
918
+ return await self._make_request("GET", url, params=params)
919
+
920
+ async def futures_funding_rate(
921
+ self,
922
+ symbol: str | None = None,
923
+ start_time: int | None = None,
924
+ end_time: int | None = None,
925
+ limit: int | None = None,
926
+ ) -> list[dict]:
927
+ """Получение истории ставок финансирования.
928
+
929
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-History
930
+ """
931
+ url = self._BASE_FUTURES_URL + "/fapi/v1/fundingRate"
932
+ params = {
933
+ "symbol": symbol,
934
+ "startTime": start_time,
935
+ "endTime": end_time,
936
+ "limit": limit,
937
+ }
938
+
939
+ return await self._make_request("GET", url, params=params)
940
+
941
+ async def futures_funding_info(self) -> list[dict]:
942
+ """Получение информации о ставках финансирования.
943
+
944
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Funding-Rate-Info
945
+ """
946
+ url = self._BASE_FUTURES_URL + "/fapi/v1/fundingInfo"
947
+
948
+ return await self._make_request("GET", url)
949
+
950
+ async def open_interest_hist(
951
+ self,
952
+ symbol: str,
953
+ period: str,
954
+ start_time: int | None = None,
955
+ end_time: int | None = None,
956
+ limit: int | None = None,
957
+ ) -> list[dict]:
958
+ """Получение истории открытого интереса.
959
+
960
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest-Statistics
961
+ """
962
+ url = self._BASE_FUTURES_URL + "/futures/data/openInterestHist"
963
+ params = {
964
+ "symbol": symbol,
965
+ "period": period,
966
+ "startTime": start_time,
967
+ "endTime": end_time,
968
+ "limit": limit,
969
+ }
970
+
971
+ return await self._make_request("GET", url, params=params)
972
+
973
+ async def futures_long_short_ratio_accounts(
974
+ self,
975
+ symbol: str,
976
+ period: str,
977
+ start_time: int | None = None,
978
+ end_time: int | None = None,
979
+ limit: int | None = None,
980
+ ) -> list[dict]:
981
+ """Получение соотношения лонг/шорт по аккаунтам.
982
+
983
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio
984
+ """
985
+ url = self._BASE_FUTURES_URL + "/futures/data/topLongShortAccountRatio"
986
+ params = {
987
+ "symbol": symbol,
988
+ "period": period,
989
+ "startTime": start_time,
990
+ "endTime": end_time,
991
+ "limit": limit,
992
+ }
993
+
994
+ return await self._make_request("GET", url, params=params)
995
+
996
+ async def futures_long_short_ratio_positions(
997
+ self,
998
+ symbol: str,
999
+ period: str,
1000
+ start_time: int | None = None,
1001
+ end_time: int | None = None,
1002
+ limit: int | None = None,
1003
+ ) -> list[dict]:
1004
+ """Получение соотношения лонг/шорт по позициям.
1005
+
1006
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio
1007
+ """
1008
+ url = self._BASE_FUTURES_URL + "/futures/data/topLongShortPositionRatio"
1009
+ params = {
1010
+ "symbol": symbol,
1011
+ "period": period,
1012
+ "startTime": start_time,
1013
+ "endTime": end_time,
1014
+ "limit": limit,
1015
+ }
1016
+
1017
+ return await self._make_request("GET", url, params=params)
1018
+
1019
+ async def futures_global_long_short_ratio(
1020
+ self,
1021
+ symbol: str,
1022
+ period: str,
1023
+ start_time: int | None = None,
1024
+ end_time: int | None = None,
1025
+ limit: int | None = None,
1026
+ ) -> list[dict]:
1027
+ """Получение глобального соотношения лонг/шорт.
1028
+
1029
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio
1030
+ """
1031
+ url = self._BASE_FUTURES_URL + "/futures/data/globalLongShortAccountRatio"
1032
+ params = {
1033
+ "symbol": symbol,
1034
+ "period": period,
1035
+ "startTime": start_time,
1036
+ "endTime": end_time,
1037
+ "limit": limit,
1038
+ }
1039
+
1040
+ return await self._make_request("GET", url, params=params)
1041
+
1042
+ async def futures_taker_long_short_ratio(
1043
+ self,
1044
+ symbol: str,
1045
+ period: str,
1046
+ start_time: int | None = None,
1047
+ end_time: int | None = None,
1048
+ limit: int | None = None,
1049
+ ) -> list[dict]:
1050
+ """Получение соотношения лонг/шорт по тейкерам.
1051
+
1052
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Taker-Buy-Sell-Volume
1053
+ """
1054
+ url = self._BASE_FUTURES_URL + "/futures/data/takerlongshortRatio"
1055
+ params = {
1056
+ "symbol": symbol,
1057
+ "period": period,
1058
+ "startTime": start_time,
1059
+ "endTime": end_time,
1060
+ "limit": limit,
1061
+ }
1062
+
1063
+ return await self._make_request("GET", url, params=params)
1064
+
1065
+ async def futures_composite_index(self, symbol: str | None = None) -> list[dict]:
1066
+ """Получение композитного индекса.
1067
+
1068
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Composite-Index-Symbol-Information
1069
+ """
1070
+ url = self._BASE_FUTURES_URL + "/fapi/v1/indexInfo"
1071
+ params = {"symbol": symbol}
1072
+
1073
+ return await self._make_request("GET", url, params=params)
1074
+
1075
+ async def futures_api_trading_status(self) -> dict:
1076
+ """Получение статуса торгов API.
1077
+
1078
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Query-Current-API-trading-status
1079
+ """
1080
+ url = self._BASE_FUTURES_URL + "/fapi/v1/apiTradingStatus"
1081
+
1082
+ return await self._make_request("GET", url, True)
1083
+
1084
+ # topic: futures account
1085
+
1086
+ async def futures_account(self) -> dict:
1087
+ """Получение информации об аккаунте фьючерсов.
1088
+
1089
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V3
1090
+ """
1091
+ url = self._BASE_FUTURES_URL + "/fapi/v3/account"
1092
+ return await self._make_request("GET", url, True)
1093
+
1094
+ async def futures_balance(self) -> list[dict]:
1095
+ """Получение баланса фьючерсного аккаунта.
1096
+
1097
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Futures-Account-Balance-V3
1098
+ """
1099
+ url = self._BASE_FUTURES_URL + "/fapi/v3/balance"
1100
+
1101
+ return await self._make_request("GET", url, True)
1102
+
1103
+ async def futures_multi_asset_mode(self, multi_assets_margin: bool | None = None) -> dict:
1104
+ """Изменение режима мультиактивной маржи.
1105
+
1106
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Change-Multi-Assets-Mode
1107
+ """
1108
+ url = self._BASE_FUTURES_URL + "/fapi/v1/multiAssetsMargin"
1109
+ params = {"multiAssetsMargin": multi_assets_margin}
1110
+
1111
+ return await self._make_request("POST", url, True, params=params)
1112
+
1113
+ async def futures_multi_asset_mode_get(self) -> dict:
1114
+ """Получение режима мультиактивной маржи.
1115
+
1116
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Current-Multi-Assets-Mode
1117
+ """
1118
+ url = self._BASE_FUTURES_URL + "/fapi/v1/multiAssetsMargin"
1119
+
1120
+ return await self._make_request("GET", url, True)
1121
+
1122
+ # topic: futures trade
1123
+
1124
+ async def futures_order_create(
1125
+ self,
1126
+ symbol: str,
1127
+ side: str,
1128
+ type: str,
1129
+ quantity: float | None = None,
1130
+ reduce_only: bool | None = None,
1131
+ price: float | None = None,
1132
+ new_client_order_id: str | None = None,
1133
+ stop_price: float | None = None,
1134
+ close_position: bool | None = None,
1135
+ activation_price: float | None = None,
1136
+ callback_rate: float | None = None,
1137
+ time_in_force: str | None = None,
1138
+ working_type: str | None = None,
1139
+ price_protect: bool | None = None,
1140
+ position_side: str | None = None,
1141
+ price_match: str | None = None,
1142
+ self_trade_prevention_mode: str | None = None,
1143
+ good_till_date: int | None = None,
1144
+ ) -> dict:
1145
+ """Создание нового ордера на фьючерсах.
1146
+
1147
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Order
1148
+ """
1149
+ url = self._BASE_FUTURES_URL + "/fapi/v1/order"
1150
+ params = {
1151
+ "symbol": symbol,
1152
+ "side": side,
1153
+ "type": type,
1154
+ "quantity": quantity,
1155
+ "reduceOnly": reduce_only,
1156
+ "price": price,
1157
+ "newClientOrderId": new_client_order_id,
1158
+ "stopPrice": stop_price,
1159
+ "closePosition": close_position,
1160
+ "activationPrice": activation_price,
1161
+ "callbackRate": callback_rate,
1162
+ "timeInForce": time_in_force,
1163
+ "workingType": working_type,
1164
+ "priceProtect": price_protect,
1165
+ "positionSide": position_side,
1166
+ "priceMatch": price_match,
1167
+ "selfTradePreventionMode": self_trade_prevention_mode,
1168
+ "goodTillDate": good_till_date,
1169
+ }
1170
+
1171
+ return await self._make_request("POST", url, True, params=params)
1172
+
1173
+ async def futures_order_modify(
1174
+ self,
1175
+ order_id: int | None = None,
1176
+ orig_client_order_id: str | None = None,
1177
+ symbol: str | None = None,
1178
+ side: str | None = None,
1179
+ quantity: float | None = None,
1180
+ price: float | None = None,
1181
+ price_match: str | None = None,
1182
+ ) -> dict:
1183
+ """Изменение ордера на фьючерсах.
1184
+
1185
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Order
1186
+ """
1187
+ url = self._BASE_FUTURES_URL + "/fapi/v1/order"
1188
+ params = {
1189
+ "orderId": order_id,
1190
+ "origClientOrderId": orig_client_order_id,
1191
+ "symbol": symbol,
1192
+ "side": side,
1193
+ "quantity": quantity,
1194
+ "price": price,
1195
+ "priceMatch": price_match,
1196
+ }
1197
+
1198
+ return await self._make_request("PUT", url, True, params=params)
1199
+
1200
+ async def futures_order_get(
1201
+ self,
1202
+ symbol: str,
1203
+ order_id: int | None = None,
1204
+ orig_client_order_id: str | None = None,
1205
+ ) -> dict:
1206
+ """Получение информации об ордере на фьючерсах.
1207
+
1208
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-Order
1209
+ """
1210
+ url = self._BASE_FUTURES_URL + "/fapi/v1/order"
1211
+ params = {
1212
+ "symbol": symbol,
1213
+ "orderId": order_id,
1214
+ "origClientOrderId": orig_client_order_id,
1215
+ }
1216
+
1217
+ return await self._make_request("GET", url, True, params=params)
1218
+
1219
+ async def futures_orders_open(self, symbol: str | None = None) -> list[dict]:
1220
+ """Получение всех активных ордеров на фьючерсах.
1221
+
1222
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Current-All-Open-Orders
1223
+ """
1224
+ url = self._BASE_FUTURES_URL + "/fapi/v1/openOrders"
1225
+ params = {"symbol": symbol}
1226
+
1227
+ return await self._make_request("GET", url, True, params=params)
1228
+
1229
+ async def futures_orders_all(
1230
+ self,
1231
+ symbol: str,
1232
+ order_id: int | None = None,
1233
+ start_time: int | None = None,
1234
+ end_time: int | None = None,
1235
+ limit: int | None = None,
1236
+ ) -> list[dict]:
1237
+ """Получение всех ордеров на фьючерсах.
1238
+
1239
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/All-Orders
1240
+ """
1241
+ url = self._BASE_FUTURES_URL + "/fapi/v1/allOrders"
1242
+ params = {
1243
+ "symbol": symbol,
1244
+ "orderId": order_id,
1245
+ "startTime": start_time,
1246
+ "endTime": end_time,
1247
+ "limit": limit,
1248
+ }
1249
+
1250
+ return await self._make_request("GET", url, True, params=params)
1251
+
1252
+ async def futures_orders_cancel_all(self, symbol: str) -> dict:
1253
+ """Отмена всех активных ордеров на фьючерсах.
1254
+
1255
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-All-Open-Orders
1256
+ """
1257
+ url = self._BASE_FUTURES_URL + "/fapi/v1/allOpenOrders"
1258
+ params = {"symbol": symbol}
1259
+
1260
+ return await self._make_request("DELETE", url, True, params=params)
1261
+
1262
+ async def futures_countdown_cancel_all(
1263
+ self,
1264
+ symbol: str,
1265
+ countdown_time: int,
1266
+ ) -> dict:
1267
+ """Автоотмена всех активных ордеров через указанное время.
1268
+
1269
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Auto-Cancel-All-Open-Orders
1270
+ """
1271
+ url = self._BASE_FUTURES_URL + "/fapi/v1/countdownCancelAll"
1272
+ params = {
1273
+ "symbol": symbol,
1274
+ "countdownTime": countdown_time,
1275
+ }
1276
+
1277
+ return await self._make_request("POST", url, True, params=params)
1278
+
1279
+ async def futures_position_info(self, symbol: str | None = None) -> list[dict]:
1280
+ """Получение информации о позициях на фьючерсах.
1281
+
1282
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Position-Information-V3
1283
+ """
1284
+ url = self._BASE_FUTURES_URL + "/fapi/v3/positionRisk"
1285
+ params = {"symbol": symbol}
1286
+
1287
+ return await self._make_request("GET", url, True, params=params)
1288
+
1289
+ async def futures_my_trades(
1290
+ self,
1291
+ symbol: str,
1292
+ start_time: int | None = None,
1293
+ end_time: int | None = None,
1294
+ from_id: int | None = None,
1295
+ limit: int | None = None,
1296
+ ) -> list[dict]:
1297
+ """Получение истории торгов на фьючерсах.
1298
+
1299
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Trade-List
1300
+ """
1301
+ url = self._BASE_FUTURES_URL + "/fapi/v1/userTrades"
1302
+ params = {
1303
+ "symbol": symbol,
1304
+ "startTime": start_time,
1305
+ "endTime": end_time,
1306
+ "fromId": from_id,
1307
+ "limit": limit,
1308
+ }
1309
+
1310
+ return await self._make_request("GET", url, True, params=params)
1311
+
1312
+ async def futures_income(
1313
+ self,
1314
+ symbol: str | None = None,
1315
+ income_type: str | None = None,
1316
+ start_time: int | None = None,
1317
+ end_time: int | None = None,
1318
+ limit: int | None = None,
1319
+ ) -> list[dict]:
1320
+ """Получение истории доходов на фьючерсах.
1321
+
1322
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Income-History
1323
+ """
1324
+ url = self._BASE_FUTURES_URL + "/fapi/v1/income"
1325
+ params = {
1326
+ "symbol": symbol,
1327
+ "incomeType": income_type,
1328
+ "startTime": start_time,
1329
+ "endTime": end_time,
1330
+ "limit": limit,
1331
+ }
1332
+
1333
+ return await self._make_request("GET", url, True, params=params)
1334
+
1335
+ async def futures_leverage_change(self, symbol: str, leverage: int) -> dict:
1336
+ """Изменение кредитного плеча на фьючерсах.
1337
+
1338
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Change-Initial-Leverage
1339
+ """
1340
+ url = self._BASE_FUTURES_URL + "/fapi/v1/leverage"
1341
+ params = {"symbol": symbol, "leverage": leverage}
1342
+
1343
+ return await self._make_request("POST", url, True, params=params)
1344
+
1345
+ async def futures_margin_type_change(self, symbol: str, margin_type: str) -> dict:
1346
+ """Изменение типа маржи на фьючерсах.
1347
+
1348
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Change-Margin-Type
1349
+ """
1350
+ url = self._BASE_FUTURES_URL + "/fapi/v1/marginType"
1351
+ params = {"symbol": symbol, "marginType": margin_type}
1352
+
1353
+ return await self._make_request("POST", url, True, params=params)
1354
+
1355
+ async def futures_position_margin_modify(
1356
+ self,
1357
+ symbol: str,
1358
+ position_side: str,
1359
+ amount: float,
1360
+ type: int,
1361
+ ) -> dict:
1362
+ """Изменение изолированной маржи позиции.
1363
+
1364
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Modify-Isolated-Position-Margin
1365
+ """
1366
+ url = self._BASE_FUTURES_URL + "/fapi/v1/positionMargin"
1367
+ params = {
1368
+ "symbol": symbol,
1369
+ "positionSide": position_side,
1370
+ "amount": amount,
1371
+ "type": type,
1372
+ }
1373
+
1374
+ return await self._make_request("POST", url, True, params=params)
1375
+
1376
+ async def futures_position_margin_history(
1377
+ self,
1378
+ symbol: str,
1379
+ type: int | None = None,
1380
+ start_time: int | None = None,
1381
+ end_time: int | None = None,
1382
+ limit: int | None = None,
1383
+ ) -> list[dict]:
1384
+ """Получение истории изменений маржи позиции.
1385
+
1386
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Position-Margin-Change-History
1387
+ """
1388
+ url = self._BASE_FUTURES_URL + "/fapi/v1/positionMargin/history"
1389
+ params = {
1390
+ "symbol": symbol,
1391
+ "type": type,
1392
+ "startTime": start_time,
1393
+ "endTime": end_time,
1394
+ "limit": limit,
1395
+ }
1396
+
1397
+ return await self._make_request("GET", url, True, params=params)
1398
+
1399
+ async def futures_commission_rate(self, symbol: str) -> dict:
1400
+ """Получение комиссионных ставок на фьючерсах.
1401
+
1402
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/User-Commission-Rate
1403
+ """
1404
+ url = self._BASE_FUTURES_URL + "/fapi/v1/commissionRate"
1405
+ params = {"symbol": symbol}
1406
+
1407
+ return await self._make_request("GET", url, True, params=params)
1408
+
1409
+ async def futures_adl_quantile(self, symbol: str | None = None) -> list[dict]:
1410
+ """Получение информации об автоматической ликвидации.
1411
+
1412
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Position-ADL-Quantile-Estimation
1413
+ """
1414
+ url = self._BASE_FUTURES_URL + "/fapi/v1/adlQuantile"
1415
+ params = {"symbol": symbol}
1416
+
1417
+ return await self._make_request("GET", url, True, params=params)
1418
+
1419
+ async def futures_force_orders(
1420
+ self,
1421
+ symbol: str | None = None,
1422
+ auto_close_type: str | None = None,
1423
+ start_time: int | None = None,
1424
+ end_time: int | None = None,
1425
+ limit: int | None = None,
1426
+ ) -> list[dict]:
1427
+ """Получение истории принудительных ордеров пользователя.
1428
+
1429
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/User-s-Force-Orders
1430
+ """
1431
+ url = self._BASE_FUTURES_URL + "/fapi/v1/forceOrders"
1432
+ params = {
1433
+ "symbol": symbol,
1434
+ "autoCloseType": auto_close_type,
1435
+ "startTime": start_time,
1436
+ "endTime": end_time,
1437
+ "limit": limit,
1438
+ }
1439
+
1440
+ return await self._make_request("GET", url, True, params=params)
1441
+
1442
+ async def futures_api_key_permissions(self) -> dict:
1443
+ """Получение разрешений API ключа.
1444
+
1445
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-API-Key-Permission
1446
+ """
1447
+ url = self._BASE_FUTURES_URL + "/fapi/v1/apiTradingStatus"
1448
+
1449
+ return await self._make_request("GET", url, True)
1450
+
1451
+ async def futures_order_cancel(
1452
+ self, symbol: str, order_id: int | None = None, orig_client_order_id: str | None = None
1453
+ ) -> dict:
1454
+ """Отмена активного ордера на фьючерсном рынке.
1455
+
1456
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Order
1457
+ """
1458
+ url = self._BASE_FUTURES_URL + "/fapi/v1/order"
1459
+ params = {
1460
+ "symbol": symbol,
1461
+ "orderId": order_id,
1462
+ "origClientOrderId": orig_client_order_id,
1463
+ }
1464
+
1465
+ return await self._make_request("DELETE", url, params=params)
1466
+
1467
+ async def futures_batch_orders_create(self, orders: list[dict]) -> list[dict]:
1468
+ """Создание множественных ордеров одновременно на фьючерсах.
1469
+
1470
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Place-Multiple-Orders
1471
+ """
1472
+ url = self._BASE_FUTURES_URL + "/fapi/v1/batchOrders"
1473
+ params = {"batchOrders": json.dumps(orders)} # Нужен особый дамп
1474
+
1475
+ return await self._make_request("POST", url, signed=True, params=params)
1476
+
1477
+ async def futures_batch_orders_cancel(
1478
+ self,
1479
+ symbol: str,
1480
+ order_id_list: list[int] | None = None,
1481
+ orig_client_order_id_list: list[str] | None = None,
1482
+ ) -> list[dict]:
1483
+ """Отмена множественных ордеров на фьючерсах.
1484
+
1485
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Multiple-Orders
1486
+ """
1487
+ url = self._BASE_FUTURES_URL + "/fapi/v1/batchOrders"
1488
+ params = {"symbol": symbol}
1489
+
1490
+ if order_id_list:
1491
+ params["orderIdList"] = json.dumps(order_id_list) # Нужен особый дамп
1492
+
1493
+ if orig_client_order_id_list:
1494
+ params["origClientOrderIdList"] = json.dumps( # Нужен особый дамп
1495
+ orig_client_order_id_list
1496
+ )
1497
+
1498
+ return await self._make_request("DELETE", url, signed=True, params=params)
1499
+
1500
+ # topic: user data streams
1501
+
1502
+ async def listen_key(self) -> dict:
1503
+ """Создание ключа прослушивания для подключения к пользовательскому вебсокету.
1504
+
1505
+ https://developers.binance.com/docs/binance-spot-api-docs/testnet/rest-api/user-data-stream-endpoints-deprecated#start-user-data-stream-user_stream-deprecated
1506
+ """
1507
+ warnings.warn(
1508
+ "These requests have been deprecated, which means we will remove them in the future. Please subscribe to the User Data Stream through the WebSocket API instead.",
1509
+ DeprecationWarning,
1510
+ stacklevel=2,
1511
+ )
1512
+ url = self._BASE_SPOT_URL + "/api/v3/userDataStream"
1513
+
1514
+ return await super()._make_request("POST", url, headers=self._get_headers("POST"))
1515
+
1516
+ async def renew_listen_key(self, listen_key: str) -> dict:
1517
+ """Обновление ключа прослушивания для подключения к пользовательскому вебсокету.
1518
+
1519
+ https://developers.binance.com/docs/binance-spot-api-docs/testnet/rest-api/user-data-stream-endpoints-deprecated#keepalive-user-data-stream-user_stream-deprecated
1520
+ """
1521
+ warnings.warn(
1522
+ "These requests have been deprecated, which means we will remove them in the future. Please subscribe to the User Data Stream through the WebSocket API instead.",
1523
+ DeprecationWarning,
1524
+ stacklevel=2,
1525
+ )
1526
+ url = self._BASE_SPOT_URL + "/api/v3/userDataStream"
1527
+ params = {"listenKey": listen_key}
1528
+
1529
+ return await super()._make_request(
1530
+ "PUT", url, params=params, headers=self._get_headers("PUT")
1531
+ )
1532
+
1533
+ async def close_listen_key(self, listen_key: str) -> dict:
1534
+ """Закрытие ключа прослушивания для подключения к пользовательскому вебсокету.
1535
+
1536
+ https://developers.binance.com/docs/binance-spot-api-docs/testnet/rest-api/user-data-stream-endpoints-deprecated#close-user-data-stream-user_stream-deprecated
1537
+ """
1538
+ warnings.warn(
1539
+ "[!IMPORTANT] These requests have been deprecated, which means we will remove them in the future. Please subscribe to the User Data Stream through the WebSocket API instead.",
1540
+ DeprecationWarning,
1541
+ stacklevel=2,
1542
+ )
1543
+ url = self._BASE_SPOT_URL + "/api/v3/userDataStream"
1544
+ params = {"listenKey": listen_key}
1545
+
1546
+ return await super()._make_request(
1547
+ "DELETE", url, params=params, headers=self._get_headers("DELETE")
1548
+ )
1549
+
1550
+ # topic: futures user data streams
1551
+
1552
+ async def futures_listen_key(self) -> dict:
1553
+ """Создание ключа прослушивания для подключения к пользовательскому вебсокету.
1554
+
1555
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams/Start-User-Data-Stream#api-description
1556
+ """
1557
+ url = self._BASE_FUTURES_URL + "/fapi/v1/listenKey"
1558
+
1559
+ return await super()._make_request("POST", url, headers=self._get_headers("POST"))
1560
+
1561
+ async def futures_renew_listen_key(self) -> dict:
1562
+ """Обновление ключа прослушивания для подключения к пользовательскому вебсокету.
1563
+
1564
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams
1565
+ """
1566
+ url = self._BASE_FUTURES_URL + "/fapi/v1/listenKey"
1567
+
1568
+ return await super()._make_request("PUT", url, headers=self._get_headers("PUT"))
1569
+
1570
+ async def futures_close_listen_key(self) -> dict:
1571
+ """Закрытие ключа прослушивания для подключения к пользовательскому вебсокету.
1572
+
1573
+ https://developers.binance.com/docs/derivatives/usds-margined-futures/user-data-streams
1574
+ """
1575
+ url = self._BASE_FUTURES_URL + "/fapi/v1/listenKey"
1576
+
1577
+ return await super()._make_request("DELETE", url, headers=self._get_headers("DELETE"))