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
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""alltradingapi — Python SDK for the All Trading API.
|
|
2
|
+
|
|
3
|
+
Independent, unofficial API provider. Not affiliated with, endorsed by, or
|
|
4
|
+
connected to Quotex. This SDK provides market data only; it cannot place
|
|
5
|
+
trades and is not financial advice.
|
|
6
|
+
|
|
7
|
+
Quick start::
|
|
8
|
+
|
|
9
|
+
from alltradingapi import Client
|
|
10
|
+
|
|
11
|
+
with Client(api_key="ap_...") as ata:
|
|
12
|
+
candles = ata.candles("EURUSD_otc")
|
|
13
|
+
print(candles[-1].close)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
from .async_client import AsyncClient
|
|
18
|
+
from .client import ApiKey, Client
|
|
19
|
+
from .errors import (
|
|
20
|
+
ALLError,
|
|
21
|
+
AuthenticationError,
|
|
22
|
+
ConfigurationError,
|
|
23
|
+
NotFoundError,
|
|
24
|
+
PermissionDeniedError,
|
|
25
|
+
RateLimitError,
|
|
26
|
+
ServerError,
|
|
27
|
+
TimeoutError_,
|
|
28
|
+
TransportError,
|
|
29
|
+
UpdateCheckError,
|
|
30
|
+
UpdateRequiredError,
|
|
31
|
+
UpstreamError,
|
|
32
|
+
ValidationError,
|
|
33
|
+
)
|
|
34
|
+
from .logging_ import logger, set_log_level
|
|
35
|
+
from .models import (
|
|
36
|
+
APIObject,
|
|
37
|
+
Asset,
|
|
38
|
+
Candle,
|
|
39
|
+
SavedCandles,
|
|
40
|
+
TradeOutcome,
|
|
41
|
+
TradeResult,
|
|
42
|
+
)
|
|
43
|
+
from .update import UpdateInfo, UpdatePolicy
|
|
44
|
+
from .utils import is_valid_asset as validate_asset # noqa: F401
|
|
45
|
+
from .utils import redact_url # noqa: F401
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
# clients
|
|
49
|
+
"Client",
|
|
50
|
+
"AsyncClient",
|
|
51
|
+
"ApiKey",
|
|
52
|
+
# models
|
|
53
|
+
"APIObject",
|
|
54
|
+
"Asset",
|
|
55
|
+
"Candle",
|
|
56
|
+
"SavedCandles",
|
|
57
|
+
"TradeResult",
|
|
58
|
+
"TradeOutcome",
|
|
59
|
+
"UpdatePolicy",
|
|
60
|
+
"UpdateInfo",
|
|
61
|
+
# errors
|
|
62
|
+
"ALLError",
|
|
63
|
+
"ConfigurationError",
|
|
64
|
+
"AuthenticationError",
|
|
65
|
+
"PermissionDeniedError",
|
|
66
|
+
"NotFoundError",
|
|
67
|
+
"ValidationError",
|
|
68
|
+
"RateLimitError",
|
|
69
|
+
"ServerError",
|
|
70
|
+
"UpstreamError",
|
|
71
|
+
"TransportError",
|
|
72
|
+
"TimeoutError_",
|
|
73
|
+
"UpdateRequiredError",
|
|
74
|
+
"UpdateCheckError",
|
|
75
|
+
# utilities
|
|
76
|
+
"set_log_level",
|
|
77
|
+
"logger",
|
|
78
|
+
"validate_asset",
|
|
79
|
+
"redact_url",
|
|
80
|
+
"__version__",
|
|
81
|
+
]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Async client — same six endpoints as :class:`Client`, loop-offloaded.
|
|
2
|
+
|
|
3
|
+
Implementation: a bounded :class:`~concurrent.futures.ThreadPoolExecutor`
|
|
4
|
+
around the same sync transport, so there is exactly one HTTP code path to
|
|
5
|
+
audit and the event loop is never blocked.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import os
|
|
12
|
+
from collections.abc import Iterable, Mapping
|
|
13
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
14
|
+
from typing import Any, cast
|
|
15
|
+
|
|
16
|
+
from . import config as _config
|
|
17
|
+
from ._version import __version__
|
|
18
|
+
from .client import Client, ImageLike # noqa: F401 - re-exported type
|
|
19
|
+
from .models import Asset, Candle, SavedCandles, TradeResult
|
|
20
|
+
|
|
21
|
+
__all__ = ["AsyncClient"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AsyncClient:
|
|
25
|
+
"""Async SDK client wrapping :class:`~alltradingapi.client.Client`.
|
|
26
|
+
|
|
27
|
+
Example::
|
|
28
|
+
|
|
29
|
+
from alltradingapi import AsyncClient
|
|
30
|
+
|
|
31
|
+
async with AsyncClient(api_key="ap_...") as ata:
|
|
32
|
+
assets = await ata.assets(only_open=True)
|
|
33
|
+
candles = await ata.candles("EURUSD_otc")
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
api_key: str | None = None,
|
|
39
|
+
*,
|
|
40
|
+
keys: Mapping[str, str] | None = None,
|
|
41
|
+
max_concurrency: int = 8,
|
|
42
|
+
run_update_gate: bool = True,
|
|
43
|
+
**client_kwargs: Any,
|
|
44
|
+
) -> None:
|
|
45
|
+
self._sync = Client(
|
|
46
|
+
api_key=api_key,
|
|
47
|
+
keys=keys,
|
|
48
|
+
run_update_gate=run_update_gate,
|
|
49
|
+
**client_kwargs,
|
|
50
|
+
)
|
|
51
|
+
self._max_concurrency = max(1, int(max_concurrency))
|
|
52
|
+
self._executor: ThreadPoolExecutor | None = None
|
|
53
|
+
|
|
54
|
+
# -- lifecycle ---------------------------------------------------------
|
|
55
|
+
@classmethod
|
|
56
|
+
def from_env(cls, **kwargs: Any) -> AsyncClient:
|
|
57
|
+
"""Build from environment configuration, mirroring ``Client.from_env``."""
|
|
58
|
+
kwargs.setdefault("api_key", os.environ.get(_config.ENV_API_KEY) or None)
|
|
59
|
+
return cls(**kwargs)
|
|
60
|
+
|
|
61
|
+
def _get_executor(self) -> ThreadPoolExecutor:
|
|
62
|
+
if self._executor is None:
|
|
63
|
+
self._executor = ThreadPoolExecutor(
|
|
64
|
+
max_workers=self._max_concurrency,
|
|
65
|
+
thread_name_prefix="alltradingapi",
|
|
66
|
+
)
|
|
67
|
+
return self._executor
|
|
68
|
+
|
|
69
|
+
async def _run(self, method_name: str, *args: Any, **kwargs: Any) -> Any:
|
|
70
|
+
loop = asyncio.get_event_loop()
|
|
71
|
+
method = getattr(self._sync, method_name)
|
|
72
|
+
return await loop.run_in_executor(
|
|
73
|
+
self._get_executor(),
|
|
74
|
+
lambda: method(*args, **kwargs),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
async def __aenter__(self) -> AsyncClient:
|
|
78
|
+
return self
|
|
79
|
+
|
|
80
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
81
|
+
await self.close()
|
|
82
|
+
|
|
83
|
+
async def close(self) -> None:
|
|
84
|
+
"""Shut the executor down and release pooled connections."""
|
|
85
|
+
if self._executor is not None:
|
|
86
|
+
executor = self._executor
|
|
87
|
+
self._executor = None
|
|
88
|
+
await asyncio.get_event_loop().run_in_executor(None, executor.shutdown)
|
|
89
|
+
self._sync.close()
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def version(self) -> str:
|
|
93
|
+
"""Installed SDK version string."""
|
|
94
|
+
return __version__
|
|
95
|
+
|
|
96
|
+
def check_updates(self, force: bool = False) -> Any:
|
|
97
|
+
"""Sync passthrough to :meth:`Client.check_updates` (network-light)."""
|
|
98
|
+
return self._sync.check_updates(force=force)
|
|
99
|
+
|
|
100
|
+
def on_update_available(self, callback: Any) -> None:
|
|
101
|
+
"""Register the update-available hook on the underlying client."""
|
|
102
|
+
self._sync.on_update_available(callback)
|
|
103
|
+
|
|
104
|
+
def clear_cache(self) -> None:
|
|
105
|
+
"""Drop cached metadata responses."""
|
|
106
|
+
self._sync.clear_cache()
|
|
107
|
+
|
|
108
|
+
# -- endpoint surface ---------------------------------------------------
|
|
109
|
+
async def assets(
|
|
110
|
+
self,
|
|
111
|
+
*,
|
|
112
|
+
only_open: bool = False,
|
|
113
|
+
refresh: bool = False,
|
|
114
|
+
account: int | None = None,
|
|
115
|
+
api_key: str | None = None,
|
|
116
|
+
) -> list[Asset]:
|
|
117
|
+
"""List assets (see :meth:`Client.assets`)."""
|
|
118
|
+
return list(
|
|
119
|
+
await self._run(
|
|
120
|
+
"assets",
|
|
121
|
+
only_open=only_open,
|
|
122
|
+
refresh=refresh,
|
|
123
|
+
account=account,
|
|
124
|
+
api_key=api_key,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
async def candles(self, asset: str, **kwargs: Any) -> list[Candle]:
|
|
129
|
+
"""Fetch candles (see :meth:`Client.candles`)."""
|
|
130
|
+
return list(await self._run("candles", asset, **kwargs))
|
|
131
|
+
|
|
132
|
+
async def history(self, asset: str, **kwargs: Any) -> list[Candle]:
|
|
133
|
+
"""Fetch candle history (see :meth:`Client.history`)."""
|
|
134
|
+
return list(await self._run("history", asset, **kwargs))
|
|
135
|
+
|
|
136
|
+
async def saved(self, asset: str, **kwargs: Any) -> SavedCandles:
|
|
137
|
+
"""Fetch saved candles (see :meth:`Client.saved`)."""
|
|
138
|
+
return cast(SavedCandles, await self._run("saved", asset, **kwargs))
|
|
139
|
+
|
|
140
|
+
async def screenshot(self, asset: str, **kwargs: Any) -> bytes:
|
|
141
|
+
"""Download a chart screenshot (see :meth:`Client.screenshot`)."""
|
|
142
|
+
return cast(bytes, await self._run("screenshot", asset, **kwargs))
|
|
143
|
+
|
|
144
|
+
async def result(self, asset: str, **kwargs: Any) -> TradeResult:
|
|
145
|
+
"""Check a trade result (see :meth:`Client.result`)."""
|
|
146
|
+
return cast(TradeResult, await self._run("result", asset, **kwargs))
|
|
147
|
+
|
|
148
|
+
# -- fan-out -------------------------------------------------------------
|
|
149
|
+
async def scan(
|
|
150
|
+
self,
|
|
151
|
+
assets: Iterable[str],
|
|
152
|
+
*,
|
|
153
|
+
concurrency: int | None = None,
|
|
154
|
+
**kwargs: Any,
|
|
155
|
+
) -> dict[str, Any]:
|
|
156
|
+
"""Fetch candles for many assets concurrently; per-asset failures
|
|
157
|
+
never abort. Returns ``{asset: List[Candle] | Exception}``.
|
|
158
|
+
"""
|
|
159
|
+
symbols: list[str] = list(assets)
|
|
160
|
+
limit = min(self._max_concurrency, concurrency or self._max_concurrency)
|
|
161
|
+
semaphore = asyncio.Semaphore(max(1, limit))
|
|
162
|
+
results: dict[str, Any] = {}
|
|
163
|
+
|
|
164
|
+
async def _one(symbol: str) -> tuple[str, Any]:
|
|
165
|
+
async with semaphore:
|
|
166
|
+
try:
|
|
167
|
+
return symbol, await self._run("candles", symbol, **kwargs)
|
|
168
|
+
except Exception as exc: # surfaced per asset, never raised
|
|
169
|
+
return symbol, exc
|
|
170
|
+
|
|
171
|
+
done = await asyncio.gather(*(_one(s) for s in symbols))
|
|
172
|
+
for symbol, value in done:
|
|
173
|
+
results[symbol] = value
|
|
174
|
+
return results
|
alltradingapi/cache.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Thread-safe in-memory TTL cache.
|
|
2
|
+
|
|
3
|
+
Used only for the cheap, slow-changing metadata endpoints (``assets()``,
|
|
4
|
+
``timeframes()``) by default. Analysis/candles are never cached client-side.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Hashable
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
__all__ = ["TTLCache"]
|
|
15
|
+
|
|
16
|
+
_Entry = tuple[float, Any] # (expires_at, value)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TTLCache:
|
|
20
|
+
"""A tiny, thread-safe TTL cache keyed by any hashable tuple."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, ttl: float = 60.0, maxsize: int = 128) -> None:
|
|
23
|
+
self._ttl = max(0.0, float(ttl))
|
|
24
|
+
self._maxsize = max(1, int(maxsize))
|
|
25
|
+
self._store: dict[Hashable, _Entry] = {}
|
|
26
|
+
self._lock = threading.Lock()
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def ttl(self) -> float:
|
|
30
|
+
"""Configured time-to-live in seconds."""
|
|
31
|
+
return self._ttl
|
|
32
|
+
|
|
33
|
+
def get(self, key: Hashable) -> Any | None:
|
|
34
|
+
"""Return the cached value, or ``None`` when missing/expired."""
|
|
35
|
+
now = time.monotonic()
|
|
36
|
+
with self._lock:
|
|
37
|
+
entry = self._store.get(key)
|
|
38
|
+
if entry is None:
|
|
39
|
+
return None
|
|
40
|
+
expires_at, value = entry
|
|
41
|
+
if expires_at <= now:
|
|
42
|
+
del self._store[key]
|
|
43
|
+
return None
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
def put(self, key: Hashable, value: Any) -> None:
|
|
47
|
+
"""Store *value* under *key* for the configured TTL."""
|
|
48
|
+
if self._ttl <= 0:
|
|
49
|
+
return
|
|
50
|
+
now = time.monotonic()
|
|
51
|
+
with self._lock:
|
|
52
|
+
if len(self._store) >= self._maxsize and key not in self._store:
|
|
53
|
+
self._evict_oldest_locked()
|
|
54
|
+
self._store[key] = (now + self._ttl, value)
|
|
55
|
+
|
|
56
|
+
def clear(self) -> None:
|
|
57
|
+
"""Drop every entry."""
|
|
58
|
+
with self._lock:
|
|
59
|
+
self._store.clear()
|
|
60
|
+
|
|
61
|
+
def __len__(self) -> int:
|
|
62
|
+
with self._lock:
|
|
63
|
+
return len(self._store)
|
|
64
|
+
|
|
65
|
+
def _evict_oldest_locked(self) -> None:
|
|
66
|
+
if not self._store:
|
|
67
|
+
return
|
|
68
|
+
oldest_key = None
|
|
69
|
+
oldest_expiry = float("inf")
|
|
70
|
+
for k, (expires_at, _value) in self._store.items():
|
|
71
|
+
if expires_at < oldest_expiry:
|
|
72
|
+
oldest_expiry = expires_at
|
|
73
|
+
oldest_key = k
|
|
74
|
+
if oldest_key is not None:
|
|
75
|
+
del self._store[oldest_key]
|