hyperquant 0.25__py3-none-any.whl → 0.31__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,247 @@
1
+ from typing import Literal, Optional
2
+ import pybotters
3
+ from .models.ourbit import OurbitSwapDataStore
4
+
5
+
6
+ class OurbitSwap:
7
+
8
+ def __init__(self, client: pybotters.Client):
9
+ """
10
+ ✅ 完成:
11
+ 下单, 撤单, 查询资金, 查询持有订单, 查询历史订单
12
+
13
+ """
14
+ self.client = client
15
+ self.store = OurbitSwapDataStore()
16
+ self.api_url = "https://futures.ourbit.com"
17
+ self.ws_url = "wss://futures.ourbit.com/edge"
18
+
19
+ async def __aenter__(self) -> "OurbitSwap":
20
+ client = self.client
21
+ await self.store.initialize(
22
+ client.get(f"{self.api_url}/api/v1/contract/detailV2?client=web")
23
+ )
24
+ return self
25
+
26
+ async def update(
27
+ self, update_type: Literal["position", "orders", "balance", "ticker", "all"] = "all"
28
+ ):
29
+ """由于交易所很多不支持ws推送,这里使用Rest"""
30
+ all_urls = [
31
+ f"{self.api_url}/api/v1/private/position/open_positions",
32
+ f"{self.api_url}/api/v1/private/order/list/open_orders?page_size=200",
33
+ f"{self.api_url}/api/v1/private/account/assets",
34
+ f"{self.api_url}/api/v1/contract/ticker",
35
+ ]
36
+
37
+ url_map = {
38
+ "position": [all_urls[0]],
39
+ "orders": [all_urls[1]],
40
+ "balance": [all_urls[2]],
41
+ "ticker": [all_urls[3]],
42
+ "all": all_urls,
43
+ }
44
+
45
+ try:
46
+ urls = url_map[update_type]
47
+ except KeyError:
48
+ raise ValueError(f"update_type err: {update_type}")
49
+
50
+ # 直接传协程进去,initialize 会自己 await
51
+ await self.store.initialize(*(self.client.get(url) for url in urls))
52
+
53
+ async def sub_tickers(self):
54
+ self.client.ws_connect(
55
+ self.ws_url,
56
+ send_json={
57
+ "method": "sub.tickers",
58
+ "param": {
59
+ "timezone": "UTC+8"
60
+ }
61
+ },
62
+ hdlr_json=self.store.onmessage
63
+ )
64
+
65
+ async def sub_order_book(self, symbols: str | list[str]):
66
+ if isinstance(symbols, str):
67
+ symbols = [symbols]
68
+
69
+ send_jsons = []
70
+ # send_json={"method":"sub.depth.step","param":{"symbol":"BTC_USDT","step":"0.1"}},
71
+
72
+ for symbol in symbols:
73
+ step = self.store.detail.find({"symbol": symbol})[0].get("tick_size")
74
+
75
+ send_jsons.append({
76
+ "method": "sub.depth.step",
77
+ "param": {
78
+ "symbol": symbol,
79
+ "step": str(step)
80
+ }
81
+ })
82
+
83
+ await self.client.ws_connect(
84
+ self.ws_url,
85
+ send_json=send_jsons,
86
+ hdlr_json=self.store.onmessage
87
+ )
88
+
89
+ def ret_content(self, res: pybotters.FetchResult):
90
+ match res.data:
91
+ case {"success": True}:
92
+ return res.data["data"]
93
+ case _:
94
+ raise Exception(f"Failed api {res.response.url}: {res.data}")
95
+
96
+
97
+ async def place_order(
98
+ self,
99
+ symbol: str,
100
+ side: Literal["buy", "sell", "close_buy", "close_sell"],
101
+ size: float = None,
102
+ price: float = None,
103
+ order_type: Literal["market", "limit_GTC", "limit_IOC"] = "market",
104
+ usdt_amount: Optional[float] = None,
105
+ leverage: Optional[int] = 20,
106
+ position_id: Optional[int] = None,
107
+ ):
108
+ """
109
+ size为合约张数
110
+
111
+ .. code ::
112
+ {
113
+ "orderId": "219602019841167810",
114
+ "ts": 1756395601543
115
+ }
116
+
117
+ """
118
+ if (size is None) == (usdt_amount is None):
119
+ raise ValueError("params err")
120
+
121
+ max_lev = self.store.detail.find({"symbol": symbol})[0].get("max_lev")
122
+
123
+ if usdt_amount is not None:
124
+ cs = self.store.detail.find({"symbol": symbol})[0].get("contract_sz")
125
+ size = max(int(usdt_amount / cs / price), 1)
126
+
127
+
128
+ leverage = max(max_lev, leverage)
129
+
130
+ data = {
131
+ "symbol": symbol,
132
+ "side": 1 if side == "buy" else 3,
133
+ "openType": 1,
134
+ "type": "5",
135
+ "vol": size,
136
+ "leverage": leverage,
137
+ "marketCeiling": False,
138
+ "priceProtect": "0",
139
+ }
140
+
141
+ if order_type == "limit_IOC":
142
+ data["type"] = 3
143
+ data["price"] = str(price)
144
+ if order_type == "limit_GTC":
145
+ data["type"] = "1"
146
+ data["price"] = str(price)
147
+
148
+ if "close" in side:
149
+ if side == 'close_buy':
150
+ data["side"] = 4
151
+ elif side == 'close_sell':
152
+ data["side"] = 2
153
+ data["type"] = 5
154
+ if position_id is None:
155
+ raise ValueError("position_id is required for closing position")
156
+ data["positionId"] = position_id
157
+ import time
158
+ print(time.time(), '下单')
159
+ res = await self.client.fetch(
160
+ "POST", f"{self.api_url}/api/v1/private/order/create", data=data
161
+ )
162
+ return self.ret_content(res)
163
+
164
+ async def cancel_orders(self, order_ids: list[str]):
165
+ res = await self.client.fetch(
166
+ "POST",
167
+ f"{self.api_url}/api/v1/private/order/cancel",
168
+ data=order_ids,
169
+ )
170
+ return self.ret_content(res)
171
+
172
+ async def query_orders(
173
+ self,
174
+ symbol: str,
175
+ states: list[Literal["filled", "canceled"]], # filled:已成交, canceled:已撤销
176
+ start_time: Optional[int] = None,
177
+ end_time: Optional[int] = None,
178
+ page_size: int = 200,
179
+ page_num: int = 1,
180
+ ):
181
+ """查询历史订单
182
+
183
+ Args:
184
+ symbol: 交易对
185
+ states: 订单状态列表 ["filled":已成交, "canceled":已撤销]
186
+ start_time: 开始时间戳(毫秒), 可选
187
+ end_time: 结束时间戳(毫秒), 可选
188
+ page_size: 每页数量, 默认200
189
+ page_num: 页码, 默认1
190
+ """
191
+ state_map = {"filled": 3, "canceled": 4}
192
+
193
+ params = {
194
+ "symbol": symbol,
195
+ "states": ",".join(str(state_map[state]) for state in states),
196
+ "page_size": page_size,
197
+ "page_num": page_num,
198
+ "category": 1,
199
+ }
200
+
201
+ if start_time:
202
+ params["start_time"] = start_time
203
+ if end_time:
204
+ params["end_time"] = end_time
205
+
206
+ res = await self.client.fetch(
207
+ "GET",
208
+ f"{self.api_url}/api/v1/private/order/list/history_orders",
209
+ params=params,
210
+ )
211
+
212
+ return self.ret_content(res)
213
+
214
+ async def query_order(self, order_id: str):
215
+ """查询单个订单的详细信息
216
+
217
+ Args:
218
+ order_id: 订单ID
219
+
220
+ Returns:
221
+ ..code:python
222
+
223
+ 订单详情数据,例如:
224
+ [
225
+ {
226
+ "id": "38600506", # 成交ID
227
+ "symbol": "SOL_USDT", # 交易对
228
+ "side": 4, # 方向(1:买入, 3:卖出, 4:平仓)
229
+ "vol": 1, # 成交数量
230
+ "price": 204.11, # 成交价格
231
+ "fee": 0.00081644, # 手续费
232
+ "feeCurrency": "USDT", # 手续费币种
233
+ "profit": -0.0034, # 盈亏
234
+ "category": 1, # 品类
235
+ "orderId": "219079365441409152", # 订单ID
236
+ "timestamp": 1756270991000, # 时间戳
237
+ "positionMode": 1, # 持仓模式
238
+ "voucher": false, # 是否使用代金券
239
+ "taker": true # 是否是taker
240
+ }
241
+ ]
242
+ """
243
+ res = await self.client.fetch(
244
+ "GET",
245
+ f"{self.api_url}/api/v1/private/order/deal_details/{order_id}",
246
+ )
247
+ return self.ret_content(res)
@@ -0,0 +1,12 @@
1
+ import asyncio
2
+ import pybotters
3
+
4
+
5
+ class Heartbeat:
6
+ @staticmethod
7
+ async def ourbit(ws: pybotters.ws.ClientWebSocketResponse):
8
+ while not ws.closed:
9
+ await ws.send_str('{"method":"ping"}')
10
+ await asyncio.sleep(10.0)
11
+
12
+ pybotters.ws.HeartbeatHosts.items['futures.ourbit.com'] = Heartbeat.ourbit
hyperquant/core.py CHANGED
@@ -350,7 +350,7 @@ class Exchange(ExchangeBase):
350
350
  self.record_history(time)
