hyperquant 0.64__py3-none-any.whl → 0.66__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.
hyperquant/broker/auth.py CHANGED
@@ -1,7 +1,10 @@
1
+ import base64
2
+ import hmac
3
+ import urllib.parse
1
4
  import time
2
5
  import hashlib
3
6
  from typing import Any
4
- from aiohttp import ClientWebSocketResponse
7
+ from aiohttp import ClientWebSocketResponse, FormData, JsonPayload
5
8
  from multidict import CIMultiDict
6
9
  from yarl import URL
7
10
  import pybotters
@@ -13,8 +16,106 @@ def md5_hex(s: str) -> str:
13
16
  return hashlib.md5(s.encode("utf-8")).hexdigest()
14
17
 
15
18
 
19
+
20
+ def serialize(obj, prefix=''):
21
+ """
22
+ Python 版 UK/v:递归排序 + urlencode + 展平
23
+ """
24
+ def _serialize(obj, prefix=''):
25
+ if obj is None:
26
+ return []
27
+ if isinstance(obj, dict):
28
+ items = []
29
+ for k in sorted(obj.keys()):
30
+ v = obj[k]
31
+ n = f"{prefix}[{k}]" if prefix else k
32
+ items.extend(_serialize(v, n))
33
+ return items
34
+ elif isinstance(obj, list):
35
+ # JS style: output key once, then join values by &
36
+ values = []
37
+ for v in obj:
38
+ if isinstance(v, dict):
39
+ # Recursively serialize dict, but drop key= part (just use value part)
40
+ sub = _serialize(v, prefix)
41
+ # sub is a list of key=value, but we want only value part
42
+ for s in sub:
43
+ # s is like 'key=value', need only value
44
+ parts = s.split('=', 1)
45
+ if len(parts) == 2:
46
+ values.append(parts[1])
47
+ else:
48
+ values.append(parts[0])
49
+ else:
50
+ # Handle booleans and empty strings
51
+ if isinstance(v, bool):
52
+ val = "true" if v else "false"
53
+ elif v == "":
54
+ val = ""
55
+ else:
56
+ val = str(v)
57
+ values.append(val)
58
+ return [f"{urllib.parse.quote(str(prefix))}={'&'.join(values)}"]
59
+ else:
60
+ # Handle booleans and empty strings
61
+ if isinstance(obj, bool):
62
+ val = "true" if obj else "false"
63
+ elif obj == "":
64
+ val = ""
65
+ else:
66
+ val = str(obj)
67
+ return [f"{urllib.parse.quote(str(prefix))}={val}"]
68
+ return "&".join(_serialize(obj, prefix))
69
+
16
70
  # 🔑 Ourbit 的鉴权函数
17
71
  class Auth:
