hyperquant 1.48__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.
Potentially problematic release.
This version of hyperquant might be problematic. Click here for more details.
- hyperquant/__init__.py +8 -0
- hyperquant/broker/auth.py +972 -0
- hyperquant/broker/bitget.py +311 -0
- hyperquant/broker/bitmart.py +720 -0
- hyperquant/broker/coinw.py +487 -0
- hyperquant/broker/deepcoin.py +651 -0
- hyperquant/broker/edgex.py +500 -0
- hyperquant/broker/hyperliquid.py +570 -0
- hyperquant/broker/lbank.py +661 -0
- hyperquant/broker/lib/edgex_sign.py +455 -0
- hyperquant/broker/lib/hpstore.py +252 -0
- hyperquant/broker/lib/hyper_types.py +48 -0
- hyperquant/broker/lib/polymarket/ctfAbi.py +721 -0
- hyperquant/broker/lib/polymarket/safeAbi.py +1138 -0
- hyperquant/broker/lib/util.py +22 -0
- hyperquant/broker/lighter.py +679 -0
- hyperquant/broker/models/apexpro.py +150 -0
- hyperquant/broker/models/bitget.py +359 -0
- hyperquant/broker/models/bitmart.py +635 -0
- hyperquant/broker/models/coinw.py +724 -0
- hyperquant/broker/models/deepcoin.py +809 -0
- hyperquant/broker/models/edgex.py +1053 -0
- hyperquant/broker/models/hyperliquid.py +284 -0
- hyperquant/broker/models/lbank.py +557 -0
- hyperquant/broker/models/lighter.py +868 -0
- hyperquant/broker/models/ourbit.py +1155 -0
- hyperquant/broker/models/polymarket.py +1071 -0
- hyperquant/broker/ourbit.py +550 -0
- hyperquant/broker/polymarket.py +2399 -0
- hyperquant/broker/ws.py +132 -0
- hyperquant/core.py +513 -0
- hyperquant/datavison/_util.py +18 -0
- hyperquant/datavison/binance.py +111 -0
- hyperquant/datavison/coinglass.py +237 -0
- hyperquant/datavison/okx.py +177 -0
- hyperquant/db.py +191 -0
- hyperquant/draw.py +1200 -0
- hyperquant/logkit.py +205 -0
- hyperquant/notikit.py +124 -0
- hyperquant-1.48.dist-info/METADATA +32 -0
- hyperquant-1.48.dist-info/RECORD +42 -0
- hyperquant-1.48.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import uuid
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
import pybotters
|
|
9
|
+
|
|
10
|
+
from .models.bitget import BitgetDataStore
|
|
11
|
+
from .lib.util import fmt_value
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Bitget:
|
|
17
|
+
"""Bitget public/privileged client (REST + WS).
|
|
18
|
+
|
|
19
|
+
默认只支持单向持仓(One-way mode)。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
client: pybotters.Client,
|
|
25
|
+
*,
|
|
26
|
+
rest_api: str | None = None,
|
|
27
|
+
ws_url: str | None = None,
|
|
28
|
+
) -> None:
|
|
29
|
+
self.client = client
|
|
30
|
+
self.store = BitgetDataStore()
|
|
31
|
+
|
|
32
|
+
self.rest_api = rest_api or "https://api.bitget.com"
|
|
33
|
+
self.ws_url = ws_url or "wss://ws.bitget.com/v2/ws/public"
|
|
34
|
+
self.ws_url_private = ws_url or "wss://ws.bitget.com/v2/ws/private"
|
|
35
|
+
|
|
36
|
+
self.ws_app = None
|
|
37
|
+
self.has_sub_personal = False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def __aenter__(self) -> "Bitget":
|
|
41
|
+
await self.update("detail")
|
|
42
|
+
return self
|
|
43
|
+
|
|
44
|
+
async def __aexit__(self, exc_type, exc, tb) -> None: # pragma: no cover - symmetry
|
|
45
|
+
pass
|
|
46
|
+
|
|
47
|
+
async def sub_personal(self) -> None:
|
|
48
|
+
sub_msg = {
|
|
49
|
+
"op": "subscribe",
|
|
50
|
+
"args": [
|
|
51
|
+
{"instType": "USDT-FUTURES", "channel": "orders", "instId": "default"},
|
|
52
|
+
{
|
|
53
|
+
"instType": "USDT-FUTURES",
|
|
54
|
+
"channel": "positions",
|
|
55
|
+
"instId": "default",
|
|
56
|
+
},
|
|
57
|
+
{"instType": "USDT-FUTURES", "channel": "account", "coin": "default"},
|
|
58
|
+
],
|
|
59
|
+
}
|
|
60
|
+
self.ws_app = await self._ensure_private_ws()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
await self.ws_app.current_ws.send_json(sub_msg)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
self.has_sub_personal = True
|
|
67
|
+
|
|
68
|
+
async def update(
|
|
69
|
+
self,
|
|
70
|
+
update_type: Literal["detail", "ticker", "all"] = "all",
|
|
71
|
+
) -> None:
|
|
72
|
+
"""Refresh cached REST resources."""
|
|
73
|
+
|
|
74
|
+
requests: list[Any] = []
|
|
75
|
+
|
|
76
|
+
if update_type in {"detail", "all"}:
|
|
77
|
+
requests.append(
|
|
78
|
+
self.client.get(
|
|
79
|
+
f"{self.rest_api}/api/v2/mix/market/contracts",
|
|
80
|
+
params={"productType": "usdt-futures"},
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
if update_type in {"ticker", "all"}:
|
|
85
|
+
requests.append(
|
|
86
|
+
self.client.get(
|
|
87
|
+
f"{self.rest_api}/api/v2/mix/market/tickers",
|
|
88
|
+
params={"productType": "usdt-futures"},
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
if not requests:
|
|
93
|
+
raise ValueError(f"update_type err: {update_type}")
|
|
94
|
+
|
|
95
|
+
await self.store.initialize(*requests)
|
|
96
|
+
|
|
97
|
+
async def place_order(
|
|
98
|
+
self,
|
|
99
|
+
symbol: str,
|
|
100
|
+
*,
|
|
101
|
+
direction: Literal["buy", "sell", "long", "short", "0", "1"],
|
|
102
|
+
volume: float,
|
|
103
|
+
price: float | None = None,
|
|
104
|
+
order_type: Literal[
|
|
105
|
+
"market",
|
|
106
|
+
"limit_gtc",
|
|
107
|
+
"limit_ioc",
|
|
108
|
+
"limit_fok",
|
|
109
|
+
"limit_post_only",
|
|
110
|
+
"limit",
|
|
111
|
+
] = "market",
|
|
112
|
+
margin_mode: Literal["isolated", "crossed"] = "crossed",
|
|
113
|
+
product_type: str = "USDT-FUTURES",
|
|
114
|
+
margin_coin: str = "USDT",
|
|
115
|
+
reduce_only: bool | None = None,
|
|
116
|
+
offset_flag: Literal["open", "close", "0", "1"] | None = None,
|
|
117
|
+
client_order_id: str | None = None
|
|
118
|
+
) -> dict[str, Any] | None:
|
|
119
|
+
"""
|
|
120
|
+
请求成功返回示例:
|
|
121
|
+
|
|
122
|
+
.. code:: json
|
|
123
|
+
|
|
124
|
+
{
|
|
125
|
+
"clientOid": "121211212122",
|
|
126
|
+
"orderId": "121211212122"
|
|
127
|
+
}
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
side = self._normalize_direction(direction)
|
|
131
|
+
order_type_code, force_code = self._resolve_order_type(order_type)
|
|
132
|
+
|
|
133
|
+
if reduce_only is None:
|
|
134
|
+
reduce_only = self._normalize_offset(offset_flag)
|
|
135
|
+
|
|
136
|
+
detail = self._get_detail_entry(symbol)
|
|
137
|
+
volume_str = self._format_with_step(
|
|
138
|
+
volume, detail.get("step_size") or detail.get("stepSize")
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
payload: dict[str, Any] = {
|
|
142
|
+
"symbol": symbol,
|
|
143
|
+
"productType": product_type,
|
|
144
|
+
"marginMode": margin_mode,
|
|
145
|
+
"marginCoin": margin_coin,
|
|
146
|
+
"side": side,
|
|
147
|
+
"size": volume_str,
|
|
148
|
+
"orderType": order_type_code,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if force_code:
|
|
152
|
+
payload["force"] = force_code
|
|
153
|
+
|
|
154
|
+
if order_type_code == "limit":
|
|
155
|
+
if price is None:
|
|
156
|
+
raise ValueError("price is required for Bitget limit orders")
|
|
157
|
+
payload["price"] = self._format_with_step(
|
|
158
|
+
price,
|
|
159
|
+
detail.get("tick_size") or detail.get("tickSize"),
|
|
160
|
+
)
|
|
161
|
+
elif price is not None:
|
|
162
|
+
logger.debug("Price %.8f ignored for market order", price)
|
|
163
|
+
|
|
164
|
+
if reduce_only is True:
|
|
165
|
+
payload["reduceOnly"] = "YES"
|
|
166
|
+
elif reduce_only is False:
|
|
167
|
+
payload["reduceOnly"] = "NO"
|
|
168
|
+
|
|
169
|
+
if client_order_id:
|
|
170
|
+
payload["clientOid"] = client_order_id
|
|
171
|
+
|
|
172
|
+
res = await self.client.post(
|
|
173
|
+
f"{self.rest_api}/api/v2/mix/order/place-order",
|
|
174
|
+
data=payload,
|
|
175
|
+
)
|
|
176
|
+
data = await res.json()
|
|
177
|
+
return self._ensure_ok("place_order", data)
|
|
178
|
+
|
|
179
|
+
async def cancel_order(
|
|
180
|
+
self,
|
|
181
|
+
order_sys_id: str,
|
|
182
|
+
*,
|
|
183
|
+
symbol: str,
|
|
184
|
+
margin_mode: Literal["isolated", "crossed"],
|
|
185
|
+
product_type: str = "USDT-FUTURES",
|
|
186
|
+
margin_coin: str = "USDT",
|
|
187
|
+
client_order_id: str | None = None,
|
|
188
|
+
) -> dict[str, Any]:
|
|
189
|
+
"""Cancel an order via ``POST /api/v2/mix/order/cancel-order``."""
|
|
190
|
+
|
|
191
|
+
payload = {
|
|
192
|
+
"symbol": symbol,
|
|
193
|
+
"productType": product_type,
|
|
194
|
+
"marginMode": margin_mode,
|
|
195
|
+
"marginCoin": margin_coin,
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if client_order_id:
|
|
199
|
+
payload["clientOid"] = client_order_id
|
|
200
|
+
else:
|
|
201
|
+
payload["orderId"] = order_sys_id
|
|
202
|
+
|
|
203
|
+
res = await self.client.post(
|
|
204
|
+
f"{self.rest_api}/api/v2/mix/order/cancel-order",
|
|
205
|
+
data=payload,
|
|
206
|
+
)
|
|
207
|
+
data = await res.json()
|
|
208
|
+
return self._ensure_ok("cancel_order", data)
|
|
209
|
+
|
|
210
|
+
async def sub_orderbook(self, symbols: list[str], channel: str = "books1") -> None:
|
|
211
|
+
"""Subscribe to Bitget order-book snapshots/updates."""
|
|
212
|
+
|
|
213
|
+
submsg = {"op": "subscribe", "args": []}
|
|
214
|
+
for symbol in symbols:
|
|
215
|
+
submsg["args"].append(
|
|
216
|
+
{"instType": "USDT-FUTURES", "channel": channel, "instId": symbol}
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
self.client.ws_connect(
|
|
220
|
+
self.ws_url,
|
|
221
|
+
send_json=submsg,
|
|
222
|
+
hdlr_json=self.store.onmessage,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
def _get_detail_entry(self, symbol: str) -> dict[str, Any]:
|
|
226
|
+
detail = self.store.detail.get({"symbol": symbol})
|
|
227
|
+
if not detail:
|
|
228
|
+
raise ValueError(
|
|
229
|
+
f"Unknown Bitget instrument: {symbol}. Call update('detail') first or provide valid symbol."
|
|
230
|
+
)
|
|
231
|
+
return detail
|
|
232
|
+
|
|
233
|
+
async def _ensure_private_ws(self):
|
|
234
|
+
wsqueue = pybotters.WebSocketQueue()
|
|
235
|
+
ws_app = self.client.ws_connect(
|
|
236
|
+
self.ws_url_private,
|
|
237
|
+
hdlr_json=self.store.onmessage,
|
|
238
|
+
)
|
|
239
|
+
# async for msg in wsqueue:
|
|
240
|
+
# print(msg)
|
|
241
|
+
|
|
242
|
+
await ws_app._event.wait()
|
|
243
|
+
await ws_app.current_ws._wait_authtask()
|
|
244
|
+
return ws_app
|
|
245
|
+
|
|
246
|
+
@staticmethod
|
|
247
|
+
def _format_with_step(value: float, step: Any) -> str:
|
|
248
|
+
if step in (None, 0, "0"):
|
|
249
|
+
return str(value)
|
|
250
|
+
try:
|
|
251
|
+
step_float = float(step)
|
|
252
|
+
except (TypeError, ValueError): # pragma: no cover - defensive guard
|
|
253
|
+
return str(value)
|
|
254
|
+
if step_float <= 0:
|
|
255
|
+
return str(value)
|
|
256
|
+
return fmt_value(value, step_float)
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
def _normalize_direction(direction: str) -> str:
|
|
260
|
+
mapping = {
|
|
261
|
+
"buy": "buy",
|
|
262
|
+
"long": "buy",
|
|
263
|
+
"0": "buy",
|
|
264
|
+
"sell": "sell",
|
|
265
|
+
"short": "sell",
|
|
266
|
+
"1": "sell",
|
|
267
|
+
}
|
|
268
|
+
key = str(direction).lower()
|
|
269
|
+
try:
|
|
270
|
+
return mapping[key]
|
|
271
|
+
except KeyError as exc: # pragma: no cover - guard
|
|
272
|
+
raise ValueError(f"Unsupported direction: {direction}") from exc
|
|
273
|
+
|
|
274
|
+
@staticmethod
|
|
275
|
+
def _normalize_offset(
|
|
276
|
+
offset: Literal["open", "close", "0", "1"] | None,
|
|
277
|
+
) -> bool | None:
|
|
278
|
+
if offset is None:
|
|
279
|
+
return None
|
|
280
|
+
mapping = {
|
|
281
|
+
"open": False,
|
|
282
|
+
"0": False,
|
|
283
|
+
"close": True,
|
|
284
|
+
"1": True,
|
|
285
|
+
}
|
|
286
|
+
key = str(offset).lower()
|
|
287
|
+
if key in mapping:
|
|
288
|
+
return mapping[key]
|
|
289
|
+
raise ValueError(f"Unsupported offset_flag: {offset}")
|
|
290
|
+
|
|
291
|
+
@staticmethod
|
|
292
|
+
def _resolve_order_type(order_type: str) -> tuple[str, str | None]:
|
|
293
|
+
mapping = {
|
|
294
|
+
"market": ("market", None),
|
|
295
|
+
"limit": ("limit", "gtc"),
|
|
296
|
+
"limit_gtc": ("limit", "gtc"),
|
|
297
|
+
"limit_ioc": ("limit", "ioc"),
|
|
298
|
+
"limit_fok": ("limit", "fok"),
|
|
299
|
+
"limit_post_only": ("limit", "post_only"),
|
|
300
|
+
}
|
|
301
|
+
key = str(order_type).lower()
|
|
302
|
+
try:
|
|
303
|
+
return mapping[key]
|
|
304
|
+
except KeyError as exc: # pragma: no cover - guard
|
|
305
|
+
raise ValueError(f"Unsupported order_type: {order_type}") from exc
|
|
306
|
+
|
|
307
|
+
@staticmethod
|
|
308
|
+
def _ensure_ok(operation: str, data: Any) -> dict[str, Any]:
|
|
309
|
+
if not isinstance(data, dict) or data.get("code") != "00000":
|
|
310
|
+
raise RuntimeError(f"{operation} failed: {data}")
|
|
311
|
+
return data.get("data") or {}
|