351
351
 
352
352
  # 自动更新账户状态
353
- self.Update({symbol: price}, time=time)
353
+ self.Update({symbol: price}, time=time)
354
354
 
355
355
  return trade
356
356
 
@@ -377,41 +377,92 @@ class Exchange(ExchangeBase):
377
377
  trades.append(trade)
378
378
  return trades
379
379
 
380
- def Update(self, close_price, symbols=None, **kwargs):
380
+ def _recalc_aggregates(self):
381
+ """基于 self.account 中已保存的各 symbol 状态,重算聚合字段。"""
382
+ usdt = self.account['USDT']
383
+ usdt['unrealised_profit'] = 0
384
+ usdt['hold'] = 0
385
+ usdt['long'] = 0
386
+ usdt['short'] = 0
387
+
388
+ for symbol in self.trade_symbols:
389
+ if symbol not in self.account:
390
+ continue
391
+ sym = self.account[symbol]
392
+ px = sym.get('price', 0)
393
+ amt = sym.get('amount', 0)
394
+ hp = sym.get('hold_price', 0)
395
+
396
+ # 仅当价格有效时计入聚合
397
+ if px is not None and not np.isnan(px) and px != 0:
398
+ sym['unrealised_profit'] = (px - hp) * amt
399
+ sym['value'] = amt * px
400
+
401
+ if amt > 0:
402
+ usdt['long'] += sym['value']
403
+ elif amt < 0:
404
+ usdt['short'] += sym['value']
405
+
406
+ usdt['hold'] += abs(sym['value'])
407
+ usdt['unrealised_profit'] += sym['unrealised_profit']
408
+
409
+ usdt['total'] = round(self.account['USDT']['realised_profit'] + self.initial_balance + usdt['unrealised_profit'], 6)
410
+ usdt['leverage'] = round(usdt['hold'] / usdt['total'] if usdt['total'] != 0 else 0.0, 3)
411
+
412
+ def Update(self, close_price=None, symbols=None, partial=True, **kwargs):
413
+ """
414
+ 更新账户状态。
415
+ - partial=True:只更新给定 symbols 的逐符号状态,然后对所有符号做一次聚合重算(推荐)。
416
+ - partial=False:与原逻辑兼容;当提供一部分 symbol 时,也会聚合重算,不会清空未提供符号的信息。
417
+
418
+ 支持三种入参形式:
419
+ 1) close_price 为 dict/Series:symbols 自动取其键/索引
420
+ 2) close_price 为标量 + symbols 为单个字符串
421
+ 3) 显式传 symbols=list[...],close_price 为 dict/Series(从中取价)
422
+ 如果既不传 close_price 也不传 symbols,则只做一次聚合重算(例如你先前已经手动修改了某些 symbol 的 price)。
423
+ """
381
424
  if self.recorded and 'time' not in kwargs:
