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/client.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""The synchronous :class:`Client` — typed access to the six v1 endpoints.
|
|
2
|
+
|
|
3
|
+
Endpoints covered:
|
|
4
|
+
|
|
5
|
+
* ``assets()`` -> ``/qx_assets`` (asset data)
|
|
6
|
+
* ``candles()`` -> ``/qx_candles`` (current candles)
|
|
7
|
+
* ``history()`` -> ``/qx_history`` (candle history)
|
|
8
|
+
* ``saved()`` -> ``/qx_saved`` (saved candles)
|
|
9
|
+
* ``screenshot()`` -> ``/qx_ss_pro_v2`` (chart image, PNG bytes)
|
|
10
|
+
* ``result()`` -> ``/qx_result`` (trade result check)
|
|
11
|
+
|
|
12
|
+
Key resolution order (first hit wins):
|
|
13
|
+
|
|
14
|
+
1. explicit per-call ``api_key``
|
|
15
|
+
2. ``keys[product]`` (product id such as ``"quotex-quotes"``)
|
|
16
|
+
3. ``keys["default"]``
|
|
17
|
+
4. constructor ``api_key``
|
|
18
|
+
5. environment ``ATA_API_KEY``
|
|
19
|
+
6. environment ``ATA_KEY_<PRODUCT_UPPER_SNAKE>`` (e.g. ``ATA_KEY_QUOTEX_QUOTES``)
|
|
20
|
+
|
|
21
|
+
If nothing resolves, calls raise :class:`AuthenticationError` with an
|
|
22
|
+
actionable message — never a bare ``KeyError``.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import logging
|
|
28
|
+
import os
|
|
29
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
30
|
+
from typing import (
|
|
31
|
+
Any,
|
|
32
|
+
Union,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
from . import config as _config
|
|
36
|
+
from . import update as _update
|
|
37
|
+
from ._version import __version__
|
|
38
|
+
from .cache import TTLCache
|
|
39
|
+
from .errors import ALLError, AuthenticationError, ConfigurationError
|
|
40
|
+
from .logging_ import logger
|
|
41
|
+
from .models import Asset, Candle, SavedCandles, TradeResult
|
|
42
|
+
from .params import validate_params
|
|
43
|
+
from .transport import Response, Transport
|
|
44
|
+
from .utils import redact_url
|
|
45
|
+
|
|
46
|
+
__all__ = ["Client", "ApiKey"]
|
|
47
|
+
|
|
48
|
+
# Public alias: an API key is just a string (``ap_`` + 32 hex chars).
|
|
49
|
+
ApiKey = str
|
|
50
|
+
|
|
51
|
+
ImageLike = Union[bytes, str, "os.PathLike[str]"]
|
|
52
|
+
|
|
53
|
+
_ROUTES: dict[str, str] = {
|
|
54
|
+
"assets": "/qx_assets",
|
|
55
|
+
"candles": "/qx_candles",
|
|
56
|
+
"history": "/qx_history",
|
|
57
|
+
"saved": "/qx_saved",
|
|
58
|
+
"screenshot": "/qx_ss_pro_v2",
|
|
59
|
+
"result": "/qx_result",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
# Which product id (and therefore which key) each call needs.
|
|
63
|
+
_PRODUCTS: dict[str, str] = {
|
|
64
|
+
"assets": "quotex-assets",
|
|
65
|
+
"candles": "quotex-quotes",
|
|
66
|
+
"history": "quotex-realtime",
|
|
67
|
+
"saved": "quotex-saved",
|
|
68
|
+
"screenshot": "quotex-screenshots",
|
|
69
|
+
"result": "quotex-results",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Client:
|
|
74
|
+
"""Synchronous SDK client for the All Trading API.
|
|
75
|
+
|
|
76
|
+
Example::
|
|
77
|
+
|
|
78
|
+
from alltradingapi import Client
|
|
79
|
+
|
|
80
|
+
with Client(api_key="ap_...") as ata:
|
|
81
|
+
candles = ata.candles("EURUSD_otc")
|
|
82
|
+
print(candles[-1].close)
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
api_key: str | None = None,
|
|
88
|
+
*,
|
|
89
|
+
keys: Mapping[str, str] | None = None,
|
|
90
|
+
base_url: str = _config.BASE_URL,
|
|
91
|
+
timeout: float = _config.DEFAULT_TIMEOUT,
|
|
92
|
+
connect_timeout: float = _config.DEFAULT_CONNECT_TIMEOUT,
|
|
93
|
+
max_retries: int = _config.DEFAULT_MAX_RETRIES,
|
|
94
|
+
backoff_factor: float = _config.DEFAULT_BACKOFF_FACTOR,
|
|
95
|
+
retry_statuses: Sequence[int] = _config.DEFAULT_RETRY_STATUSES,
|
|
96
|
+
user_agent: str | None = None,
|
|
97
|
+
auth_mode: str = _config.DEFAULT_AUTH_MODE,
|
|
98
|
+
cache_ttl: float = _config.DEFAULT_CACHE_TTL,
|
|
99
|
+
update_policy: Any | None = None,
|
|
100
|
+
allow_outdated: bool = False,
|
|
101
|
+
interactive: bool | None = None,
|
|
102
|
+
verify: bool = True,
|
|
103
|
+
logger: logging.Logger | None = None, # noqa: A002 - spec parity
|
|
104
|
+
transport: Transport | None = None,
|
|
105
|
+
run_update_gate: bool = True,
|
|
106
|
+
) -> None:
|
|
107
|
+
if auth_mode not in ("bearer", "query"):
|
|
108
|
+
raise ConfigurationError(
|
|
109
|
+
"auth_mode must be 'bearer' (recommended: keeps keys out of "
|
|
110
|
+
"URLs and logs) or 'query'."
|
|
111
|
+
)
|
|
112
|
+
self._keys: dict[str, str] = {}
|
|
113
|
+
if keys:
|
|
114
|
+
for product, key in keys.items():
|
|
115
|
+
if not key:
|
|
116
|
+
continue
|
|
117
|
+
self._keys[str(product)] = str(key)
|
|
118
|
+
if api_key:
|
|
119
|
+
self._keys["__constructor__"] = api_key
|
|
120
|
+
self._auth_mode = auth_mode
|
|
121
|
+
self._cache_ttl = float(cache_ttl)
|
|
122
|
+
self._cache = TTLCache(ttl=self._cache_ttl)
|
|
123
|
+
self._update_policy = update_policy
|
|
124
|
+
self._allow_outdated = allow_outdated
|
|
125
|
+
self._interactive = interactive
|
|
126
|
+
self._logger = logger or logging.getLogger("alltradingapi")
|
|
127
|
+
self._update_hooks: list[Callable[[Any], None]] = []
|
|
128
|
+
self._closed = False
|
|
129
|
+
|
|
130
|
+
self._transport = transport or Transport(
|
|
131
|
+
base_url=base_url,
|
|
132
|
+
connect_timeout=connect_timeout,
|
|
133
|
+
max_retries=max_retries,
|
|
134
|
+
backoff_factor=backoff_factor,
|
|
135
|
+
retry_statuses=retry_statuses,
|
|
136
|
+
verify=verify,
|
|
137
|
+
user_agent=user_agent,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
if run_update_gate:
|
|
141
|
+
self._run_update_gate()
|
|
142
|
+
|
|
143
|
+
# ------------------------------------------------------------------
|
|
144
|
+
# Lifecycle
|
|
145
|
+
# ------------------------------------------------------------------
|
|
146
|
+
@classmethod
|
|
147
|
+
def from_env(cls, **kwargs: Any) -> Client:
|
|
148
|
+
"""Build a client from environment configuration (ATA_* variables)."""
|
|
149
|
+
kwargs.setdefault("api_key", os.environ.get(_config.ENV_API_KEY) or None)
|
|
150
|
+
return cls(**kwargs)
|
|
151
|
+
|
|
152
|
+
def __enter__(self) -> Client:
|
|
153
|
+
return self
|
|
154
|
+
|
|
155
|
+
def __exit__(self, *exc: Any) -> None:
|
|
156
|
+
self.close()
|
|
157
|
+
|
|
158
|
+
def close(self) -> None:
|
|
159
|
+
"""Release pooled connections. Safe to call multiple times."""
|
|
160
|
+
if not self._closed:
|
|
161
|
+
self._transport.close()
|
|
162
|
+
self._closed = True
|
|
163
|
+
|
|
164
|
+
# ------------------------------------------------------------------
|
|
165
|
+
# Update gate & info
|
|
166
|
+
# ------------------------------------------------------------------
|
|
167
|
+
def _run_update_gate(self) -> None:
|
|
168
|
+
try:
|
|
169
|
+
info = _update.ensure_usable(
|
|
170
|
+
self.version,
|
|
171
|
+
policy=self._update_policy,
|
|
172
|
+
allow_outdated=self._allow_outdated,
|
|
173
|
+
interactive=self._interactive,
|
|
174
|
+
installer=None,
|
|
175
|
+
)
|
|
176
|
+
except ALLError:
|
|
177
|
+
raise
|
|
178
|
+
except Exception as exc: # fail-open: the gate must never crash the SDK
|
|
179
|
+
logger.debug("update gate skipped: %s", exc)
|
|
180
|
+
return
|
|
181
|
+
if info is not None and info.is_outdated:
|
|
182
|
+
for hook in self._update_hooks:
|
|
183
|
+
try:
|
|
184
|
+
hook(info)
|
|
185
|
+
except Exception: # pragma: no cover - user callback errors
|
|
186
|
+
logger.debug("update hook raised", exc_info=True)
|
|
187
|
+
|
|
188
|
+
def on_update_available(self, callback: Callable[[Any], None]) -> None:
|
|
189
|
+
"""Register a callback receiving :class:`~alltradingapi.update.UpdateInfo`."""
|
|
190
|
+
self._update_hooks.append(callback)
|
|
191
|
+
|
|
192
|
+
def check_updates(self, force: bool = False) -> Any:
|
|
193
|
+
"""Return :class:`~alltradingapi.update.UpdateInfo`; never raises for network issues."""
|
|
194
|
+
try:
|
|
195
|
+
return _update.check_for_update(force=force, installed=self.version)
|
|
196
|
+
except ALLError:
|
|
197
|
+
raise
|
|
198
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
199
|
+
logger.debug("update check failed: %s", exc)
|
|
200
|
+
return _update.UpdateInfo(
|
|
201
|
+
installed=self.version,
|
|
202
|
+
latest=None,
|
|
203
|
+
is_outdated=False,
|
|
204
|
+
checked_at=0.0,
|
|
205
|
+
source="error",
|
|
206
|
+
known=False,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def version(self) -> str:
|
|
211
|
+
"""Installed SDK version string."""
|
|
212
|
+
return __version__
|
|
213
|
+
|
|
214
|
+
# ------------------------------------------------------------------
|
|
215
|
+
# Key resolution
|
|
216
|
+
# ------------------------------------------------------------------
|
|
217
|
+
def _resolve_key(self, call: str, api_key: str | None) -> str:
|
|
218
|
+
if api_key:
|
|
219
|
+
return api_key
|
|
220
|
+
product = _PRODUCTS.get(call)
|
|
221
|
+
if product and product in self._keys:
|
|
222
|
+
return self._keys[product]
|
|
223
|
+
if "default" in self._keys:
|
|
224
|
+
return self._keys["default"]
|
|
225
|
+
if "__constructor__" in self._keys:
|
|
226
|
+
return self._keys["__constructor__"]
|
|
227
|
+
env_default = os.environ.get(_config.ENV_API_KEY)
|
|
228
|
+
if env_default:
|
|
229
|
+
return env_default
|
|
230
|
+
if product:
|
|
231
|
+
env_product = os.environ.get(_config.ENV_KEY_PREFIX + product.upper().replace("-", "_"))
|
|
232
|
+
if env_product:
|
|
233
|
+
return env_product
|
|
234
|
+
raise AuthenticationError(
|
|
235
|
+
"No API key available for '{}'. Pass api_key=..., build the client "
|
|
236
|
+
"with keys={{'{}': 'ap_...'}}, or set the environment variable "
|
|
237
|
+
"ATA_API_KEY (or ATA_KEY_{}). Each product needs its own key "
|
|
238
|
+
"from https://alltradingapi.com.".format(
|
|
239
|
+
call,
|
|
240
|
+
product or "default",
|
|
241
|
+
(product or "DEFAULT").upper().replace("-", "_"),
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def _request(
|
|
246
|
+
self,
|
|
247
|
+
call: str,
|
|
248
|
+
method: str = "GET",
|
|
249
|
+
params: list[tuple[str, str]] | None = None,
|
|
250
|
+
body: bytes | None = None,
|
|
251
|
+
headers: dict[str, str] | None = None,
|
|
252
|
+
api_key: str | None = None,
|
|
253
|
+
timeout: float | None = None,
|
|
254
|
+
) -> Response:
|
|
255
|
+
key = self._resolve_key(call, api_key)
|
|
256
|
+
auth_headers = dict(headers or {})
|
|
257
|
+
query: list[tuple[str, str]] = list(params or [])
|
|
258
|
+
if self._auth_mode == "bearer":
|
|
259
|
+
auth_headers["Authorization"] = "Bearer " + key
|
|
260
|
+
else:
|
|
261
|
+
query.append(("key", key))
|
|
262
|
+
path = _ROUTES[call]
|
|
263
|
+
return self._transport.request(
|
|
264
|
+
method,
|
|
265
|
+
path,
|
|
266
|
+
params=query,
|
|
267
|
+
body=body,
|
|
268
|
+
headers=auth_headers,
|
|
269
|
+
timeout=timeout,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
def _cached_json(self, cache_key: tuple[Any, ...], call: str, **kw: Any) -> Any:
|
|
273
|
+
if not kw.get("refresh"):
|
|
274
|
+
hit = self._cache.get(cache_key)
|
|
275
|
+
if hit is not None:
|
|
276
|
+
return hit
|
|
277
|
+
response = self._request(call, **{k: v for k, v in kw.items() if k != "refresh"})
|
|
278
|
+
payload = response.json()
|
|
279
|
+
self._cache.put(cache_key, payload)
|
|
280
|
+
return payload
|
|
281
|
+
|
|
282
|
+
def clear_cache(self) -> None:
|
|
283
|
+
"""Drop all client-side cached responses."""
|
|
284
|
+
self._cache.clear()
|
|
285
|
+
|
|
286
|
+
# ------------------------------------------------------------------
|
|
287
|
+
# Asset data
|
|
288
|
+
# ------------------------------------------------------------------
|
|
289
|
+
def assets(
|
|
290
|
+
self,
|
|
291
|
+
*,
|
|
292
|
+
only_open: bool = False,
|
|
293
|
+
refresh: bool = False,
|
|
294
|
+
account: int | None = None,
|
|
295
|
+
api_key: str | None = None,
|
|
296
|
+
) -> list[Asset]:
|
|
297
|
+
"""List every tradable asset with open/closed state and payouts.
|
|
298
|
+
|
|
299
|
+
Args:
|
|
300
|
+
only_open: Return only assets currently open for trading.
|
|
301
|
+
refresh: Bypass the client-side TTL cache.
|
|
302
|
+
account: Optional account selector (server-defined values).
|
|
303
|
+
"""
|
|
304
|
+
params = validate_params("assets", account=account)
|
|
305
|
+
key = ("assets", tuple(params), bool(refresh), self._auth_mode)
|
|
306
|
+
payload = self._cached_json(key, "assets", params=params, api_key=api_key, refresh=refresh)
|
|
307
|
+
rows = payload if isinstance(payload, list) else []
|
|
308
|
+
assets = Asset.from_rows(rows)
|
|
309
|
+
if only_open:
|
|
310
|
+
assets = [a for a in assets if a.is_open]
|
|
311
|
+
return assets
|
|
312
|
+
|
|
313
|
+
# ------------------------------------------------------------------
|
|
314
|
+
# Candles
|
|
315
|
+
# ------------------------------------------------------------------
|
|
316
|
+
def candles(
|
|
317
|
+
self,
|
|
318
|
+
asset: str,
|
|
319
|
+
*,
|
|
320
|
+
hours: int | None = None,
|
|
321
|
+
timeframe: str | None = None,
|
|
322
|
+
timezone: str | None = None, # noqa: A002 - server parameter name
|
|
323
|
+
offset: int | None = None,
|
|
324
|
+
timestamp: int | None = None,
|
|
325
|
+
period: int | None = None,
|
|
326
|
+
account: int | None = None,
|
|
327
|
+
timeout: int | None = None,
|
|
328
|
+
verbose_logging: bool | None = None,
|
|
329
|
+
api_key: str | None = None,
|
|
330
|
+
) -> list[Candle]:
|
|
331
|
+
"""Fetch recent candles for *asset* (default ~2h of 1m bars).
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
asset: Symbol such as ``EURUSD_otc``.
|
|
335
|
+
hours: 1..24 hours of history (server default 2).
|
|
336
|
+
timeframe: One of 5s..4h (server default 1m).
|
|
337
|
+
timezone: e.g. ``-3``, ``UTC``, ``Asia/Dhaka`` (default Asia/Dhaka).
|
|
338
|
+
"""
|
|
339
|
+
return self._candles(
|
|
340
|
+
"candles",
|
|
341
|
+
asset,
|
|
342
|
+
hours=hours,
|
|
343
|
+
timeframe=timeframe,
|
|
344
|
+
timezone=timezone,
|
|
345
|
+
offset=offset,
|
|
346
|
+
timestamp=timestamp,
|
|
347
|
+
period=period,
|
|
348
|
+
account=account,
|
|
349
|
+
timeout=timeout,
|
|
350
|
+
verbose_logging=verbose_logging,
|
|
351
|
+
api_key=api_key,
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
def history(
|
|
355
|
+
self,
|
|
356
|
+
asset: str,
|
|
357
|
+
*,
|
|
358
|
+
hours: int | None = None,
|
|
359
|
+
timeframe: str | None = None,
|
|
360
|
+
timezone: str | None = None, # noqa: A002
|
|
361
|
+
offset: int | None = None,
|
|
362
|
+
timestamp: int | None = None,
|
|
363
|
+
period: int | None = None,
|
|
364
|
+
account: int | None = None,
|
|
365
|
+
timeout: int | None = None,
|
|
366
|
+
verbose_logging: bool | None = None,
|
|
367
|
+
api_key: str | None = None,
|
|
368
|
+
) -> list[Candle]:
|
|
369
|
+
"""Fetch candle history for *asset* (same parameters as candles)."""
|
|
370
|
+
return self._candles(
|
|
371
|
+
"history",
|
|
372
|
+
asset,
|
|
373
|
+
hours=hours,
|
|
374
|
+
timeframe=timeframe,
|
|
375
|
+
timezone=timezone,
|
|
376
|
+
offset=offset,
|
|
377
|
+
timestamp=timestamp,
|
|
378
|
+
period=period,
|
|
379
|
+
account=account,
|
|
380
|
+
timeout=timeout,
|
|
381
|
+
verbose_logging=verbose_logging,
|
|
382
|
+
api_key=api_key,
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
def _candles(self, call: str, asset: str, **kw: Any) -> list[Candle]:
|
|
386
|
+
params = validate_params(
|
|
387
|
+
call,
|
|
388
|
+
asset=asset,
|
|
389
|
+
**{k: v for k, v in kw.items() if k != "api_key"},
|
|
390
|
+
)
|
|
391
|
+
response = self._request(
|
|
392
|
+
call,
|
|
393
|
+
params=params,
|
|
394
|
+
api_key=kw.get("api_key"),
|
|
395
|
+
timeout=_effective_timeout(kw.get("timeout")),
|
|
396
|
+
)
|
|
397
|
+
rows = response.json()
|
|
398
|
+
return Candle.from_rows(rows if isinstance(rows, list) else [])
|
|
399
|
+
|
|
400
|
+
def saved(
|
|
401
|
+
self,
|
|
402
|
+
asset: str,
|
|
403
|
+
*,
|
|
404
|
+
timeframe: str | None = None,
|
|
405
|
+
count: int | None = None,
|
|
406
|
+
timezone: str | None = None, # noqa: A002
|
|
407
|
+
raw: bool | None = None,
|
|
408
|
+
nocache: bool = False,
|
|
409
|
+
api_key: str | None = None,
|
|
410
|
+
) -> SavedCandles:
|
|
411
|
+
"""Fetch server-side saved candles (scanned from the 5s archive)."""
|
|
412
|
+
params = validate_params(
|
|
413
|
+
"saved",
|
|
414
|
+
asset=asset,
|
|
415
|
+
timeframe=timeframe,
|
|
416
|
+
timezone=timezone,
|
|
417
|
+
count=count,
|
|
418
|
+
raw=raw,
|
|
419
|
+
nocache=nocache,
|
|
420
|
+
)
|
|
421
|
+
response = self._request("saved", params=params, api_key=api_key)
|
|
422
|
+
return SavedCandles.from_payload(response.json())
|
|
423
|
+
|
|
424
|
+
def screenshot(
|
|
425
|
+
self,
|
|
426
|
+
asset: str,
|
|
427
|
+
*,
|
|
428
|
+
timeframe: str | None = None,
|
|
429
|
+
timezone: str | None = None, # noqa: A002
|
|
430
|
+
time: str | None = None, # noqa: A002
|
|
431
|
+
result: str | None = None,
|
|
432
|
+
names: str | None = None,
|
|
433
|
+
api_key: str | None = None,
|
|
434
|
+
) -> bytes:
|
|
435
|
+
"""Download a chart screenshot (PNG bytes) for *asset*.
|
|
436
|
+
|
|
437
|
+
Returns raw PNG bytes; save with ``open(path, "wb")``.
|
|
438
|
+
"""
|
|
439
|
+
params = validate_params(
|
|
440
|
+
"screenshot",
|
|
441
|
+
asset=asset,
|
|
442
|
+
timeframe=timeframe,
|
|
443
|
+
timezone=timezone,
|
|
444
|
+
time=time,
|
|
445
|
+
result=result,
|
|
446
|
+
names=names,
|
|
447
|
+
)
|
|
448
|
+
response = self._request("screenshot", params=params, api_key=api_key)
|
|
449
|
+
if not response.content_type.startswith("image/"):
|
|
450
|
+
raise ALLError(
|
|
451
|
+
"Expected an image from /qx_ss_pro_v2 but got Content-Type "
|
|
452
|
+
f"'{response.content_type}' (status {response.status}). The server may have returned an error; "
|
|
453
|
+
"check the asset/time parameter values.",
|
|
454
|
+
status=response.status,
|
|
455
|
+
url=redact_url(response.url),
|
|
456
|
+
)
|
|
457
|
+
return response.content
|
|
458
|
+
|
|
459
|
+
def result(
|
|
460
|
+
self,
|
|
461
|
+
asset: str,
|
|
462
|
+
*,
|
|
463
|
+
time: str, # noqa: A002 - server parameter name
|
|
464
|
+
direction: str,
|
|
465
|
+
timeframe: str | None = None,
|
|
466
|
+
timezone: str | None = None, # noqa: A002
|
|
467
|
+
mtg: int | None = None,
|
|
468
|
+
api_key: str | None = None,
|
|
469
|
+
) -> TradeResult:
|
|
470
|
+
"""Check a past trade entry (call/put at HH:MM) and its outcome(s)."""
|
|
471
|
+
params = validate_params(
|
|
472
|
+
"result",
|
|
473
|
+
asset=asset,
|
|
474
|
+
time=time,
|
|
475
|
+
direction=direction,
|
|
476
|
+
timeframe=timeframe,
|
|
477
|
+
timezone=timezone,
|
|
478
|
+
mtg=mtg,
|
|
479
|
+
)
|
|
480
|
+
response = self._request("result", params=params, api_key=api_key)
|
|
481
|
+
return TradeResult(response.json())
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
# ---------------------------------------------------------------------------
|
|
485
|
+
# Helpers
|
|
486
|
+
# ---------------------------------------------------------------------------
|
|
487
|
+
def _effective_timeout(param_timeout: int | None) -> float | None:
|
|
488
|
+
"""The server-side 'timeout' param hints at feed latency; pad for transport."""
|
|
489
|
+
if param_timeout is None:
|
|
490
|
+
return None
|
|
491
|
+
return float(param_timeout) + 5.0
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
__all__ += ["ImageLike"]
|
alltradingapi/config.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Package-wide constants and environment helpers.
|
|
2
|
+
|
|
3
|
+
Everything user-tunable lives here so tests and docs can point at one place.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
# ---------------------------------------------------------------------------
|
|
9
|
+
# Service coordinates
|
|
10
|
+
# ---------------------------------------------------------------------------
|
|
11
|
+
BASE_URL = "https://alltradingapi.com"
|
|
12
|
+
PYPI_JSON_URL = "https://pypi.org/pypi/alltradingapi/json"
|
|
13
|
+
PYPI_PACKAGE = "alltradingapi"
|
|
14
|
+
|
|
15
|
+
# ---------------------------------------------------------------------------
|
|
16
|
+
# Request behaviour
|
|
17
|
+
# ---------------------------------------------------------------------------
|
|
18
|
+
DEFAULT_TIMEOUT = 30.0 # read timeout, seconds
|
|
19
|
+
DEFAULT_CONNECT_TIMEOUT = 10.0 # connect timeout, seconds
|
|
20
|
+
DEFAULT_MAX_RETRIES = 2 # extra attempts after the first
|
|
21
|
+
DEFAULT_BACKOFF_FACTOR = 0.5 # seconds, exponential with full jitter
|
|
22
|
+
DEFAULT_RETRY_STATUSES = (429, 500, 502, 503, 504)
|
|
23
|
+
DEFAULT_USER_AGENT = "alltradingapi-python/1.0.0"
|
|
24
|
+
MAX_RESPONSE_BYTES = 32 * 1024 * 1024 # 32 MiB safety cap per response
|
|
25
|
+
DEFAULT_AUTH_MODE = "bearer" # "bearer" (preferred) or "query"
|
|
26
|
+
DEFAULT_CACHE_TTL = 60.0 # seconds; assets()/timeframes() only
|
|
27
|
+
CONNECTION_POOL_SIZE = 8 # idle keep-alive connections per host
|
|
28
|
+
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
# Update gate
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
UPDATE_CHECK_TIMEOUT = 2.0 # hard cap so the gate can never hang
|
|
33
|
+
UPDATE_CACHE_TTL = 6 * 3600 # 6 hours between live PyPI checks
|
|
34
|
+
UPDATE_CACHE_FILE = "alltradingapi/update.json"
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------------------
|
|
37
|
+
# Environment variables
|
|
38
|
+
# ---------------------------------------------------------------------------
|
|
39
|
+
ENV_API_KEY = "ATA_API_KEY"
|
|
40
|
+
ENV_KEY_PREFIX = "ATA_KEY_" # + PRODUCT.upper().replace("-", "_")
|
|
41
|
+
ENV_UPDATE_POLICY = "ATA_UPDATE_POLICY"
|
|
42
|
+
ENV_UPDATE_TTL = "ATA_UPDATE_TTL"
|
|
43
|
+
ENV_SKIP_UPDATE = "ATA_SKIP_UPDATE"
|
|
44
|
+
ENV_NO_PROMPT = "ATA_NO_PROMPT"
|
|
45
|
+
ENV_CI = "ATA_CI"
|
|
46
|
+
ENV_HTTP_PROXY = "ATA_HTTP_PROXY"
|
|
47
|
+
ENV_HTTPS_PROXY = "ATA_HTTPS_PROXY"
|
|
48
|
+
ENV_LIVE = "ATA_LIVE" # gates the optional live probe script
|
|
49
|
+
|
|
50
|
+
CI_ENV_VARS = ("CI", "GITHUB_ACTIONS")
|
|
51
|
+
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
# Products
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
PRODUCTS = (
|
|
56
|
+
"quotex-assets",
|
|
57
|
+
"quotex-quotes",
|
|
58
|
+
"quotex-realtime",
|
|
59
|
+
"quotex-saved",
|
|
60
|
+
"quotex-screenshots",
|
|
61
|
+
"quotex-results",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# Asset symbols are validated before any request is made.
|
|
65
|
+
ASSET_PATTERN = r"^[A-Za-z0-9_]{2,40}$"
|
|
66
|
+
|
|
67
|
+
TIMEFRAME_LABELS = (
|
|
68
|
+
"5s",
|
|
69
|
+
"10s",
|
|
70
|
+
"15s",
|
|
71
|
+
"30s",
|
|
72
|
+
"1m",
|
|
73
|
+
"2m",
|
|
74
|
+
"3m",
|
|
75
|
+
"5m",
|
|
76
|
+
"10m",
|
|
77
|
+
"15m",
|
|
78
|
+
"30m",
|
|
79
|
+
"1h",
|
|
80
|
+
"2h",
|
|
81
|
+
"4h",
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
TIMEFRAME_SECONDS = {
|
|
85
|
+
"5s": 5,
|
|
86
|
+
"10s": 10,
|
|
87
|
+
"15s": 15,
|
|
88
|
+
"30s": 30,
|
|
89
|
+
"1m": 60,
|
|
90
|
+
"2m": 120,
|
|
91
|
+
"3m": 180,
|
|
92
|
+
"5m": 300,
|
|
93
|
+
"10m": 600,
|
|
94
|
+
"15m": 900,
|
|
95
|
+
"30m": 1800,
|
|
96
|
+
"1h": 3600,
|
|
97
|
+
"2h": 7200,
|
|
98
|
+
"4h": 14400,
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def env(name: str, default: str = "") -> str:
|
|
103
|
+
"""Read an environment variable, returning *default* when unset/blank."""
|
|
104
|
+
value = os.environ.get(name)
|
|
105
|
+
if value is None or value == "":
|
|
106
|
+
return default
|
|
107
|
+
return value
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def env_bool(name: str, default: bool = False) -> bool:
|
|
111
|
+
"""Read a boolean-ish environment variable (1/true/yes/on)."""
|
|
112
|
+
raw = os.environ.get(name)
|
|
113
|
+
if raw is None or raw == "":
|
|
114
|
+
return default
|
|
115
|
+
return raw.strip().lower() in ("1", "true", "yes", "on")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def env_float(name: str, default: float) -> float:
|
|
119
|
+
"""Read a float environment variable, falling back on garbage."""
|
|
120
|
+
raw = os.environ.get(name)
|
|
121
|
+
if raw is None or raw == "":
|
|
122
|
+
return default
|
|
123
|
+
try:
|
|
124
|
+
return float(raw)
|
|
125
|
+
except ValueError:
|
|
126
|
+
return default
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def is_ci() -> bool:
|
|
130
|
+
"""True when running inside CI (ATA_CI, CI, GITHUB_ACTIONS)."""
|
|
131
|
+
if env_bool(ENV_CI):
|
|
132
|
+
return True
|
|
133
|
+
for name in CI_ENV_VARS:
|
|
134
|
+
value = os.environ.get(name, "")
|
|
135
|
+
if value and value.lower() not in ("0", "false", ""):
|
|
136
|
+
return True
|
|
137
|
+
return False
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def is_interactive() -> bool:
|
|
141
|
+
"""True when stdin is a TTY and we are not inside CI."""
|
|
142
|
+
import sys
|
|
143
|
+
|
|
144
|
+
if is_ci():
|
|
145
|
+
return False
|
|
146
|
+
if env_bool(ENV_NO_PROMPT):
|
|
147
|
+
return False
|
|
148
|
+
try:
|
|
149
|
+
return bool(sys.stdin.isatty())
|
|
150
|
+
except Exception: # pragma: no cover - exotic stdin wrappers
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def cache_dir() -> str:
|
|
155
|
+
"""Best-effort per-user cache directory (Windows %LOCALAPPDATA% first)."""
|
|
156
|
+
candidates = [
|
|
157
|
+
os.environ.get("LOCALAPPDATA"),
|
|
158
|
+
os.environ.get("APPDATA"),
|
|
159
|
+
os.environ.get("XDG_CACHE_HOME"),
|
|
160
|
+
os.path.join(os.path.expanduser("~"), ".cache"),
|
|
161
|
+
]
|
|
162
|
+
for path in candidates:
|
|
163
|
+
if path:
|
|
164
|
+
return path
|
|
165
|
+
import tempfile
|
|
166
|
+
|
|
167
|
+
return tempfile.gettempdir() # pragma: no cover - HOME-less systems
|