alltradingapi 0.0.0-stage → 1.0.0

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,686 @@
1
+ /**
2
+ * Single source of truth for the installed SDK version.
3
+ *
4
+ * Mirrored in `package.json`; `tests/packaging.test.ts` asserts both match.
5
+ */
6
+ declare const VERSION = "1.0.0";
7
+
8
+ /** Small shared type aliases used across the SDK. */
9
+ /** A plain JSON object record. */
10
+ type RecordLike = Record<string, unknown>;
11
+ type ParamValue = string | number | boolean | null | undefined;
12
+ /** Ordered query-parameter pair, ready for urlencoding. */
13
+ type QueryParam = [string, string];
14
+
15
+ /**
16
+ * Shared model plumbing: the `APIObject` base and the SDK's outcome enum.
17
+ */
18
+
19
+ /**
20
+ * Dict-backed base class for every API model.
21
+ *
22
+ * - `get(key)` maps to payload keys; hyphens/spaces in keys are normalised to
23
+ * underscores for lookup.
24
+ * - Nested objects convert lazily to `APIObject`; nested arrays convert their
25
+ * object members on access.
26
+ * - `toJSON()` round-trips to the original payload.
27
+ */
28
+ declare class APIObject {
29
+ protected readonly _data: RecordLike;
30
+ constructor(data?: unknown);
31
+ /** The underlying payload dict (shallow copy). */
32
+ get raw(): RecordLike;
33
+ /** The live underlying payload dict. */
34
+ get data(): RecordLike;
35
+ /** Return `payload[key]` or `defaultValue`, with lazy conversion applied. */
36
+ get(key: string, defaultValue?: unknown): unknown;
37
+ has(key: string): boolean;
38
+ get size(): number;
39
+ keys(): string[];
40
+ items(): Array<[string, unknown]>;
41
+ [Symbol.iterator](): IterableIterator<string>;
42
+ /** Return a plain object copy that round-trips to the original payload. */
43
+ toJSON(): RecordLike;
44
+ /** Build a list of instances from a bare-array payload. */
45
+ static fromRows<T extends APIObject>(this: new (row: unknown) => T, rows: unknown): T[];
46
+ }
47
+ /** Outcome values returned by /qx_result. */
48
+ declare const TradeOutcome: {
49
+ readonly WIN: "win";
50
+ readonly WIN_1: "win1";
51
+ readonly WIN_2: "win2";
52
+ readonly REFUND: "refund";
53
+ readonly LOSE: "lose";
54
+ readonly PENDING: "pending";
55
+ };
56
+ type TradeOutcome = (typeof TradeOutcome)[keyof typeof TradeOutcome];
57
+ /** Coerce `value` to a `TradeOutcome` with tolerant matching, else null. */
58
+ declare function coerceOutcome(value: unknown): TradeOutcome | null;
59
+ /** True for win / win1 / win2. */
60
+ declare function outcomeWon(value: TradeOutcome): boolean;
61
+ /** True for lose. */
62
+ declare function outcomeLost(value: TradeOutcome): boolean;
63
+ /** True for pending. */
64
+ declare function outcomePending(value: TradeOutcome): boolean;
65
+
66
+ /** Asset model — one entry of the bare-array response from `/qx_assets`. */
67
+
68
+ /** A tradable Quotex asset with live open/closed state and payout. */
69
+ declare class Asset extends APIObject {
70
+ /** Numeric asset id (e.g. `368`). */
71
+ get id(): number;
72
+ /** Trading symbol, e.g. `EURUSD_otc`. */
73
+ get symbol(): string;
74
+ /** Display name, e.g. `Euro / US Dollar (OTC)`. */
75
+ get name(): string;
76
+ /** True when the asset is open for trading right now. */
77
+ get isOpen(): boolean;
78
+ /** Asset class: currency, cryptocurrency, commodity, ... */
79
+ get type(): string;
80
+ /** Base payout percentage (e.g. `77`). */
81
+ get payout(): number;
82
+ /** 24h change, when the market reports it. */
83
+ get change24h(): number | null;
84
+ /** Payout for 1-minute expiry. */
85
+ get profit1m(): number | null;
86
+ /** Payout for 5-minute expiry. */
87
+ get profit5m(): number | null;
88
+ /** True when the symbol carries the `_otc` suffix. */
89
+ get isOtc(): boolean;
90
+ toString(): string;
91
+ }
92
+
93
+ /** Candle models — OHLC bars from `/qx_candles`, `/qx_history`, `/qx_saved`. */
94
+
95
+ /** One OHLC bar with tick metadata and typed convenience helpers. */
96
+ declare class Candle extends APIObject {
97
+ /** Bar open time as unix seconds. */
98
+ get time(): number;
99
+ get open(): number;
100
+ get high(): number;
101
+ get low(): number;
102
+ get close(): number;
103
+ get ticks(): number;
104
+ /** Unix timestamp (with fraction) of the last tick in the bar. */
105
+ get lastTick(): number;
106
+ get asset(): string;
107
+ get assetName(): string;
108
+ /** Formatted bar time as the server rendered it. */
109
+ get timeRead(): string;
110
+ /** Bar open time as a JS `Date` (UTC epoch based). */
111
+ get dt(): Date;
112
+ /** `"call"` when bullish, `"put"` when bearish, else `"neutral"`. */
113
+ get direction(): "call" | "put" | "neutral";
114
+ get isBullish(): boolean;
115
+ /** Absolute open-to-close distance. */
116
+ get body(): number;
117
+ /** High-to-low distance. */
118
+ get range(): number;
119
+ /** True when the body is smaller than `threshold` of the full range. */
120
+ isDoji(threshold?: number): boolean;
121
+ /** Compact `(time, open, high, low, close)` row for tabular output. */
122
+ toRow(): {
123
+ time: number;
124
+ open: number;
125
+ high: number;
126
+ low: number;
127
+ close: number;
128
+ };
129
+ }
130
+ /** Envelope returned by `/qx_saved` (with `raw=true` the body may be a bare list). */
131
+ declare class SavedCandles extends APIObject {
132
+ get asset(): string;
133
+ get timeframe(): string;
134
+ get period(): number;
135
+ get requestedCount(): number;
136
+ get returnedCount(): number;
137
+ get basePeriod(): number;
138
+ get daysScanned(): number;
139
+ get raw5sCandles(): number;
140
+ get fromCache(): boolean;
141
+ get candles(): Candle[];
142
+ get length(): number;
143
+ /** Accept either the object envelope or a bare candle list. */
144
+ static fromPayload(payload: unknown): SavedCandles;
145
+ }
146
+
147
+ /** Trade-result models from `/qx_result`. */
148
+
149
+ /** Outcome of a checked trade entry from `/qx_result`. */
150
+ declare class TradeResult extends APIObject {
151
+ get success(): boolean;
152
+ get asset(): string;
153
+ get timeframe(): string;
154
+ get direction(): string;
155
+ get mtg(): number;
156
+ get entryTime(): string;
157
+ /** Coerced per-candle outcome values (candles that carry a status). */
158
+ get outcomes(): TradeOutcome[];
159
+ /** Raw per-check status strings from the payload. */
160
+ get checks(): string[];
161
+ get candleDirections(): string[];
162
+ /** Final result coerced to a `TradeOutcome`. */
163
+ get result(): TradeOutcome | null;
164
+ /** Candles attached to the result (pending markers are skipped). */
165
+ get candles(): Candle[];
166
+ /** Convenience: true when any reported outcome is a win. */
167
+ get won(): boolean;
168
+ }
169
+
170
+ /**
171
+ * HTTP transport built on `node:http` / `node:https` — zero dependencies.
172
+ *
173
+ * Design notes:
174
+ *
175
+ * - Keep-alive connection pool (bounded idle connections per host).
176
+ * - `Accept-Encoding: gzip, deflate` with transparent decompression.
177
+ * - Explicit connect + read timeouts; no redirects (the API has none).
178
+ * - Bounded retries with exponential backoff + **full jitter** on 429/5xx and
179
+ * transient socket errors; honours `Retry-After`.
180
+ * - GET retries freely (idempotent); POST retries at most once and only on 5xx.
181
+ * - Response size cap (32 MiB) so a hostile response cannot exhaust memory.
182
+ * - TLS verification via Node defaults; `verify: false` is an explicit opt-in
183
+ * for local testing only.
184
+ * - Optional proxy via `ATA_HTTP_PROXY` / `ATA_HTTPS_PROXY` (https goes through
185
+ * a CONNECT tunnel).
186
+ * - API keys are redacted from URLs in logs and errors, always.
187
+ */
188
+
189
+ /** A small, dependency-free HTTP response object. */
190
+ declare class Response {
191
+ readonly status: number;
192
+ readonly headers: Record<string, string>;
193
+ private readonly _body;
194
+ readonly url: string;
195
+ readonly elapsedMs: number;
196
+ constructor(status: number, headers: Record<string, string>, body: Buffer, url: string, elapsedMs: number);
197
+ /** Body decoded as UTF-8 with replacement characters for bad sequences. */
198
+ get text(): string;
199
+ /** Parse the body as JSON (throws SyntaxError on non-JSON bodies). */
200
+ json(): unknown;
201
+ get contentType(): string;
202
+ /** Raw body bytes. */
203
+ get content(): Buffer;
204
+ /** Case-insensitive header lookup. */
205
+ header(name: string, fallback?: string | null): string | null;
206
+ }
207
+ interface RequestOptions {
208
+ params?: QueryParam[] | null;
209
+ body?: Buffer | null;
210
+ headers?: Record<string, string> | null;
211
+ /** Read timeout in seconds. */
212
+ timeout?: number | null;
213
+ }
214
+ interface TransportOptions {
215
+ baseUrl?: string;
216
+ connectTimeout?: number;
217
+ maxRetries?: number;
218
+ backoffFactor?: number;
219
+ retryStatuses?: number[];
220
+ verify?: boolean;
221
+ userAgent?: string | null;
222
+ }
223
+ /** Low-level HTTP client used by `Client`. */
224
+ declare class Transport {
225
+ readonly baseUrl: string;
226
+ readonly scheme: string;
227
+ readonly host: string;
228
+ readonly port: number;
229
+ readonly prefix: string;
230
+ readonly connectTimeout: number;
231
+ readonly maxRetries: number;
232
+ readonly backoffFactor: number;
233
+ readonly retryStatuses: readonly number[];
234
+ readonly verify: boolean;
235
+ /** `null` -> a random browser User-Agent is picked per request. */
236
+ readonly userAgent: string | null;
237
+ private readonly _agentHttp;
238
+ private readonly _agentHttps;
239
+ private readonly _agentHttpProxy;
240
+ private readonly _proxyHost;
241
+ private readonly _proxyPort;
242
+ private _lastSocket;
243
+ constructor(opts?: TransportOptions);
244
+ /** Perform `method` against `path` and return a `Response`. */
245
+ request(method: string, path: string, opts?: RequestOptions): Promise<Response>;
246
+ /** Close pooled connections. Safe to call multiple times. */
247
+ close(): void;
248
+ private _resolveProxy;
249
+ private _buildUrl;
250
+ private _sendOnce;
251
+ private _rawRequest;
252
+ private _wireErrors;
253
+ private _tunnel;
254
+ private _readBounded;
255
+ private _shouldRetrySocket;
256
+ private _shouldRetryStatus;
257
+ private get maxAttempts();
258
+ private _sleepBackoff;
259
+ private _backoffDelay;
260
+ private _networkError;
261
+ private _discardConnection;
262
+ }
263
+
264
+ type UpdatePolicy = "strict" | "ask" | "warn" | "off";
265
+ declare const UPDATE_POLICIES: readonly UpdatePolicy[];
266
+ /** Tolerant coercion from strings; `null` passes through as `fallback`. */
267
+ declare function coerceUpdatePolicy(value: unknown, fallback?: UpdatePolicy | null): UpdatePolicy | null;
268
+ declare class UpdateInfo {
269
+ readonly installed: string;
270
+ readonly latest: string | null;
271
+ readonly isOutdated: boolean;
272
+ readonly checkedAt: number;
273
+ readonly source: string;
274
+ /** False when the check failed / was offline (fail-open). */
275
+ readonly known: boolean;
276
+ constructor(installed: string, latest: string | null, isOutdated: boolean, checkedAt: number, source: string, known: boolean);
277
+ toDict(): Record<string, unknown>;
278
+ }
279
+ type MainKey = [number, number[], number, number, number, number];
280
+ type VersionKey = [MainKey, number];
281
+ /**
282
+ * Parse a version string into a sortable key.
283
+ *
284
+ * Returns `null` when the text is not a recognisable version, which makes
285
+ * comparisons fail open (treated as equal) instead of crashing.
286
+ */
287
+ declare function parseVersion(text: string | null | undefined): VersionKey | null;
288
+ /**
289
+ * Compare two version strings PEP-440-style.
290
+ *
291
+ * Returns `-1` if `a < b`, `0` if equal/unparsable, `1` if `a > b`.
292
+ * Unparsable versions fail open (equal) by design.
293
+ */
294
+ declare function compareVersions(a: string | null | undefined, b: string | null | undefined): number;
295
+ /** True when `latest` is strictly greater than `installed`. */
296
+ declare function isOutdated(installed: string | null | undefined, latest: string | null | undefined): boolean;
297
+ type Fetcher = (checkUrl: string, timeout: number) => Promise<string | null>;
298
+ declare function fetchLatest(checkUrl?: string, timeout?: number): Promise<string | null>;
299
+ declare function resolvePolicy(explicit?: unknown): UpdatePolicy;
300
+ /** Forget the in-process gate result (used by tests). */
301
+ declare function resetGateState(): void;
302
+ interface EnsureUsableOptions {
303
+ policy?: unknown;
304
+ allowOutdated?: boolean;
305
+ interactive?: boolean | null;
306
+ checkUrl?: string;
307
+ cacheDir?: string | null;
308
+ ttl?: number | null;
309
+ now?: number | null;
310
+ fetcher?: Fetcher | null;
311
+ installer?: ((command: string[]) => Promise<{
312
+ code: number;
313
+ output: string;
314
+ }>) | null;
315
+ inputFn?: ((prompt: string) => Promise<string | null>) | null;
316
+ printer?: ((text: string) => void) | null;
317
+ }
318
+ /**
319
+ * Check the npm registry for a newer release, honouring the disk cache.
320
+ *
321
+ * Never throws for network problems; a failed check returns `known: false`
322
+ * with `latest: null` (fail-open). Throws {@link UpdateCheckError} only when
323
+ * the *installed* version cannot be determined.
324
+ */
325
+ declare function checkForUpdate(force?: boolean, installed?: string | null, opts?: {
326
+ checkUrl?: string;
327
+ cacheDir?: string | null;
328
+ ttl?: number | null;
329
+ now?: number | null;
330
+ fetcher?: Fetcher | null;
331
+ }): Promise<UpdateInfo>;
332
+ /** The exact command used (and printed on failure) to self-upgrade. */
333
+ declare function upgradeCommand(): string[];
334
+ /** Run `npm install alltradingapi@latest` and report (ok, output tail). */
335
+ declare function installUpdate(opts?: {
336
+ installer?: ((command: string[]) => Promise<{
337
+ code: number;
338
+ output: string;
339
+ }>) | null;
340
+ timeout?: number;
341
+ }): Promise<[boolean, string]>;
342
+ /**
343
+ * Run the update gate; resolve `UpdateInfo` when usable.
344
+ *
345
+ * Throws {@link UpdateRequiredError} when the strict gate blocks operation.
346
+ * Runs at most one network check per process (cached afterwards).
347
+ */
348
+ declare function ensureUsable(installed: string, opts?: EnsureUsableOptions): Promise<UpdateInfo | null>;
349
+
350
+ /**
351
+ * The `Client` — typed access to the six v1 endpoints.
352
+ *
353
+ * Endpoints covered:
354
+ *
355
+ * - `assets()` -> `/qx_assets` (asset data)
356
+ * - `candles()` -> `/qx_candles` (current candles)
357
+ * - `history()` -> `/qx_history` (candle history)
358
+ * - `saved()` -> `/qx_saved` (saved candles)
359
+ * - `screenshot()` -> `/qx_ss_pro_v2` (chart image, PNG bytes)
360
+ * - `result()` -> `/qx_result` (trade result check)
361
+ *
362
+ * Key resolution order (first hit wins):
363
+ *
364
+ * 1. explicit per-call `apiKey`
365
+ * 2. `keys[product]` (product id such as `"quotex-quotes"`)
366
+ * 3. `keys["default"]`
367
+ * 4. constructor `apiKey`
368
+ * 5. environment `ATA_API_KEY`
369
+ * 6. environment `ATA_KEY_<PRODUCT_UPPER_SNAKE>` (e.g. `ATA_KEY_QUOTEX_QUOTES`)
370
+ *
371
+ * If nothing resolves, calls throw `AuthenticationError` with an actionable
372
+ * message — never a bare `undefined` key.
373
+ */
374
+
375
+ type UpdateCallback = (info: UpdateInfo) => void | Promise<void>;
376
+ interface ClientOptions {
377
+ apiKey?: string;
378
+ keys?: Record<string, string>;
379
+ baseUrl?: string;
380
+ /** Read timeout in seconds. */
381
+ timeout?: number;
382
+ /** Connect timeout in seconds. */
383
+ connectTimeout?: number;
384
+ maxRetries?: number;
385
+ backoffFactor?: number;
386
+ retryStatuses?: number[];
387
+ userAgent?: string | null;
388
+ authMode?: "bearer" | "query";
389
+ cacheTtl?: number;
390
+ updatePolicy?: UpdatePolicy | string;
391
+ allowOutdated?: boolean;
392
+ interactive?: boolean | null;
393
+ transport?: Transport;
394
+ runUpdateGate?: boolean;
395
+ /** Concurrent requests used by `scan()`. */
396
+ maxConcurrency?: number;
397
+ }
398
+ interface AssetsOptions {
399
+ onlyOpen?: boolean;
400
+ refresh?: boolean;
401
+ account?: number | null;
402
+ apiKey?: string;
403
+ }
404
+ interface CandleOptions {
405
+ hours?: number | null;
406
+ timeframe?: string | null;
407
+ timezone?: string | null;
408
+ offset?: number | null;
409
+ timestamp?: number | null;
410
+ period?: number | null;
411
+ account?: number | null;
412
+ /** Server-side hint at feed latency; the SDK pads transport timeout by 5 s. */
413
+ timeout?: number | null;
414
+ verboseLogging?: boolean | null;
415
+ apiKey?: string;
416
+ }
417
+ interface SavedOptions {
418
+ timeframe?: string | null;
419
+ count?: number | null;
420
+ timezone?: string | null;
421
+ raw?: boolean | null;
422
+ nocache?: boolean;
423
+ apiKey?: string;
424
+ }
425
+ interface ScreenshotOptions {
426
+ timeframe?: string | null;
427
+ timezone?: string | null;
428
+ time?: string | null;
429
+ result?: string | null;
430
+ names?: string | null;
431
+ apiKey?: string;
432
+ }
433
+ interface ResultOptions {
434
+ time: string;
435
+ direction: string;
436
+ timeframe?: string | null;
437
+ timezone?: string | null;
438
+ mtg?: number | null;
439
+ apiKey?: string;
440
+ }
441
+ interface ScanOptions {
442
+ concurrency?: number;
443
+ apiKey?: string;
444
+ }
445
+ declare class Client {
446
+ private _keys;
447
+ private _authMode;
448
+ private _cacheTtl;
449
+ private _cache;
450
+ private _updatePolicy;
451
+ private _allowOutdated;
452
+ private _interactive;
453
+ private _updateHooks;
454
+ private _gatePromise;
455
+ private _maxConcurrency;
456
+ protected _transport: Transport;
457
+ protected _closed: boolean;
458
+ constructor(options?: ClientOptions);
459
+ /** Build a client from environment configuration (ATA_* variables). */
460
+ static fromEnv(options?: ClientOptions): Client;
461
+ close(): void;
462
+ /** Installed SDK version string. */
463
+ get version(): string;
464
+ private _runGate;
465
+ /** Register a callback receiving `UpdateInfo` when a newer SDK exists. */
466
+ onUpdateAvailable(callback: UpdateCallback): void;
467
+ /** Return `UpdateInfo`; never throws for network issues. */
468
+ checkUpdates(force?: boolean): Promise<UpdateInfo>;
469
+ private _resolveKey;
470
+ private _request;
471
+ private _cachedJson;
472
+ /** Drop all client-side cached responses. */
473
+ clearCache(): void;
474
+ /** List every tradable asset with open/closed state and payouts. */
475
+ assets(options?: AssetsOptions): Promise<Asset[]>;
476
+ /** Fetch recent candles for `asset` (default ~2h of 1m bars). */
477
+ candles(asset: string, options?: CandleOptions): Promise<Candle[]>;
478
+ /** Fetch candle history for `asset` (same parameters as candles). */
479
+ history(asset: string, options?: CandleOptions): Promise<Candle[]>;
480
+ private _candles;
481
+ /** Fetch server-side saved candles (scanned from the 5s archive). */
482
+ saved(asset: string, options?: SavedOptions): Promise<SavedCandles>;
483
+ /** Download a chart screenshot (PNG bytes) for `asset`. */
484
+ screenshot(asset: string, options?: ScreenshotOptions): Promise<Buffer>;
485
+ /** Check a past trade entry (call/put at HH:MM) and its outcome(s). */
486
+ result(asset: string, options: ResultOptions): Promise<TradeResult>;
487
+ /**
488
+ * Fetch candles for many assets concurrently; per-asset failures never
489
+ * abort. Returns `{ [symbol]: Candle[] | Error }`.
490
+ */
491
+ scan(symbols: Iterable<string>, options?: ScanOptions & Partial<CandleOptions>): Promise<Record<string, Candle[] | Error>>;
492
+ }
493
+ /** Async SDK client — same surface as `Client` (all methods promise-based). */
494
+ declare class AsyncClient extends Client {
495
+ }
496
+
497
+ /**
498
+ * Error hierarchy for the All Trading API SDK.
499
+ *
500
+ * Every error carries structured context (status, payload, redacted URL) and a
501
+ * message that tells the user what to do next. API keys never appear in error
502
+ * text, `toString()` or URLs.
503
+ */
504
+
505
+ declare class ALLError extends Error {
506
+ /** Short machine-readable code (e.g. `rate_limited`). */
507
+ code: string;
508
+ /** HTTP status code when the error came from a response. */
509
+ status: number | null;
510
+ /** Parsed JSON body of the failing response, when present. */
511
+ payload: RecordLike;
512
+ /** Request URL with any credentials redacted. */
513
+ url: string | null;
514
+ /** Server-provided request id when available. */
515
+ requestId: string | null;
516
+ constructor(message: string, opts?: {
517
+ status?: number | null;
518
+ payload?: RecordLike | null;
519
+ url?: string | null;
520
+ requestId?: string | null;
521
+ });
522
+ /** Return a JSON-serialisable view (URL already key-redacted). */
523
+ toDict(): Record<string, unknown>;
524
+ }
525
+ /** The SDK was constructed or called with impossible configuration. */
526
+ declare class ConfigurationError extends ALLError {
527
+ code: string;
528
+ }
529
+ /** HTTP 401 — missing or invalid API key. */
530
+ declare class AuthenticationError extends ALLError {
531
+ code: string;
532
+ }
533
+ /** HTTP 403 — the key does not include this product, or is paused. */
534
+ declare class PermissionDeniedError extends ALLError {
535
+ code: string;
536
+ }
537
+ /** HTTP 404 — unknown route (the server only serves pretty routes). */
538
+ declare class NotFoundError extends ALLError {
539
+ code: string;
540
+ }
541
+ /** HTTP 400 — bad/missing/unknown parameter (rejected client-side or server-side). */
542
+ declare class ValidationError extends ALLError {
543
+ code: string;
544
+ }
545
+ /** HTTP 429 — rate limit reached; `retryAfter` says when to retry. */
546
+ declare class RateLimitError extends ALLError {
547
+ code: string;
548
+ retryAfter: number | null;
549
+ constructor(message: string, opts?: {
550
+ retryAfter?: number | null;
551
+ status?: number | null;
552
+ payload?: RecordLike | null;
553
+ url?: string | null;
554
+ requestId?: string | null;
555
+ });
556
+ }
557
+ /** HTTP 5xx — server error on the API side. */
558
+ declare class ServerError extends ALLError {
559
+ code: string;
560
+ }
561
+ /** HTTP 502 — market-feed failure or insufficient candles upstream. */
562
+ declare class UpstreamError extends ServerError {
563
+ code: string;
564
+ }
565
+ /** Network-level failure: DNS, TCP, TLS. */
566
+ declare class TransportError extends ALLError {
567
+ code: string;
568
+ }
569
+ /** A request exceeded its timeout. */
570
+ declare class TimeoutError extends ALLError {
571
+ code: string;
572
+ }
573
+ /**
574
+ * The installed SDK is outdated and the strict update gate blocked it.
575
+ */
576
+ declare class UpdateRequiredError extends ALLError {
577
+ code: string;
578
+ installed: string | null;
579
+ latest: string | null;
580
+ /** True when `npm install alltradingapi@latest` succeeded in-process; restart to load it. */
581
+ installedNow: boolean;
582
+ constructor(message: string, opts?: {
583
+ installed?: string | null;
584
+ latest?: string | null;
585
+ installedNow?: boolean;
586
+ });
587
+ }
588
+ /** Raised only by `Client.checkUpdates` when local version config is invalid. */
589
+ declare class UpdateCheckError extends ALLError {
590
+ code: string;
591
+ }
592
+ /** A consistent, actionable hint used across update-related errors. */
593
+ declare function updateHint(command?: string): string;
594
+
595
+ /**
596
+ * Logging setup for the SDK.
597
+ *
598
+ * The SDK logs to stderr at these levels:
599
+ *
600
+ * - DEBUG — request/response lines with **redacted** keys and timings
601
+ * - WARNING — retries
602
+ * - INFO — update-gate events
603
+ * - ERROR — failures
604
+ *
605
+ * Payloads are never logged at INFO. Keys are redacted everywhere.
606
+ */
607
+ type LogLevel = "debug" | "info" | "warn" | "error";
608
+ interface Logger {
609
+ debug(message: string, ...rest: unknown[]): void;
610
+ info(message: string, ...rest: unknown[]): void;
611
+ warn(message: string, ...rest: unknown[]): void;
612
+ error(message: string, ...rest: unknown[]): void;
613
+ }
614
+ /** Default SDK logger. Attach your own via `Client({ logger })`. */
615
+ declare const logger: Logger;
616
+ /**
617
+ * Configure the SDK logger level (`"DEBUG"`, `"INFO"`, `"WARN"`, `"ERROR"`).
618
+ * Unknown levels fall back to WARN, mirroring the Python SDK.
619
+ */
620
+ declare function setLogLevel(level: string): void;
621
+
622
+ /**
623
+ * Declarative endpoint parameter validation.
624
+ *
625
+ * The live server rejects ANY undocumented query parameter with HTTP 400
626
+ * ("That parameter is not available on this API."). To save a round trip and
627
+ * give better errors, this module declares, per endpoint, exactly which params
628
+ * are allowed, their types, ranges, enums and defaults — and validates/serialises
629
+ * them *before* the request is made.
630
+ *
631
+ * Rules enforced here:
632
+ *
633
+ * - unknown param -> ValidationError listing allowed names
634
+ * - out-of-range value -> ValidationError with the accepted range
635
+ * - invalid enum -> ValidationError listing valid values
636
+ * - booleans serialise as -> "true" when true; omitted when false
637
+ * (the server rejects `param=false` with a 400)
638
+ * - `null`/`undefined` -> omitted entirely from the query string
639
+ * - asset format -> validated against ^[A-Za-z0-9_]{2,40}$ (input is
640
+ * trimmed for validation but never mutated)
641
+ */
642
+
643
+ /** Return the documented parameter names for `endpoint`. */
644
+ declare function allowedParams(endpoint: string): string[];
645
+ /**
646
+ * Validate and serialise `params` for `endpoint`.
647
+ *
648
+ * Returns an ordered `[[name, value], ...]` list ready for urlencoding.
649
+ * Raises {@link ValidationError} before any network I/O when a parameter is
650
+ * unknown, out of range, an invalid enum, or of the wrong type.
651
+ */
652
+ declare function validateParams(endpoint: string, params?: Record<string, ParamValue>): QueryParam[];
653
+
654
+ /**
655
+ * Return `url` with every credential removed or replaced by `***`.
656
+ *
657
+ * Safe to store in logs, exceptions and test assertions.
658
+ */
659
+ declare function redactUrl(url: string | null | undefined): string | null;
660
+ /** True when `asset` matches the server's documented symbol regex. */
661
+ declare function isValidAsset(asset: string): boolean;
662
+
663
+ /**
664
+ * In-memory TTL cache.
665
+ *
666
+ * Used only for the cheap, slow-changing metadata endpoints (`assets()`) by
667
+ * default. Candles and analysis are never cached client-side.
668
+ */
669
+ declare class TTLCache {
670
+ private readonly _ttl;
671
+ private readonly _maxsize;
672
+ private readonly _store;
673
+ constructor(ttl?: number, maxsize?: number);
674
+ /** Configured time-to-live in seconds. */
675
+ get ttl(): number;
676
+ /** Return the cached value, or `undefined` when missing/expired. */
677
+ get(key: PropertyKey): unknown;
678
+ /** Store `value` under `key` for the configured TTL. */
679
+ put(key: PropertyKey, value: unknown): void;
680
+ /** Drop every entry. */
681
+ clear(): void;
682
+ get size(): number;
683
+ private _evictOldest;
684
+ }
685
+
686
+ export { ALLError, APIObject, Asset, type AssetsOptions, AsyncClient, AuthenticationError, Candle, type CandleOptions, Client, type ClientOptions, ConfigurationError, type LogLevel, type Logger, NotFoundError, PermissionDeniedError, RateLimitError, Response, type ResultOptions, SavedCandles, type SavedOptions, type ScanOptions, type ScreenshotOptions, ServerError, TTLCache, TimeoutError, TradeOutcome, TradeResult, Transport, TransportError, UPDATE_POLICIES, UpdateCheckError, UpdateInfo, type UpdatePolicy, UpdateRequiredError, UpstreamError, ValidationError, VERSION as __version, allowedParams, checkForUpdate, coerceOutcome, coerceUpdatePolicy, compareVersions, ensureUsable, fetchLatest, installUpdate, isOutdated, logger, outcomeLost, outcomePending, outcomeWon, parseVersion, redactUrl, resetGateState, resolvePolicy, setLogLevel, updateHint, upgradeCommand, isValidAsset as validateAsset, validateParams };