382
425
  raise ValueError("Time parameter is required in recorded mode.")
383
426
 
384
427
  time = kwargs.get('time', pd.Timestamp.now())
385
- self.account['USDT']['unrealised_profit'] = 0
386
- self.account['USDT']['hold'] = 0
387
- self.account['USDT']['long'] = 0
388
- self.account['USDT']['short'] = 0
428
+
429
+ # 解析 symbols & 价格获取器
389
430
  if symbols is None:
390
- # symbols = self.trade_symbols
391
- # 如果symbols是dict类型, 则取出所有的key, 如果是Series类型, 则取出所有的index
392
431
  if isinstance(close_price, dict):
393
432
  symbols = list(close_price.keys())
394
433
  elif isinstance(close_price, pd.Series):
395
- symbols = close_price.index
434
+ symbols = list(close_price.index)
396
435
  else:
397
- raise ValueError("Symbols should be a list, dict or Series.")
398
-
399
- for symbol in symbols:
400
- if symbol not in self.trade_symbols:
436
+ symbols = []
437
+ elif isinstance(symbols, str):
438
+ symbols = [symbols]
439
+
440
+ def get_px(sym):
441
+ if isinstance(close_price, (int, float, np.floating)) and len(symbols) == 1:
442
+ return float(close_price)
443
+ if isinstance(close_price, dict):
444
+ return close_price.get(sym, np.nan)
445
+ if isinstance(close_price, pd.Series):
446
+ return close_price.get(sym, np.nan)
447
+ return np.nan
448
+
449
+ # 仅更新传入的 symbols(部分更新,不动其它符号已保存信息)
450
+ for sym in symbols:
451
+ if sym not in self.trade_symbols or sym not in self.account:
452
+ # 未登记的交易对直接跳过(或可选择自动登记,但此处保持严格)
453
+ continue
454
+ px = get_px(sym)
455
+ if px is None or np.isnan(px):
456
+ # 价格无效则不覆盖旧价格
401
457
  continue
