alltradingapi 1.0.0__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.
- alltradingapi/__init__.py +81 -0
- alltradingapi/_version.py +8 -0
- alltradingapi/async_client.py +174 -0
- alltradingapi/cache.py +75 -0
- alltradingapi/client.py +494 -0
- alltradingapi/config.py +167 -0
- alltradingapi/errors.py +307 -0
- alltradingapi/logging_.py +67 -0
- alltradingapi/models/__init__.py +16 -0
- alltradingapi/models/asset.py +94 -0
- alltradingapi/models/base.py +190 -0
- alltradingapi/models/candle.py +191 -0
- alltradingapi/models/trade_result.py +84 -0
- alltradingapi/params.py +272 -0
- alltradingapi/py.typed +0 -0
- alltradingapi/transport.py +425 -0
- alltradingapi/update.py +657 -0
- alltradingapi/utils.py +103 -0
- alltradingapi-1.0.0.dist-info/METADATA +204 -0
- alltradingapi-1.0.0.dist-info/RECORD +22 -0
- alltradingapi-1.0.0.dist-info/WHEEL +4 -0
- alltradingapi-1.0.0.dist-info/licenses/LICENSE +21 -0
alltradingapi/errors.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Error hierarchy for the All Trading API SDK.
|
|
2
|
+
|
|
3
|
+
Every error carries structured context (status, payload, redacted URL) and a
|
|
4
|
+
message that tells the user what to do next. API keys never appear in error
|
|
5
|
+
text, ``repr`` or URLs.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .utils import redact_url
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"ALLError",
|
|
17
|
+
"ConfigurationError",
|
|
18
|
+
"AuthenticationError",
|
|
19
|
+
"PermissionDeniedError",
|
|
20
|
+
"NotFoundError",
|
|
21
|
+
"ValidationError",
|
|
22
|
+
"RateLimitError",
|
|
23
|
+
"ServerError",
|
|
24
|
+
"UpstreamError",
|
|
25
|
+
"TransportError",
|
|
26
|
+
"TimeoutError_",
|
|
27
|
+
"UpdateRequiredError",
|
|
28
|
+
"UpdateCheckError",
|
|
29
|
+
"update_hint",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ALLError(Exception):
|
|
34
|
+
"""Base class for every error raised by this SDK.
|
|
35
|
+
|
|
36
|
+
Attributes:
|
|
37
|
+
message: Human-readable explanation including a next step.
|
|
38
|
+
status: HTTP status code when the error came from a response.
|
|
39
|
+
code: Short machine-readable code (e.g. ``rate_limited``).
|
|
40
|
+
request_id: Server-provided request id when available.
|
|
41
|
+
payload: Parsed JSON body of the failing response, when present.
|
|
42
|
+
url: Request URL with any credentials redacted.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
code: str = "all_error"
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
message: str,
|
|
50
|
+
*,
|
|
51
|
+
status: int | None = None,
|
|
52
|
+
payload: dict[str, Any] | None = None,
|
|
53
|
+
url: str | None = None,
|
|
54
|
+
request_id: str | None = None,
|
|
55
|
+
) -> None:
|
|
56
|
+
super().__init__(message)
|
|
57
|
+
self.message = message
|
|
58
|
+
self.status = status
|
|
59
|
+
self.payload = payload or {}
|
|
60
|
+
self.url = url
|
|
61
|
+
self.request_id = request_id
|
|
62
|
+
|
|
63
|
+
def __repr__(self) -> str: # pragma: no cover - trivial
|
|
64
|
+
return f"<{type(self).__name__} code={self.code} status={self.status}>"
|
|
65
|
+
|
|
66
|
+
def to_dict(self) -> dict[str, Any]:
|
|
67
|
+
"""Return a JSON-serialisable view (URL already key-redacted)."""
|
|
68
|
+
return {
|
|
69
|
+
"error": self.code,
|
|
70
|
+
"message": self.message,
|
|
71
|
+
"status": self.status,
|
|
72
|
+
"request_id": self.request_id,
|
|
73
|
+
"url": self.url,
|
|
74
|
+
"payload": self.payload,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ConfigurationError(ALLError):
|
|
79
|
+
"""The SDK was constructed or called with impossible configuration."""
|
|
80
|
+
|
|
81
|
+
code = "configuration_error"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class AuthenticationError(ALLError):
|
|
85
|
+
"""HTTP 401 — missing or invalid API key."""
|
|
86
|
+
|
|
87
|
+
code = "authentication_error"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class PermissionDeniedError(ALLError):
|
|
91
|
+
"""HTTP 403 — the key does not include this product, or is paused."""
|
|
92
|
+
|
|
93
|
+
code = "permission_denied"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class NotFoundError(ALLError):
|
|
97
|
+
"""HTTP 404 — unknown route (the server only serves pretty routes)."""
|
|
98
|
+
|
|
99
|
+
code = "not_found"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ValidationError(ALLError):
|
|
103
|
+
"""HTTP 400 — bad/missing/unknown parameter (rejected client-side or server-side)."""
|
|
104
|
+
|
|
105
|
+
code = "validation_error"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class RateLimitError(ALLError):
|
|
109
|
+
"""HTTP 429 — rate limit reached; ``retry_after`` says when to retry."""
|
|
110
|
+
|
|
111
|
+
code = "rate_limited"
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
message: str,
|
|
116
|
+
*,
|
|
117
|
+
retry_after: float | None = None,
|
|
118
|
+
**kwargs: Any,
|
|
119
|
+
) -> None:
|
|
120
|
+
super().__init__(message, **kwargs)
|
|
121
|
+
self.retry_after = retry_after
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class ServerError(ALLError):
|
|
125
|
+
"""HTTP 5xx — server error on the API side."""
|
|
126
|
+
|
|
127
|
+
code = "server_error"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class UpstreamError(ServerError):
|
|
131
|
+
"""HTTP 502 — market-feed failure or insufficient candles upstream."""
|
|
132
|
+
|
|
133
|
+
code = "upstream_error"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class TransportError(ALLError):
|
|
137
|
+
"""Network-level failure: DNS, TCP, TLS."""
|
|
138
|
+
|
|
139
|
+
code = "transport_error"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class TimeoutError_(ALLError):
|
|
143
|
+
"""A request exceeded its timeout. Alias avoids shadowing builtins."""
|
|
144
|
+
|
|
145
|
+
code = "timeout"
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class UpdateRequiredError(ALLError):
|
|
149
|
+
"""The installed SDK is outdated and the strict update gate blocked it.
|
|
150
|
+
|
|
151
|
+
Attributes:
|
|
152
|
+
installed: Version currently running.
|
|
153
|
+
latest: Version found on PyPI.
|
|
154
|
+
installed_now: True when ``pip install --upgrade`` was run in-process;
|
|
155
|
+
the running interpreter still holds the old code, so restart.
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
code = "update_required"
|
|
159
|
+
|
|
160
|
+
def __init__(
|
|
161
|
+
self,
|
|
162
|
+
message: str,
|
|
163
|
+
*,
|
|
164
|
+
installed: str | None = None,
|
|
165
|
+
latest: str | None = None,
|
|
166
|
+
installed_now: bool = False,
|
|
167
|
+
**kwargs: Any,
|
|
168
|
+
) -> None:
|
|
169
|
+
super().__init__(message, **kwargs)
|
|
170
|
+
self.installed = installed
|
|
171
|
+
self.latest = latest
|
|
172
|
+
self.installed_now = installed_now
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class UpdateCheckError(ALLError):
|
|
176
|
+
"""Raised only by ``Client.check_updates`` when local version config is invalid."""
|
|
177
|
+
|
|
178
|
+
code = "update_check_error"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def update_hint(command: str = "pip install --upgrade alltradingapi") -> str:
|
|
182
|
+
"""A consistent, actionable hint used across update-related errors."""
|
|
183
|
+
return f"Run: {command}"
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def error_from_response(
|
|
187
|
+
status: int,
|
|
188
|
+
body: bytes,
|
|
189
|
+
url: str,
|
|
190
|
+
*,
|
|
191
|
+
headers: dict[str, str] | None = None,
|
|
192
|
+
) -> ALLError:
|
|
193
|
+
"""Map an HTTP response to the matching SDK error.
|
|
194
|
+
|
|
195
|
+
The server's JSON envelope is ``{"error": "..."}``. The server text is
|
|
196
|
+
preserved, and every message keeps an actionable SDK hint. URLs are
|
|
197
|
+
key-redacted before storage.
|
|
198
|
+
"""
|
|
199
|
+
raw_headers = {k.lower(): v for k, v in (headers or {}).items()}
|
|
200
|
+
server_text = None
|
|
201
|
+
payload: dict[str, Any] = {}
|
|
202
|
+
try:
|
|
203
|
+
decoded = json.loads(body.decode("utf-8", errors="replace"))
|
|
204
|
+
if isinstance(decoded, dict):
|
|
205
|
+
payload = decoded
|
|
206
|
+
server_text = decoded.get("error") or decoded.get("message")
|
|
207
|
+
except (ValueError, UnicodeDecodeError):
|
|
208
|
+
pass
|
|
209
|
+
|
|
210
|
+
def msg(hint: str) -> str:
|
|
211
|
+
if server_text and server_text != hint:
|
|
212
|
+
return f"{hint} (server: {server_text})"
|
|
213
|
+
return hint
|
|
214
|
+
|
|
215
|
+
retry_after: float | None = None
|
|
216
|
+
retry_after_raw = raw_headers.get("retry-after")
|
|
217
|
+
if retry_after_raw is not None:
|
|
218
|
+
try:
|
|
219
|
+
retry_after = float(retry_after_raw)
|
|
220
|
+
except ValueError:
|
|
221
|
+
retry_after = None
|
|
222
|
+
|
|
223
|
+
safe_url = redact_url(url)
|
|
224
|
+
|
|
225
|
+
if status == 400:
|
|
226
|
+
return ValidationError(
|
|
227
|
+
msg(
|
|
228
|
+
"The request was rejected (400). Check parameter names, values "
|
|
229
|
+
"and ranges — this SDK validates documented parameters "
|
|
230
|
+
"client-side, so a 400 usually means the server-side set "
|
|
231
|
+
"changed."
|
|
232
|
+
),
|
|
233
|
+
status=status,
|
|
234
|
+
payload=payload,
|
|
235
|
+
url=safe_url,
|
|
236
|
+
)
|
|
237
|
+
if status == 401:
|
|
238
|
+
return AuthenticationError(
|
|
239
|
+
msg(
|
|
240
|
+
"A valid API key is required (401). Pass api_key=..., build "
|
|
241
|
+
"the client with a keys mapping, or set the ATA_API_KEY "
|
|
242
|
+
"environment variable for the product you are calling."
|
|
243
|
+
),
|
|
244
|
+
status=status,
|
|
245
|
+
payload=payload,
|
|
246
|
+
url=safe_url,
|
|
247
|
+
)
|
|
248
|
+
if status == 403:
|
|
249
|
+
return PermissionDeniedError(
|
|
250
|
+
msg(
|
|
251
|
+
"This API key does not include this product, or the "
|
|
252
|
+
"subscription is paused (403). Check your product "
|
|
253
|
+
"subscription — each product needs its own key."
|
|
254
|
+
),
|
|
255
|
+
status=status,
|
|
256
|
+
payload=payload,
|
|
257
|
+
url=safe_url,
|
|
258
|
+
)
|
|
259
|
+
if status == 404:
|
|
260
|
+
return NotFoundError(
|
|
261
|
+
msg(
|
|
262
|
+
"Unknown route (404). The server exposes pretty routes only "
|
|
263
|
+
"(e.g. /qx_candles); direct /api/*.php URLs are blocked by "
|
|
264
|
+
"design."
|
|
265
|
+
),
|
|
266
|
+
status=status,
|
|
267
|
+
payload=payload,
|
|
268
|
+
url=safe_url,
|
|
269
|
+
)
|
|
270
|
+
if status == 429:
|
|
271
|
+
return RateLimitError(
|
|
272
|
+
msg(
|
|
273
|
+
"Rate limit reached (429). The SDK already honours Retry-After "
|
|
274
|
+
"and retries automatically; slow down your polling rate or "
|
|
275
|
+
"upgrade your plan."
|
|
276
|
+
),
|
|
277
|
+
status=status,
|
|
278
|
+
payload=payload,
|
|
279
|
+
url=safe_url,
|
|
280
|
+
retry_after=retry_after,
|
|
281
|
+
)
|
|
282
|
+
if status == 502:
|
|
283
|
+
return UpstreamError(
|
|
284
|
+
msg(
|
|
285
|
+
"The market feed is unavailable upstream (502) or did not "
|
|
286
|
+
"return enough candles. The SDK retries automatically; if it "
|
|
287
|
+
"persists, the feed itself is down — try again shortly."
|
|
288
|
+
),
|
|
289
|
+
status=status,
|
|
290
|
+
payload=payload,
|
|
291
|
+
url=safe_url,
|
|
292
|
+
)
|
|
293
|
+
if 500 <= status <= 599:
|
|
294
|
+
return ServerError(
|
|
295
|
+
msg(
|
|
296
|
+
f"Server error {status} from the API. The SDK retries transient 5xx automatically."
|
|
297
|
+
),
|
|
298
|
+
status=status,
|
|
299
|
+
payload=payload,
|
|
300
|
+
url=safe_url,
|
|
301
|
+
)
|
|
302
|
+
return ALLError(
|
|
303
|
+
msg(f"Unexpected HTTP status {status} from the API."),
|
|
304
|
+
status=status,
|
|
305
|
+
payload=payload,
|
|
306
|
+
url=safe_url,
|
|
307
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Logging setup for the SDK.
|
|
2
|
+
|
|
3
|
+
The SDK logs under the ``"alltradingapi"`` logger:
|
|
4
|
+
|
|
5
|
+
* DEBUG — request/response lines with **redacted** keys and timings
|
|
6
|
+
* WARNING — retries
|
|
7
|
+
* INFO — update-gate events
|
|
8
|
+
* ERROR — failures
|
|
9
|
+
|
|
10
|
+
Payloads are never logged at INFO. Keys are redacted everywhere.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
|
|
17
|
+
from .utils import REDACTED, redact_url
|
|
18
|
+
|
|
19
|
+
__all__ = ["logger", "set_log_level", "http_debug_line"]
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger("alltradingapi")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def set_log_level(level: str, *, log_http: bool = True) -> None:
|
|
25
|
+
"""Configure the SDK logger.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
level: Standard level name (``"DEBUG"``, ``"INFO"``, ...).
|
|
29
|
+
log_http: When True (default) attach the redacting HTTP handler at
|
|
30
|
+
DEBUG level. Set False for fully silent HTTP logging.
|
|
31
|
+
"""
|
|
32
|
+
numeric = getattr(logging, str(level).upper(), logging.WARNING)
|
|
33
|
+
logger.setLevel(numeric)
|
|
34
|
+
if not logger.handlers:
|
|
35
|
+
handler = logging.StreamHandler()
|
|
36
|
+
handler.setFormatter(logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s"))
|
|
37
|
+
logger.addHandler(handler)
|
|
38
|
+
logger.propagate = True
|
|
39
|
+
if log_http and numeric <= logging.DEBUG:
|
|
40
|
+
logger.debug("alltradingapi HTTP logging enabled (keys are redacted)")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def http_debug_line(
|
|
44
|
+
method: str,
|
|
45
|
+
url: str,
|
|
46
|
+
*,
|
|
47
|
+
status: int | None = None,
|
|
48
|
+
elapsed_ms: float | None = None,
|
|
49
|
+
attempt: int = 0,
|
|
50
|
+
) -> str:
|
|
51
|
+
"""Build a single redacted DEBUG line for a request/response."""
|
|
52
|
+
safe_url = redact_url(url)
|
|
53
|
+
parts = [method, safe_url or "<url>"]
|
|
54
|
+
if status is not None:
|
|
55
|
+
parts.append(f"-> {status}")
|
|
56
|
+
if elapsed_ms is not None:
|
|
57
|
+
parts.append(f"{elapsed_ms:.0f}ms")
|
|
58
|
+
if attempt:
|
|
59
|
+
parts.append(f"attempt={attempt + 1}")
|
|
60
|
+
return " ".join(parts)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def redacted_key(key: str | None) -> str:
|
|
64
|
+
"""Return a non-sensitive fingerprint of an API key for cache/debug keys."""
|
|
65
|
+
if not key:
|
|
66
|
+
return "none"
|
|
67
|
+
return REDACTED
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Typed model exports for the All Trading API SDK."""
|
|
2
|
+
|
|
3
|
+
from .asset import Asset
|
|
4
|
+
from .base import APIObject, TradeOutcome, coerce_enum
|
|
5
|
+
from .candle import Candle, SavedCandles
|
|
6
|
+
from .trade_result import TradeResult
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"APIObject",
|
|
10
|
+
"Asset",
|
|
11
|
+
"Candle",
|
|
12
|
+
"SavedCandles",
|
|
13
|
+
"TradeResult",
|
|
14
|
+
"TradeOutcome",
|
|
15
|
+
"coerce_enum",
|
|
16
|
+
]
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Asset model — one entry of the bare-array response from ``/qx_assets``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .base import APIObject
|
|
8
|
+
|
|
9
|
+
__all__ = ["Asset"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Asset(APIObject):
|
|
13
|
+
"""A tradable Quotex asset with live open/closed state and payout."""
|
|
14
|
+
|
|
15
|
+
__slots__ = ()
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def id(self) -> int:
|
|
19
|
+
"""Numeric asset id (e.g. ``368``)."""
|
|
20
|
+
return int(self._data.get("asset_id", 0) or 0)
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def symbol(self) -> str:
|
|
24
|
+
"""Trading symbol, e.g. ``EURUSD_otc``."""
|
|
25
|
+
return str(self._data.get("asset", "") or "")
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def name(self) -> str:
|
|
29
|
+
"""Display name, e.g. ``Euro / US Dollar (OTC)``."""
|
|
30
|
+
return str(self._data.get("asset_name", "") or "")
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def is_open(self) -> bool:
|
|
34
|
+
"""True when the asset is open for trading right now."""
|
|
35
|
+
return bool(self._data.get("is_open", False))
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def type(self) -> str:
|
|
39
|
+
"""Asset class: currency, cryptocurrency, commodity, ..."""
|
|
40
|
+
return str(self._data.get("type", "") or "")
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def payout(self) -> int:
|
|
44
|
+
"""Base payout percentage (e.g. ``77``)."""
|
|
45
|
+
return int(self._data.get("payout", 0) or 0)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def change_24h(self) -> float | None:
|
|
49
|
+
"""24h change, when the market reports it."""
|
|
50
|
+
value = self._data.get("change_24h")
|
|
51
|
+
if value is None:
|
|
52
|
+
return None
|
|
53
|
+
try:
|
|
54
|
+
return float(value)
|
|
55
|
+
except (TypeError, ValueError):
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def profit_1m(self) -> int | None:
|
|
60
|
+
"""Payout for 1-minute expiry."""
|
|
61
|
+
profit = self._data.get("profit")
|
|
62
|
+
if isinstance(profit, dict):
|
|
63
|
+
return _int_or_none(profit.get("1M"))
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def profit_5m(self) -> int | None:
|
|
68
|
+
"""Payout for 5-minute expiry."""
|
|
69
|
+
profit = self._data.get("profit")
|
|
70
|
+
if isinstance(profit, dict):
|
|
71
|
+
return _int_or_none(profit.get("5M"))
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def is_otc(self) -> bool:
|
|
76
|
+
"""True when the symbol carries the ``_otc`` suffix."""
|
|
77
|
+
return self.symbol.lower().endswith("_otc")
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_rows(cls, rows: list[dict[str, Any]]) -> list[Asset]:
|
|
81
|
+
"""Build a list of :class:`Asset` from the bare-array payload."""
|
|
82
|
+
return [cls(row) for row in rows if isinstance(row, dict)]
|
|
83
|
+
|
|
84
|
+
def __str__(self) -> str: # pragma: no cover - trivial
|
|
85
|
+
return self.symbol
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _int_or_none(value: Any) -> int | None:
|
|
89
|
+
if value is None:
|
|
90
|
+
return None
|
|
91
|
+
try:
|
|
92
|
+
return int(value)
|
|
93
|
+
except (TypeError, ValueError):
|
|
94
|
+
return None
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Shared model plumbing: the :class:`APIObject` base and the SDK's enums."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any, TypeVar, cast
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"APIObject",
|
|
11
|
+
"TradeOutcome",
|
|
12
|
+
"coerce_enum",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
_JSONLike = dict[str, Any] | list[Any] | str | int | float | bool | None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class APIObject:
|
|
19
|
+
"""Dict-backed base class for every API model.
|
|
20
|
+
|
|
21
|
+
* Attribute access maps to payload keys; hyphens/spaces in keys are
|
|
22
|
+
normalised to underscores.
|
|
23
|
+
* Nested dicts convert lazily to :class:`APIObject`; nested lists convert
|
|
24
|
+
their dict members on access.
|
|
25
|
+
* Unknown attributes raise :class:`AttributeError` listing available keys.
|
|
26
|
+
* ``to_dict()`` round-trips to the original payload.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__slots__ = ("_data",)
|
|
30
|
+
|
|
31
|
+
_data: dict[str, Any]
|
|
32
|
+
|
|
33
|
+
def __init__(self, data: dict[str, Any]) -> None:
|
|
34
|
+
object.__setattr__(self, "_data", dict(data) if isinstance(data, dict) else {})
|
|
35
|
+
|
|
36
|
+
# -- data access ------------------------------------------------------
|
|
37
|
+
@property
|
|
38
|
+
def raw(self) -> dict[str, Any]:
|
|
39
|
+
"""The underlying payload dict (shallow copy)."""
|
|
40
|
+
return dict(self._data)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def data(self) -> dict[str, Any]:
|
|
44
|
+
"""The live underlying payload dict."""
|
|
45
|
+
return self._data
|
|
46
|
+
|
|
47
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
48
|
+
"""Return ``payload[key]`` or *default*, with lazy conversion applied."""
|
|
49
|
+
value = self._data.get(key, default)
|
|
50
|
+
return _convert(value)
|
|
51
|
+
|
|
52
|
+
def keys(self) -> Iterator[str]:
|
|
53
|
+
return iter(self._data.keys())
|
|
54
|
+
|
|
55
|
+
def items(self) -> Iterator[tuple[str, Any]]:
|
|
56
|
+
for key in self._data:
|
|
57
|
+
yield key, self.get(key)
|
|
58
|
+
|
|
59
|
+
def __contains__(self, key: object) -> bool:
|
|
60
|
+
return key in self._data
|
|
61
|
+
|
|
62
|
+
def __iter__(self) -> Iterator[str]:
|
|
63
|
+
return iter(self._data)
|
|
64
|
+
|
|
65
|
+
def __len__(self) -> int:
|
|
66
|
+
return len(self._data)
|
|
67
|
+
|
|
68
|
+
def __getattr__(self, name: str) -> Any:
|
|
69
|
+
# Only called when normal attribute lookup fails.
|
|
70
|
+
data = object.__getattribute__(self, "_data")
|
|
71
|
+
if name.startswith("_"):
|
|
72
|
+
raise AttributeError(name)
|
|
73
|
+
if name in data:
|
|
74
|
+
return _convert(data[name])
|
|
75
|
+
normalized = {k.replace("-", "_").replace(" ", "_"): k for k in data}
|
|
76
|
+
if name in normalized:
|
|
77
|
+
return _convert(data[normalized[name]])
|
|
78
|
+
raise AttributeError(
|
|
79
|
+
"{} has no attribute {!r}. Available keys: {}".format(
|
|
80
|
+
type(self).__name__, name, ", ".join(sorted(data)) or "(none)"
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
85
|
+
if name.startswith("_"):
|
|
86
|
+
object.__setattr__(self, name, value)
|
|
87
|
+
else:
|
|
88
|
+
self._data[name] = value
|
|
89
|
+
|
|
90
|
+
def __eq__(self, other: object) -> bool:
|
|
91
|
+
if isinstance(other, APIObject):
|
|
92
|
+
return self._data == other._data
|
|
93
|
+
if isinstance(other, dict):
|
|
94
|
+
return self._data == other
|
|
95
|
+
return NotImplemented
|
|
96
|
+
|
|
97
|
+
def __hash__(self) -> int: # pragma: no cover - unhashable payloads
|
|
98
|
+
raise TypeError("APIObject instances are unhashable")
|
|
99
|
+
|
|
100
|
+
def __repr__(self) -> str:
|
|
101
|
+
label = type(self).__name__
|
|
102
|
+
keys = ", ".join(sorted(self._data)[:8])
|
|
103
|
+
more = ", …" if len(self._data) > 8 else ""
|
|
104
|
+
return f"<{label} {keys}{more}>"
|
|
105
|
+
|
|
106
|
+
def to_dict(self) -> dict[str, Any]:
|
|
107
|
+
"""Return a plain dict copy that round-trips to the original payload."""
|
|
108
|
+
return cast(dict[str, Any], _to_plain(self._data))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _convert(value: Any) -> Any:
|
|
112
|
+
"""Lazily convert nested dicts/lists into APIObject-friendly structures."""
|
|
113
|
+
if isinstance(value, dict):
|
|
114
|
+
return APIObject(value)
|
|
115
|
+
if isinstance(value, list):
|
|
116
|
+
return [_convert(item) for item in value]
|
|
117
|
+
return value
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _to_plain(value: Any) -> Any:
|
|
121
|
+
if isinstance(value, dict):
|
|
122
|
+
return {k: _to_plain(v) for k, v in value.items()}
|
|
123
|
+
if isinstance(value, list):
|
|
124
|
+
return [_to_plain(v) for v in value]
|
|
125
|
+
if isinstance(value, APIObject):
|
|
126
|
+
return _to_plain(value._data)
|
|
127
|
+
return value
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
# Enums
|
|
132
|
+
# ---------------------------------------------------------------------------
|
|
133
|
+
_EnumType = TypeVar("_EnumType", bound="_StrEnum")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def coerce_enum(
|
|
137
|
+
enum_cls: type[_EnumType], value: Any, default: _EnumType | None = None
|
|
138
|
+
) -> _EnumType | None:
|
|
139
|
+
"""Coerce *value* to *enum_cls* with tolerant matching, else *default*."""
|
|
140
|
+
if isinstance(value, enum_cls):
|
|
141
|
+
return value
|
|
142
|
+
if value is None:
|
|
143
|
+
return default
|
|
144
|
+
text = str(value)
|
|
145
|
+
for member in enum_cls:
|
|
146
|
+
if text == member.value:
|
|
147
|
+
return member
|
|
148
|
+
if text.upper().replace("-", "_").replace(" ", "_") == member.name:
|
|
149
|
+
return member
|
|
150
|
+
return default
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class _StrEnum(str, Enum):
|
|
154
|
+
"""String enum with a friendly label and tolerant coercion."""
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def coerce(cls, value: Any, default: Any = None) -> Any:
|
|
158
|
+
"""Tolerant coercion; ``None`` passes through unchanged."""
|
|
159
|
+
return coerce_enum(cls, value, default)
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def label(self) -> str:
|
|
163
|
+
"""Human-readable label, e.g. ``'CALL / BUY'`` for ``TradeSetup`` sides."""
|
|
164
|
+
return str(self.value).replace("_", " ").title()
|
|
165
|
+
|
|
166
|
+
def __str__(self) -> str: # pragma: no cover - trivial
|
|
167
|
+
return str(self.value)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class TradeOutcome(_StrEnum):
|
|
171
|
+
"""Outcome values returned by /qx_result."""
|
|
172
|
+
|
|
173
|
+
WIN = "win"
|
|
174
|
+
WIN_1 = "win1"
|
|
175
|
+
WIN_2 = "win2"
|
|
176
|
+
REFUND = "refund"
|
|
177
|
+
LOSE = "lose"
|
|
178
|
+
PENDING = "pending"
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def won(self) -> bool:
|
|
182
|
+
return self in (TradeOutcome.WIN, TradeOutcome.WIN_1, TradeOutcome.WIN_2)
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def lost(self) -> bool:
|
|
186
|
+
return self is TradeOutcome.LOSE
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def is_pending(self) -> bool:
|
|
190
|
+
return self is TradeOutcome.PENDING
|