72
+ @staticmethod
73
+ def edgex(args: tuple[str, URL], kwargs: dict[str, Any]) -> tuple[str, URL]:
74
+ method: str = args[0]
75
+ url: URL = args[1]
76
+ data = kwargs.get("data") or {}
77
+ headers: CIMultiDict = kwargs["headers"]
78
+
79
+ session = kwargs["session"]
80
+ api_key:str = session.__dict__["_apis"][pybotters.auth.Hosts.items[url.host].name][0]
81
+ secret = session.__dict__["_apis"][pybotters.auth.Hosts.items[url.host].name][1]
82
+ passphrase:str = session.__dict__["_apis"][pybotters.auth.Hosts.items[url.host].name][2]
83
+ passphrase = passphrase.split("-")[0]
84
+ timestamp = str(int(time.time() * 1000))
85
+ # timestamp = "1758535055061"
86
+
87
+ raw_body = ""
88
+ if data and method.upper() in ["POST", "PUT", "PATCH"] and data:
89
+ raw_body = serialize(data)
90
+ else:
91
+ raw_body = serialize(dict(url.query.items()))
92
+
93
+
94
+ secret_quoted = urllib.parse.quote(secret, safe="")
95
+ b64_secret = base64.b64encode(secret_quoted.encode("utf-8")).decode()
96
+ message = f"{timestamp}{method.upper()}{url.raw_path}{raw_body}"
97
+ sign = hmac.new(b64_secret.encode("utf-8"), message.encode("utf-8"), hashlib.sha256).hexdigest()
98
+
99
+ sigh_header = {
100
+ "X-edgeX-Api-Key": api_key,
101
+ "X-edgeX-Passphrase": passphrase,
102
+ "X-edgeX-Signature": sign,
103
+ "X-edgeX-Timestamp": timestamp,
104
+ }
105
+ # ws单独进行签名
106
+ if headers.get("Upgrade") == "websocket":
107
+ json_str = pyjson.dumps(sigh_header, separators=(",", ":"))
108
+ b64_str = base64.b64encode(json_str.encode("utf-8")).decode("utf-8")
109
+ b64_str.replace("=", "")
110
+ headers.update({"Sec-WebSocket-Protocol": b64_str})
111
+ else:
112
+ headers.update(sigh_header)
113
+
114
+ if data:
115
+ kwargs.update({"data": JsonPayload(data)})
116
+
117
+ return args
118
+
18
119
  @staticmethod
19
120
  def ourbit(args: tuple[str, URL], kwargs: dict[str, Any]) -> tuple[str, URL]:
20
121
  method: str = args[0]
@@ -67,16 +168,6 @@ class Auth:
67
168
  token = session.__dict__["_apis"][pybotters.auth.Hosts.items[url.host].name][0]
68
169
  cookie = f"uc_token={token}; u_id={token}; "
69
170
  headers.update({"cookie": cookie})
70
-
71
- # wss消息增加参数
72
- # if headers.get("Upgrade") == "websocket":
73
- # args = (method, url)
74
- # # 拼接 token
75
- # q = dict(url.query)
76
- # q["token"] = token
77
- # url = url.with_query(q)
78
-
79
-
80
171
  return args
81
172
 
82
173
 
