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.
package/dist/index.mjs ADDED
@@ -0,0 +1,2053 @@
1
+ // src/version.ts
2
+ var VERSION = "1.0.0";
3
+
4
+ // src/config.ts
5
+ import os from "os";
6
+ import path from "path";
7
+ var BASE_URL = "https://alltradingapi.com";
8
+ var NPM_REGISTRY_URL = "https://registry.npmjs.org/alltradingapi/latest";
9
+ var DEFAULT_TIMEOUT = 30;
10
+ var DEFAULT_CONNECT_TIMEOUT = 10;
11
+ var DEFAULT_MAX_RETRIES = 2;
12
+ var DEFAULT_BACKOFF_FACTOR = 0.5;
13
+ var DEFAULT_RETRY_STATUSES = [429, 500, 502, 503, 504];
14
+ var DEFAULT_USER_AGENT = "alltradingapi-js/1.0.0";
15
+ var MAX_RESPONSE_BYTES = 32 * 1024 * 1024;
16
+ var DEFAULT_AUTH_MODE = "bearer";
17
+ var DEFAULT_CACHE_TTL = 60;
18
+ var CONNECTION_POOL_SIZE = 8;
19
+ var UPDATE_CHECK_TIMEOUT = 2;
20
+ var UPDATE_CACHE_TTL = 6 * 3600;
21
+ var UPDATE_CACHE_FILE = "alltradingapi/update.json";
22
+ var ENV_API_KEY = "ATA_API_KEY";
23
+ var ENV_KEY_PREFIX = "ATA_KEY_";
24
+ var ENV_UPDATE_POLICY = "ATA_UPDATE_POLICY";
25
+ var ENV_UPDATE_TTL = "ATA_UPDATE_TTL";
26
+ var ENV_SKIP_UPDATE = "ATA_SKIP_UPDATE";
27
+ var ENV_NO_PROMPT = "ATA_NO_PROMPT";
28
+ var ENV_CI = "ATA_CI";
29
+ var ENV_HTTP_PROXY = "ATA_HTTP_PROXY";
30
+ var ENV_HTTPS_PROXY = "ATA_HTTPS_PROXY";
31
+ var CI_ENV_VARS = ["CI", "GITHUB_ACTIONS"];
32
+ var TIMEFRAME_LABELS = [
33
+ "5s",
34
+ "10s",
35
+ "15s",
36
+ "30s",
37
+ "1m",
38
+ "2m",
39
+ "3m",
40
+ "5m",
41
+ "10m",
42
+ "15m",
43
+ "30m",
44
+ "1h",
45
+ "2h",
46
+ "4h"
47
+ ];
48
+ function env(name, fallback = "") {
49
+ const value = process.env[name];
50
+ if (value === void 0 || value === "") return fallback;
51
+ return value;
52
+ }
53
+ function envBool(name, fallback = false) {
54
+ const raw = process.env[name];
55
+ if (raw === void 0 || raw === "") return fallback;
56
+ return ["1", "true", "yes", "on"].includes(raw.trim().toLowerCase());
57
+ }
58
+ function envFloat(name, fallback) {
59
+ const raw = process.env[name];
60
+ if (raw === void 0 || raw === "") return fallback;
61
+ const parsed = Number.parseFloat(raw);
62
+ return Number.isFinite(parsed) ? parsed : fallback;
63
+ }
64
+ function isCI() {
65
+ if (envBool(ENV_CI)) return true;
66
+ for (const name of CI_ENV_VARS) {
67
+ const value = process.env[name] ?? "";
68
+ if (value && value.toLowerCase() !== "0" && value.toLowerCase() !== "false") {
69
+ return true;
70
+ }
71
+ }
72
+ return false;
73
+ }
74
+ function isInteractive() {
75
+ if (isCI()) return false;
76
+ if (envBool(ENV_NO_PROMPT)) return false;
77
+ try {
78
+ return Boolean(process.stdin.isTTY);
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+ function cacheDir() {
84
+ const candidates = [
85
+ process.env.LOCALAPPDATA,
86
+ process.env.APPDATA,
87
+ process.env.XDG_CACHE_HOME,
88
+ path.join(os.homedir(), ".cache")
89
+ ];
90
+ for (const candidate of candidates) {
91
+ if (candidate) return candidate;
92
+ }
93
+ return os.tmpdir();
94
+ }
95
+
96
+ // src/cache.ts
97
+ var TTLCache = class {
98
+ _ttl;
99
+ _maxsize;
100
+ _store = /* @__PURE__ */ new Map();
101
+ constructor(ttl = 60, maxsize = 128) {
102
+ this._ttl = Math.max(0, ttl);
103
+ this._maxsize = Math.max(1, Math.floor(maxsize));
104
+ }
105
+ /** Configured time-to-live in seconds. */
106
+ get ttl() {
107
+ return this._ttl;
108
+ }
109
+ /** Return the cached value, or `undefined` when missing/expired. */
110
+ get(key) {
111
+ const now = Date.now();
112
+ const entry = this._store.get(key);
113
+ if (!entry) return void 0;
114
+ if (entry.expiresAt <= now) {
115
+ this._store.delete(key);
116
+ return void 0;
117
+ }
118
+ return entry.value;
119
+ }
120
+ /** Store `value` under `key` for the configured TTL. */
121
+ put(key, value) {
122
+ if (this._ttl <= 0) return;
123
+ const now = Date.now();
124
+ if (this._store.size >= this._maxsize && !this._store.has(key)) {
125
+ this._evictOldest();
126
+ }
127
+ this._store.set(key, { expiresAt: now + this._ttl * 1e3, value });
128
+ }
129
+ /** Drop every entry. */
130
+ clear() {
131
+ this._store.clear();
132
+ }
133
+ get size() {
134
+ return this._store.size;
135
+ }
136
+ _evictOldest() {
137
+ let oldestKey;
138
+ let oldestExpiry = Number.POSITIVE_INFINITY;
139
+ for (const [key, entry] of this._store) {
140
+ if (entry.expiresAt < oldestExpiry) {
141
+ oldestExpiry = entry.expiresAt;
142
+ oldestKey = key;
143
+ }
144
+ }
145
+ if (oldestKey !== void 0) this._store.delete(oldestKey);
146
+ }
147
+ };
148
+
149
+ // src/utils.ts
150
+ var REDACTED = "***";
151
+ var SECRET_QUERY_KEYS_RE = /([?&])(key|api_key|apikey|token)=([^&]+)/gi;
152
+ var BEARER_RE = /bearer\s+[ap0-9a-z_]+/gi;
153
+ var ASSET_RE = /^[A-Za-z0-9_]{2,40}$/;
154
+ var TIME_RE = /^\d{1,2}:\d{2}(:\d{2})?$/;
155
+ function redactUrl(url) {
156
+ if (!url) return url ?? null;
157
+ return url.replace(BEARER_RE, `Bearer ${REDACTED}`).replace(
158
+ SECRET_QUERY_KEYS_RE,
159
+ (_m, lead, name) => `${lead}${name}=${REDACTED}`
160
+ );
161
+ }
162
+ function normalizeAsset(asset2) {
163
+ return asset2.trim();
164
+ }
165
+ function isValidAsset(asset2) {
166
+ return ASSET_RE.test(normalizeAsset(asset2));
167
+ }
168
+ function isValidTime(value) {
169
+ return TIME_RE.test(value.trim());
170
+ }
171
+ function coerceBoolStr(value) {
172
+ if (typeof value === "boolean") return value ? "true" : "false";
173
+ return String(value).toLowerCase();
174
+ }
175
+
176
+ // src/errors.ts
177
+ var ALLError = class extends Error {
178
+ /** Short machine-readable code (e.g. `rate_limited`). */
179
+ code = "all_error";
180
+ /** HTTP status code when the error came from a response. */
181
+ status;
182
+ /** Parsed JSON body of the failing response, when present. */
183
+ payload;
184
+ /** Request URL with any credentials redacted. */
185
+ url;
186
+ /** Server-provided request id when available. */
187
+ requestId;
188
+ constructor(message, opts = {}) {
189
+ super(message);
190
+ this.name = new.target.name;
191
+ this.message = message;
192
+ this.status = opts.status ?? null;
193
+ this.payload = opts.payload ?? {};
194
+ this.url = redactUrl(opts.url ?? null);
195
+ this.requestId = opts.requestId ?? null;
196
+ }
197
+ /** Return a JSON-serialisable view (URL already key-redacted). */
198
+ toDict() {
199
+ return {
200
+ error: this.code,
201
+ message: this.message,
202
+ status: this.status,
203
+ request_id: this.requestId,
204
+ url: this.url,
205
+ payload: this.payload
206
+ };
207
+ }
208
+ };
209
+ var ConfigurationError = class extends ALLError {
210
+ code = "configuration_error";
211
+ };
212
+ var AuthenticationError = class extends ALLError {
213
+ code = "authentication_error";
214
+ };
215
+ var PermissionDeniedError = class extends ALLError {
216
+ code = "permission_denied";
217
+ };
218
+ var NotFoundError = class extends ALLError {
219
+ code = "not_found";
220
+ };
221
+ var ValidationError = class extends ALLError {
222
+ code = "validation_error";
223
+ };
224
+ var RateLimitError = class extends ALLError {
225
+ code = "rate_limited";
226
+ retryAfter;
227
+ constructor(message, opts = {}) {
228
+ super(message, opts);
229
+ this.retryAfter = opts.retryAfter ?? null;
230
+ }
231
+ };
232
+ var ServerError = class extends ALLError {
233
+ code = "server_error";
234
+ };
235
+ var UpstreamError = class extends ServerError {
236
+ code = "upstream_error";
237
+ };
238
+ var TransportError = class extends ALLError {
239
+ code = "transport_error";
240
+ };
241
+ var TimeoutError = class extends ALLError {
242
+ code = "timeout";
243
+ };
244
+ var UpdateRequiredError = class extends ALLError {
245
+ code = "update_required";
246
+ installed;
247
+ latest;
248
+ /** True when `npm install alltradingapi@latest` succeeded in-process; restart to load it. */
249
+ installedNow;
250
+ constructor(message, opts = {}) {
251
+ super(message);
252
+ this.installed = opts.installed ?? null;
253
+ this.latest = opts.latest ?? null;
254
+ this.installedNow = opts.installedNow ?? false;
255
+ }
256
+ };
257
+ var UpdateCheckError = class extends ALLError {
258
+ code = "update_check_error";
259
+ };
260
+ function updateHint(command = "npm install alltradingapi@latest") {
261
+ return `Run: ${command}`;
262
+ }
263
+ function errorFromResponse(status, body, url, headers = {}) {
264
+ const rawHeaders = {};
265
+ for (const [k, v] of Object.entries(headers)) rawHeaders[k.toLowerCase()] = v;
266
+ let serverText = null;
267
+ let payload = {};
268
+ try {
269
+ const decoded = JSON.parse(body.toString("utf-8"));
270
+ if (decoded && typeof decoded === "object" && !Array.isArray(decoded)) {
271
+ payload = decoded;
272
+ const err = decoded.error;
273
+ const msg2 = decoded.message;
274
+ serverText = typeof err === "string" ? err : typeof msg2 === "string" ? msg2 : null;
275
+ }
276
+ } catch {
277
+ }
278
+ const msg = (hint) => {
279
+ if (serverText && serverText !== hint) return `${hint} (server: ${serverText})`;
280
+ return hint;
281
+ };
282
+ let retryAfter = null;
283
+ const retryAfterRaw = rawHeaders["retry-after"];
284
+ if (retryAfterRaw !== void 0) {
285
+ const parsed = Number.parseFloat(retryAfterRaw);
286
+ if (Number.isFinite(parsed)) retryAfter = parsed;
287
+ }
288
+ const safeUrl = redactUrl(url) ?? url;
289
+ const base = { status, payload, url: safeUrl };
290
+ const table = {
291
+ 400: {
292
+ ctor: ValidationError,
293
+ hint: "The request was rejected (400). Check parameter names, values and ranges \u2014 this SDK validates documented parameters client-side, so a 400 usually means the server-side set changed."
294
+ },
295
+ 401: {
296
+ ctor: AuthenticationError,
297
+ hint: "A valid API key is required (401). Pass apiKey=..., build the client with a keys mapping, or set the ATA_API_KEY environment variable for the product you are calling."
298
+ },
299
+ 403: {
300
+ ctor: PermissionDeniedError,
301
+ hint: "This API key does not include this product, or the subscription is paused (403). Check your product subscription \u2014 each product needs its own key."
302
+ },
303
+ 404: {
304
+ ctor: NotFoundError,
305
+ hint: "Unknown route (404). The server exposes pretty routes only (e.g. /qx_candles); direct /api/*.php URLs are blocked by design."
306
+ },
307
+ 429: {
308
+ ctor: RateLimitError,
309
+ hint: "Rate limit reached (429). The SDK already honours Retry-After and retries automatically; slow down your polling rate or upgrade your plan.",
310
+ retryAfter: true
311
+ },
312
+ 502: {
313
+ ctor: UpstreamError,
314
+ hint: "The market feed is unavailable upstream (502) or did not return enough candles. The SDK retries automatically; if it persists, the feed itself is down \u2014 try again shortly."
315
+ }
316
+ };
317
+ if (table[status]) {
318
+ const entry = table[status];
319
+ const opts = { ...base, ...entry.retryAfter ? { retryAfter } : {} };
320
+ return new entry.ctor(msg(entry.hint), opts);
321
+ }
322
+ if (status >= 500 && status <= 599) {
323
+ return new ServerError(
324
+ msg(`Server error ${status} from the API. The SDK retries transient 5xx automatically.`),
325
+ base
326
+ );
327
+ }
328
+ return new ALLError(msg(`Unexpected HTTP status ${status} from the API.`), base);
329
+ }
330
+
331
+ // src/logging.ts
332
+ var LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
333
+ var currentLevel = LEVELS.warn;
334
+ function format(args) {
335
+ if (args.length === 0) return "";
336
+ return " " + args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
337
+ }
338
+ function stamp() {
339
+ return (/* @__PURE__ */ new Date()).toISOString();
340
+ }
341
+ function emit(level, threshold, message, rest) {
342
+ if (LEVELS[level] < threshold) return;
343
+ process.stderr.write(`${stamp()} alltradingapi ${level.toUpperCase()} ${message}${format(rest)}
344
+ `);
345
+ }
346
+ var logger = {
347
+ debug: (message, ...rest) => emit("debug", currentLevel, message, rest),
348
+ info: (message, ...rest) => emit("info", currentLevel, message, rest),
349
+ warn: (message, ...rest) => emit("warn", currentLevel, message, rest),
350
+ error: (message, ...rest) => emit("error", currentLevel, message, rest)
351
+ };
352
+ function setLogLevel(level) {
353
+ const key = String(level).toLowerCase();
354
+ currentLevel = LEVELS[key] ?? LEVELS.warn;
355
+ }
356
+ function httpDebugLine(method, url, opts = {}) {
357
+ const safeUrl = redactUrl(url) ?? "<url>";
358
+ const parts = [method, safeUrl];
359
+ if (opts.status !== void 0) parts.push(`-> ${opts.status}`);
360
+ if (opts.elapsedMs !== void 0) parts.push(`${Math.round(opts.elapsedMs)}ms`);
361
+ if (opts.attempt) parts.push(`attempt=${opts.attempt + 1}`);
362
+ return parts.join(" ");
363
+ }
364
+
365
+ // src/types.ts
366
+ function isRecordLike(value) {
367
+ return typeof value === "object" && value !== null && !Array.isArray(value);
368
+ }
369
+
370
+ // src/models/base.ts
371
+ function convert(value) {
372
+ if (isRecordLike(value)) return new APIObject(value);
373
+ if (Array.isArray(value)) return value.map((item) => convert(item));
374
+ return value;
375
+ }
376
+ function toPlain(value) {
377
+ if (isRecordLike(value)) {
378
+ const out = {};
379
+ for (const [k, v] of Object.entries(value)) out[k] = toPlain(v);
380
+ return out;
381
+ }
382
+ if (Array.isArray(value)) return value.map((item) => toPlain(item));
383
+ if (value instanceof APIObject) return toPlain(value.data);
384
+ return value;
385
+ }
386
+ var APIObject = class {
387
+ _data;
388
+ constructor(data) {
389
+ this._data = isRecordLike(data) ? { ...data } : {};
390
+ }
391
+ /** The underlying payload dict (shallow copy). */
392
+ get raw() {
393
+ return { ...this._data };
394
+ }
395
+ /** The live underlying payload dict. */
396
+ get data() {
397
+ return this._data;
398
+ }
399
+ /** Return `payload[key]` or `defaultValue`, with lazy conversion applied. */
400
+ get(key, defaultValue) {
401
+ if (key in this._data) return convert(this._data[key]);
402
+ const normalized = {};
403
+ for (const k of Object.keys(this._data)) {
404
+ normalized[k.replace(/-/g, "_").replace(/ /g, "_")] = k;
405
+ }
406
+ if (key in normalized) {
407
+ const mapped = normalized[key];
408
+ if (mapped !== void 0) return convert(this._data[mapped]);
409
+ }
410
+ return defaultValue;
411
+ }
412
+ has(key) {
413
+ return key in this._data;
414
+ }
415
+ get size() {
416
+ return Object.keys(this._data).length;
417
+ }
418
+ keys() {
419
+ return Object.keys(this._data);
420
+ }
421
+ items() {
422
+ return Object.keys(this._data).map((key) => [key, this.get(key)]);
423
+ }
424
+ [Symbol.iterator]() {
425
+ return Object.keys(this._data)[Symbol.iterator]();
426
+ }
427
+ /** Return a plain object copy that round-trips to the original payload. */
428
+ toJSON() {
429
+ return toPlain(this._data);
430
+ }
431
+ /** Build a list of instances from a bare-array payload. */
432
+ static fromRows(rows) {
433
+ if (!Array.isArray(rows)) return [];
434
+ return rows.filter(isRecordLike).map((row) => new this(row));
435
+ }
436
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
437
+ const keys = Object.keys(this._data).sort().slice(0, 8);
438
+ const more = Object.keys(this._data).length > 8 ? ", \u2026" : "";
439
+ return `<${this.constructor.name} ${keys.join(", ")}${more}>`;
440
+ }
441
+ };
442
+ var TradeOutcome = {
443
+ WIN: "win",
444
+ WIN_1: "win1",
445
+ WIN_2: "win2",
446
+ REFUND: "refund",
447
+ LOSE: "lose",
448
+ PENDING: "pending"
449
+ };
450
+ var TRADE_OUTCOME_VALUES = [
451
+ TradeOutcome.WIN,
452
+ TradeOutcome.WIN_1,
453
+ TradeOutcome.WIN_2,
454
+ TradeOutcome.REFUND,
455
+ TradeOutcome.LOSE,
456
+ TradeOutcome.PENDING
457
+ ];
458
+ function coerceOutcome(value) {
459
+ if (typeof value !== "string" && typeof value !== "number") return null;
460
+ const text = String(value);
461
+ for (const member of TRADE_OUTCOME_VALUES) {
462
+ if (text === member) return member;
463
+ if (text.toUpperCase().replace(/-/g, "_").replace(/ /g, "_") === member.toUpperCase()) {
464
+ return member;
465
+ }
466
+ }
467
+ return null;
468
+ }
469
+ function outcomeWon(value) {
470
+ return value === TradeOutcome.WIN || value === TradeOutcome.WIN_1 || value === TradeOutcome.WIN_2;
471
+ }
472
+ function outcomeLost(value) {
473
+ return value === TradeOutcome.LOSE;
474
+ }
475
+ function outcomePending(value) {
476
+ return value === TradeOutcome.PENDING;
477
+ }
478
+
479
+ // src/models/asset.ts
480
+ function intOrNone(value) {
481
+ if (value === null || value === void 0) return null;
482
+ const parsed = Number(value);
483
+ return Number.isFinite(parsed) ? Math.trunc(parsed) : null;
484
+ }
485
+ var Asset = class extends APIObject {
486
+ /** Numeric asset id (e.g. `368`). */
487
+ get id() {
488
+ return Math.trunc(Number(this._data["asset_id"] ?? 0)) || 0;
489
+ }
490
+ /** Trading symbol, e.g. `EURUSD_otc`. */
491
+ get symbol() {
492
+ return String(this._data["asset"] ?? "") || "";
493
+ }
494
+ /** Display name, e.g. `Euro / US Dollar (OTC)`. */
495
+ get name() {
496
+ return String(this._data["asset_name"] ?? "") || "";
497
+ }
498
+ /** True when the asset is open for trading right now. */
499
+ get isOpen() {
500
+ return Boolean(this._data["is_open"]);
501
+ }
502
+ /** Asset class: currency, cryptocurrency, commodity, ... */
503
+ get type() {
504
+ return String(this._data["type"] ?? "") || "";
505
+ }
506
+ /** Base payout percentage (e.g. `77`). */
507
+ get payout() {
508
+ return Math.trunc(Number(this._data["payout"] ?? 0)) || 0;
509
+ }
510
+ /** 24h change, when the market reports it. */
511
+ get change24h() {
512
+ const value = this._data["change_24h"];
513
+ if (value === null || value === void 0) return null;
514
+ const parsed = Number(value);
515
+ return Number.isFinite(parsed) ? parsed : null;
516
+ }
517
+ /** Payout for 1-minute expiry. */
518
+ get profit1m() {
519
+ const profit = this._data["profit"];
520
+ if (isRecordLike(profit)) return intOrNone(profit["1M"]);
521
+ return null;
522
+ }
523
+ /** Payout for 5-minute expiry. */
524
+ get profit5m() {
525
+ const profit = this._data["profit"];
526
+ if (isRecordLike(profit)) return intOrNone(profit["5M"]);
527
+ return null;
528
+ }
529
+ /** True when the symbol carries the `_otc` suffix. */
530
+ get isOtc() {
531
+ return this.symbol.toLowerCase().endsWith("_otc");
532
+ }
533
+ toString() {
534
+ return this.symbol;
535
+ }
536
+ };
537
+
538
+ // src/models/candle.ts
539
+ var DOJI_BODY_RATIO = 0.1;
540
+ function intOrZero(value) {
541
+ const parsed = Number(value ?? 0);
542
+ return Number.isFinite(parsed) ? Math.trunc(parsed) : 0;
543
+ }
544
+ var Candle = class extends APIObject {
545
+ /** Bar open time as unix seconds. */
546
+ get time() {
547
+ return intOrZero(this._data["time"]);
548
+ }
549
+ get open() {
550
+ return Number(this._data["open"] ?? 0) || 0;
551
+ }
552
+ get high() {
553
+ return Number(this._data["high"] ?? 0) || 0;
554
+ }
555
+ get low() {
556
+ return Number(this._data["low"] ?? 0) || 0;
557
+ }
558
+ get close() {
559
+ return Number(this._data["close"] ?? 0) || 0;
560
+ }
561
+ get ticks() {
562
+ return intOrZero(this._data["ticks"]);
563
+ }
564
+ /** Unix timestamp (with fraction) of the last tick in the bar. */
565
+ get lastTick() {
566
+ const parsed = Number(this._data["last_tick"] ?? 0);
567
+ return Number.isFinite(parsed) ? parsed : 0;
568
+ }
569
+ get asset() {
570
+ return String(this._data["asset"] ?? "") || "";
571
+ }
572
+ get assetName() {
573
+ return String(this._data["asset_name"] ?? "") || "";
574
+ }
575
+ /** Formatted bar time as the server rendered it. */
576
+ get timeRead() {
577
+ return String(this._data["time_read"] ?? "") || "";
578
+ }
579
+ // -- derived helpers ---------------------------------------------------
580
+ /** Bar open time as a JS `Date` (UTC epoch based). */
581
+ get dt() {
582
+ return new Date(this.time * 1e3);
583
+ }
584
+ /** `"call"` when bullish, `"put"` when bearish, else `"neutral"`. */
585
+ get direction() {
586
+ if (this.close > this.open) return "call";
587
+ if (this.close < this.open) return "put";
588
+ return "neutral";
589
+ }
590
+ get isBullish() {
591
+ return this.close > this.open;
592
+ }
593
+ /** Absolute open-to-close distance. */
594
+ get body() {
595
+ return Math.abs(this.close - this.open);
596
+ }
597
+ /** High-to-low distance. */
598
+ get range() {
599
+ return Math.abs(this.high - this.low);
600
+ }
601
+ /** True when the body is smaller than `threshold` of the full range. */
602
+ isDoji(threshold = DOJI_BODY_RATIO) {
603
+ const full = this.range;
604
+ if (full <= 0) return true;
605
+ return this.body / full < threshold;
606
+ }
607
+ /** Compact `(time, open, high, low, close)` row for tabular output. */
608
+ toRow() {
609
+ return {
610
+ time: this.time,
611
+ open: this.open,
612
+ high: this.high,
613
+ low: this.low,
614
+ close: this.close
615
+ };
616
+ }
617
+ };
618
+ var SavedCandles = class _SavedCandles extends APIObject {
619
+ get asset() {
620
+ return String(this._data["asset"] ?? "") || "";
621
+ }
622
+ get timeframe() {
623
+ return String(this._data["timeframe"] ?? "") || "";
624
+ }
625
+ get period() {
626
+ return intOrZero(this._data["period"]);
627
+ }
628
+ get requestedCount() {
629
+ return intOrZero(this._data["requested_count"]);
630
+ }
631
+ get returnedCount() {
632
+ return intOrZero(this._data["returned_count"]);
633
+ }
634
+ get basePeriod() {
635
+ return intOrZero(this._data["base_period"]);
636
+ }
637
+ get daysScanned() {
638
+ return intOrZero(this._data["days_scanned"]);
639
+ }
640
+ get raw5sCandles() {
641
+ return intOrZero(this._data["raw_5s_candles"]);
642
+ }
643
+ get fromCache() {
644
+ return Boolean(this._data["from_cache"]);
645
+ }
646
+ get candles() {
647
+ const rows = this._data["candles"];
648
+ if (Array.isArray(rows)) {
649
+ return rows.filter(isRecordLike).map((row) => new Candle(row));
650
+ }
651
+ return [];
652
+ }
653
+ get length() {
654
+ return this.candles.length;
655
+ }
656
+ /** Accept either the object envelope or a bare candle list. */
657
+ static fromPayload(payload) {
658
+ if (Array.isArray(payload)) return new _SavedCandles({ candles: payload });
659
+ if (isRecordLike(payload)) return new _SavedCandles(payload);
660
+ return new _SavedCandles({});
661
+ }
662
+ };
663
+
664
+ // src/models/tradeResult.ts
665
+ function intOrZero2(value) {
666
+ const parsed = Number(value ?? 0);
667
+ return Number.isFinite(parsed) ? Math.trunc(parsed) : 0;
668
+ }
669
+ var TradeResult = class extends APIObject {
670
+ get success() {
671
+ return Boolean(this._data["success"]);
672
+ }
673
+ get asset() {
674
+ return String(this._data["asset"] ?? "") || "";
675
+ }
676
+ get timeframe() {
677
+ return String(this._data["timeframe"] ?? "") || "";
678
+ }
679
+ get direction() {
680
+ return String(this._data["direction"] ?? "") || "";
681
+ }
682
+ get mtg() {
683
+ return intOrZero2(this._data["mtg"]);
684
+ }
685
+ get entryTime() {
686
+ return String(this._data["entry_time"] ?? "") || "";
687
+ }
688
+ /** Coerced per-candle outcome values (candles that carry a status). */
689
+ get outcomes() {
690
+ const values = [];
691
+ const candles = this._data["candles"] ?? [];
692
+ if (Array.isArray(candles)) {
693
+ for (const entry of candles) {
694
+ if (isRecordLike(entry) && "status" in entry) {
695
+ const coerced = coerceOutcome(entry["status"]);
696
+ if (coerced !== null) values.push(coerced);
697
+ }
698
+ }
699
+ }
700
+ const resultValue = this.result;
701
+ if (resultValue !== null && (values.length === 0 || this.mtg > 1)) {
702
+ values.push(resultValue);
703
+ }
704
+ return values;
705
+ }
706
+ /** Raw per-check status strings from the payload. */
707
+ get checks() {
708
+ const value = this._data["checks"];
709
+ if (Array.isArray(value)) return value.map((v) => String(v));
710
+ return [];
711
+ }
712
+ get candleDirections() {
713
+ const value = this._data["candle_directions"];
714
+ if (Array.isArray(value)) return value.map((v) => String(v));
715
+ return [];
716
+ }
717
+ /** Final result coerced to a `TradeOutcome`. */
718
+ get result() {
719
+ return coerceOutcome(this._data["result"]);
720
+ }
721
+ /** Candles attached to the result (pending markers are skipped). */
722
+ get candles() {
723
+ const entries = this._data["candles"] ?? [];
724
+ if (!Array.isArray(entries)) return [];
725
+ const out = [];
726
+ for (const entry of entries) {
727
+ if (isRecordLike(entry) && "time" in entry) out.push(new Candle(entry));
728
+ }
729
+ return out;
730
+ }
731
+ /** Convenience: true when any reported outcome is a win. */
732
+ get won() {
733
+ return this.outcomes.some((o) => outcomeWon(o));
734
+ }
735
+ };
736
+
737
+ // src/params.ts
738
+ function rule(opts) {
739
+ return {
740
+ kind: opts.kind,
741
+ required: opts.required ?? false,
742
+ choices: opts.choices ?? null,
743
+ minValue: opts.minValue ?? null,
744
+ maxValue: opts.maxValue ?? null,
745
+ transform: opts.transform ?? null,
746
+ doc: opts.doc ?? ""
747
+ };
748
+ }
749
+ var str = (opts = {}) => rule({ kind: "str", ...opts });
750
+ var int = (opts = {}) => rule({ kind: "int", ...opts });
751
+ var bool = (opts = {}) => rule({ kind: "bool", ...opts });
752
+ function timeStr(value) {
753
+ if (!isValidTime(value)) {
754
+ throw new ValidationError(`Invalid time '${value}'. Expected 'HH:MM' or 'HH:MM:SS'.`);
755
+ }
756
+ return value.trim();
757
+ }
758
+ function asset(value) {
759
+ const trimmed = value.trim();
760
+ if (!isValidAsset(trimmed)) {
761
+ throw new ValidationError(
762
+ `Invalid asset '${value}'. Asset symbols look like 'EURUSD_otc' or 'AUDCAD' and must match ^[A-Za-z0-9_]{2,40}$.`
763
+ );
764
+ }
765
+ return trimmed;
766
+ }
767
+ var CANDLE_PARAMS = {
768
+ asset: str({ required: true, transform: asset, doc: "Asset symbol, e.g. EURUSD_otc." }),
769
+ account: int({ minValue: 0, maxValue: 99 }),
770
+ hours: int({ minValue: 1, maxValue: 24, doc: "Hours of history, 1..24 (default 2)." }),
771
+ timeframe: str({ choices: TIMEFRAME_LABELS }),
772
+ timezone: str({ doc: "e.g. '-3', 'UTC', 'Asia/Dhaka'." }),
773
+ offset: int({ minValue: 0, maxValue: 604800 }),
774
+ timestamp: int({ minValue: 1, maxValue: 4102444800 }),
775
+ timeout: int({ minValue: 1, maxValue: 30 }),
776
+ verbose_logging: bool(),
777
+ period: int({ minValue: 1, maxValue: 86400 })
778
+ };
779
+ var ENDPOINT_PARAMS = {
780
+ assets: {
781
+ account: int({ minValue: 0, maxValue: 99, doc: "Account selector (server-defined values)." })
782
+ },
783
+ candles: CANDLE_PARAMS,
784
+ history: CANDLE_PARAMS,
785
+ // same parameter set as candles
786
+ saved: {
787
+ asset: str({ required: true, transform: asset }),
788
+ timeframe: str({ choices: TIMEFRAME_LABELS }),
789
+ timezone: str(),
790
+ count: int({ minValue: 1, maxValue: 1e3 }),
791
+ raw: bool(),
792
+ nocache: bool()
793
+ },
794
+ screenshot: {
795
+ asset: str({ required: true, transform: asset }),
796
+ timeframe: str({ choices: TIMEFRAME_LABELS }),
797
+ timezone: str(),
798
+ time: str({ transform: timeStr }),
799
+ result: str({ doc: "Trade-result filter shown on the chart." }),
800
+ names: str({ doc: "Pattern names overlay." })
801
+ },
802
+ result: {
803
+ asset: str({ required: true, transform: asset }),
804
+ time: str({ required: true, transform: timeStr }),
805
+ timeframe: str({ choices: TIMEFRAME_LABELS }),
806
+ timezone: str(),
807
+ direction: str({ required: true, choices: ["call", "put"] }),
808
+ mtg: int({ minValue: 0, maxValue: 2 })
809
+ }
810
+ };
811
+ function allowedParams(endpoint) {
812
+ return Object.keys(ENDPOINT_PARAMS[endpoint] ?? {});
813
+ }
814
+ function validateParams(endpoint, params = {}) {
815
+ const table = ENDPOINT_PARAMS[endpoint];
816
+ if (!table) throw new ValidationError(`Unknown endpoint '${endpoint}'.`);
817
+ const unknown = Object.keys(params).filter(
818
+ (k) => !(k in table) && params[k] !== null && params[k] !== void 0
819
+ );
820
+ if (unknown.length > 0) {
821
+ throw new ValidationError(
822
+ `Unknown parameter(s) ${unknown.sort().map((u) => `'${u}'`).join(", ")} for '${endpoint}'. This API validates the exact set of documented parameters; allowed names: ${Object.keys(table).join(", ") || "(none)"}.`
823
+ );
824
+ }
825
+ const out = [];
826
+ for (const [name, ruleEntry] of Object.entries(table)) {
827
+ const value = params[name];
828
+ if (value === null || value === void 0) {
829
+ if (ruleEntry.required) {
830
+ throw new ValidationError(`Missing required parameter '${name}' for '${endpoint}'.`);
831
+ }
832
+ continue;
833
+ }
834
+ if (ruleEntry.kind === "bool" && value === false) {
835
+ continue;
836
+ }
837
+ out.push([name, serialize(name, ruleEntry, value)]);
838
+ }
839
+ return out;
840
+ }
841
+ function serialize(name, ruleEntry, value) {
842
+ if (ruleEntry.kind === "bool") {
843
+ if (typeof value !== "boolean") {
844
+ throw new ValidationError(
845
+ `Parameter '${name}' expects a boolean (true/false); got ${JSON.stringify(value)}.`
846
+ );
847
+ }
848
+ return coerceBoolStr(value);
849
+ }
850
+ if (ruleEntry.kind === "int") {
851
+ if (typeof value !== "number" || !Number.isInteger(value)) {
852
+ throw new ValidationError(
853
+ `Parameter '${name}' expects an integer; got ${JSON.stringify(value)}.`
854
+ );
855
+ }
856
+ checkRange(name, ruleEntry, value);
857
+ return String(value);
858
+ }
859
+ if (ruleEntry.kind === "float") {
860
+ if (typeof value !== "number" || Number.isNaN(value)) {
861
+ throw new ValidationError(
862
+ `Parameter '${name}' expects a number; got ${JSON.stringify(value)}.`
863
+ );
864
+ }
865
+ checkRange(name, ruleEntry, value);
866
+ return String(value);
867
+ }
868
+ if (typeof value !== "string") {
869
+ throw new ValidationError(`Parameter '${name}' expects a string; got ${JSON.stringify(value)}.`);
870
+ }
871
+ let text = value;
872
+ if (ruleEntry.transform) text = ruleEntry.transform(text);
873
+ if (ruleEntry.choices && !ruleEntry.choices.includes(text)) {
874
+ throw new ValidationError(
875
+ `Invalid ${name} '${text}'. Valid values: ${ruleEntry.choices.join(", ")}.`
876
+ );
877
+ }
878
+ return text;
879
+ }
880
+ function checkRange(name, ruleEntry, num) {
881
+ const { minValue, maxValue } = ruleEntry;
882
+ if (minValue !== null && num < minValue) {
883
+ throw new ValidationError(`Parameter '${name}' must be >= ${minValue}; got ${num}.`);
884
+ }
885
+ if (maxValue !== null && num > maxValue) {
886
+ throw new ValidationError(`Parameter '${name}' must be <= ${maxValue}; got ${num}.`);
887
+ }
888
+ }
889
+
890
+ // src/transport.ts
891
+ import http from "http";
892
+ import https from "https";
893
+ import net from "net";
894
+ import tls from "tls";
895
+ import zlib from "zlib";
896
+ import { performance } from "perf_hooks";
897
+ var BROWSER_USER_AGENTS = [
898
+ // Chrome on Windows 10/11
899
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
900
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
901
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
902
+ // Chrome on macOS
903
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
904
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
905
+ // Edge on Windows / macOS
906
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
907
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
908
+ // Firefox on Windows / macOS / Linux
909
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
910
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
911
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:133.0) Gecko/20100101 Firefox/133.0",
912
+ "Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0",
913
+ // Safari on macOS / iOS
914
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
915
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",
916
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1",
917
+ // Chrome on Android
918
+ "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36"
919
+ ];
920
+ var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
921
+ "ECONNRESET",
922
+ "ECONNREFUSED",
923
+ "EPIPE",
924
+ "ETIMEDOUT",
925
+ "EHOSTUNREACH",
926
+ "ENETUNREACH",
927
+ "EAI_AGAIN",
928
+ "ERR_SOCKET_CONNECTION_TIMEOUT",
929
+ "ERR_STREAM_PREMATURE_CLOSE",
930
+ "HPE_HEADER_OVERFLOW"
931
+ ]);
932
+ var TimeoutSignal = class extends Error {
933
+ };
934
+ function isRetryableNetworkError(err) {
935
+ if (err instanceof TimeoutSignal) return true;
936
+ if (!(err instanceof Error)) return false;
937
+ const code = err.code;
938
+ if (code && RETRYABLE_ERROR_CODES.has(code)) return true;
939
+ const message = err.message ?? "";
940
+ return /socket hang up|other side closed|connection terminated|premature close/i.test(message);
941
+ }
942
+ var Response = class {
943
+ status;
944
+ headers;
945
+ _body;
946
+ url;
947
+ elapsedMs;
948
+ constructor(status, headers, body, url, elapsedMs) {
949
+ this.status = status;
950
+ this.headers = headers;
951
+ this._body = body;
952
+ this.url = url;
953
+ this.elapsedMs = elapsedMs;
954
+ }
955
+ /** Body decoded as UTF-8 with replacement characters for bad sequences. */
956
+ get text() {
957
+ return this._body.toString("utf-8");
958
+ }
959
+ /** Parse the body as JSON (throws SyntaxError on non-JSON bodies). */
960
+ json() {
961
+ return JSON.parse(this.text);
962
+ }
963
+ get contentType() {
964
+ return this.headers["content-type"] ?? "";
965
+ }
966
+ /** Raw body bytes. */
967
+ get content() {
968
+ return this._body;
969
+ }
970
+ /** Case-insensitive header lookup. */
971
+ header(name, fallback = null) {
972
+ return this.headers[name.toLowerCase()] ?? fallback;
973
+ }
974
+ };
975
+ var Transport = class {
976
+ baseUrl;
977
+ scheme;
978
+ host;
979
+ port;
980
+ prefix;
981
+ connectTimeout;
982
+ maxRetries;
983
+ backoffFactor;
984
+ retryStatuses;
985
+ verify;
986
+ /** `null` -> a random browser User-Agent is picked per request. */
987
+ userAgent;
988
+ _agentHttp;
989
+ _agentHttps;
990
+ _agentHttpProxy;
991
+ _proxyHost;
992
+ _proxyPort;
993
+ _lastSocket = null;
994
+ constructor(opts = {}) {
995
+ const baseUrl = opts.baseUrl ?? BASE_URL;
996
+ let parsed;
997
+ try {
998
+ parsed = new URL(baseUrl);
999
+ } catch {
1000
+ throw new Error("base_url must start with http:// or https://");
1001
+ }
1002
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1003
+ throw new Error("base_url must start with http:// or https://");
1004
+ }
1005
+ this.baseUrl = baseUrl;
1006
+ this.scheme = parsed.protocol.replace(":", "");
1007
+ this.host = parsed.hostname;
1008
+ this.port = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
1009
+ this.prefix = parsed.pathname.replace(/\/+$/, "");
1010
+ this.connectTimeout = opts.connectTimeout ?? DEFAULT_CONNECT_TIMEOUT;
1011
+ this.maxRetries = Math.max(0, Math.floor(opts.maxRetries ?? DEFAULT_MAX_RETRIES));
1012
+ this.backoffFactor = Math.max(0, opts.backoffFactor ?? DEFAULT_BACKOFF_FACTOR);
1013
+ this.retryStatuses = [...opts.retryStatuses ?? DEFAULT_RETRY_STATUSES];
1014
+ this.verify = opts.verify ?? true;
1015
+ this.userAgent = opts.userAgent ?? null;
1016
+ const pool = { keepAlive: true, maxSockets: CONNECTION_POOL_SIZE, keepAliveMsecs: 3e4 };
1017
+ this._agentHttp = new http.Agent(pool);
1018
+ this._agentHttps = new https.Agent({ ...pool, rejectUnauthorized: this.verify });
1019
+ this._agentHttpProxy = new http.Agent(pool);
1020
+ const proxy = this._resolveProxy();
1021
+ this._proxyHost = proxy[0];
1022
+ this._proxyPort = proxy[1];
1023
+ }
1024
+ /** Perform `method` against `path` and return a `Response`. */
1025
+ async request(method, path3, opts = {}) {
1026
+ const verb = method.toUpperCase();
1027
+ const readTimeoutMs = (opts.timeout !== void 0 && opts.timeout !== null ? opts.timeout : DEFAULT_TIMEOUT) * 1e3;
1028
+ const extraHeaders = {};
1029
+ for (const [k, v] of Object.entries(opts.headers ?? {})) {
1030
+ extraHeaders[k.toLowerCase()] = v;
1031
+ }
1032
+ const url = this._buildUrl(path3, opts.params ?? null);
1033
+ let attempt = 0;
1034
+ const maxAttempts = this.maxRetries + 1;
1035
+ let postRetriesUsed = 0;
1036
+ let lastError = null;
1037
+ while (attempt < maxAttempts) {
1038
+ attempt += 1;
1039
+ let response;
1040
+ try {
1041
+ response = await this._sendOnce(verb, url, extraHeaders, opts.body ?? null, readTimeoutMs);
1042
+ } catch (err) {
1043
+ lastError = err;
1044
+ this._discardConnection();
1045
+ if (this._shouldRetrySocket(verb, attempt, postRetriesUsed) && isRetryableNetworkError(err)) {
1046
+ postRetriesUsed += 1;
1047
+ await this._sleepBackoff(attempt);
1048
+ continue;
1049
+ }
1050
+ throw this._networkError(err, url);
1051
+ }
1052
+ const { status } = response;
1053
+ logger.debug(
1054
+ httpDebugLine(verb, url, { status, elapsedMs: response.elapsedMs, attempt })
1055
+ );
1056
+ if (status < 400) return response;
1057
+ if (this._shouldRetryStatus(verb, status, attempt, postRetriesUsed)) {
1058
+ postRetriesUsed += 1;
1059
+ lastError = null;
1060
+ await this._sleepBackoff(attempt, response.header("retry-after"));
1061
+ continue;
1062
+ }
1063
+ throw errorFromResponse(status, response.content, url, response.headers);
1064
+ }
1065
+ if (lastError !== null) throw this._networkError(lastError, url);
1066
+ throw new ServerError(`Request failed after ${maxAttempts} attempts.`, {
1067
+ url: redactUrl(url) ?? url
1068
+ });
1069
+ }
1070
+ /** Close pooled connections. Safe to call multiple times. */
1071
+ close() {
1072
+ for (const agent of [this._agentHttp, this._agentHttps, this._agentHttpProxy]) {
1073
+ agent.destroy();
1074
+ }
1075
+ }
1076
+ // -- internals ---------------------------------------------------------
1077
+ _resolveProxy() {
1078
+ const raw = env(ENV_HTTPS_PROXY) || env(ENV_HTTP_PROXY);
1079
+ if (!raw) return ["", 0];
1080
+ const cleaned = raw.split("://").pop().replace(/\/+$/, "");
1081
+ const [host, portS] = cleaned.split(":");
1082
+ if (!host) return ["", 0];
1083
+ const port = portS !== void 0 ? Number.parseInt(portS, 10) : NaN;
1084
+ return [host, Number.isFinite(port) ? port : 80];
1085
+ }
1086
+ _buildUrl(path3, params) {
1087
+ let url = this.prefix + path3;
1088
+ if (params && params.length > 0) {
1089
+ const search = new URLSearchParams();
1090
+ for (const [name, value] of params) search.append(name, value);
1091
+ url = url + "?" + search.toString();
1092
+ }
1093
+ return url;
1094
+ }
1095
+ async _sendOnce(verb, url, extraHeaders, body, readTimeoutMs) {
1096
+ const headers = {
1097
+ "User-Agent": this.userAgent ?? BROWSER_USER_AGENTS[Math.floor(Math.random() * BROWSER_USER_AGENTS.length)] ?? "alltradingapi-js",
1098
+ "Accept-Encoding": "gzip, deflate",
1099
+ Accept: "application/json, image/png, */*",
1100
+ "Accept-Language": "en-US,en;q=0.9",
1101
+ Connection: "keep-alive",
1102
+ ...extraHeaders
1103
+ };
1104
+ if (body !== null) {
1105
+ if (!("content-length" in headers)) headers["content-length"] = String(body.length);
1106
+ headers["content-type"] = headers["content-type"] ?? "application/octet-stream";
1107
+ }
1108
+ const started = performance.now();
1109
+ const raw = await this._rawRequest(verb, url, headers, body, readTimeoutMs);
1110
+ let data = await this._readBounded(raw, url);
1111
+ const elapsed = performance.now() - started;
1112
+ const encoding = (raw.headers["content-encoding"] ?? "").toLowerCase();
1113
+ if (encoding === "gzip" && data.subarray(0, 2).toString("latin1") === "\x8B") {
1114
+ try {
1115
+ data = zlib.gunzipSync(data);
1116
+ } catch {
1117
+ }
1118
+ } else if (encoding === "deflate") {
1119
+ try {
1120
+ data = zlib.inflateSync(data);
1121
+ } catch {
1122
+ try {
1123
+ data = zlib.inflateRawSync(data);
1124
+ } catch {
1125
+ }
1126
+ }
1127
+ }
1128
+ const headerDict = {};
1129
+ for (const [name, value] of Object.entries(raw.headers)) {
1130
+ if (value === void 0) continue;
1131
+ headerDict[name.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value);
1132
+ }
1133
+ headerDict["content-length"] = String(data.length);
1134
+ return new Response(raw.statusCode ?? 0, headerDict, data, url, elapsed);
1135
+ }
1136
+ _rawRequest(verb, url, headers, body, readTimeoutMs) {
1137
+ const connectTimeoutMs = this.connectTimeout * 1e3;
1138
+ const useProxy = this._proxyHost !== "" && this.scheme === "https";
1139
+ if (this._proxyHost !== "" && this.scheme === "http") {
1140
+ const absolute = `http://${this.host}:${this.port}${url}`;
1141
+ return new Promise((resolve, reject) => {
1142
+ const req = http.request(
1143
+ absolute,
1144
+ {
1145
+ method: verb,
1146
+ headers,
1147
+ agent: this._agentHttpProxy,
1148
+ timeout: readTimeoutMs
1149
+ },
1150
+ resolve
1151
+ );
1152
+ this._wireErrors(req, connectTimeoutMs, readTimeoutMs, reject);
1153
+ req.end(body ?? void 0);
1154
+ });
1155
+ }
1156
+ if (useProxy) {
1157
+ return this._tunnel().then((tunnelSocket) => {
1158
+ const tlsSocket = tls.connect({
1159
+ socket: tunnelSocket,
1160
+ servername: this.host,
1161
+ rejectUnauthorized: this.verify
1162
+ });
1163
+ return new Promise((resolve, reject) => {
1164
+ const req = https.request(
1165
+ {
1166
+ host: this.host,
1167
+ port: this.port,
1168
+ method: verb,
1169
+ path: url,
1170
+ headers,
1171
+ agent: false,
1172
+ createConnection: () => tlsSocket,
1173
+ timeout: readTimeoutMs
1174
+ },
1175
+ resolve
1176
+ );
1177
+ this._wireErrors(req, connectTimeoutMs, readTimeoutMs, reject);
1178
+ req.end(body ?? void 0);
1179
+ });
1180
+ });
1181
+ }
1182
+ const lib = this.scheme === "https" ? https : http;
1183
+ const agent = this.scheme === "https" ? this._agentHttps : this._agentHttp;
1184
+ return new Promise((resolve, reject) => {
1185
+ const req = lib.request(
1186
+ {
1187
+ host: this.host,
1188
+ port: this.port,
1189
+ method: verb,
1190
+ path: url,
1191
+ headers,
1192
+ agent,
1193
+ timeout: readTimeoutMs
1194
+ },
1195
+ resolve
1196
+ );
1197
+ this._wireErrors(req, connectTimeoutMs, readTimeoutMs, reject);
1198
+ req.end(body ?? void 0);
1199
+ });
1200
+ }
1201
+ _wireErrors(req, connectTimeoutMs, readTimeoutMs, reject) {
1202
+ req.on("socket", (socket) => {
1203
+ this._lastSocket = socket;
1204
+ if (socket.connecting) {
1205
+ const timer = setTimeout(() => {
1206
+ socket.destroy();
1207
+ reject(new TimeoutSignal("connect timeout"));
1208
+ }, connectTimeoutMs);
1209
+ socket.once("connect", () => clearTimeout(timer));
1210
+ socket.once("error", () => clearTimeout(timer));
1211
+ socket.once("secureConnect", () => clearTimeout(timer));
1212
+ }
1213
+ });
1214
+ req.setTimeout(readTimeoutMs, () => {
1215
+ req.destroy(new TimeoutSignal("read timeout"));
1216
+ });
1217
+ req.on("error", (err) => reject(err));
1218
+ }
1219
+ _tunnel() {
1220
+ return new Promise((resolve, reject) => {
1221
+ const socket = net.connect({ host: this._proxyHost, port: this._proxyPort });
1222
+ socket.setTimeout(this.connectTimeout * 1e3, () => {
1223
+ socket.destroy();
1224
+ reject(new TimeoutSignal("proxy connect timeout"));
1225
+ });
1226
+ socket.once("error", (err) => reject(err));
1227
+ socket.once("connect", () => {
1228
+ socket.write(`CONNECT ${this.host}:${this.port} HTTP/1.1\r
1229
+ Host: ${this.host}:${this.port}\r
1230
+ \r
1231
+ `);
1232
+ });
1233
+ let buffer = "";
1234
+ const onData = (chunk) => {
1235
+ buffer += chunk.toString("latin1");
1236
+ const end = buffer.indexOf("\r\n\r\n");
1237
+ if (end === -1) return;
1238
+ socket.off("data", onData);
1239
+ socket.setTimeout(0);
1240
+ if (/^HTTP\/1\.[01] 200/.test(buffer)) {
1241
+ const rest = buffer.slice(end + 4);
1242
+ if (rest) socket.unshift(Buffer.from(rest, "latin1"));
1243
+ resolve(socket);
1244
+ } else {
1245
+ socket.destroy();
1246
+ reject(new TransportError(`Proxy CONNECT failed: ${buffer.split("\r\n")[0]}`));
1247
+ }
1248
+ };
1249
+ socket.on("data", onData);
1250
+ });
1251
+ }
1252
+ async _readBounded(raw, url) {
1253
+ const chunks = [];
1254
+ let total = 0;
1255
+ for await (const chunk of raw) {
1256
+ const buf = chunk;
1257
+ total += buf.length;
1258
+ if (total > MAX_RESPONSE_BYTES) {
1259
+ raw.destroy();
1260
+ throw new TransportError(
1261
+ `Response exceeded the ${Math.floor(MAX_RESPONSE_BYTES / (1024 * 1024))} MiB safety cap; refusing to load it into memory.`,
1262
+ { url: redactUrl(url) ?? url }
1263
+ );
1264
+ }
1265
+ chunks.push(buf);
1266
+ }
1267
+ return Buffer.concat(chunks);
1268
+ }
1269
+ _shouldRetrySocket(verb, attempt, postRetriesUsed) {
1270
+ if (verb === "POST") return postRetriesUsed < 1;
1271
+ return attempt < this.maxAttempts;
1272
+ }
1273
+ _shouldRetryStatus(verb, status, attempt, postRetriesUsed) {
1274
+ if (!this.retryStatuses.includes(status)) return false;
1275
+ if (verb === "POST") return status >= 500 && postRetriesUsed < 1;
1276
+ return attempt < this.maxAttempts;
1277
+ }
1278
+ get maxAttempts() {
1279
+ return this.maxRetries + 1;
1280
+ }
1281
+ async _sleepBackoff(attempt, retryAfter = null) {
1282
+ const delay = this._backoffDelay(attempt, retryAfter);
1283
+ if (delay > 0) {
1284
+ logger.warn(`Retrying in ${delay.toFixed(2)}s (attempt ${attempt + 1})`);
1285
+ await new Promise((resolve) => setTimeout(resolve, delay * 1e3));
1286
+ }
1287
+ }
1288
+ _backoffDelay(attempt, retryAfter = null) {
1289
+ if (retryAfter !== null) {
1290
+ const parsed = Number.parseFloat(retryAfter);
1291
+ if (Number.isFinite(parsed)) return Math.min(Math.max(0, parsed), 30);
1292
+ }
1293
+ const base = this.backoffFactor * 2 ** (attempt - 1);
1294
+ return Math.random() * base;
1295
+ }
1296
+ _networkError(err, url) {
1297
+ if (err instanceof TimeoutSignal || err instanceof Error && err.message.includes("timeout")) {
1298
+ return new TimeoutError(
1299
+ "Request timed out. Every request carries a timeout so nothing hangs; raise Client({ timeout: ... }) if the endpoint is slow.",
1300
+ { url: redactUrl(url) ?? url }
1301
+ );
1302
+ }
1303
+ const detail = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
1304
+ return new TransportError(
1305
+ `Network error: ${detail}. Check connectivity; the SDK retries transient socket errors automatically.`,
1306
+ { url: redactUrl(url) ?? url }
1307
+ );
1308
+ }
1309
+ _discardConnection() {
1310
+ if (this._lastSocket && !this._lastSocket.destroyed) {
1311
+ this._lastSocket.destroy();
1312
+ }
1313
+ this._lastSocket = null;
1314
+ }
1315
+ };
1316
+
1317
+ // src/update.ts
1318
+ import { spawnSync } from "child_process";
1319
+ import fs from "fs";
1320
+ import https2 from "https";
1321
+ import path2 from "path";
1322
+ import readline from "readline";
1323
+ var REGISTRY_CHECK_URL = NPM_REGISTRY_URL;
1324
+ var UPDATE_POLICIES = ["strict", "ask", "warn", "off"];
1325
+ function coerceUpdatePolicy(value, fallback = null) {
1326
+ if (value === null || value === void 0) return fallback;
1327
+ const text = String(value).trim().toLowerCase();
1328
+ return UPDATE_POLICIES.includes(text) ? text : fallback;
1329
+ }
1330
+ var UpdateInfo = class {
1331
+ installed;
1332
+ latest;
1333
+ isOutdated;
1334
+ checkedAt;
1335
+ source;
1336
+ /** False when the check failed / was offline (fail-open). */
1337
+ known;
1338
+ constructor(installed, latest, isOutdated2, checkedAt, source, known) {
1339
+ this.installed = installed;
1340
+ this.latest = latest;
1341
+ this.isOutdated = isOutdated2;
1342
+ this.checkedAt = checkedAt;
1343
+ this.source = source;
1344
+ this.known = known;
1345
+ }
1346
+ toDict() {
1347
+ return {
1348
+ installed: this.installed,
1349
+ latest: this.latest,
1350
+ is_outdated: this.isOutdated,
1351
+ checked_at: this.checkedAt,
1352
+ source: this.source,
1353
+ known: this.known
1354
+ };
1355
+ }
1356
+ };
1357
+ var VERSION_RE = /^\s*v?(?:(\d+)!)?(\d+(?:\.\d+)*)(?:[._-]?(a|b|c|rc|alpha|beta|pre|preview)(?:[._-]?(\d+))?)?(?:[._-]?(post|rev|r)(?:[._-]?(\d+))?)?(?:[._-]?dev(?:[._-]?(\d+))?)?(?:\+.*)?\s*$/i;
1358
+ var PRE_RANK = {
1359
+ a: 1,
1360
+ alpha: 1,
1361
+ b: 2,
1362
+ beta: 2,
1363
+ c: 3,
1364
+ pre: 3,
1365
+ preview: 3,
1366
+ rc: 3
1367
+ };
1368
+ var RELEASE_PAD = 8;
1369
+ function parseVersion(text) {
1370
+ if (text === null || text === void 0) return null;
1371
+ const match = VERSION_RE.exec(String(text));
1372
+ if (!match) return null;
1373
+ const epoch = Number.parseInt(match[1] ?? "0", 10) || 0;
1374
+ const releaseRaw = match[2] ?? "0";
1375
+ const release = releaseRaw.split(".").map((p) => Number.parseInt(p, 10) || 0);
1376
+ const padded = [...release];
1377
+ while (padded.length < RELEASE_PAD) padded.push(0);
1378
+ const preLabel = (match[3] ?? "").toLowerCase();
1379
+ const preNum = Number.parseInt(match[4] ?? "0", 10) || 0;
1380
+ let stage;
1381
+ let stageRank;
1382
+ if (preLabel) {
1383
+ stage = 1;
1384
+ stageRank = PRE_RANK[preLabel] ?? 1;
1385
+ } else {
1386
+ stage = 2;
1387
+ stageRank = 0;
1388
+ }
1389
+ const postLabel = (match[5] ?? "").toLowerCase();
1390
+ const post = postLabel ? Number.parseInt(match[6] ?? "0", 10) || 0 : 0;
1391
+ const dev = Number.parseInt(match[7] ?? "0", 10) || 0;
1392
+ const effectiveStage = dev > 0 && !preLabel ? 0 : stage;
1393
+ return [[epoch, padded, effectiveStage, stageRank, preNum, post], dev];
1394
+ }
1395
+ function compareVersions(a, b) {
1396
+ const keyA = parseVersion(a);
1397
+ const keyB = parseVersion(b);
1398
+ if (keyA === null || keyB === null) return 0;
1399
+ const [mainA, devA] = keyA;
1400
+ const [mainB, devB] = keyB;
1401
+ const mainCompare = compareArrays(mainA, mainB);
1402
+ if (mainCompare !== 0) return mainCompare < 0 ? -1 : 1;
1403
+ if (devA !== devB) return devA > devB ? -1 : 1;
1404
+ return 0;
1405
+ }
1406
+ function compareArrays(a, b) {
1407
+ if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;
1408
+ const releaseA = a[1];
1409
+ const releaseB = b[1];
1410
+ for (let j = 0; j < RELEASE_PAD; j += 1) {
1411
+ const av = releaseA[j] ?? 0;
1412
+ const bv = releaseB[j] ?? 0;
1413
+ if (av !== bv) return av < bv ? -1 : 1;
1414
+ }
1415
+ for (const idx of [2, 3, 4, 5]) {
1416
+ if (a[idx] !== b[idx]) return (a[idx] ?? 0) < (b[idx] ?? 0) ? -1 : 1;
1417
+ }
1418
+ return 0;
1419
+ }
1420
+ function isOutdated(installed, latest) {
1421
+ if (!installed || !latest) return false;
1422
+ return compareVersions(installed, latest) < 0;
1423
+ }
1424
+ async function fetchLatest(checkUrl = REGISTRY_CHECK_URL, timeout = UPDATE_CHECK_TIMEOUT) {
1425
+ try {
1426
+ const url = new URL(checkUrl);
1427
+ if (url.protocol !== "https:") return null;
1428
+ const body = await new Promise((resolve, reject) => {
1429
+ const req = https2.request(
1430
+ url,
1431
+ {
1432
+ method: "GET",
1433
+ headers: {
1434
+ "User-Agent": DEFAULT_USER_AGENT,
1435
+ Accept: "application/json",
1436
+ "Accept-Encoding": "identity",
1437
+ Connection: "close"
1438
+ },
1439
+ timeout: timeout * 1e3
1440
+ },
1441
+ (res) => {
1442
+ const chunks = [];
1443
+ let size = 0;
1444
+ res.on("data", (chunk) => {
1445
+ size += chunk.length;
1446
+ if (size > 1 << 20) {
1447
+ res.destroy();
1448
+ resolve("");
1449
+ return;
1450
+ }
1451
+ chunks.push(chunk);
1452
+ });
1453
+ res.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
1454
+ res.on("error", reject);
1455
+ }
1456
+ );
1457
+ req.setTimeout(timeout * 1e3, () => {
1458
+ req.destroy(new Error("registry check timeout"));
1459
+ });
1460
+ req.on("error", reject);
1461
+ req.end();
1462
+ });
1463
+ if (!body) return null;
1464
+ let payload;
1465
+ try {
1466
+ payload = JSON.parse(body);
1467
+ } catch {
1468
+ return null;
1469
+ }
1470
+ const record = payload;
1471
+ const version = record.version ?? record.info?.version;
1472
+ return typeof version === "string" && version ? version : null;
1473
+ } catch {
1474
+ return null;
1475
+ }
1476
+ }
1477
+ function cachePath(cacheDir2) {
1478
+ const base = cacheDir2 ?? cacheDir();
1479
+ return path2.join(base, ...UPDATE_CACHE_FILE.split("/"));
1480
+ }
1481
+ function readCache(cacheDir2) {
1482
+ try {
1483
+ const data = JSON.parse(fs.readFileSync(cachePath(cacheDir2), "utf-8"));
1484
+ if (data && typeof data === "object" && !Array.isArray(data) && "checked_at" in data) {
1485
+ return data;
1486
+ }
1487
+ } catch {
1488
+ }
1489
+ return null;
1490
+ }
1491
+ function writeCache(record, cacheDir2) {
1492
+ const target = cachePath(cacheDir2);
1493
+ try {
1494
+ fs.mkdirSync(path2.dirname(target), { recursive: true });
1495
+ const tmpPath = target + ".tmp";
1496
+ fs.writeFileSync(tmpPath, JSON.stringify(record), "utf-8");
1497
+ fs.renameSync(tmpPath, target);
1498
+ return true;
1499
+ } catch {
1500
+ return false;
1501
+ }
1502
+ }
1503
+ function resolvePolicy(explicit) {
1504
+ const envPolicy = env(ENV_UPDATE_POLICY);
1505
+ const chosen = coerceUpdatePolicy(explicit, null);
1506
+ if (chosen === null && envPolicy) return coerceUpdatePolicy(envPolicy, null) ?? "strict";
1507
+ return chosen ?? "strict";
1508
+ }
1509
+ var gateState = null;
1510
+ var gatePromise = null;
1511
+ function resetGateState() {
1512
+ gateState = null;
1513
+ gatePromise = null;
1514
+ }
1515
+ async function installedVersion(fallback = VERSION) {
1516
+ return fallback;
1517
+ }
1518
+ async function checkForUpdate(force = false, installed, opts = {}) {
1519
+ const installedVersionStr = installed ?? await installedVersion();
1520
+ if (!installedVersionStr) {
1521
+ throw new UpdateCheckError(
1522
+ "Could not determine the installed SDK version; reinstall with: npm install alltradingapi@latest"
1523
+ );
1524
+ }
1525
+ const ttlSeconds = opts.ttl ?? envFloat(ENV_UPDATE_TTL, UPDATE_CACHE_TTL);
1526
+ const current = opts.now ?? Date.now() / 1e3;
1527
+ const fetch = opts.fetcher ?? fetchLatest;
1528
+ const checkUrl = opts.checkUrl ?? REGISTRY_CHECK_URL;
1529
+ if (!force && gateState?.info instanceof UpdateInfo && current - gateState.info.checkedAt < ttlSeconds) {
1530
+ return gateState.info;
1531
+ }
1532
+ if (!force) {
1533
+ const cached = readCache(opts.cacheDir);
1534
+ if (cached) {
1535
+ let age = ttlSeconds + 1;
1536
+ const checkedAt2 = Number(cached["checked_at"]);
1537
+ if (Number.isFinite(checkedAt2)) age = current - checkedAt2;
1538
+ if (age < ttlSeconds) {
1539
+ const latest2 = typeof cached["latest"] === "string" ? cached["latest"] : null;
1540
+ return new UpdateInfo(
1541
+ installedVersionStr,
1542
+ latest2,
1543
+ isOutdated(installedVersionStr, latest2),
1544
+ checkedAt2 || 0,
1545
+ typeof cached["source"] === "string" ? cached["source"] : "cache",
1546
+ Boolean(latest2)
1547
+ );
1548
+ }
1549
+ }
1550
+ }
1551
+ const latest = await fetch(checkUrl, UPDATE_CHECK_TIMEOUT);
1552
+ const checkedAt = current;
1553
+ const info = new UpdateInfo(
1554
+ installedVersionStr,
1555
+ latest,
1556
+ isOutdated(installedVersionStr, latest),
1557
+ checkedAt,
1558
+ "npm",
1559
+ Boolean(latest)
1560
+ );
1561
+ if (info.known) {
1562
+ writeCache({ checked_at: checkedAt, latest, source: "npm" }, opts.cacheDir);
1563
+ gateState = { info, blocked: gateState?.blocked ?? false, installedNow: false };
1564
+ }
1565
+ return info;
1566
+ }
1567
+ function upgradeCommand() {
1568
+ return ["npm", "install", "alltradingapi@latest"];
1569
+ }
1570
+ async function installUpdate(opts = {}) {
1571
+ const command = upgradeCommand();
1572
+ if (opts.installer) {
1573
+ const result = await opts.installer(command);
1574
+ return [result.code === 0, redactUrl(result.output ?? "") ?? ""];
1575
+ }
1576
+ try {
1577
+ const [command0, ...commandRest] = command;
1578
+ const completed = spawnSync(command0 ?? "npm", commandRest, {
1579
+ shell: process.platform === "win32",
1580
+ timeout: opts.timeout ?? 3e5,
1581
+ encoding: "utf-8"
1582
+ });
1583
+ const output = `${completed.stdout ?? ""}${completed.stderr ?? ""}`.trim();
1584
+ const tail = output.length > 800 ? output.slice(-800) : output;
1585
+ return [completed.status === 0, redactUrl(tail) ?? ""];
1586
+ } catch (err) {
1587
+ return [false, `npm failed: ${redactUrl(String(err))}`];
1588
+ }
1589
+ }
1590
+ async function timedInput(timeout = 30) {
1591
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
1592
+ const answer = await new Promise((resolve) => {
1593
+ const timer = setTimeout(() => {
1594
+ rl.close();
1595
+ resolve(null);
1596
+ }, timeout * 1e3);
1597
+ rl.question("", (text) => {
1598
+ clearTimeout(timer);
1599
+ rl.close();
1600
+ resolve(text);
1601
+ });
1602
+ rl.on("close", () => {
1603
+ clearTimeout(timer);
1604
+ resolve(null);
1605
+ });
1606
+ });
1607
+ return answer;
1608
+ }
1609
+ function printNotice(lines, printer) {
1610
+ const width = Math.max(...lines.map((l) => l.length)) + 2;
1611
+ printer("-".repeat(width));
1612
+ for (const line of lines) printer(line);
1613
+ printer("-".repeat(width));
1614
+ }
1615
+ async function runGate(installed, opts) {
1616
+ const effective = resolvePolicy(opts.policy);
1617
+ const allowOutdated = opts.allowOutdated ?? false;
1618
+ const policy = allowOutdated && (effective === "strict" || effective === "ask") ? "warn" : effective;
1619
+ if (policy === "off") return { info: null, blocked: false, installedNow: false };
1620
+ const info = await checkForUpdate(false, installed, {
1621
+ checkUrl: opts.checkUrl,
1622
+ cacheDir: opts.cacheDir,
1623
+ ttl: opts.ttl,
1624
+ now: opts.now ?? void 0,
1625
+ fetcher: opts.fetcher ?? void 0
1626
+ });
1627
+ if (!info.isOutdated || !info.known) return { info, blocked: false, installedNow: false };
1628
+ const emit2 = opts.printer ?? ((text) => process.stderr.write(text + "\n"));
1629
+ const notify = () => {
1630
+ emit2(
1631
+ `alltradingapi: a newer SDK is available (${info.installed} -> ${info.latest}). Run: npm install alltradingapi@latest`
1632
+ );
1633
+ };
1634
+ if (policy === "warn") {
1635
+ logger.info(`update available: ${info.installed} -> ${info.latest} (policy=warn)`);
1636
+ notify();
1637
+ return { info, blocked: false, installedNow: false };
1638
+ }
1639
+ const isInteractiveMode = opts.interactive ?? isInteractive();
1640
+ logger.info(
1641
+ `update available: ${info.installed} -> ${info.latest} (policy=${policy} interactive=${isInteractiveMode})`
1642
+ );
1643
+ if (isInteractiveMode) {
1644
+ const latestDisplay = info.latest ?? "unknown";
1645
+ printNotice(
1646
+ [
1647
+ `A newer All Trading API SDK is available: ${info.installed} -> ${latestDisplay}`,
1648
+ "This SDK requires the update to operate. Update now? [Y/n]"
1649
+ ],
1650
+ emit2
1651
+ );
1652
+ const reader = opts.inputFn ?? (async () => timedInput());
1653
+ const answer = (await reader("") ?? "").trim().toLowerCase();
1654
+ if (answer === "" || answer === "y" || answer === "yes") {
1655
+ const [ok, tail] = await installUpdate({ installer: opts.installer ?? void 0 });
1656
+ if (ok) {
1657
+ emit2(`Updated to ${info.latest}. Restart your program to load the new code.`);
1658
+ return { info, blocked: true, installedNow: true };
1659
+ }
1660
+ emit2(
1661
+ `Automatic update failed. Update manually:
1662
+ npm install alltradingapi@latest
1663
+ npm output tail:
1664
+ ${tail}`
1665
+ );
1666
+ return { info, blocked: true, installedNow: false };
1667
+ }
1668
+ if (policy === "ask") {
1669
+ logger.warn("update declined; continuing (policy=ask)");
1670
+ notify();
1671
+ return { info, blocked: false, installedNow: false };
1672
+ }
1673
+ return { info, blocked: true, installedNow: false };
1674
+ }
1675
+ return { info, blocked: true, installedNow: false };
1676
+ }
1677
+ async function ensureUsable(installed, opts = {}) {
1678
+ if (gateState) {
1679
+ if (gateState.blocked) throw buildError(gateState.info, false);
1680
+ return gateState.info;
1681
+ }
1682
+ if (envBool(ENV_SKIP_UPDATE)) return null;
1683
+ if (!gatePromise) gatePromise = runGate(installed, opts);
1684
+ let state;
1685
+ try {
1686
+ state = await gatePromise;
1687
+ } catch (err) {
1688
+ gatePromise = null;
1689
+ throw err;
1690
+ }
1691
+ gateState = state;
1692
+ gatePromise = null;
1693
+ if (state.blocked) throw buildError(state.info, state.installedNow);
1694
+ return state.info;
1695
+ }
1696
+ function buildError(info, installedNow) {
1697
+ const latest = info?.latest ?? "the latest version";
1698
+ const current = info?.installed ?? "the installed version";
1699
+ if (installedNow) {
1700
+ return new UpdateRequiredError(
1701
+ `Updated to ${latest} successfully, but this process still runs the old code (${current}). Restart your program to load the updated SDK.`,
1702
+ { installed: current, latest: info?.latest ?? null, installedNow: true }
1703
+ );
1704
+ }
1705
+ return new UpdateRequiredError(
1706
+ `A newer All Trading API SDK is required: installed ${current} but ${latest} is available. This SDK refuses to operate when outdated.
1707
+ Update now:
1708
+ npm install alltradingapi@latest
1709
+ Escape hatches (documented, not silent): set ATA_UPDATE_POLICY=off, ATA_SKIP_UPDATE=1, or pass new Client({ allowOutdated: true }).`,
1710
+ { installed: current, latest: info?.latest ?? null, installedNow: false }
1711
+ );
1712
+ }
1713
+
1714
+ // src/client.ts
1715
+ var ROUTES = {
1716
+ assets: "/qx_assets",
1717
+ candles: "/qx_candles",
1718
+ history: "/qx_history",
1719
+ saved: "/qx_saved",
1720
+ screenshot: "/qx_ss_pro_v2",
1721
+ result: "/qx_result"
1722
+ };
1723
+ var PRODUCTS = {
1724
+ assets: "quotex-assets",
1725
+ candles: "quotex-quotes",
1726
+ history: "quotex-realtime",
1727
+ saved: "quotex-saved",
1728
+ screenshot: "quotex-screenshots",
1729
+ result: "quotex-results"
1730
+ };
1731
+ var Client = class _Client {
1732
+ _keys = {};
1733
+ _authMode;
1734
+ _cacheTtl;
1735
+ _cache;
1736
+ _updatePolicy;
1737
+ _allowOutdated;
1738
+ _interactive;
1739
+ _updateHooks = [];
1740
+ _gatePromise = null;
1741
+ _maxConcurrency;
1742
+ _transport;
1743
+ _closed = false;
1744
+ constructor(options = {}) {
1745
+ const authMode = options.authMode ?? DEFAULT_AUTH_MODE;
1746
+ if (authMode !== "bearer" && authMode !== "query") {
1747
+ throw new ConfigurationError(
1748
+ "authMode must be 'bearer' (recommended: keeps keys out of URLs and logs) or 'query'."
1749
+ );
1750
+ }
1751
+ if (options.keys) {
1752
+ for (const [product, key] of Object.entries(options.keys)) {
1753
+ if (!key) continue;
1754
+ this._keys[product] = key;
1755
+ }
1756
+ }
1757
+ if (options.apiKey) this._keys["__constructor__"] = options.apiKey;
1758
+ this._authMode = authMode;
1759
+ this._cacheTtl = options.cacheTtl ?? DEFAULT_CACHE_TTL;
1760
+ this._cache = new TTLCache(this._cacheTtl);
1761
+ this._updatePolicy = options.updatePolicy;
1762
+ this._allowOutdated = options.allowOutdated ?? false;
1763
+ this._interactive = options.interactive ?? null;
1764
+ this._maxConcurrency = Math.max(1, Math.floor(options.maxConcurrency ?? 8));
1765
+ this._transport = options.transport ?? new Transport({
1766
+ baseUrl: options.baseUrl ?? BASE_URL,
1767
+ connectTimeout: options.connectTimeout,
1768
+ maxRetries: options.maxRetries,
1769
+ backoffFactor: options.backoffFactor,
1770
+ retryStatuses: options.retryStatuses,
1771
+ userAgent: options.userAgent ?? null
1772
+ });
1773
+ }
1774
+ // ------------------------------------------------------------------
1775
+ // Lifecycle
1776
+ // ------------------------------------------------------------------
1777
+ /** Build a client from environment configuration (ATA_* variables). */
1778
+ static fromEnv(options = {}) {
1779
+ return new _Client({
1780
+ ...options,
1781
+ apiKey: options.apiKey ?? process.env[ENV_API_KEY] ?? void 0
1782
+ });
1783
+ }
1784
+ close() {
1785
+ if (!this._closed) {
1786
+ this._transport.close();
1787
+ this._closed = true;
1788
+ }
1789
+ }
1790
+ // ------------------------------------------------------------------
1791
+ // Update gate & info
1792
+ // ------------------------------------------------------------------
1793
+ /** Installed SDK version string. */
1794
+ get version() {
1795
+ return VERSION;
1796
+ }
1797
+ _runGate() {
1798
+ if (!this._gatePromise) {
1799
+ this._gatePromise = ensureUsable(this.version, {
1800
+ policy: this._updatePolicy,
1801
+ allowOutdated: this._allowOutdated,
1802
+ interactive: this._interactive
1803
+ }).then((info) => {
1804
+ if (info !== null && info.isOutdated) {
1805
+ for (const hook of this._updateHooks) {
1806
+ Promise.resolve().then(() => hook(info)).catch((err) => logger.debug(`update hook raised: ${String(err)}`));
1807
+ }
1808
+ }
1809
+ }).catch((err) => {
1810
+ this._gatePromise = null;
1811
+ throw err;
1812
+ });
1813
+ }
1814
+ return this._gatePromise;
1815
+ }
1816
+ /** Register a callback receiving `UpdateInfo` when a newer SDK exists. */
1817
+ onUpdateAvailable(callback) {
1818
+ this._updateHooks.push(callback);
1819
+ }
1820
+ /** Return `UpdateInfo`; never throws for network issues. */
1821
+ async checkUpdates(force = false) {
1822
+ try {
1823
+ return await checkForUpdate(force, this.version);
1824
+ } catch (err) {
1825
+ if (err instanceof ALLError) throw err;
1826
+ logger.debug(`update check failed: ${String(err)}`);
1827
+ return new UpdateInfo(this.version, null, false, 0, "error", false);
1828
+ }
1829
+ }
1830
+ // ------------------------------------------------------------------
1831
+ // Key resolution
1832
+ // ------------------------------------------------------------------
1833
+ _resolveKey(call, apiKey) {
1834
+ if (apiKey) return apiKey;
1835
+ const product = PRODUCTS[call];
1836
+ if (product !== void 0 && Object.hasOwn(this._keys, product)) {
1837
+ return this._keys[product];
1838
+ }
1839
+ if (Object.hasOwn(this._keys, "default")) return this._keys["default"];
1840
+ if (Object.hasOwn(this._keys, "__constructor__")) return this._keys["__constructor__"];
1841
+ const envDefault = process.env[ENV_API_KEY];
1842
+ if (envDefault) return envDefault;
1843
+ if (product !== void 0) {
1844
+ const envProduct = process.env[ENV_KEY_PREFIX + product.toUpperCase().replace(/-/g, "_")];
1845
+ if (envProduct) return envProduct;
1846
+ }
1847
+ throw new AuthenticationError(
1848
+ `No API key available for '${call}'. Pass apiKey=..., build the client with keys={{ '${product ?? "default"}': 'ap_...' }}, or set the environment variable ATA_API_KEY (or ATA_KEY_${(product ?? "DEFAULT").toUpperCase().replace(/-/g, "_")}). Each product needs its own key from https://alltradingapi.com.`
1849
+ );
1850
+ }
1851
+ async _request(call, opts = {}) {
1852
+ await this._runGate();
1853
+ const key = this._resolveKey(call, opts.apiKey);
1854
+ const headers = { ...opts.headers ?? {} };
1855
+ const query = [...opts.params ?? []];
1856
+ if (this._authMode === "bearer") {
1857
+ headers["Authorization"] = `Bearer ${key}`;
1858
+ } else {
1859
+ query.push(["key", key]);
1860
+ }
1861
+ const path3 = ROUTES[call];
1862
+ if (path3 === void 0) {
1863
+ throw new ConfigurationError(`Unknown endpoint '${call}'.`);
1864
+ }
1865
+ return this._transport.request(opts.method ?? "GET", path3, {
1866
+ params: query,
1867
+ headers,
1868
+ timeout: opts.timeout ?? null
1869
+ });
1870
+ }
1871
+ async _cachedJson(cacheKey, call, opts) {
1872
+ if (!opts.refresh) {
1873
+ const hit = this._cache.get(cacheKey);
1874
+ if (hit !== void 0) return hit;
1875
+ }
1876
+ const response = await this._request(call, { params: opts.params, apiKey: opts.apiKey });
1877
+ const payload = response.json();
1878
+ this._cache.put(cacheKey, payload);
1879
+ return payload;
1880
+ }
1881
+ /** Drop all client-side cached responses. */
1882
+ clearCache() {
1883
+ this._cache.clear();
1884
+ }
1885
+ // ------------------------------------------------------------------
1886
+ // Asset data
1887
+ // ------------------------------------------------------------------
1888
+ /** List every tradable asset with open/closed state and payouts. */
1889
+ async assets(options = {}) {
1890
+ const { onlyOpen = false, refresh = false, account = null, apiKey } = options;
1891
+ const params = validateParams("assets", { account });
1892
+ const key = ["assets", JSON.stringify(params), String(refresh), this._authMode].join("\0");
1893
+ const payload = await this._cachedJson(key, "assets", { refresh, params, apiKey });
1894
+ const rows = Array.isArray(payload) ? payload : [];
1895
+ let assets = Asset.fromRows(rows);
1896
+ if (onlyOpen) assets = assets.filter((a) => a.isOpen);
1897
+ return assets;
1898
+ }
1899
+ // ------------------------------------------------------------------
1900
+ // Candles
1901
+ // ------------------------------------------------------------------
1902
+ /** Fetch recent candles for `asset` (default ~2h of 1m bars). */
1903
+ candles(asset2, options = {}) {
1904
+ return this._candles("candles", asset2, options);
1905
+ }
1906
+ /** Fetch candle history for `asset` (same parameters as candles). */
1907
+ history(asset2, options = {}) {
1908
+ return this._candles("history", asset2, options);
1909
+ }
1910
+ async _candles(call, asset2, options) {
1911
+ const { apiKey, verboseLogging, ...rest } = options;
1912
+ const params = validateParams(call, {
1913
+ asset: asset2,
1914
+ ...rest,
1915
+ verbose_logging: verboseLogging
1916
+ });
1917
+ const response = await this._request(call, {
1918
+ params,
1919
+ apiKey,
1920
+ timeout: effectiveTimeout(rest.timeout)
1921
+ });
1922
+ const rows = response.json();
1923
+ return Candle.fromRows(Array.isArray(rows) ? rows : []);
1924
+ }
1925
+ // ------------------------------------------------------------------
1926
+ // Saved candles
1927
+ // ------------------------------------------------------------------
1928
+ /** Fetch server-side saved candles (scanned from the 5s archive). */
1929
+ async saved(asset2, options = {}) {
1930
+ const { apiKey, ...rest } = options;
1931
+ const params = validateParams("saved", { asset: asset2, ...rest });
1932
+ const response = await this._request("saved", { params, apiKey });
1933
+ return SavedCandles.fromPayload(response.json());
1934
+ }
1935
+ // ------------------------------------------------------------------
1936
+ // Chart screenshots
1937
+ // ------------------------------------------------------------------
1938
+ /** Download a chart screenshot (PNG bytes) for `asset`. */
1939
+ async screenshot(asset2, options = {}) {
1940
+ const { apiKey, ...rest } = options;
1941
+ const params = validateParams("screenshot", { asset: asset2, ...rest });
1942
+ const response = await this._request("screenshot", { params, apiKey });
1943
+ if (!response.contentType.startsWith("image/")) {
1944
+ throw new ALLError(
1945
+ `Expected an image from /qx_ss_pro_v2 but got Content-Type '${response.contentType}' (status ${response.status}). The server may have returned an error; check the asset/time parameter values.`,
1946
+ { status: response.status, url: redactUrl(response.url) ?? response.url }
1947
+ );
1948
+ }
1949
+ return response.content;
1950
+ }
1951
+ // ------------------------------------------------------------------
1952
+ // Trade result
1953
+ // ------------------------------------------------------------------
1954
+ /** Check a past trade entry (call/put at HH:MM) and its outcome(s). */
1955
+ async result(asset2, options) {
1956
+ const { apiKey, ...rest } = options;
1957
+ const params = validateParams("result", { asset: asset2, ...rest });
1958
+ const response = await this._request("result", { params, apiKey });
1959
+ return new TradeResult(response.json());
1960
+ }
1961
+ // ------------------------------------------------------------------
1962
+ // Fan-out
1963
+ // ------------------------------------------------------------------
1964
+ /**
1965
+ * Fetch candles for many assets concurrently; per-asset failures never
1966
+ * abort. Returns `{ [symbol]: Candle[] | Error }`.
1967
+ */
1968
+ async scan(symbols, options = {}) {
1969
+ const list = [...symbols];
1970
+ const { concurrency, ...candleOptions } = options;
1971
+ const limit = Math.max(1, Math.min(this._maxConcurrency, concurrency ?? this._maxConcurrency));
1972
+ const results = {};
1973
+ let index = 0;
1974
+ const workers = [];
1975
+ for (let w = 0; w < Math.min(limit, list.length); w += 1) {
1976
+ workers.push(
1977
+ (async () => {
1978
+ while (index < list.length) {
1979
+ const current = index;
1980
+ index += 1;
1981
+ const symbol = list[current];
1982
+ if (symbol === void 0) break;
1983
+ try {
1984
+ results[symbol] = await this.candles(symbol, candleOptions);
1985
+ } catch (err) {
1986
+ results[symbol] = err instanceof Error ? err : new Error(String(err));
1987
+ }
1988
+ }
1989
+ })()
1990
+ );
1991
+ }
1992
+ await Promise.all(workers);
1993
+ return results;
1994
+ }
1995
+ };
1996
+ function effectiveTimeout(paramTimeout) {
1997
+ if (paramTimeout === null || paramTimeout === void 0) return null;
1998
+ return paramTimeout + 5;
1999
+ }
2000
+ var AsyncClient = class extends Client {
2001
+ };
2002
+ export {
2003
+ ALLError,
2004
+ APIObject,
2005
+ Asset,
2006
+ AsyncClient,
2007
+ AuthenticationError,
2008
+ Candle,
2009
+ Client,
2010
+ ConfigurationError,
2011
+ NotFoundError,
2012
+ PermissionDeniedError,
2013
+ RateLimitError,
2014
+ Response,
2015
+ SavedCandles,
2016
+ ServerError,
2017
+ TTLCache,
2018
+ TimeoutError,
2019
+ TradeOutcome,
2020
+ TradeResult,
2021
+ Transport,
2022
+ TransportError,
2023
+ UPDATE_POLICIES,
2024
+ UpdateCheckError,
2025
+ UpdateInfo,
2026
+ UpdateRequiredError,
2027
+ UpstreamError,
2028
+ ValidationError,
2029
+ VERSION as __version,
2030
+ allowedParams,
2031
+ checkForUpdate,
2032
+ coerceOutcome,
2033
+ coerceUpdatePolicy,
2034
+ compareVersions,
2035
+ ensureUsable,
2036
+ fetchLatest,
2037
+ installUpdate,
2038
+ isOutdated,
2039
+ logger,
2040
+ outcomeLost,
2041
+ outcomePending,
2042
+ outcomeWon,
2043
+ parseVersion,
2044
+ redactUrl,
2045
+ resetGateState,
2046
+ resolvePolicy,
2047
+ setLogLevel,
2048
+ updateHint,
2049
+ upgradeCommand,
2050
+ isValidAsset as validateAsset,
2051
+ validateParams
2052
+ };
2053
+ //# sourceMappingURL=index.mjs.map