hyperquant 0.8__py3-none-any.whl → 0.9__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/broker/auth.py +74 -1
- hyperquant/broker/coinup.py +556 -0
- hyperquant/broker/coinw.py +487 -0
- hyperquant/broker/lbank.py +73 -0
- hyperquant/broker/models/coinup.py +290 -0
- hyperquant/broker/models/coinw.py +724 -0
- hyperquant/broker/ws.py +53 -4
- {hyperquant-0.8.dist-info → hyperquant-0.9.dist-info}/METADATA +4 -2
- {hyperquant-0.8.dist-info → hyperquant-0.9.dist-info}/RECORD +10 -6
- {hyperquant-0.8.dist-info → hyperquant-0.9.dist-info}/WHEEL +0 -0
hyperquant/broker/auth.py
CHANGED
|
@@ -198,6 +198,75 @@ class Auth:
|
|
|
198
198
|
|
|
199
199
|
return args
|
|
200
200
|
|
|
201
|
+
@staticmethod
|
|
202
|
+
def coinw(args: tuple[str, URL], kwargs: dict[str, Any]) -> tuple[str, URL]:
|
|
203
|
+
method: str = args[0]
|
|
204
|
+
url: URL = args[1]
|
|
205
|
+
headers: CIMultiDict = kwargs["headers"]
|
|
206
|
+
|
|
207
|
+
session = kwargs["session"]
|
|
208
|
+
try:
|
|
209
|
+
api_key, secret, _ = session.__dict__["_apis"][pybotters.auth.Hosts.items[url.host].name]
|
|
210
|
+
except (KeyError, ValueError):
|
|
211
|
+
raise RuntimeError("CoinW credentials (api_key, secret) are required")
|
|
212
|
+
|
|
213
|
+
timestamp = str(int(time.time() * 1000))
|
|
214
|
+
method_upper = method.upper()
|
|
215
|
+
|
|
216
|
+
params = kwargs.get("params")
|
|
217
|
+
query_string = ""
|
|
218
|
+
if isinstance(params, dict) and params:
|
|
219
|
+
query_items = [
|
|
220
|
+
f"{key}={value}"
|
|
221
|
+
for key, value in params.items()
|
|
222
|
+
if value is not None
|
|
223
|
+
]
|
|
224
|
+
query_string = "&".join(query_items)
|
|
225
|
+
elif url.query_string:
|
|
226
|
+
query_string = url.query_string
|
|
227
|
+
|
|
228
|
+
body_str = ""
|
|
229
|
+
|
|
230
|
+
if method_upper == "GET":
|
|
231
|
+
body = None
|
|
232
|
+
data = None
|
|
233
|
+
else:
|
|
234
|
+
body = kwargs.get("json")
|
|
235
|
+
data = kwargs.get("data")
|
|
236
|
+
payload = body if body is not None else data
|
|
237
|
+
if isinstance(payload, (dict, list)):
|
|
238
|
+
body_str = pyjson.dumps(payload, separators=(",", ":"), ensure_ascii=False)
|
|
239
|
+
kwargs["data"] = body_str
|
|
240
|
+
kwargs.pop("json", None)
|
|
241
|
+
elif payload is not None:
|
|
242
|
+
body_str = str(payload)
|
|
243
|
+
kwargs["data"] = body_str
|
|
244
|
+
kwargs.pop("json", None)
|
|
245
|
+
|
|
246
|
+
if query_string:
|
|
247
|
+
path = f"{url.raw_path}?{query_string}"
|
|
248
|
+
else:
|
|
249
|
+
path = url.raw_path
|
|
250
|
+
|
|
251
|
+
message = f"{timestamp}{method_upper}{path}{body_str}"
|
|
252
|
+
signature = hmac.new(
|
|
253
|
+
secret, message.encode("utf-8"), hashlib.sha256
|
|
254
|
+
).digest()
|
|
255
|
+
signature_b64 = base64.b64encode(signature).decode("ascii")
|
|
256
|
+
|
|
257
|
+
headers.update(
|
|
258
|
+
{
|
|
259
|
+
"sign": signature_b64,
|
|
260
|
+
"api_key": api_key,
|
|
261
|
+
"timestamp": timestamp,
|
|
262
|
+
}
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
if method_upper in {"POST", "PUT", "PATCH", "DELETE"} and "data" in kwargs:
|
|
266
|
+
headers.setdefault("Content-Type", "application/json")
|
|
267
|
+
|
|
268
|
+
return args
|
|
269
|
+
|
|
201
270
|
pybotters.auth.Hosts.items["futures.ourbit.com"] = pybotters.auth.Item(
|
|
202
271
|
"ourbit", Auth.ourbit
|
|
203
272
|
)
|
|
@@ -220,4 +289,8 @@ pybotters.auth.Hosts.items["quote.edgex.exchange"] = pybotters.auth.Item(
|
|
|
220
289
|
|
|
221
290
|
pybotters.auth.Hosts.items["uuapi.rerrkvifj.com"] = pybotters.auth.Item(
|
|
222
291
|
"lbank", Auth.lbank
|
|
223
|
-
)
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
pybotters.auth.Hosts.items["api.coinw.com"] = pybotters.auth.Item(
|
|
295
|
+
"coinw", Auth.coinw
|
|
296
|
+
)
|
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from typing import Any, Literal, Sequence
|
|
9
|
+
|
|
10
|
+
import pybotters
|
|
11
|
+
import rnet
|
|
12
|
+
|
|
13
|
+
from .models.coinup import CoinUpDataStore
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
_DEFAULT_SECURITY_INFO = (
|
|
18
|
+
'{"log_BSDeviceFingerprint":"0","log_original":"0","log_CHFIT_DEVICEID":"0"}'
|
|
19
|
+
)
|
|
20
|
+
_SECRET_PREFIX = "HJ@%*AZ_J"
|
|
21
|
+
_DEFAULT_UA = (
|
|
22
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
|
23
|
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
24
|
+
"Chrome/141.0.0.0 Safari/537.36"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Coinup:
|
|
29
|
+
"""CoinUp 永续合约客户端(REST via rnet + WebSocket depth)。
|
|
30
|
+
|
|
31
|
+
与 CoinW 客户端结构保持一致,差异点:
|
|
32
|
+
|
|
33
|
+
- REST 请求使用 :mod:`rnet`,以规避指纹检测。
|
|
34
|
+
- 仅订单簿 ``book`` 频道依赖 WebSocket,其他数据通过 REST 刷新。
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
client: pybotters.Client,
|
|
40
|
+
*,
|
|
41
|
+
rest_client: rnet.Client | None = None,
|
|
42
|
+
rest_api_common: str | None = None,
|
|
43
|
+
rest_api_futures: str | None = None,
|
|
44
|
+
ws_url: str | None = None,
|
|
45
|
+
security_info: str | None = None,
|
|
46
|
+
exchange_token: str | None = None,
|
|
47
|
+
emulation: rnet.Emulation | rnet.EmulationOption | None = None,
|
|
48
|
+
rest_headers_common: dict[str, str] | None = None,
|
|
49
|
+
rest_headers_futures: dict[str, str] | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
self.client = client
|
|
52
|
+
self.store = CoinUpDataStore()
|
|
53
|
+
|
|
54
|
+
self.rest_api_common = rest_api_common or "https://www.coinup.io/fe-co-api"
|
|
55
|
+
self.rest_api_futures = rest_api_futures or "https://futures.coinup.io/fe-co-api"
|
|
56
|
+
self.ws_url = ws_url or "wss://futuresws.marketketac.com/kline-api/ws"
|
|
57
|
+
|
|
58
|
+
self.security_info = security_info or _DEFAULT_SECURITY_INFO
|
|
59
|
+
self._emulation = emulation or rnet.Emulation.Safari26
|
|
60
|
+
|
|
61
|
+
self._rest_client = rest_client or rnet.Client(
|
|
62
|
+
emulation=self._emulation,
|
|
63
|
+
headers={"User-Agent": _DEFAULT_UA},
|
|
64
|
+
allow_redirects=False,
|
|
65
|
+
history=False,
|
|
66
|
+
)
|
|
67
|
+
self._owns_rest_client = rest_client is None
|
|
68
|
+
|
|
69
|
+
common_headers = {
|
|
70
|
+
"Content-Type": "application/json",
|
|
71
|
+
"Origin": "https://www.coinup.io",
|
|
72
|
+
"Referer": "https://www.coinup.io/",
|
|
73
|
+
"User-Agent": _DEFAULT_UA,
|
|
74
|
+
}
|
|
75
|
+
futures_headers = {
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
"Origin": "https://futures.coinup.io",
|
|
78
|
+
"Referer": "https://futures.coinup.io/zh_CN/trade",
|
|
79
|
+
"User-Agent": _DEFAULT_UA,
|
|
80
|
+
"exchange-client": "pc",
|
|
81
|
+
"exchange-language": "zh_CN",
|
|
82
|
+
}
|
|
83
|
+
if rest_headers_common:
|
|
84
|
+
common_headers.update(rest_headers_common)
|
|
85
|
+
if rest_headers_futures:
|
|
86
|
+
futures_headers.update(rest_headers_futures)
|
|
87
|
+
|
|
88
|
+
self._exchange_token = exchange_token or self._extract_exchange_token()
|
|
89
|
+
if self._exchange_token:
|
|
90
|
+
futures_headers["exchange-token"] = self._exchange_token
|
|
91
|
+
|
|
92
|
+
self._headers_common = common_headers
|
|
93
|
+
self._headers_futures = futures_headers
|
|
94
|
+
|
|
95
|
+
async def __aenter__(self) -> "Coinup":
|
|
96
|
+
await self.update("detail")
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
async def __aexit__(self, exc_type, exc, tb) -> None: # pragma: no cover - symmetry
|
|
100
|
+
await self.aclose()
|
|
101
|
+
|
|
102
|
+
async def aclose(self) -> None:
|
|
103
|
+
"""Close the underlying rnet client if we created it."""
|
|
104
|
+
|
|
105
|
+
if self._owns_rest_client and hasattr(self._rest_client, "close"):
|
|
106
|
+
await self._rest_client.close()
|
|
107
|
+
|
|
108
|
+
def get_contract_id(self, symbol: str) -> str | None:
|
|
109
|
+
"""根据交易对获取合约 ID。"""
|
|
110
|
+
|
|
111
|
+
detail = self.store.detail.get({"symbol": symbol})
|
|
112
|
+
if detail is None:
|
|
113
|
+
return None
|
|
114
|
+
contract_id = detail.get("id")
|
|
115
|
+
if contract_id is None:
|
|
116
|
+
return None
|
|
117
|
+
return str(contract_id)
|
|
118
|
+
|
|
119
|
+
async def update(
|
|
120
|
+
self,
|
|
121
|
+
update_type: Literal["detail", "position", "balance", "orders", "all"] = "all",
|
|
122
|
+
*,
|
|
123
|
+
detail_payload: dict[str, Any] | None = None,
|
|
124
|
+
assets_payload: dict[str, Any] | None = None,
|
|
125
|
+
assets_endpoint: Literal["get_assets_list", "wallet_and_unrealized"] = "get_assets_list",
|
|
126
|
+
orders_payload: dict[str, Any] | None = None,
|
|
127
|
+
) -> None:
|
|
128
|
+
"""刷新本地缓存,所有 REST 请求通过 rnet 发送。
|
|
129
|
+
|
|
130
|
+
- detail: ``POST /common/public_info`` (公共接口)
|
|
131
|
+
- position/balance: ``POST /position/get_assets_list`` (返回仓位 & 余额)
|
|
132
|
+
- 备选 ``/position/wallet_and_unrealized`` 可通过 ``assets_endpoint`` 指定
|
|
133
|
+
- orders: ``POST /order/current_order_list`` (私有)
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
include_detail = update_type in {"detail", "all"}
|
|
137
|
+
include_position = update_type in {"position", "all"}
|
|
138
|
+
include_balance = update_type in {"balance", "all"}
|
|
139
|
+
include_orders = update_type in {"orders", "all"}
|
|
140
|
+
|
|
141
|
+
include_assets = include_position or include_balance
|
|
142
|
+
|
|
143
|
+
if not (include_detail or include_assets or include_orders):
|
|
144
|
+
raise ValueError(f"Unsupported update_type: {update_type}")
|
|
145
|
+
|
|
146
|
+
tasks: dict[str, asyncio.Task[Any]] = {}
|
|
147
|
+
|
|
148
|
+
if include_detail:
|
|
149
|
+
tasks["detail"] = asyncio.create_task(
|
|
150
|
+
self._fetch_detail(detail_payload)
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if include_assets:
|
|
154
|
+
tasks["assets"] = asyncio.create_task(
|
|
155
|
+
self._fetch_assets(assets_payload, endpoint=assets_endpoint)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
if include_orders:
|
|
159
|
+
tasks["orders"] = asyncio.create_task(self._fetch_orders(orders_payload))
|
|
160
|
+
|
|
161
|
+
results: dict[str, Any] = {}
|
|
162
|
+
try:
|
|
163
|
+
for key, task in tasks.items():
|
|
164
|
+
results[key] = await task
|
|
165
|
+
except Exception:
|
|
166
|
+
for task in tasks.values():
|
|
167
|
+
task.cancel()
|
|
168
|
+
raise
|
|
169
|
+
|
|
170
|
+
if include_detail and "detail" in results:
|
|
171
|
+
self.store.detail._onresponse(results["detail"])
|
|
172
|
+
|
|
173
|
+
assets_data = results.get("assets")
|
|
174
|
+
if assets_data is not None:
|
|
175
|
+
if include_position:
|
|
176
|
+
self.store.position._onresponse(assets_data)
|
|
177
|
+
if include_balance:
|
|
178
|
+
self.store.balance._onresponse(assets_data)
|
|
179
|
+
|
|
180
|
+
if include_orders:
|
|
181
|
+
orders_data = results.get("orders")
|
|
182
|
+
if orders_data is not None:
|
|
183
|
+
self.store.orders._onresponse(orders_data)
|
|
184
|
+
|
|
185
|
+
async def sub_orderbook(
|
|
186
|
+
self,
|
|
187
|
+
channels: Sequence[str] | str,
|
|
188
|
+
*,
|
|
189
|
+
depth_step: str = "step0",
|
|
190
|
+
depth_limit: int | None = None,
|
|
191
|
+
) -> pybotters.ws.WebSocketApp:
|
|
192
|
+
"""订阅订单簿深度频道。
|
|
193
|
+
|
|
194
|
+
参数 ``channels`` 支持 ``subSymbol`` 或完整频道名称:
|
|
195
|
+
|
|
196
|
+
- ``"e_wlfiusdt"`` -> 发送 ``market_e_wlfiusdt_depth_step0``
|
|
197
|
+
- ``"market_e_wlfiusdt_depth_step0"`` -> 原样发送
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
if isinstance(channels, str):
|
|
201
|
+
channels = [channels]
|
|
202
|
+
|
|
203
|
+
payloads = []
|
|
204
|
+
for channel in channels:
|
|
205
|
+
ch = channel.lower()
|
|
206
|
+
if not ch.startswith("market_"):
|
|
207
|
+
ch = f"market_{ch}_depth_{depth_step}"
|
|
208
|
+
payloads.append(
|
|
209
|
+
{
|
|
210
|
+
"event": "sub",
|
|
211
|
+
"params": {
|
|
212
|
+
"channel": ch,
|
|
213
|
+
"cb_id": ch.split("_depth_", 1)[0].replace("market_", ""),
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
if not payloads:
|
|
219
|
+
raise ValueError("channels must not be empty")
|
|
220
|
+
|
|
221
|
+
self.store.book.limit = depth_limit
|
|
222
|
+
|
|
223
|
+
ws_headers = {
|
|
224
|
+
"Origin": "https://futures.coinup.io",
|
|
225
|
+
"Referer": "https://futures.coinup.io/zh_CN/trade",
|
|
226
|
+
"User-Agent": _DEFAULT_UA,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
ws_app = self.client.ws_connect(
|
|
230
|
+
self.ws_url,
|
|
231
|
+
hdlr_bytes=self.store.onmessage,
|
|
232
|
+
headers=ws_headers,
|
|
233
|
+
autoping=False,
|
|
234
|
+
)
|
|
235
|
+
await ws_app._event.wait()
|
|
236
|
+
|
|
237
|
+
for payload in payloads:
|
|
238
|
+
await ws_app.current_ws.send_json(payload)
|
|
239
|
+
await asyncio.sleep(0.05)
|
|
240
|
+
|
|
241
|
+
return ws_app
|
|
242
|
+
|
|
243
|
+
async def place_order(
|
|
244
|
+
self,
|
|
245
|
+
symbol: str,
|
|
246
|
+
*,
|
|
247
|
+
side: Literal["buy", "sell", "BUY", "SELL"],
|
|
248
|
+
volume: float | int | str,
|
|
249
|
+
order_type: Literal["limit", "market", 1, 2] = "limit",
|
|
250
|
+
price: float | int | str | None = None,
|
|
251
|
+
position_type: int | str = 1,
|
|
252
|
+
leverage_level: int | str = 1,
|
|
253
|
+
offset: Literal["open", "close", "OPEN", "CLOSE"] = "open",
|
|
254
|
+
order_unit: int | str = 2,
|
|
255
|
+
trigger_price: float | int | str | None = None,
|
|
256
|
+
is_condition_order: bool = False,
|
|
257
|
+
is_oto: bool = False,
|
|
258
|
+
is_check_liq: int | bool = 1,
|
|
259
|
+
secret: str | None = None,
|
|
260
|
+
take_profit_trigger: float | int | str | None = None,
|
|
261
|
+
take_profit_price: float | int | str | None = 0,
|
|
262
|
+
take_profit_type: int | None = 2,
|
|
263
|
+
stop_loss_trigger: float | int | str | None = None,
|
|
264
|
+
stop_loss_price: float | int | str | None = 0,
|
|
265
|
+
stop_loss_type: int | None = 2,
|
|
266
|
+
extra_params: dict[str, Any] | None = None,
|
|
267
|
+
) -> dict[str, Any]:
|
|
268
|
+
"""
|
|
269
|
+
``POST /order/order_create`` 下单(默认支持限价/市价)。
|
|
270
|
+
当 close 时, volume为张数
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
symbol: 交易对符号(如 "BTC_USDT"),将自动解析为 contract_id。
|
|
274
|
+
"""
|
|
275
|
+
contract_id = self.get_contract_id(symbol)
|
|
276
|
+
if contract_id is None:
|
|
277
|
+
raise ValueError(f"Invalid symbol: {symbol}")
|
|
278
|
+
|
|
279
|
+
normalized_side = self._normalize_side(side)
|
|
280
|
+
normalized_offset = self._normalize_offset(offset)
|
|
281
|
+
order_type_code = self._normalize_order_type(order_type)
|
|
282
|
+
|
|
283
|
+
if order_type_code == 1 and price is None:
|
|
284
|
+
raise ValueError("price is required for CoinUp limit orders")
|
|
285
|
+
price_value = self._format_price(price)
|
|
286
|
+
if order_type_code == 1 and price_value is None:
|
|
287
|
+
raise ValueError("price is required for CoinUp limit orders")
|
|
288
|
+
if price_value is None:
|
|
289
|
+
price_value = 0
|
|
290
|
+
|
|
291
|
+
volume_str = self._format_volume(volume)
|
|
292
|
+
trigger_price_value = self._format_price(trigger_price)
|
|
293
|
+
take_profit_trigger_value = self._format_price(take_profit_trigger)
|
|
294
|
+
take_profit_price_value = self._format_price(take_profit_price)
|
|
295
|
+
stop_loss_trigger_value = self._format_price(stop_loss_trigger)
|
|
296
|
+
stop_loss_price_value = self._format_price(stop_loss_price)
|
|
297
|
+
|
|
298
|
+
payload: dict[str, Any] = {
|
|
299
|
+
"contractId": contract_id,
|
|
300
|
+
"positionType": int(position_type),
|
|
301
|
+
"side": normalized_side,
|
|
302
|
+
"leverageLevel": int(leverage_level),
|
|
303
|
+
"price": price_value,
|
|
304
|
+
"volume": volume_str,
|
|
305
|
+
"triggerPrice": trigger_price_value,
|
|
306
|
+
"open": normalized_offset,
|
|
307
|
+
"type": order_type_code,
|
|
308
|
+
"isConditionOrder": bool(is_condition_order),
|
|
309
|
+
"isOto": bool(is_oto),
|
|
310
|
+
"orderUnit": int(order_unit),
|
|
311
|
+
"isCheckLiq": int(is_check_liq),
|
|
312
|
+
"takerProfitTrigger": take_profit_trigger_value,
|
|
313
|
+
"takerProfitPrice": take_profit_price_value,
|
|
314
|
+
"takerProfitType": take_profit_type,
|
|
315
|
+
"stopLossTrigger": stop_loss_trigger_value,
|
|
316
|
+
"stopLossPrice": stop_loss_price_value,
|
|
317
|
+
"stopLossType": stop_loss_type,
|
|
318
|
+
}
|
|
319
|
+
if extra_params:
|
|
320
|
+
payload.update(extra_params)
|
|
321
|
+
|
|
322
|
+
if secret is None:
|
|
323
|
+
payload["secret"] = self._generate_secret(
|
|
324
|
+
contract_id=str(contract_id),
|
|
325
|
+
leverage_level=str(leverage_level),
|
|
326
|
+
position_type=str(position_type),
|
|
327
|
+
price=price_value,
|
|
328
|
+
side=normalized_side,
|
|
329
|
+
order_type=str(order_type_code),
|
|
330
|
+
volume=volume_str,
|
|
331
|
+
)
|
|
332
|
+
else:
|
|
333
|
+
payload["secret"] = secret
|
|
334
|
+
|
|
335
|
+
body = self._build_payload(payload)
|
|
336
|
+
data = await self._rest_post(
|
|
337
|
+
f"{self.rest_api_futures}/order/order_create",
|
|
338
|
+
body,
|
|
339
|
+
self._headers_futures,
|
|
340
|
+
)
|
|
341
|
+
result = self._ensure_success("place_order", data)
|
|
342
|
+
return result.get("data") or {}
|
|
343
|
+
|
|
344
|
+
async def cancel_order(
|
|
345
|
+
self,
|
|
346
|
+
symbol: str,
|
|
347
|
+
order_id: str | int,
|
|
348
|
+
*,
|
|
349
|
+
is_condition_order: bool = False,
|
|
350
|
+
extra_params: dict[str, Any] | None = None,
|
|
351
|
+
) -> dict[str, Any] | None:
|
|
352
|
+
"""
|
|
353
|
+
``POST /order/order_cancel`` 取消指定订单。
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
symbol: 交易对符号(如 "BTC_USDT"),将自动解析为 contract_id。
|
|
357
|
+
"""
|
|
358
|
+
contract_id = self.get_contract_id(symbol)
|
|
359
|
+
if contract_id is None:
|
|
360
|
+
raise ValueError(f"Invalid symbol: {symbol}")
|
|
361
|
+
|
|
362
|
+
payload: dict[str, Any] = {
|
|
363
|
+
"contractId": contract_id,
|
|
364
|
+
"orderId": str(order_id),
|
|
365
|
+
"isConditionOrder": bool(is_condition_order),
|
|
366
|
+
}
|
|
367
|
+
if extra_params:
|
|
368
|
+
payload.update(extra_params)
|
|
369
|
+
|
|
370
|
+
body = self._build_payload(payload)
|
|
371
|
+
data = await self._rest_post(
|
|
372
|
+
f"{self.rest_api_futures}/order/order_cancel",
|
|
373
|
+
body,
|
|
374
|
+
self._headers_futures,
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
result = self._ensure_success("cancel_order", data)
|
|
378
|
+
return result.get("data")
|
|
379
|
+
|
|
380
|
+
def set_exchange_token(self, token: str | None) -> None:
|
|
381
|
+
"""Update the ``exchange-token`` header used for CoinUp private REST calls."""
|
|
382
|
+
|
|
383
|
+
self._exchange_token = token
|
|
384
|
+
if token:
|
|
385
|
+
self._headers_futures["exchange-token"] = token
|
|
386
|
+
else:
|
|
387
|
+
self._headers_futures.pop("exchange-token", None)
|
|
388
|
+
|
|
389
|
+
def _build_payload(self, overrides: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
390
|
+
payload = {
|
|
391
|
+
"uaTime": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
|
|
392
|
+
"securityInfo": self.security_info,
|
|
393
|
+
}
|
|
394
|
+
if overrides:
|
|
395
|
+
payload.update(overrides)
|
|
396
|
+
return payload
|
|
397
|
+
|
|
398
|
+
async def _fetch_detail(self, payload: dict[str, Any] | None) -> Any:
|
|
399
|
+
url = f"{self.rest_api_common}/common/public_info"
|
|
400
|
+
data = await self._rest_post(
|
|
401
|
+
url,
|
|
402
|
+
self._build_payload(payload),
|
|
403
|
+
self._headers_common,
|
|
404
|
+
)
|
|
405
|
+
return data
|
|
406
|
+
|
|
407
|
+
async def _fetch_assets(
|
|
408
|
+
self,
|
|
409
|
+
payload: dict[str, Any] | None,
|
|
410
|
+
*,
|
|
411
|
+
endpoint: str,
|
|
412
|
+
) -> Any:
|
|
413
|
+
url = f"{self.rest_api_futures}/position/{endpoint}"
|
|
414
|
+
data = await self._rest_post(
|
|
415
|
+
url,
|
|
416
|
+
self._build_payload(payload),
|
|
417
|
+
self._headers_futures,
|
|
418
|
+
)
|
|
419
|
+
return data
|
|
420
|
+
|
|
421
|
+
async def _rest_post(
|
|
422
|
+
self,
|
|
423
|
+
url: str,
|
|
424
|
+
payload: dict[str, Any],
|
|
425
|
+
headers: dict[str, str],
|
|
426
|
+
) -> Any:
|
|
427
|
+
response = await self._rest_client.post(
|
|
428
|
+
url,
|
|
429
|
+
json=payload,
|
|
430
|
+
headers=headers,
|
|
431
|
+
)
|
|
432
|
+
try:
|
|
433
|
+
status = response.status.as_int()
|
|
434
|
+
if status >= 400:
|
|
435
|
+
text = await response.text()
|
|
436
|
+
raise RuntimeError(
|
|
437
|
+
f"CoinUp REST request failed ({status}): {text}"
|
|
438
|
+
)
|
|
439
|
+
return await response.json()
|
|
440
|
+
finally:
|
|
441
|
+
await response.close()
|
|
442
|
+
|
|
443
|
+
async def _fetch_orders(self, payload: dict[str, Any] | None) -> Any:
|
|
444
|
+
url = f"{self.rest_api_futures}/order/current_order_list"
|
|
445
|
+
data = await self._rest_post(
|
|
446
|
+
url,
|
|
447
|
+
self._build_payload(payload or {"contractId": ""}),
|
|
448
|
+
self._headers_futures,
|
|
449
|
+
)
|
|
450
|
+
return data
|
|
451
|
+
|
|
452
|
+
def _extract_exchange_token(self) -> str | None:
|
|
453
|
+
"""Best-effort fetch of token from pybotters credential store."""
|
|
454
|
+
|
|
455
|
+
session = getattr(self.client, "_session", None)
|
|
456
|
+
if not session:
|
|
457
|
+
return None
|
|
458
|
+
apis = getattr(session, "__dict__", {}).get("_apis")
|
|
459
|
+
if not isinstance(apis, dict):
|
|
460
|
+
return None
|
|
461
|
+
creds = apis.get("coinup")
|
|
462
|
+
if not creds:
|
|
463
|
+
return None
|
|
464
|
+
token = creds[0]
|
|
465
|
+
return str(token) if token else None
|
|
466
|
+
|
|
467
|
+
@staticmethod
|
|
468
|
+
def _ensure_success(operation: str, payload: Any) -> dict[str, Any]:
|
|
469
|
+
if not isinstance(payload, dict):
|
|
470
|
+
raise RuntimeError(f"{operation} failed: unexpected response {payload}")
|
|
471
|
+
code = payload.get("code")
|
|
472
|
+
succ = payload.get("succ")
|
|
473
|
+
if code is not None and str(code) != "0":
|
|
474
|
+
raise RuntimeError(f"{operation} failed: {payload}")
|
|
475
|
+
if succ is False:
|
|
476
|
+
raise RuntimeError(f"{operation} failed: {payload}")
|
|
477
|
+
return payload
|
|
478
|
+
|
|
479
|
+
@staticmethod
|
|
480
|
+
def _normalize_side(side: str) -> str:
|
|
481
|
+
value = str(side).upper()
|
|
482
|
+
if value not in {"BUY", "SELL"}:
|
|
483
|
+
raise ValueError(f"Unsupported side: {side}")
|
|
484
|
+
return value
|
|
485
|
+
|
|
486
|
+
@staticmethod
|
|
487
|
+
def _normalize_offset(offset: str) -> str:
|
|
488
|
+
value = str(offset).upper()
|
|
489
|
+
mapping = {"OPEN": "OPEN", "CLOSE": "CLOSE"}
|
|
490
|
+
try:
|
|
491
|
+
return mapping[value]
|
|
492
|
+
except KeyError as exc:
|
|
493
|
+
raise ValueError(f"Unsupported offset: {offset}") from exc
|
|
494
|
+
|
|
495
|
+
@staticmethod
|
|
496
|
+
def _normalize_order_type(order_type: Literal["limit", "market", 1, 2]) -> int:
|
|
497
|
+
mapping = {
|
|
498
|
+
"limit": 1,
|
|
499
|
+
"market": 2,
|
|
500
|
+
1: 1,
|
|
501
|
+
2: 2,
|
|
502
|
+
}
|
|
503
|
+
try:
|
|
504
|
+
return mapping[order_type] # type: ignore[index]
|
|
505
|
+
except KeyError as exc:
|
|
506
|
+
raise ValueError(f"Unsupported order_type: {order_type}") from exc
|
|
507
|
+
|
|
508
|
+
@staticmethod
|
|
509
|
+
def _generate_secret(
|
|
510
|
+
contract_id: str,
|
|
511
|
+
leverage_level: str,
|
|
512
|
+
position_type: str,
|
|
513
|
+
price: float | int | str,
|
|
514
|
+
side: str,
|
|
515
|
+
order_type: str,
|
|
516
|
+
volume: str,
|
|
517
|
+
) -> str:
|
|
518
|
+
data = {
|
|
519
|
+
"contractId": contract_id,
|
|
520
|
+
"leverageLevel": leverage_level,
|
|
521
|
+
"positionType": position_type,
|
|
522
|
+
"price": Coinup._stringify_number(price),
|
|
523
|
+
"side": side,
|
|
524
|
+
"type": order_type,
|
|
525
|
+
"volume": Coinup._stringify_number(volume),
|
|
526
|
+
}
|
|
527
|
+
text = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
|
|
528
|
+
raw = f"{_SECRET_PREFIX}{text}"
|
|
529
|
+
return hashlib.md5(raw.encode("utf-8")).hexdigest()
|
|
530
|
+
|
|
531
|
+
@staticmethod
|
|
532
|
+
def _format_price(value: float | int | str | None) -> float | int | str | None:
|
|
533
|
+
if value is None:
|
|
534
|
+
return None
|
|
535
|
+
if isinstance(value, (float, int)):
|
|
536
|
+
return float(value)
|
|
537
|
+
return value
|
|
538
|
+
|
|
539
|
+
@staticmethod
|
|
540
|
+
def _format_volume(value: float | int | str) -> str:
|
|
541
|
+
return str(value)
|
|
542
|
+
|
|
543
|
+
@staticmethod
|
|
544
|
+
def _stringify_number(value: float | int | str | None) -> str:
|
|
545
|
+
if value is None:
|
|
546
|
+
return "0"
|
|
547
|
+
if isinstance(value, str):
|
|
548
|
+
return value
|
|
549
|
+
if isinstance(value, int):
|
|
550
|
+
return str(value)
|
|
551
|
+
if isinstance(value, float):
|
|
552
|
+
if value.is_integer():
|
|
553
|
+
return str(int(value))
|
|
554
|
+
text = format(value, "f").rstrip("0").rstrip(".")
|
|
555
|
+
return text or "0"
|
|
556
|
+
return str(value)
|