402
- if not np.isnan(close_price[symbol]):
403
- self.account[symbol]['unrealised_profit'] = (close_price[symbol] - self.account[symbol]['hold_price']) * self.account[symbol]['amount']
404
- self.account[symbol]['price'] = close_price[symbol]
405
- self.account[symbol]['value'] = self.account[symbol]['amount'] * close_price[symbol]
406
- if self.account[symbol]['amount'] > 0:
407
- self.account['USDT']['long'] += self.account[symbol]['value']
408
- if self.account[symbol]['amount'] < 0:
409
- self.account['USDT']['short'] += self.account[symbol]['value']
410
- self.account['USDT']['hold'] += abs(self.account[symbol]['value'])
411
- self.account['USDT']['unrealised_profit'] += self.account[symbol]['unrealised_profit']
412
-
413
- self.account['USDT']['total'] = round(self.account['USDT']['realised_profit'] + self.initial_balance + self.account['USDT']['unrealised_profit'], 6)
414
- self.account['USDT']['leverage'] = round(self.account['USDT']['hold'] / self.account['USDT']['total'], 3)
458
+
459
+ self.account[sym]['price'] = float(px)
460
+ amt = self.account[sym]['amount']
461
+ self.account[sym]['value'] = amt * float(px)
462
+ # 不在这里算 unrealised_profit,聚合阶段统一算
463
+
464
+ # 无论 partial 与否,最后都用“账户中保存的所有 symbol 当前状态”做一次聚合重算
465
+ self._recalc_aggregates()
415
466
 
416
467
  # 记录账户总资产到 history
417
468
  if self.recorded:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperquant
3
- Version: 0.25
3
+ Version: 0.31
4
4
  Summary: A minimal yet hyper-efficient backtesting framework for quantitative trading
5
5
  Project-URL: Homepage, https://github.com/yourusername/hyperquant
6
6
  Project-URL: Issues, https://github.com/yourusername/hyperquant/issues
@@ -19,7 +19,7 @@ Requires-Dist: cryptography>=44.0.2
19
19
  Requires-Dist: duckdb>=1.2.2
20
20
  Requires-Dist: numpy>=1.21.0
21
21
  Requires-Dist: pandas>=2.2.3
22
- Requires-Dist: pybotters>=1.9.0
22
+ Requires-Dist: pybotters>=1.9.1
23
23
  Requires-Dist: pyecharts>=2.0.8
24
24
  Description-Content-Type: text/markdown
25
25
 