@@ -86,3 +177,12 @@ pybotters.auth.Hosts.items["futures.ourbit.com"] = pybotters.auth.Item(
86
177
  pybotters.auth.Hosts.items["www.ourbit.com"] = pybotters.auth.Item(
87
178
  "ourbit", Auth.ourbit_spot
88
179
  )
180
+
181
+ pybotters.auth.Hosts.items["pro.edgex.exchange"] = pybotters.auth.Item(
182
+ "edgex", Auth.edgex
183
+ )
184
+
185
+
186
+ pybotters.auth.Hosts.items["quote.edgex.exchange"] = pybotters.auth.Item(
187
+ "edgex", Auth.edgex
188
+ )
@@ -1,12 +1,43 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import asyncio
4
+ from decimal import Decimal
5
+ import hashlib
6
+ import math
7
+ import random
8
+ import re
3
9
  import time
4
10
  from typing import Any, Iterable, Literal
5
11
 
6
12
  import pybotters
7
13
 
8
14
  from .models.edgex import EdgexDataStore
9
-
15
+ from .lib.edgex_sign import LimitOrderMessage, LimitOrderSigner
16
+ from .lib.util import fmt_value
17
+
18
+ def gen_client_id():
19
+ # 1. 生成 [0,1) 的浮点数
20
+ r = random.random()
21
+ # 2. 转成字符串
22
+ s = str(r) # e.g. "0.123456789"
23
+ # 3. 去掉 "0."
24
+ digits = s[2:]
25
+ # 4. 去掉前导 0
26
+ digits = re.sub(r"^0+", "", digits)
27
+ return digits
28
+
29
+
30
+ def calc_nonce(client_order_id: str) -> int:
31
+ digest = hashlib.sha256(client_order_id.encode()).hexdigest()
32
+ return int(digest[:8], 16)
33
+
34
+ def bignumber_to_string(x: Decimal) -> str:
35
+ # normalize 去掉尾随零,然后用 f 格式避免科学计数法
36
+ s = format(x.normalize(), "f")
37
+ # 去掉小数点后多余的 0
38
+ if "." in s:
39
+ s = s.rstrip("0").rstrip(".")
40
+ return s
10
41
 
11
42
  class Edgex:
12
43
  """
@@ -35,11 +66,47 @@ class Edgex:
35
66
  # 公共端点可能因环境/地区不同而变化,允许外部覆盖。
36
67
  self.api_url = api_url or "https://pro.edgex.exchange"
37
68
  self.ws_url = "wss://quote.edgex.exchange"
69
+ self.userid = None
70
+ self.eth_address = None
71
+ self.l2key = None
72
+
73
+ api = self.client._session.__dict__['_apis'].get("edgex") # type: ignore
74
+ if api:
75
+ self.l2key = api[2].split("-")[1]
38
76
 
39
77
  async def __aenter__(self) -> "Edgex":
40
78
  # 初始化基础合约元数据,便于后续使用 tickSize 等字段。
41
79
  await self.update_detail()
80
+ await self.sync_user()
42
81
  return self
82
+
83
+ async def sync_user(self) -> dict[str, Any]:
84
+ # https://pro.edgex.exchange/api/v1/private/user/getUserInfo
85
+ # https://pro.edgex.exchange/api/v1/private/account/getAccountPage?size=100
86
+ # url = self._resolve_api_path("/api/v1/private/user/getUserInfo")
87
+ # url = self._resolve_api_path("/api/v1/private/account/getAccountPage")
88
+
89
+ res = await self.client.get(f'{self.api_url}/api/v1/private/account/getAccountPage?size=100')
90
+
91
+ data = await res.json()
92
+
93
+ # 重新取 userId ethAddress accountId
94
+ data = data.get("data", {})
95
+ accounts = data.get("dataList", [])
96
+ if accounts:
97
+ account = accounts[0]
98
+ self.userid = account.get("userId")
99
+ self.eth_address = account.get("ethAddress")
100
+ self.accountid = account.get("id")
101
+ else:
102
+ raise ValueError("No account data found in response")
103
+
104
+ async def sub_personal(self) -> None:
105
+ """订阅用户相关的私有频道(需要登录)。"""
106
+ await self.client.ws_connect(
107
+ f"{self.ws_url}/api/v1/private/ws?accountId={self.accountid}&timestamp=" + str(int(time.time() * 1000)),
108
+ hdlr_json=self.store.onmessage,
109
+ )
43
110
 
44
111
  async def __aexit__(
45
112
  self,
@@ -53,20 +120,46 @@ class Edgex:
53
120
  async def update_detail(self) -> dict[str, Any]:
54
121
  """Fetch and cache contract metadata via the public REST endpoint."""
55
122
 
56
- url = self._resolve_api_path("/api/v1/public/meta/getMetaData")
57
- res = await self.client.get(url)
58
- res.raise_for_status()
59
- data = await res.json()
123
+ await self.store.initialize(
124
+ self.client.get(f'{self.api_url}/api/v1/public/meta/getMetaData'),
125
+ )
60
126
 
61
- if data.get("code") != "SUCCESS": # pragma: no cover - defensive guard
62
- raise RuntimeError(f"Failed to fetch Edgex metadata: {data}")
127
+ async def update(
128
+ self,
129
+ update_type: Literal["balance", "position", "orders", "all"] = "all",
130
+ ):
131
+ """使用 REST 刷新本地缓存的账户资产、持仓及活动订单。"""
132
+
133
+ if not getattr(self, "accountid", None):
134
+ raise ValueError("accountid not set; call sync_user() before update().")
135
+
136
+ account_asset_url = (
137
+ f"{self.api_url}/api/v1/private/account/getAccountAsset"
138
+ f"?accountId={self.accountid}"
139
+ )
140
+ active_orders_url = (
141
+ f"{self.api_url}/api/v1/private/order/getActiveOrderPage"
142
+ f"?accountId={self.accountid}&size=200"
143
+ )
144
+
145
+ all_urls = [account_asset_url, active_orders_url]
146
+
147
+ url_map = {
148
+ "balance": [account_asset_url],
149
+ "position": [account_asset_url],
150
+ "orders": [active_orders_url],
151
+ "all": all_urls,
152
+ }
153
+
154
+ try:
155
+ urls = url_map[update_type]
156
+ except KeyError:
157
+ raise ValueError(f"update_type err: {update_type}")
158
+
159
+ # 直接传协程进去,initialize 会自己 await
160
+ await self.store.initialize(*(self.client.get(url) for url in urls))
63
161
 
64
- self.store._apply_metadata(data)
65
- return data
66
162
 
67
- def _resolve_api_path(self, path: str) -> str:
68
- base = (self.api_url or "").rstrip("/")
69
- return f"{base}{path}"
70
163
 
71
164
  async def sub_orderbook(
72
165
  self,
@@ -172,6 +265,218 @@ class Edgex:
172
265
  wsapp = self.client.ws_connect(url, send_json=payload, hdlr_json=self.store.onmessage)
173
266
  await wsapp._event.wait()
174
267
 
268
+ def _fmt_price(self, symbol: str, price: float) -> str:
269
+ o = self.store.detail.get({"contractName": symbol})
270
+ if not o:
271
+ raise ValueError(f"Unknown Edgex symbol: {symbol}")
272
+ tick = float(o.get("tickSize"))
273
+ return fmt_value(price, float(tick))
274
+
275
+ def _fmt_size(self, symbol: str, size: float) -> str:
276
+ o = self.store.detail.get({"contractName": symbol})
277
+ if not o:
278
+ raise ValueError(f"Unknown Edgex symbol: {symbol}")
279
+ step = float(o.get("stepSize"))
280
+ return fmt_value(size, float(step))
281
+
282
+
283
+ async def place_order(
284
+ self,
285
+ symbol: str,
286
+ side: Literal["buy", "sell"],
287
+ price: float = None,
288
+ quantity: float = None,
289
+ order_type: Literal["market", "limit_ioc", "limit_gtc"] = "limit_ioc",
290
+ usdt_amount: float = None,
291
+ ):
292
+ """下单接口(私有 REST)。
293
+ 返回值order_id: str
294
+ """
295
+
296
+ # 前端请求模板
297
+ args = {
298
+ "price": "210.00",
299
+ "size": "1.0",
300
+ "type": "LIMIT",
301
+ "timeInForce": "GOOD_TIL_CANCEL",
302
+ "reduceOnly": False,
303
+ "isPositionTpsl": False,
304
+ "isSetOpenTp": False,
305
+ "isSetOpenSl": False,
306
+ "accountId": "663528067938910372",
307
+ "contractId": "10000003",
308
+ "side": "BUY",
309
+ "triggerPrice": "",
310
+ "triggerPriceType": "LAST_PRICE",
311
+ "clientOrderId": "39299826149407513",
312
+ "expireTime": "1760352231536",
313
+ "l2Nonce": "1872301",
314
+ "l2Value": "210",
315
+ "l2Size": "1.0",
316
+ "l2LimitFee": "1",
317
+ "l2ExpireTime": "1761129831536",
318
+ "l2Signature": "03c4d84c30586b12ab9fec939a875201e58dac9a0391f15eb6118ab2fb50464804ce38b19cc5e07c973fc66b449bec0274058ea2d012c1c7a580f805d2c7a1d3",
319
+ "extraType": "",
320
+ "extraDataJson": "",
321
+ "symbol": "SOLUSD",
322
+ "showEqualValInput": False,
323
+ "maxSellQTY": 1, # 不需要特别计算, 服务器不校验
324
+ "maxBuyQTY": 1 # 不需要特别计算, 服务器不校验
325
+ }
326
+
327
+ try:
328
+ size = Decimal(self._fmt_size(symbol, quantity))
329
+ price = Decimal(self._fmt_price(symbol, price))
330
+ except (ValueError, TypeError):
331
+ raise ValueError("failed to parse size or price")
332
+
333
+ if 'gtc' in order_type:
334
+ args['timeInForce'] = "GOOD_TIL_CANCEL"
335
+ if 'ioc' in order_type:
336
+ args['timeInForce'] = "IMMEDIATE_OR_CANCEL"
337
+ if 'limit' in order_type:
338
+ args['type'] = "LIMIT"
339
+ if 'market' in order_type:
340
+ args['type'] = "MARKET"
341
+
342
+ if side == 'buy':
343
+ price = price * 10
344
+ else:
345
+ tick_size = self.store.detail.get({'contractName': symbol}).get("tickSize")
346
+ price = Decimal(tick_size)
347
+
348
+ if not self.l2key or not self.userid:
349
+ raise ValueError("L2 key or userId is not set. Ensure API keys are correctly configured.")
350
+
351
+
352
+ collateral_coin = self.store.app.get({'appName': 'edgeX'})
353
+
354
+ c = self.store.detail.get({'contractName': symbol})
355
+ if not c:
356
+ raise ValueError(f"Unknown Edgex symbol: {symbol}")
357
+ hex_resolution = c.get("starkExResolution", "0x0")
358
+ hex_resolution = hex_resolution.replace("0x", "")
359
+
360
+ try:
361
+ resolution_int = int(hex_resolution, 16)
362
+ resolution = Decimal(resolution_int)
363
+ except (ValueError, TypeError):
364
+ raise ValueError("failed to parse hex resolution")
365
+
366
+ client_order_id = gen_client_id()
367
+
368
+ # Calculate values
369
+ value_dm:Decimal = price * size
370
+
371
+ amount_synthetic = int(size * resolution)
372
+ amount_collateral = int(value_dm * Decimal("1000000")) # Shift 6 decimal places
373
+
374
+
375
+ # Calculate fee based on order type (maker/taker)
376
+ try:
377
+ fee_rate = Decimal(c.get("defaultTakerFeeRate", "0"))
378
+ except (ValueError, TypeError):
379
+ raise ValueError("failed to parse fee rate")
380
+
381
+ # Calculate fee amount in decimal with ceiling to integer
382
+ amount_fee_dm = Decimal(str(math.ceil(float(value_dm * fee_rate))))
383
+ amount_fee_str = str(amount_fee_dm)
384
+
385
+ # Convert to the required integer format for the protocol
386
+ amount_fee = int(amount_fee_dm * Decimal("1000000")) # Shift 6 decimal places
387
+
388
+ nonce = calc_nonce(client_order_id)
389
+ now = int(time.time() * 1000)
390
+ l2_expire_time = int(now + 2592e6) # 30 天后
391
+ expireTime = int(l2_expire_time - 7776e5) # 提前 9 天
392
+
393
+
394
+ # Calculate signature using asset IDs from metadata
395
+ expire_time_unix = int(l2_expire_time // (60 * 60 * 1000))
396
+
397
+ asset_id_synthetic = c.get("starkExSyntheticAssetId")
398
+
399
+ act_id = self.accountid
400
+
401
+ message = LimitOrderMessage(
402
+ asset_id_synthetic=asset_id_synthetic, # SOLUSD
403
+ asset_id_collateral=collateral_coin.get("starkExCollateralStarkExAssetId"), # USDT
404
+ asset_id_fee=collateral_coin.get("starkExCollateralStarkExAssetId"),
405
+ is_buy= side=='buy', # isBuyingSynthetic
406
+ amount_synthetic=amount_synthetic, # quantumsAmountSynthetic
407
+ amount_collateral=amount_collateral, # quantumsAmountCollateral
408
+ amount_fee=amount_fee, # quantumsAmountFee
409
+ nonce=int(nonce), # nonce
410
+ position_id=int(act_id), # positionId
411
+ expiration_epoch_hours=int(expire_time_unix), # 此处也比较重要 # TODO: 计算
412
+ )
413
+
414
+ # 取 L2 私钥
415
+
416
+
417
+ signer = LimitOrderSigner(self.l2key)
418
+ hash_hex, signature_hex = signer.sign(message)
419
+ value_str = bignumber_to_string(value_dm)
420
+
421
+ price_str = str(price) if 'limit' in order_type else "0"
422
+
423
+ args.update({
424
+ 'price': price_str,
425
+ 'size': str(float(size)),
426
+ 'side': side.upper(),
427
+ 'accountId': str(act_id),
428
+ 'contractId': str(c.get("contractId")),
429
+ 'clientOrderId': client_order_id,
430
+ 'expireTime': str(expireTime),
431
+ 'l2ExpireTime': str(l2_expire_time),
432
+ 'l2Nonce': str(nonce),
433
+ 'l2Value': value_str,
434
+ 'l2Size': str(float(size)),
435
+ 'l2LimitFee': amount_fee_str,
436
+ 'l2Signature': signature_hex,
437
+ 'symbol': symbol
438
+ })
439
+
440
+
441
+
442
+ res = await self.client.post(
443
+ f'{self.api_url}/api/v1/private/order/createOrder',
444
+ data=args
445
+ )
446
+
447
+ data:dict = await res.json()
448
+ if data.get("code") != "SUCCESS": # pragma: no cover - defensive guard
449
+ raise RuntimeError(f"Failed to place Edgex order: {data}")
450
+
451
+ # latency = int(data.get("responseTime",0)) - int(data.get("requestTime",0))
452
+
453
+ order_id = data.get("data", {}).get("orderId")
454
+ return order_id
455
+
456
+ async def cancel_orders(self, order_ids: list[str]) -> dict[str, Any]:
457
+ """
458
+ 批量撤单接口(私有 REST)。
459
+
460
+ .. code:: json
461
+ {
462
+ "665186247567737508": "SUCCESS"
463
+ }
464
+ """
465
+
466
+ args = {
467
+ "orderIdList": order_ids,
468
+ "accountId": str(self.accountid),
469
+ }
470
+ res = await self.client.post(
471
+ f'{self.api_url}/api/v1/private/order/cancelOrderById',
472
+ data=args
473
+ )
474
+ data: dict = await res.json()
475
+ print(data)
476
+ if data.get("code") != "SUCCESS": # pragma: no cover - defensive guard
477
+ raise RuntimeError(f"Failed to cancel Edgex orders: {data}")
478
+ return data.get("data", {}).get("cancelResultMap", {})
479
+
175
480
 
176
481
  async def __aexit__(
177
482
  self,
@@ -180,4 +485,4 @@ class Edgex:
180
485
  tb: BaseException | None,
181
486
  ) -> None:
182
487
  # Edgex 当前没有需要关闭的资源;保持接口与 Ourbit 等类一致。
183
- return None
488
+ return None
@@ -102,4 +102,9 @@ class Lbank:
102
102
  self.store.register_book_channel(str(y), symbol)
103
103
  y += 1
104
104
 
105
- await asyncio.gather(*(sub(send_json) for send_json in send_jsons))
105
+ # Rate limit: max 5 subscriptions per second
106
+ for i in range(0, len(send_jsons), 5):
107
+ batch = send_jsons[i:i+5]
108
+ await asyncio.gather(*(sub(send_json) for send_json in batch))
109
+ if i + 5 < len(send_jsons):
110
+ await asyncio.sleep(0.1)