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.
@@ -0,0 +1,191 @@
1
+ """Candle models — OHLC bars from ``/qx_candles``, ``/qx_history``, ``/qx_saved``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Any
7
+
8
+ from .base import APIObject
9
+
10
+ __all__ = ["Candle", "SavedCandles"]
11
+
12
+ _DOJI_BODY_RATIO = 0.1 # body < 10% of full range counts as a doji
13
+
14
+
15
+ class Candle(APIObject):
16
+ """One OHLC bar with tick metadata and typed convenience helpers."""
17
+
18
+ __slots__ = ()
19
+
20
+ @property
21
+ def time(self) -> int:
22
+ """Bar open time as unix seconds."""
23
+ return int(self._data.get("time", 0) or 0)
24
+
25
+ @property
26
+ def open(self) -> float:
27
+ return float(self._data.get("open", 0.0) or 0.0)
28
+
29
+ @property
30
+ def high(self) -> float:
31
+ return float(self._data.get("high", 0.0) or 0.0)
32
+
33
+ @property
34
+ def low(self) -> float:
35
+ return float(self._data.get("low", 0.0) or 0.0)
36
+
37
+ @property
38
+ def close(self) -> float:
39
+ return float(self._data.get("close", 0.0) or 0.0)
40
+
41
+ @property
42
+ def ticks(self) -> int:
43
+ return int(self._data.get("ticks", 0) or 0)
44
+
45
+ @property
46
+ def last_tick(self) -> float:
47
+ """Unix timestamp (with fraction) of the last tick in the bar."""
48
+ return float(self._data.get("last_tick", 0.0) or 0.0)
49
+
50
+ @property
51
+ def asset(self) -> str:
52
+ return str(self._data.get("asset", "") or "")
53
+
54
+ @property
55
+ def asset_name(self) -> str:
56
+ return str(self._data.get("asset_name", "") or "")
57
+
58
+ @property
59
+ def time_read(self) -> str:
60
+ """Formatted bar time as the server rendered it."""
61
+ return str(self._data.get("time_read", "") or "")
62
+
63
+ # -- derived helpers ---------------------------------------------------
64
+ @property
65
+ def dt(self) -> datetime:
66
+ """Bar open time as a UTC-aware :class:`datetime`."""
67
+ return datetime.fromtimestamp(self.time, tz=timezone.utc)
68
+
69
+ @property
70
+ def direction(self) -> str:
71
+ """``"call"`` when bullish, ``"put"`` when bearish, else ``"neutral"``."""
72
+ if self.close > self.open:
73
+ return "call"
74
+ if self.close < self.open:
75
+ return "put"
76
+ return "neutral"
77
+
78
+ @property
79
+ def is_bullish(self) -> bool:
80
+ return self.close > self.open
81
+
82
+ @property
83
+ def body(self) -> float:
84
+ """Absolute open-to-close distance."""
85
+ return abs(self.close - self.open)
86
+
87
+ @property
88
+ def range(self) -> float: # noqa: A003 - mirrors the OHLC term
89
+ """High-to-low distance."""
90
+ return abs(self.high - self.low)
91
+
92
+ def is_doji(self, threshold: float = _DOJI_BODY_RATIO) -> bool:
93
+ """True when the body is smaller than *threshold* of the full range."""
94
+ full = self.range
95
+ if full <= 0:
96
+ return True
97
+ return self.body / full < threshold
98
+
99
+ def to_row(self) -> dict[str, Any]:
100
+ """Compact ``(time, open, high, low, close)`` row for tabular output."""
101
+ return {
102
+ "time": self.time,
103
+ "open": self.open,
104
+ "high": self.high,
105
+ "low": self.low,
106
+ "close": self.close,
107
+ }
108
+
109
+ @classmethod
110
+ def from_rows(cls, rows: list[dict[str, Any]]) -> list[Candle]:
111
+ """Build candles from a bare-array payload."""
112
+ return [cls(row) for row in rows if isinstance(row, dict)]
113
+
114
+
115
+ class SavedCandles(APIObject):
116
+ """Envelope returned by ``/qx_saved`` (with ``raw=true`` the body may be a bare list)."""
117
+
118
+ __slots__ = ()
119
+
120
+ @property
121
+ def asset(self) -> str:
122
+ return str(self._data.get("asset", "") or "")
123
+
124
+ @property
125
+ def timeframe(self) -> str:
126
+ return str(self._data.get("timeframe", "") or "")
127
+
128
+ @property
129
+ def period(self) -> int:
130
+ try:
131
+ return int(self._data.get("period", 0) or 0)
132
+ except (TypeError, ValueError):
133
+ return 0
134
+
135
+ @property
136
+ def requested_count(self) -> int:
137
+ try:
138
+ return int(self._data.get("requested_count", 0) or 0)
139
+ except (TypeError, ValueError):
140
+ return 0
141
+
142
+ @property
143
+ def returned_count(self) -> int:
144
+ try:
145
+ return int(self._data.get("returned_count", 0) or 0)
146
+ except (TypeError, ValueError):
147
+ return 0
148
+
149
+ @property
150
+ def base_period(self) -> int:
151
+ try:
152
+ return int(self._data.get("base_period", 0) or 0)
153
+ except (TypeError, ValueError):
154
+ return 0
155
+
156
+ @property
157
+ def days_scanned(self) -> int:
158
+ try:
159
+ return int(self._data.get("days_scanned", 0) or 0)
160
+ except (TypeError, ValueError):
161
+ return 0
162
+
163
+ @property
164
+ def raw_5s_candles(self) -> int:
165
+ try:
166
+ return int(self._data.get("raw_5s_candles", 0) or 0)
167
+ except (TypeError, ValueError):
168
+ return 0
169
+
170
+ @property
171
+ def from_cache(self) -> bool:
172
+ return bool(self._data.get("from_cache", False))
173
+
174
+ @property
175
+ def candles(self) -> list[Candle]:
176
+ rows = self._data.get("candles", [])
177
+ if isinstance(rows, list):
178
+ return [Candle(r) for r in rows if isinstance(r, dict)]
179
+ return []
180
+
181
+ def __len__(self) -> int:
182
+ return len(self.candles)
183
+
184
+ @classmethod
185
+ def from_payload(cls, payload: Any) -> SavedCandles:
186
+ """Accept either the object envelope or a bare candle list."""
187
+ if isinstance(payload, list):
188
+ return cls({"candles": payload})
189
+ if isinstance(payload, dict):
190
+ return cls(payload)
191
+ return cls({})
@@ -0,0 +1,84 @@
1
+ """Trade-result models from ``/qx_result``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .base import APIObject, TradeOutcome, coerce_enum
6
+ from .candle import Candle
7
+
8
+ __all__ = ["TradeResult"]
9
+
10
+
11
+ class TradeResult(APIObject):
12
+ """Outcome of a checked trade entry from ``/qx_result``."""
13
+
14
+ __slots__ = ()
15
+
16
+ @property
17
+ def success(self) -> bool:
18
+ return bool(self._data.get("success", False))
19
+
20
+ @property
21
+ def asset(self) -> str:
22
+ return str(self._data.get("asset", "") or "")
23
+
24
+ @property
25
+ def timeframe(self) -> str:
26
+ return str(self._data.get("timeframe", "") or "")
27
+
28
+ @property
29
+ def direction(self) -> str:
30
+ return str(self._data.get("direction", "") or "")
31
+
32
+ @property
33
+ def mtg(self) -> int:
34
+ try:
35
+ return int(self._data.get("mtg", 0) or 0)
36
+ except (TypeError, ValueError):
37
+ return 0
38
+
39
+ @property
40
+ def entry_time(self) -> str:
41
+ return str(self._data.get("entry_time", "") or "")
42
+
43
+ @property
44
+ def outcomes(self) -> list[TradeOutcome]:
45
+ """Coerced per-candle outcome values (candles that carry a status)."""
46
+ values: list[TradeOutcome] = []
47
+ for entry in self._data.get("candles", []) or []:
48
+ if isinstance(entry, dict) and "status" in entry:
49
+ coerced = coerce_enum(TradeOutcome, entry.get("status"), None)
50
+ if coerced is not None:
51
+ values.append(coerced)
52
+ result_value = self.result
53
+ if result_value is not None and (not values or self.mtg > 1):
54
+ values.append(result_value)
55
+ return values
56
+
57
+ @property
58
+ def checks(self) -> list[str]:
59
+ """Raw per-check status strings from the payload."""
60
+ value = self._data.get("checks", [])
61
+ if isinstance(value, list):
62
+ return [str(v) for v in value]
63
+ return []
64
+
65
+ @property
66
+ def candle_directions(self) -> list[str]:
67
+ value = self._data.get("candle_directions", [])
68
+ if isinstance(value, list):
69
+ return [str(v) for v in value]
70
+ return []
71
+
72
+ @property
73
+ def result(self) -> TradeOutcome | None:
74
+ """Final result coerced to a :class:`TradeOutcome`."""
75
+ return coerce_enum(TradeOutcome, self._data.get("result"), None)
76
+
77
+ @property
78
+ def candles(self) -> list[Candle]:
79
+ """Candles attached to the result (pending markers are skipped)."""
80
+ out: list[Candle] = []
81
+ for entry in self._data.get("candles", []) or []:
82
+ if isinstance(entry, dict) and "time" in entry:
83
+ out.append(Candle(entry))
84
+ return out
@@ -0,0 +1,272 @@
1
+ """Declarative endpoint parameter validation.
2
+
3
+ The live server rejects ANY undocumented query parameter with HTTP 400
4
+ ("That parameter is not available on this API."). To save a round trip and
5
+ give better errors, this module declares, per endpoint, exactly which params
6
+ are allowed, their types, ranges, enums and defaults — and validates/serialises
7
+ them *before* the request is made.
8
+
9
+ Rules enforced here:
10
+
11
+ * unknown kwarg -> ValidationError listing allowed names
12
+ * out-of-range value -> ValidationError with the accepted range
13
+ * invalid enum -> ValidationError listing valid values
14
+ * booleans serialise as -> "true" / "false"
15
+ * ``None`` values -> omitted entirely from the query string
16
+ * asset format -> validated against ^[A-Za-z0-9_]{2,40}$ (input is
17
+ trimmed for validation but never mutated)
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from typing import Any
24
+
25
+ from .config import TIMEFRAME_LABELS
26
+ from .errors import ValidationError
27
+ from .utils import coerce_bool_str, is_valid_asset, is_valid_date, is_valid_time
28
+
29
+ __all__ = ["validate_params", "allowed_params", "ENDPOINT_PARAMS"]
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Spec language
33
+ # ---------------------------------------------------------------------------
34
+ StrParam = "str"
35
+ IntParam = "int"
36
+ FloatParam = "float"
37
+ BoolParam = "bool"
38
+
39
+
40
+ def _tf_timeframe(value: str) -> str:
41
+ """Timeframe labels the server accepts verbatim."""
42
+ lowered = str(value).strip().lower()
43
+ if lowered not in TIMEFRAME_LABELS:
44
+ raise ValidationError(
45
+ "Invalid timeframe {!r}. Valid timeframes: {}.".format(
46
+ value, ", ".join(TIMEFRAME_LABELS)
47
+ )
48
+ )
49
+ return lowered
50
+
51
+
52
+ def _time_str(value: str) -> str:
53
+ if not is_valid_time(str(value)):
54
+ raise ValidationError(f"Invalid time {value!r}. Expected 'HH:MM' or 'HH:MM:SS'.")
55
+ return str(value).strip()
56
+
57
+
58
+ def _date_str(value: str) -> str:
59
+ if not is_valid_date(str(value)):
60
+ raise ValidationError(f"Invalid date {value!r}. Expected 'YYYY-MM-DD'.")
61
+ return str(value).strip()
62
+
63
+
64
+ def _csv_timeframes(value: Any) -> str:
65
+ """Comma-separated timeframe list, e.g. ``1m,5m,15m``."""
66
+ parts = [p.strip().lower() for p in str(value).split(",") if p.strip()]
67
+ if not parts:
68
+ raise ValidationError("timeframes must be a non-empty comma-separated list.")
69
+ for part in parts:
70
+ if part not in TIMEFRAME_LABELS:
71
+ raise ValidationError(
72
+ "Invalid timeframe {!r} in timeframes. Valid: {}.".format(
73
+ part, ", ".join(TIMEFRAME_LABELS)
74
+ )
75
+ )
76
+ return ",".join(parts)
77
+
78
+
79
+ def _asset(value: str) -> str:
80
+ asset = str(value).strip()
81
+ if not is_valid_asset(asset):
82
+ raise ValidationError(
83
+ f"Invalid asset {value!r}. Asset symbols look like 'EURUSD_otc' or "
84
+ "'AUDCAD' and must match ^[A-Za-z0-9_]{2,40}$."
85
+ )
86
+ return asset
87
+
88
+
89
+ # name -> (type, required, choices, min, max, transformer, default)
90
+ class _Rule:
91
+ __slots__ = (
92
+ "kind",
93
+ "required",
94
+ "choices",
95
+ "min_value",
96
+ "max_value",
97
+ "transform",
98
+ "default",
99
+ "doc",
100
+ )
101
+
102
+ def __init__(
103
+ self,
104
+ kind: str,
105
+ required: bool = False,
106
+ choices: tuple[Any, ...] | None = None,
107
+ min_value: float | None = None,
108
+ max_value: float | None = None,
109
+ transform: Any | None = None,
110
+ default: Any = None,
111
+ doc: str = "",
112
+ ) -> None:
113
+ self.kind = kind
114
+ self.required = required
115
+ self.choices = choices
116
+ self.min_value = min_value
117
+ self.max_value = max_value
118
+ self.transform = transform
119
+ self.default = default
120
+ self.doc = doc
121
+
122
+
123
+ def _s(doc: str = "", **kw: Any) -> _Rule:
124
+ return _rule(kind=StrParam, doc=doc, **kw)
125
+
126
+
127
+ def _rule(kind: str = StrParam, **kw: Any) -> _Rule:
128
+ return _Rule(kind=kind, **kw)
129
+
130
+
131
+ _TIMEFRAMES_TF = tuple(TIMEFRAME_LABELS)
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # Per-endpoint parameter tables (exactly the documented sets — nothing more)
135
+ # ---------------------------------------------------------------------------
136
+ ENDPOINT_PARAMS: dict[str, dict[str, _Rule]] = {
137
+ "assets": {
138
+ "account": _rule(
139
+ IntParam, min_value=0, max_value=99, doc="Account selector (server-defined values)."
140
+ ),
141
+ },
142
+ "candles": {
143
+ "asset": _rule(
144
+ StrParam, required=True, transform=_asset, doc="Asset symbol, e.g. EURUSD_otc."
145
+ ),
146
+ "account": _rule(IntParam, min_value=0, max_value=99),
147
+ "hours": _rule(
148
+ IntParam,
149
+ min_value=1,
150
+ max_value=24,
151
+ default=2,
152
+ doc="Hours of history, 1..24 (default 2).",
153
+ ),
154
+ "timeframe": _rule(StrParam, choices=_TIMEFRAMES_TF, default="1m"),
155
+ "timezone": _s(doc="e.g. '-3', 'UTC', 'Asia/Dhaka'."),
156
+ "offset": _rule(IntParam, min_value=0, max_value=604800, default=3600),
157
+ "timestamp": _rule(IntParam, min_value=1, max_value=4102444800),
158
+ "timeout": _rule(IntParam, min_value=1, max_value=30, default=16),
159
+ "verbose_logging": _rule(BoolParam),
160
+ "period": _rule(IntParam, min_value=1, max_value=86400),
161
+ },
162
+ "history": {}, # filled below from candles
163
+ "saved": {
164
+ "asset": _rule(StrParam, required=True, transform=_asset),
165
+ "timeframe": _rule(StrParam, choices=_TIMEFRAMES_TF, default="1m"),
166
+ "timezone": _s(),
167
+ "count": _rule(IntParam, min_value=1, max_value=1000, default=100),
168
+ "raw": _rule(BoolParam),
169
+ "nocache": _rule(BoolParam),
170
+ },
171
+ "screenshot": {
172
+ "asset": _rule(StrParam, required=True, transform=_asset),
173
+ "timeframe": _rule(StrParam, choices=_TIMEFRAMES_TF, default="1m"),
174
+ "timezone": _s(),
175
+ "time": _rule(StrParam, transform=_time_str),
176
+ "result": _s(doc="Trade-result filter shown on the chart."),
177
+ "names": _s(doc="Pattern names overlay."),
178
+ },
179
+ "result": {
180
+ "asset": _rule(StrParam, required=True, transform=_asset),
181
+ "time": _rule(StrParam, required=True, transform=_time_str),
182
+ "timeframe": _rule(StrParam, choices=_TIMEFRAMES_TF, default="1m"),
183
+ "timezone": _s(),
184
+ "direction": _rule(StrParam, required=True, choices=("call", "put")),
185
+ "mtg": _rule(IntParam, min_value=0, max_value=2, default=1),
186
+ },
187
+ }
188
+
189
+ ENDPOINT_PARAMS["history"] = dict(ENDPOINT_PARAMS["candles"])
190
+
191
+ _ASSET_RE = re.compile(r"^[A-Za-z0-9_]{2,40}$")
192
+
193
+
194
+ def allowed_params(endpoint: str) -> tuple[str, ...]:
195
+ """Return the documented parameter names for *endpoint*."""
196
+ return tuple(ENDPOINT_PARAMS.get(endpoint, {}).keys())
197
+
198
+
199
+ def validate_params(endpoint: str, **params: Any) -> list[tuple[str, str]]:
200
+ """Validate and serialise *params* for *endpoint*.
201
+
202
+ Returns an ordered ``[(name, value), ...]`` list ready for urlencode.
203
+ Raises :class:`ValidationError` before any network I/O when a parameter is
204
+ unknown, out of range, an invalid enum, or of the wrong type.
205
+ """
206
+ table = ENDPOINT_PARAMS.get(endpoint)
207
+ if table is None:
208
+ raise ValidationError(f"Unknown endpoint {endpoint!r}.")
209
+
210
+ unknown = [k for k in params if k not in table and params[k] is not None]
211
+ if unknown:
212
+ raise ValidationError(
213
+ "Unknown parameter(s) {} for '{}'. This API validates the exact "
214
+ "set of documented parameters; allowed names: {}.".format(
215
+ ", ".join(repr(u) for u in sorted(unknown)),
216
+ endpoint,
217
+ ", ".join(table.keys()) or "(none)",
218
+ )
219
+ )
220
+
221
+ out: list[tuple[str, str]] = []
222
+ for name, rule in table.items():
223
+ value = params.get(name, None)
224
+ if value is None:
225
+ if rule.required:
226
+ raise ValidationError(f"Missing required parameter '{name}' for '{endpoint}'.")
227
+ continue
228
+ out.append((name, _serialize(name, rule, value)))
229
+ return out
230
+
231
+
232
+ def _serialize(name: str, rule: _Rule, value: Any) -> str:
233
+ if rule.kind == BoolParam:
234
+ if not isinstance(value, bool):
235
+ raise ValidationError(
236
+ f"Parameter '{name}' expects a boolean (True/False); got {value!r}."
237
+ )
238
+ return coerce_bool_str(value)
239
+
240
+ if rule.kind == IntParam:
241
+ if isinstance(value, bool) or not isinstance(value, int):
242
+ raise ValidationError(f"Parameter '{name}' expects an integer; got {value!r}.")
243
+ _check_range(name, rule, float(value))
244
+ return str(value)
245
+
246
+ if rule.kind == FloatParam:
247
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
248
+ raise ValidationError(f"Parameter '{name}' expects a number; got {value!r}.")
249
+ _check_range(name, rule, float(value))
250
+ return repr(float(value))
251
+
252
+ # StrParam
253
+ if not isinstance(value, str):
254
+ raise ValidationError(f"Parameter '{name}' expects a string; got {value!r}.")
255
+ if rule.transform is not None:
256
+ value = rule.transform(value)
257
+ if rule.choices is not None:
258
+ if value not in rule.choices:
259
+ raise ValidationError(
260
+ "Invalid {} {!r}. Valid values: {}.".format(
261
+ name, value, ", ".join(str(c) for c in rule.choices)
262
+ )
263
+ )
264
+ return str(value)
265
+
266
+
267
+ def _check_range(name: str, rule: _Rule, number: float) -> None:
268
+ low, high = rule.min_value, rule.max_value
269
+ if low is not None and number < low:
270
+ raise ValidationError(f"Parameter '{name}' must be >= {low}; got {number}.")
271
+ if high is not None and number > high:
272
+ raise ValidationError(f"Parameter '{name}' must be <= {high}; got {number}.")
alltradingapi/py.typed ADDED
File without changes