@@ -0,0 +1,21 @@
1
+ hyperquant/__init__.py,sha256=UpjiX4LS5jmrBc2kE8RiLR02eCfD8JDQrR1q8zkLNcQ,161
2
+ hyperquant/core.py,sha256=7XrpuHvccWl9lNyVihqaptupqUMsG3xYmQr8eEDrwS4,20610
3
+ hyperquant/db.py,sha256=i2TjkCbmH4Uxo7UTDvOYBfy973gLcGexdzuT_YcSeIE,6678
4
+ hyperquant/draw.py,sha256=up_lQ3pHeVLoNOyh9vPjgNwjD0M-6_IetSGviQUgjhY,54624
5
+ hyperquant/logkit.py,sha256=WALpXpIA3Ywr5DxKKK3k5EKubZ2h-ISGfc5dUReQUBQ,7795
6
+ hyperquant/notikit.py,sha256=x5yAZ_tAvLQRXcRbcg-VabCaN45LUhvlTZnUqkIqfAA,3596
7
+ hyperquant/broker/auth.py,sha256=hrdVuBTZwD3xSy5GI5JTFJhKiHhvIjZHA_7G5IUFznQ,1580
8
+ hyperquant/broker/hyperliquid.py,sha256=7MxbI9OyIBcImDelPJu-8Nd53WXjxPB5TwE6gsjHbto,23252
9
+ hyperquant/broker/ourbit.py,sha256=VE1eLvQ1hakOxWbXHmW8KXwYrP_Apsv0_FOPtmU3MKs,8033
10
+ hyperquant/broker/ws.py,sha256=98Djt5n5sHUJKVbQ8Ql1t-G-Wiwu__4MYcUr5P6SDL0,326
11
+ hyperquant/broker/lib/hpstore.py,sha256=LnLK2zmnwVvhEbLzYI-jz_SfYpO1Dv2u2cJaRAb84D8,8296
12
+ hyperquant/broker/lib/hyper_types.py,sha256=HqjjzjUekldjEeVn6hxiWA8nevAViC2xHADOzDz9qyw,991
13
+ hyperquant/broker/models/hyperliquid.py,sha256=c4r5739ibZfnk69RxPjQl902AVuUOwT8RNvKsMtwXBY,9459
14
+ hyperquant/broker/models/ourbit.py,sha256=zvjtx6fmOuOPAJ8jxD2RK9_mao2XuE2EXkxR74nmXKM,18525
15
+ hyperquant/datavison/_util.py,sha256=92qk4vO856RqycO0YqEIHJlEg-W9XKapDVqAMxe6rbw,533
16
+ hyperquant/datavison/binance.py,sha256=3yNKTqvt_vUQcxzeX4ocMsI5k6Q6gLZrvgXxAEad6Kc,5001
17
+ hyperquant/datavison/coinglass.py,sha256=PEjdjISP9QUKD_xzXNzhJ9WFDTlkBrRQlVL-5pxD5mo,10482
18
+ hyperquant/datavison/okx.py,sha256=yg8WrdQ7wgWHNAInIgsWPM47N3Wkfr253169IPAycAY,6898
19
+ hyperquant-0.31.dist-info/METADATA,sha256=ZfMLDTVVmQdtj-qCg1kwN1fl1TJfRpzHki-6AoUnhEI,4317
20
+ hyperquant-0.31.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
21
+ hyperquant-0.31.dist-info/RECORD,,
@@ -1,16 +0,0 @@
1
- hyperquant/__init__.py,sha256=gUuAPVpg5k8X_dpda5OpqmMyZ-ZXNQq-xwx-6JR5Jr4,131
2
- hyperquant/core.py,sha256=vKv8KElo1eGhr_aw0I-j6ZxPOneDx86KqAoOI-wbq0A,18838
3
- hyperquant/db.py,sha256=i2TjkCbmH4Uxo7UTDvOYBfy973gLcGexdzuT_YcSeIE,6678
4
- hyperquant/draw.py,sha256=up_lQ3pHeVLoNOyh9vPjgNwjD0M-6_IetSGviQUgjhY,54624
5
- hyperquant/logkit.py,sha256=WALpXpIA3Ywr5DxKKK3k5EKubZ2h-ISGfc5dUReQUBQ,7795
6
- hyperquant/notikit.py,sha256=x5yAZ_tAvLQRXcRbcg-VabCaN45LUhvlTZnUqkIqfAA,3596
7
- hyperquant/broker/hyperliquid.py,sha256=mSBVfmjcv6ciI1vWrmHYwBOTHrg-NQrwcyVFUXYEgVw,21998
8
- hyperquant/broker/lib/hpstore.py,sha256=LnLK2zmnwVvhEbLzYI-jz_SfYpO1Dv2u2cJaRAb84D8,8296
9
- hyperquant/broker/lib/hyper_types.py,sha256=HqjjzjUekldjEeVn6hxiWA8nevAViC2xHADOzDz9qyw,991
10
- hyperquant/datavison/_util.py,sha256=92qk4vO856RqycO0YqEIHJlEg-W9XKapDVqAMxe6rbw,533
11
- hyperquant/datavison/binance.py,sha256=3yNKTqvt_vUQcxzeX4ocMsI5k6Q6gLZrvgXxAEad6Kc,5001
12
- hyperquant/datavison/coinglass.py,sha256=PEjdjISP9QUKD_xzXNzhJ9WFDTlkBrRQlVL-5pxD5mo,10482
13
- hyperquant/datavison/okx.py,sha256=yg8WrdQ7wgWHNAInIgsWPM47N3Wkfr253169IPAycAY,6898
14
- hyperquant-0.25.dist-info/METADATA,sha256=re5JjxsJCj3BOunjieCHlp7c_fOuyaHZVZc8RDrCNKw,4317
15
- hyperquant-0.25.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
- hyperquant-0.25.dist-info/RECORD,,