atlaas 0.1.1 → 0.3.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.js CHANGED
@@ -5,32 +5,42 @@ var AtlasError = class extends Error {
5
5
  statusCode;
6
6
  errorCode;
7
7
  requestId;
8
- constructor(message, statusCode = 0, errorCode, requestId) {
8
+ code;
9
+ retryable;
10
+ brokerCode;
11
+ replayed;
12
+ body;
13
+ constructor(message, statusCode = 0, errorCode, requestId, details = {}) {
9
14
  super(message);
10
15
  this.name = "AtlasError";
11
16
  this.statusCode = statusCode;
12
17
  this.errorCode = errorCode;
13
18
  this.requestId = requestId;
19
+ this.code = details.code;
20
+ this.retryable = details.retryable;
21
+ this.brokerCode = details.brokerCode;
22
+ this.replayed = details.replayed;
23
+ this.body = details.body;
14
24
  }
15
25
  };
16
26
  var AtlasAuthError = class extends AtlasError {
17
- constructor(message, requestId) {
18
- super(message, 401, void 0, requestId);
27
+ constructor(message, requestId, details) {
28
+ super(message, 401, void 0, requestId, details);
19
29
  this.name = "AtlasAuthError";
20
30
  }
21
31
  };
22
32
  var AtlasRateLimitError = class extends AtlasError {
23
33
  retryAfter;
24
- constructor(message, retryAfter, requestId) {
25
- super(message, 429, void 0, requestId);
34
+ constructor(message, retryAfter, requestId, details) {
35
+ super(message, 429, void 0, requestId, details);
26
36
  this.name = "AtlasRateLimitError";
27
37
  this.retryAfter = retryAfter;
28
38
  }
29
39
  };
30
40
  var AtlasValidationError = class extends AtlasError {
31
41
  fields;
32
- constructor(message, fields, requestId) {
33
- super(message, 400, void 0, requestId);
42
+ constructor(message, fields, requestId, details) {
43
+ super(message, 400, void 0, requestId, details);
34
44
  this.name = "AtlasValidationError";
35
45
  this.fields = fields;
36
46
  }
@@ -45,6 +55,8 @@ var AtlasNetworkError = class extends AtlasError {
45
55
  };
46
56
 
47
57
  // src/http.ts
58
+ var REPLAYED_HEADER = "Idempotent-Replayed";
59
+ var MAX_RETRY_DELAY_MS = 1e4;
48
60
  function buildUrl(baseUrl, path, query) {
49
61
  const url = new URL(path, baseUrl);
50
62
  if (query) {
@@ -56,12 +68,42 @@ function buildUrl(baseUrl, path, query) {
56
68
  }
57
69
  return url.toString();
58
70
  }
59
- function isRetryable(status) {
60
- return status >= 500 || status === 408 || status === 429;
61
- }
62
71
  function jitter(base) {
63
72
  return base * (0.5 + Math.random() * 0.5);
64
73
  }
74
+ function isRead(method) {
75
+ const m = method.toUpperCase();
76
+ return m === "GET" || m === "HEAD";
77
+ }
78
+ function errorDetails(body, replayed) {
79
+ if (!body) return { replayed };
80
+ if (typeof body.error === "object" && body.error !== null) {
81
+ return { code: body.error.code, retryable: body.error.retryable, brokerCode: body.error.brokerCode, replayed, body };
82
+ }
83
+ return { code: body.code, replayed, body };
84
+ }
85
+ function errorMessage(status, body, text) {
86
+ if (body) {
87
+ if (typeof body.error === "object" && body.error !== null) return body.error.message ?? body.message ?? `Request failed with status ${status}`;
88
+ if (typeof body.message === "string" && body.error === "rate_limited") return body.message;
89
+ if (typeof body.error === "string") return body.error;
90
+ }
91
+ const snippet = text.trim().slice(0, 200);
92
+ return snippet ? `Request failed with status ${status}: ${snippet}` : `Request failed with status ${status}`;
93
+ }
94
+ function shouldRetry(method, idempotent, error) {
95
+ const replaySafe = isRead(method) || idempotent;
96
+ if (error.replayed) return false;
97
+ if (error.code === "OUTCOME_UNKNOWN") return false;
98
+ if (error instanceof AtlasNetworkError) return replaySafe;
99
+ if (error.statusCode === 429 && error.body !== void 0 && error.body.error === "rate_limited") return true;
100
+ if (error.retryable !== void 0) return error.retryable && replaySafe;
101
+ if (error.code === "IDEMPOTENCY_IN_PROGRESS" || error.code === "IDEMPOTENCY_UNAVAILABLE") return true;
102
+ if (error.statusCode === 504) return isRead(method);
103
+ if (error.statusCode === 501) return false;
104
+ if (error.statusCode >= 500 || error.statusCode === 408 || error.statusCode === 429) return replaySafe;
105
+ return false;
106
+ }
65
107
  var HttpTransport = class {
66
108
  baseUrl;
67
109
  apiKey;
@@ -75,67 +117,252 @@ var HttpTransport = class {
75
117
  this.maxRetries = options.maxRetries ?? 2;
76
118
  this.logger = options.logger;
77
119
  }
120
+ /** The `data` of a successful response. */
78
121
  async request(options) {
122
+ return (await this.requestEnvelope(options)).data;
123
+ }
124
+ /** The whole successful body, with any freshness fields beside `data`. */
125
+ async requestEnvelope(options) {
79
126
  const url = buildUrl(this.baseUrl, options.path, options.query);
127
+ const idempotencyKey = options.idempotencyKey ?? (isRead(options.method) ? void 0 : globalThis.crypto.randomUUID());
80
128
  let lastError;
81
129
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
82
130
  if (attempt > 0) {
83
- const delay = jitter(Math.min(1e3 * 2 ** (attempt - 1), 1e4));
131
+ const backoff = jitter(Math.min(1e3 * 2 ** (attempt - 1), MAX_RETRY_DELAY_MS));
132
+ const retryAfterMs = lastError instanceof AtlasRateLimitError && lastError.retryAfter !== void 0 ? lastError.retryAfter * 1e3 : 0;
133
+ const delay = Math.max(backoff, retryAfterMs);
84
134
  this.logger?.debug?.(`Retry attempt ${attempt} after ${Math.round(delay)}ms`, { url, attempt });
85
135
  await new Promise((resolve) => setTimeout(resolve, delay));
86
136
  }
87
- const controller = new AbortController();
88
- const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
89
137
  try {
90
- const response = await fetch(url, {
91
- method: options.method,
92
- headers: {
93
- "Content-Type": "application/json",
94
- Authorization: `Bearer ${this.apiKey}`
95
- },
96
- body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
97
- signal: options.signal ?? controller.signal
98
- });
99
- clearTimeout(timeout);
100
- if (response.status === 429) {
101
- const retryAfter = response.headers.get("Retry-After");
102
- if (attempt < this.maxRetries) {
103
- lastError = new AtlasRateLimitError("Rate limited", retryAfter ? Number(retryAfter) : void 0);
104
- continue;
105
- }
106
- throw new AtlasRateLimitError("Rate limited", retryAfter ? Number(retryAfter) : void 0);
107
- }
108
- const body = await response.json();
109
- if (!body.success) {
110
- const err = body;
111
- throw this.mapError(response.status, err.error, err.errorCode);
112
- }
113
- return body.data;
138
+ return await this.attempt(url, options, idempotencyKey);
114
139
  } catch (error) {
115
- clearTimeout(timeout);
116
- if (error instanceof AtlasError) {
117
- if (isRetryable(error.statusCode) && attempt < this.maxRetries) {
118
- lastError = error;
119
- continue;
120
- }
121
- throw error;
122
- }
123
- if (error instanceof DOMException && error.name === "AbortError") {
124
- lastError = new AtlasNetworkError("Request timed out", error);
125
- if (attempt < this.maxRetries) continue;
126
- throw lastError;
127
- }
128
- lastError = new AtlasNetworkError(error instanceof Error ? error.message : "Network request failed", error);
129
- if (attempt < this.maxRetries) continue;
130
- throw lastError;
140
+ if (!(error instanceof AtlasError)) throw error;
141
+ lastError = error;
142
+ const canRetry = attempt < this.maxRetries && shouldRetry(options.method, options.idempotent === true, error);
143
+ const waitTooLong = error instanceof AtlasRateLimitError && error.retryAfter !== void 0 && error.retryAfter * 1e3 > MAX_RETRY_DELAY_MS;
144
+ if (!canRetry || waitTooLong || options.signal?.aborted) throw error;
131
145
  }
132
146
  }
133
147
  throw lastError ?? new AtlasNetworkError("Request failed after all retries");
134
148
  }
135
- mapError(status, message, errorCode) {
136
- if (status === 401) return new AtlasAuthError(message);
137
- if (status === 400) return new AtlasValidationError(message);
138
- return new AtlasError(message, status, errorCode);
149
+ async attempt(url, options, idempotencyKey) {
150
+ const controller = new AbortController();
151
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? this.timeoutMs);
152
+ const abortOnCaller = () => controller.abort();
153
+ if (options.signal?.aborted) controller.abort();
154
+ options.signal?.addEventListener("abort", abortOnCaller, { once: true });
155
+ let response;
156
+ let text;
157
+ try {
158
+ response = await fetch(url, {
159
+ method: options.method,
160
+ headers: {
161
+ "Content-Type": "application/json",
162
+ Authorization: `Bearer ${this.apiKey}`,
163
+ ...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}
164
+ },
165
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
166
+ signal: controller.signal
167
+ });
168
+ text = await response.text();
169
+ } catch (error) {
170
+ if (error instanceof Error && error.name === "AbortError") {
171
+ throw new AtlasNetworkError(options.signal?.aborted ? "Request aborted" : "Request timed out", error);
172
+ }
173
+ throw new AtlasNetworkError(error instanceof Error ? error.message : "Network request failed", error);
174
+ } finally {
175
+ clearTimeout(timeout);
176
+ options.signal?.removeEventListener("abort", abortOnCaller);
177
+ }
178
+ let parsed = null;
179
+ if (text) {
180
+ try {
181
+ parsed = JSON.parse(text);
182
+ } catch {
183
+ parsed = null;
184
+ }
185
+ }
186
+ const body = parsed;
187
+ if (response.ok && body && body.success === true) return body;
188
+ if (response.ok && !text) return { success: true, data: void 0 };
189
+ const errBody = body && body.success === false ? body : null;
190
+ throw this.mapError(response, errBody, text);
191
+ }
192
+ mapError(response, body, text) {
193
+ const status = response.status;
194
+ const message = errorMessage(status, body, text);
195
+ const details = errorDetails(body, response.headers.get(REPLAYED_HEADER) === "true");
196
+ if (status === 401) return new AtlasAuthError(message, void 0, details);
197
+ if (status === 429) {
198
+ const header = response.headers.get("Retry-After");
199
+ const retryAfter = header !== null && Number.isFinite(Number(header)) ? Number(header) : body?.retryAfterSeconds;
200
+ return new AtlasRateLimitError(message, retryAfter, void 0, details);
201
+ }
202
+ if (status === 400) return new AtlasValidationError(message, void 0, void 0, details);
203
+ return new AtlasError(message, status, body?.errorCode, void 0, details);
204
+ }
205
+ };
206
+
207
+ // src/resources/backtests.ts
208
+ var BacktestsResource = class {
209
+ constructor(http) {
210
+ this.http = http;
211
+ }
212
+ run(runId, action) {
213
+ return `/api/external/backtests/runs/${encodeURIComponent(runId)}/${action}`;
214
+ }
215
+ group(groupId, action = "") {
216
+ return `/api/external/backtests/${encodeURIComponent(groupId)}${action ? `/${action}` : ""}`;
217
+ }
218
+ // ── Groups ────────────────────────────────────────────────────────────
219
+ /** Your backtests, newest first. Page with `nextCursor`. */
220
+ async list(query) {
221
+ return this.http.request({ method: "GET", path: "/api/external/backtests", query: { limit: query?.limit, cursor: query?.cursor } });
222
+ }
223
+ /** Queue a backtest: a single run, an optimization (`optimization`) or a
224
+ * walk-forward (`optimization` + `walkForward`). 402 when credits are short. */
225
+ async create(body) {
226
+ return this.http.request({ method: "POST", path: "/api/external/backtests", body });
227
+ }
228
+ /** Time and credits a backtest would take. Queues nothing. */
229
+ async estimate(query) {
230
+ return this.http.request({
231
+ method: "GET",
232
+ path: "/api/external/backtests/estimate",
233
+ query: {
234
+ tickMode: query.tickMode,
235
+ fromDate: query.fromDate,
236
+ toDate: query.toDate,
237
+ passes: query.passes,
238
+ folds: query.folds,
239
+ isRatio: query.isRatio,
240
+ anchored: query.anchored,
241
+ splitDate: query.splitDate,
242
+ timeframe: query.timeframe,
243
+ runs: query.runs
244
+ }
245
+ });
246
+ }
247
+ /** A group with its runs and their tester logs. */
248
+ async get(groupId) {
249
+ return this.http.request({ method: "GET", path: this.group(groupId) });
250
+ }
251
+ /** 409 while a run is still on a terminal: cancel it first. */
252
+ async delete(groupId) {
253
+ return this.http.request({ method: "DELETE", path: this.group(groupId) });
254
+ }
255
+ /** Up to 2000 characters; null clears it. */
256
+ async setNote(groupId, note) {
257
+ return this.http.request({ method: "PATCH", path: this.group(groupId, "note"), body: { note }, idempotent: true });
258
+ }
259
+ /** Pin this group as its EA's baseline. */
260
+ async setBaseline(groupId) {
261
+ return this.http.request({ method: "POST", path: this.group(groupId, "baseline"), idempotent: true });
262
+ }
263
+ /** Unpin this group if it is its EA's baseline. */
264
+ async clearBaseline(groupId) {
265
+ return this.http.request({ method: "DELETE", path: this.group(groupId, "baseline"), idempotent: true });
266
+ }
267
+ /** Unlock the out-of-sample run. Every call is counted in `oosRevealCount`. */
268
+ async revealOos(groupId) {
269
+ return this.http.request({ method: "POST", path: this.group(groupId, "reveal-oos") });
270
+ }
271
+ /** Folds, walk-forward efficiency, the stitched OOS equity and parameter stability. */
272
+ async walkForward(groupId) {
273
+ return this.http.request({ method: "GET", path: this.group(groupId, "walk-forward") });
274
+ }
275
+ // ── Several runs at once ───────────────────────────────────────────────
276
+ /** Every symbol on every timeframe as its own backtest (up to 12). */
277
+ async createBatch(body) {
278
+ return this.http.request({ method: "POST", path: "/api/external/backtests/batch", body });
279
+ }
280
+ async getBatch(batchId) {
281
+ return this.http.request({ method: "GET", path: `/api/external/backtests/batches/${encodeURIComponent(batchId)}` });
282
+ }
283
+ /** Rerun a single backtest with its numeric inputs nudged at random, to see how fragile it is. */
284
+ async createNoiseTest(body) {
285
+ return this.http.request({ method: "POST", path: "/api/external/backtests/noise-test", body });
286
+ }
287
+ /** One walk-forward per in-sample ratio and fold count (up to 9). */
288
+ async createWalkForwardMatrix(body) {
289
+ return this.http.request({ method: "POST", path: "/api/external/backtests/wf-matrix", body });
290
+ }
291
+ /** Combine 2 to 20 finished runs into one account. Changes nothing. */
292
+ async portfolio(body) {
293
+ return this.http.request({ method: "POST", path: "/api/external/backtests/portfolio", body, idempotent: true });
294
+ }
295
+ // ── One run ───────────────────────────────────────────────────────────
296
+ /** Presigned links to the result JSON and the MT5 report, valid for 10 minutes. */
297
+ async result(runId) {
298
+ return this.http.request({ method: "GET", path: this.run(runId, "result") });
299
+ }
300
+ /** Report numbers, breakdowns and compact analytics. 409 until the run is DONE. */
301
+ async stats(runId) {
302
+ return this.http.request({ method: "GET", path: this.run(runId, "stats") });
303
+ }
304
+ async trades(runId, query = {}) {
305
+ const list = (values) => values && values.length > 0 ? values.join(",") : void 0;
306
+ return this.http.request({
307
+ method: "GET",
308
+ path: this.run(runId, "trades"),
309
+ query: {
310
+ type: query.type,
311
+ outcome: query.outcome,
312
+ minProfit: query.minProfit,
313
+ maxProfit: query.maxProfit,
314
+ minDurationSec: query.minDurationSec,
315
+ maxDurationSec: query.maxDurationSec,
316
+ minR: query.minR,
317
+ maxR: query.maxR,
318
+ from: query.from,
319
+ to: query.to,
320
+ weekdays: list(query.weekdays),
321
+ hours: list(query.hours),
322
+ exitReasons: list(query.exitReasons),
323
+ commentContains: query.commentContains,
324
+ sort: query.sort,
325
+ limit: query.limit,
326
+ aggregate: query.aggregate
327
+ }
328
+ });
329
+ }
330
+ /** An optimization run's passes, best first by default. */
331
+ async passes(runId, query) {
332
+ return this.http.request({ method: "GET", path: this.run(runId, "passes"), query: { sort: query?.sort, limit: query?.limit } });
333
+ }
334
+ /** Where the run sits among your other finished runs of the same EA. */
335
+ async peer(runId) {
336
+ return this.http.request({ method: "GET", path: this.run(runId, "peer") });
337
+ }
338
+ /** Stop a queued or running run. 409 once it has finished. */
339
+ async cancel(runId) {
340
+ return this.http.request({ method: "POST", path: this.run(runId, "cancel") });
341
+ }
342
+ /** An AI summary of the run, cached; `refresh` makes a new one (at most every 10 minutes). */
343
+ async summary(runId, options) {
344
+ return this.http.request({ method: "POST", path: this.run(runId, "summary"), query: { refresh: options?.refresh ? "1" : void 0 } });
345
+ }
346
+ /** A plain-language explanation of one trade of the run. */
347
+ async explainTrade(runId, positionId) {
348
+ return this.http.request({ method: "POST", path: this.run(runId, "explain-trade"), body: { positionId } });
349
+ }
350
+ /** Rerun a single run on another tick model, as a new linked backtest. */
351
+ async rerunOnTickModel(runId, tickMode) {
352
+ return this.http.request({ method: "POST", path: this.run(runId, "tick-model"), body: { tickMode } });
353
+ }
354
+ // ── Research ──────────────────────────────────────────────────────────
355
+ /** A unified diff of two EA versions' .mq5 source. */
356
+ async sourceDiff(fromVersionId, toVersionId) {
357
+ return this.http.request({ method: "GET", path: "/api/external/backtests/source-diff", query: { from: fromVersionId, to: toVersionId } });
358
+ }
359
+ /** Swap carry across your terminals' brokers: long on one, short on another. */
360
+ async swapArbitrage() {
361
+ return this.http.request({ method: "GET", path: "/api/external/backtests/swap-arbitrage" });
362
+ }
363
+ /** The spread by hour your terminal has seen on a symbol, and the execution delay to test with. */
364
+ async spreadCalibration(instanceId, symbol) {
365
+ return this.http.request({ method: "GET", path: "/api/external/backtests/spread-calibration", query: { instanceId, symbol } });
139
366
  }
140
367
  };
141
368
 
@@ -182,11 +409,16 @@ var BrokerConnectionResource = class {
182
409
  this.subscriptions = new BrokerSubscriptionsResource(http, this.basePath);
183
410
  }
184
411
  // Orders
185
- async placeOrder(body) {
412
+ /** Place an order in the broker's own fields. Runs at most once per
413
+ * Idempotency-Key, so a retry never places twice. */
414
+ async placeOrder(order, options) {
186
415
  return this.http.request({
187
416
  method: "POST",
188
417
  path: `${this.basePath}/orders`,
189
- body
418
+ body: unwrap(order, "order"),
419
+ idempotencyKey: options?.idempotencyKey,
420
+ signal: options?.signal,
421
+ idempotent: true
190
422
  });
191
423
  }
192
424
  async getOrders() {
@@ -201,18 +433,25 @@ var BrokerConnectionResource = class {
201
433
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`
202
434
  });
203
435
  }
204
- async modifyOrder(orderId, body) {
436
+ /** Change a working order, in the broker's own fields. */
437
+ async modifyOrder(orderId, changes, options) {
205
438
  return this.http.request({
206
439
  method: "PUT",
207
440
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
208
- body
441
+ body: unwrap(changes, "changes"),
442
+ idempotencyKey: options?.idempotencyKey,
443
+ signal: options?.signal,
444
+ idempotent: true
209
445
  });
210
446
  }
211
- async cancelOrder(orderId, body) {
447
+ async cancelOrder(orderId, body, options) {
212
448
  return this.http.request({
213
449
  method: "DELETE",
214
450
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
215
- body
451
+ body,
452
+ idempotencyKey: options?.idempotencyKey,
453
+ signal: options?.signal,
454
+ idempotent: true
216
455
  });
217
456
  }
218
457
  // Trades
@@ -245,12 +484,39 @@ var BrokerConnectionResource = class {
245
484
  query
246
485
  });
247
486
  }
487
+ // Options (Dhan only)
488
+ /** Option expiries for an underlying, through this Dhan connection. */
489
+ async getOptionExpiries(underlying) {
490
+ return this.http.request({
491
+ method: "GET",
492
+ path: `${this.basePath}/option-expiries`,
493
+ query: underlyingQuery(underlying)
494
+ });
495
+ }
496
+ /** Dhan's option chain for one expiry (YYYY-MM-DD), through this Dhan connection.
497
+ * `atlas.v2.market.optionChain()` serves the same data without a connection. */
498
+ async getOptionChain(underlying, expiry) {
499
+ return this.http.request({
500
+ method: "GET",
501
+ path: `${this.basePath}/option-chain`,
502
+ query: { ...underlyingQuery(underlying), expiry }
503
+ });
504
+ }
248
505
  };
506
+ function unwrap(body, key) {
507
+ const keys = Object.keys(body);
508
+ const inner = body[key];
509
+ return keys.length === 1 && keys[0] === key && typeof inner === "object" && inner !== null && !Array.isArray(inner) ? inner : body;
510
+ }
511
+ function underlyingQuery(underlying) {
512
+ if ("underlyingSymbol" in underlying) return { underlyingSymbol: underlying.underlyingSymbol };
513
+ return { underlyingSecurityId: underlying.underlyingSecurityId, underlyingSegment: underlying.underlyingSegment };
514
+ }
249
515
  var BrokersResource = class {
250
516
  constructor(http) {
251
517
  this.http = http;
252
518
  }
253
- http;
519
+ /** `connectionId` is the connection's `externalRef`. */
254
520
  connection(brokerName, connectionId) {
255
521
  return new BrokerConnectionResource(this.http, brokerName, connectionId);
256
522
  }
@@ -262,124 +528,83 @@ var ConnectionsV2 = class {
262
528
  this.http = http;
263
529
  this.connectionId = connectionId;
264
530
  }
265
- http;
266
- connectionId;
267
- async orders(params) {
531
+ path(suffix) {
532
+ return `/api/v2/connections/${encodeURIComponent(this.connectionId)}${suffix}`;
533
+ }
534
+ read(suffix, query) {
535
+ return this.http.request({ method: "GET", path: this.path(suffix), query });
536
+ }
537
+ write(method, suffix, body, options) {
268
538
  return this.http.request({
269
- method: "GET",
270
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
271
- query: params
539
+ method,
540
+ path: this.path(suffix),
541
+ body,
542
+ query: { includeRaw: options?.includeRaw },
543
+ idempotencyKey: options?.idempotencyKey,
544
+ signal: options?.signal,
545
+ idempotent: true
272
546
  });
273
547
  }
548
+ async orders(params) {
549
+ return this.read("/orders", { includeRaw: params?.includeRaw });
550
+ }
274
551
  async order(orderId, params) {
275
- return this.http.request({
276
- method: "GET",
277
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
278
- query: params
279
- });
552
+ return this.read(`/orders/${encodeURIComponent(orderId)}`, { includeRaw: params?.includeRaw });
280
553
  }
281
- async trades() {
282
- return this.http.request({
283
- method: "GET",
284
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/trades`
285
- });
554
+ async trades(params) {
555
+ return this.read("/trades", { includeRaw: params?.includeRaw });
286
556
  }
557
+ /** `scope` defaults to `NET`; MT5 and Motilal are net-only and always answer `NET`. */
287
558
  async positions(params) {
288
- return this.http.request({
289
- method: "GET",
290
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions`,
291
- query: params
292
- });
559
+ return this.read("/positions", { scope: params?.scope, includeRaw: params?.includeRaw });
293
560
  }
294
- async holdings() {
295
- return this.http.request({
296
- method: "GET",
297
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/holdings`
298
- });
561
+ async holdings(params) {
562
+ return this.read("/holdings", { includeRaw: params?.includeRaw });
299
563
  }
300
- async funds() {
301
- return this.http.request({
302
- method: "GET",
303
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/funds`
304
- });
564
+ async funds(params) {
565
+ return this.read("/funds", { includeRaw: params?.includeRaw });
305
566
  }
306
- async profile() {
307
- return this.http.request({
308
- method: "GET",
309
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/profile`
310
- });
567
+ async profile(params) {
568
+ return this.read("/profile", { includeRaw: params?.includeRaw });
311
569
  }
312
570
  /** MT5 only: the broker server's contract specs (contract size, volume limits, tick size…),
313
571
  * keyed to instruments where a ref exists. Held server-side for ~10 min; `symbol` filters. */
314
572
  async symbols(params) {
315
- return this.http.request({
316
- method: "GET",
317
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/symbols`,
318
- query: params
319
- });
573
+ return this.read("/symbols", { symbol: params?.symbol });
320
574
  }
321
575
  async capabilities() {
322
- return this.http.request({
323
- method: "GET",
324
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/capabilities`
325
- });
576
+ return this.read("/capabilities");
326
577
  }
578
+ /** Every read in one call; each section reports ok or error on its own. Positions are `NET`. */
327
579
  async snapshot(params) {
328
- return this.http.request({
329
- method: "GET",
330
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/snapshot`,
331
- query: params
332
- });
580
+ return this.read("/snapshot", { includeRaw: params?.includeRaw });
333
581
  }
334
- // ── Writes (U3) ──────────────────────────────────────────────────────
335
- async place(body, params) {
336
- return this.http.request({
337
- method: "POST",
338
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
339
- body,
340
- query: params
341
- });
582
+ // ── Writes ───────────────────────────────────────────────────────────
583
+ // Each runs at most once per Idempotency-Key, so a retry never acts twice.
584
+ async place(body, options) {
585
+ return this.write("POST", "/orders", body, options);
342
586
  }
343
- async modify(orderId, body, params) {
344
- return this.http.request({
345
- method: "PUT",
346
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
347
- body,
348
- query: params
349
- });
587
+ async modify(orderId, body, options) {
588
+ return this.write("PUT", `/orders/${encodeURIComponent(orderId)}`, body, options);
350
589
  }
351
- async cancel(orderId, params) {
352
- return this.http.request({
353
- method: "DELETE",
354
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
355
- query: params
356
- });
590
+ async cancel(orderId, options) {
591
+ return this.write("DELETE", `/orders/${encodeURIComponent(orderId)}`, void 0, options);
357
592
  }
358
- async closePosition(body, params) {
359
- return this.http.request({
360
- method: "POST",
361
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions/close`,
362
- body,
363
- query: params
364
- });
593
+ async closePosition(body, options) {
594
+ return this.write("POST", "/positions/close", body, options);
365
595
  }
366
596
  /** SL / TP on a live position (MT5). An omitted side keeps its level; 0 clears it. */
367
- async modifyPosition(positionId, body, params) {
368
- return this.http.request({
369
- method: "PUT",
370
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions/${encodeURIComponent(positionId)}`,
371
- body,
372
- query: params
373
- });
597
+ async modifyPosition(positionId, body, options) {
598
+ return this.write("PUT", `/positions/${encodeURIComponent(positionId)}`, body, options);
374
599
  }
375
600
  };
376
601
 
377
602
  // src/resources/eas.ts
603
+ var SAVE_SOURCE_TIMEOUT_MS = 12e4;
378
604
  var EasResource = class {
379
605
  constructor(http) {
380
606
  this.http = http;
381
607
  }
382
- http;
383
608
  // ── Registry ──────────────────────────────────────────────────────────
384
609
  async list() {
385
610
  return this.http.request({
@@ -437,6 +662,29 @@ var EasResource = class {
437
662
  body
438
663
  });
439
664
  }
665
+ /** Save .mq5 source as a version. Atlaas compile-checks it first (up to a
666
+ * minute): a failure is a 422 whose `AtlasError.body` is an `EaCompileFailure`
667
+ * with the compiler's diagnostics. The saved version then compiles in the
668
+ * background (`compileStatus: "PENDING"`). The request waits up to
669
+ * `SAVE_SOURCE_TIMEOUT_MS` (2 minutes) whatever the client's `timeoutMs`,
670
+ * and like every non-order write it is never sent twice. */
671
+ async saveSource(eaId, body, options) {
672
+ return this.http.request({
673
+ method: "POST",
674
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/source`,
675
+ body,
676
+ // At least the compile window, even on a client with a shorter timeout.
677
+ timeoutMs: options?.timeoutMs ?? SAVE_SOURCE_TIMEOUT_MS,
678
+ signal: options?.signal
679
+ });
680
+ }
681
+ /** The .mq5 source of a version (by version id). 409 for an .ex5-only version. */
682
+ async getVersionSource(eaId, versionId) {
683
+ return this.http.request({
684
+ method: "GET",
685
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}/source`
686
+ });
687
+ }
440
688
  /** Mark a version LIVE (rollback) without re-uploading. */
441
689
  async promoteVersion(eaId, versionId) {
442
690
  return this.http.request({
@@ -450,6 +698,26 @@ var EasResource = class {
450
698
  path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}`
451
699
  });
452
700
  }
701
+ // ── Presets: named .set inputs saved on an EA ──────────────────────────
702
+ async listPresets(eaId) {
703
+ return this.http.request({
704
+ method: "GET",
705
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/presets`
706
+ });
707
+ }
708
+ async createPreset(eaId, body) {
709
+ return this.http.request({
710
+ method: "POST",
711
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/presets`,
712
+ body
713
+ });
714
+ }
715
+ async deletePreset(eaId, presetId) {
716
+ return this.http.request({
717
+ method: "DELETE",
718
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/presets/${encodeURIComponent(presetId)}`
719
+ });
720
+ }
453
721
  // ── Deployments ───────────────────────────────────────────────────────
454
722
  async listDeployments(query) {
455
723
  return this.http.request({
@@ -486,6 +754,38 @@ var EasResource = class {
486
754
  path: `/api/external/deployments/${encodeURIComponent(id)}`
487
755
  });
488
756
  }
757
+ /** The newest live comparison of a deployment: its live trades matched against a backtest of the same window. */
758
+ async getLiveComparison(deploymentId) {
759
+ return this.http.request({
760
+ method: "GET",
761
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/live-comparison`
762
+ });
763
+ }
764
+ /** Queue a backtest of the deployment over `from`..`to` (billed as a
765
+ * backtest); the comparison is ready from `getLiveComparison` once it finishes. */
766
+ async runLiveComparison(deploymentId, body) {
767
+ return this.http.request({
768
+ method: "POST",
769
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/live-comparison`,
770
+ body
771
+ });
772
+ }
773
+ /** The deployment's monitor: a scheduled re-backtest checked against its live trades. */
774
+ async getMonitor(deploymentId) {
775
+ return this.http.request({
776
+ method: "GET",
777
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/monitor`
778
+ });
779
+ }
780
+ async setMonitor(deploymentId, body) {
781
+ return this.http.request({
782
+ method: "PUT",
783
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/monitor`,
784
+ body,
785
+ // Sets the same state each time, so it may be sent again.
786
+ idempotent: true
787
+ });
788
+ }
489
789
  };
490
790
 
491
791
  // src/resources/instances.ts
@@ -493,7 +793,6 @@ var InstancesResource = class {
493
793
  constructor(http) {
494
794
  this.http = http;
495
795
  }
496
- http;
497
796
  async list(query) {
498
797
  return this.http.request({
499
798
  method: "GET",
@@ -517,9 +816,13 @@ var InstancesResource = class {
517
816
  return this.http.request({
518
817
  method: "POST",
519
818
  path: "/api/atlas/instances/by-external-refs",
520
- body: { refs }
819
+ body: { refs },
820
+ // A lookup sent as POST: it changes nothing, so it may be retried.
821
+ idempotent: true
521
822
  });
522
823
  }
824
+ /** Create an instance, or update yours that has the same `externalRef`.
825
+ * Read the whole instance with `get(result.id)`. */
523
826
  async create(body) {
524
827
  return this.http.request({
525
828
  method: "POST",
@@ -537,7 +840,8 @@ var InstancesResource = class {
537
840
  /**
538
841
  * Wind an instance down: the host runner kills the terminal process and
539
842
  * deletes the instance folder. Credentials stay stored, so the instance
540
- * can be re-enabled later. Returns the updated instance.
843
+ * can be re-enabled later. Returns the updated instance (null if it was
844
+ * deleted meanwhile).
541
845
  */
542
846
  async disable(id) {
543
847
  return this.http.request({
@@ -547,7 +851,8 @@ var InstancesResource = class {
547
851
  }
548
852
  /**
549
853
  * Re-enable a wound-down instance: resets it to PENDING so the runner
550
- * redeploys it fresh. Returns the updated instance.
854
+ * redeploys it fresh. Returns the updated instance (null if it was
855
+ * deleted meanwhile).
551
856
  */
552
857
  async enable(id) {
553
858
  return this.http.request({
@@ -561,6 +866,15 @@ var InstancesResource = class {
561
866
  path: `/api/atlas/instances/${encodeURIComponent(id)}`
562
867
  });
563
868
  }
869
+ /** Check broker credentials before you store them. For Dhan this logs in
870
+ * and returns the minted access token; other brokers are not checked. */
871
+ async validateBrokerCredentials(body) {
872
+ return this.http.request({
873
+ method: "POST",
874
+ path: "/api/atlas/broker-credentials/validate",
875
+ body
876
+ });
877
+ }
564
878
  };
565
879
 
566
880
  // src/resources/instruments-v2.ts
@@ -568,7 +882,6 @@ var InstrumentsV2 = class {
568
882
  constructor(http) {
569
883
  this.http = http;
570
884
  }
571
- http;
572
885
  async list(params = {}) {
573
886
  return this.http.request({
574
887
  method: "GET",
@@ -596,10 +909,10 @@ var MarketV2 = class {
596
909
  constructor(http) {
597
910
  this.http = http;
598
911
  }
599
- http;
600
912
  /** Latest tick. A vendor key nobody is watching is subscribed and read
601
913
  * once from the vendor's REST endpoint, so this answers with a
602
- * `mode: "LTP"` snapshot rather than a retry-later 404. */
914
+ * `mode: "LTP"` snapshot. An FX key with no tick yet answers a retryable
915
+ * 404 (`VALIDATION`) while its subscription opens. */
603
916
  async quote(instrumentKey) {
604
917
  return this.http.request({ method: "GET", path: "/api/v2/market/quote", query: { instrumentKey } });
605
918
  }
@@ -628,12 +941,72 @@ var MarketV2 = class {
628
941
  }
629
942
  };
630
943
 
944
+ // src/resources/mt5.ts
945
+ var Mt5Resource = class {
946
+ constructor(http) {
947
+ this.http = http;
948
+ }
949
+ path(accountId, suffix = "") {
950
+ return `/api/external/instances/${encodeURIComponent(accountId)}${suffix}`;
951
+ }
952
+ /** Your account's MT5 terminals, newest first. */
953
+ async list() {
954
+ return this.http.request({ method: "GET", path: "/api/external/instances" });
955
+ }
956
+ /** Deploy a terminal. It starts as PENDING and the account is charged the provisioning fee. */
957
+ async create(body) {
958
+ return this.http.request({ method: "POST", path: "/api/external/instances", body });
959
+ }
960
+ async get(accountId) {
961
+ return this.http.request({ method: "GET", path: this.path(accountId) });
962
+ }
963
+ /** Remove the terminal. No credits are refunded. */
964
+ async delete(accountId) {
965
+ await this.http.request({ method: "DELETE", path: this.path(accountId) });
966
+ }
967
+ /** Enable the terminal and queue it to deploy again. */
968
+ async start(accountId) {
969
+ return this.http.request({ method: "POST", path: this.path(accountId, "/start") });
970
+ }
971
+ /** Disable the terminal. Allowed even while terminals are switched to read-only. */
972
+ async stop(accountId) {
973
+ return this.http.request({ method: "POST", path: this.path(accountId, "/stop") });
974
+ }
975
+ /** MT5 servers `create` accepts as `serverName`. */
976
+ async servers() {
977
+ return this.http.request({ method: "GET", path: "/api/external/servers" });
978
+ }
979
+ /** Regions with room for a new terminal, for `create`'s `regionId`. */
980
+ async regions() {
981
+ return this.http.request({ method: "GET", path: "/api/external/regions" });
982
+ }
983
+ };
984
+
985
+ // src/resources/scanner-v2.ts
986
+ var ScannerV2 = class {
987
+ constructor(http) {
988
+ this.http = http;
989
+ }
990
+ /** The current board: every ranked stock, the picks on each side, breadth and sectors. */
991
+ async board(params) {
992
+ return this.http.request({
993
+ method: "GET",
994
+ path: "/api/v2/scanner/board",
995
+ query: { paths: params?.paths ? "1" : void 0, after: params?.after }
996
+ });
997
+ }
998
+ /** Order-block zones, stops and targets on the last two sessions of 5m
999
+ * bars, for a stock the scanner ranks (`NSE:EQ:<symbol>`). 404 for any other. */
1000
+ async zones(instrumentKey) {
1001
+ return this.http.request({ method: "GET", path: "/api/v2/scanner/zones", query: { instrumentKey } });
1002
+ }
1003
+ };
1004
+
631
1005
  // src/resources/service-keys.ts
632
1006
  var ServiceKeysResource = class {
633
1007
  constructor(http) {
634
1008
  this.http = http;
635
1009
  }
636
- http;
637
1010
  async list(accountId, query) {
638
1011
  return this.http.request({
639
1012
  method: "GET",
@@ -674,7 +1047,6 @@ var SubscriptionsResource = class {
674
1047
  constructor(http) {
675
1048
  this.http = http;
676
1049
  }
677
- http;
678
1050
  path(instanceId, suffix) {
679
1051
  return `/api/instances/${encodeURIComponent(instanceId)}${suffix}`;
680
1052
  }
@@ -727,105 +1099,92 @@ var TradingResource = class {
727
1099
  constructor(http) {
728
1100
  this.http = http;
729
1101
  }
730
- http;
731
1102
  path(accountId, suffix) {
732
1103
  return `/api/external/instances/${encodeURIComponent(accountId)}${suffix}`;
733
1104
  }
1105
+ async read(accountId, suffix, freshness, query) {
1106
+ const envelope = await this.http.requestEnvelope({ method: "GET", path: this.path(accountId, suffix), query });
1107
+ if (!freshness?.withFreshness) return envelope.data;
1108
+ return { data: envelope.data, dataAsOf: envelope.dataAsOf ?? (/* @__PURE__ */ new Date()).toISOString(), lastHeartbeatAt: envelope.lastHeartbeatAt ?? null };
1109
+ }
1110
+ /** An order write: it runs at most once per Idempotency-Key. */
1111
+ write(method, accountId, suffix, body, options) {
1112
+ return this.http.request({ method, path: this.path(accountId, suffix), body, idempotencyKey: options?.idempotencyKey, signal: options?.signal, idempotent: true });
1113
+ }
734
1114
  // Orders
735
- async placeOrder(accountId, body) {
736
- return this.http.request({
737
- method: "POST",
738
- path: this.path(accountId, "/orders"),
739
- body
740
- });
1115
+ async placeOrder(accountId, body, options) {
1116
+ return this.write("POST", accountId, "/orders", body, options);
741
1117
  }
742
- async getOrders(accountId) {
743
- return this.http.request({
744
- method: "GET",
745
- path: this.path(accountId, "/orders")
746
- });
1118
+ async getOrders(accountId, options) {
1119
+ return this.read(accountId, "/orders", options);
747
1120
  }
748
- async cancelOrder(accountId, ticket) {
749
- await this.http.request({
750
- method: "DELETE",
751
- path: this.path(accountId, `/orders/${ticket}`)
752
- });
1121
+ async cancelOrder(accountId, ticket, options) {
1122
+ await this.write("DELETE", accountId, `/orders/${ticket}`, void 0, options);
753
1123
  }
754
- // Positions
755
- async getPositions(accountId) {
756
- return this.http.request({
757
- method: "GET",
758
- path: this.path(accountId, "/positions")
759
- });
1124
+ async getPositions(accountId, options) {
1125
+ return this.read(accountId, "/positions", options);
1126
+ }
1127
+ async getPosition(accountId, ticket, options) {
1128
+ return this.read(accountId, `/positions/${ticket}`, options);
760
1129
  }
761
- async getPosition(accountId, ticket) {
1130
+ /** Fully closed positions from the terminal's deal history, oldest first. Page with `since` = the last `closeTimeMs`. */
1131
+ async getClosedPositions(accountId, query) {
762
1132
  return this.http.request({
763
1133
  method: "GET",
764
- path: this.path(accountId, `/positions/${ticket}`)
1134
+ path: this.path(accountId, "/positions/closed"),
1135
+ query: { since: query.since, until: query.until, limit: query.limit }
765
1136
  });
766
1137
  }
767
- async modifyPosition(accountId, ticket, body) {
768
- return this.http.request({
769
- method: "PATCH",
770
- path: this.path(accountId, `/positions/${ticket}`),
771
- body
772
- });
1138
+ async modifyPosition(accountId, ticket, body, options) {
1139
+ return this.write("PATCH", accountId, `/positions/${ticket}`, body, options);
773
1140
  }
774
- async closePosition(accountId, ticket, body) {
775
- return this.http.request({
776
- method: "POST",
777
- path: this.path(accountId, `/positions/${ticket}/close`),
778
- body
779
- });
1141
+ async closePosition(accountId, ticket, body, options) {
1142
+ return this.write("POST", accountId, `/positions/${ticket}/close`, body, options);
780
1143
  }
781
- async closeBySymbol(accountId, body) {
782
- return this.http.request({
783
- method: "POST",
784
- path: this.path(accountId, "/positions/close-by-symbol"),
785
- body
786
- });
1144
+ async closeBySymbol(accountId, body, options) {
1145
+ return this.write("POST", accountId, "/positions/close-by-symbol", body, options);
787
1146
  }
788
- // Market data
789
- async getPrice(accountId, symbol) {
790
- return this.http.request({
791
- method: "GET",
792
- path: this.path(accountId, `/price/${encodeURIComponent(symbol)}`)
793
- });
1147
+ async getPrice(accountId, symbol, options) {
1148
+ return this.read(accountId, `/price/${encodeURIComponent(symbol)}`, options);
794
1149
  }
795
- async getSymbols(accountId) {
796
- return this.http.request({
797
- method: "GET",
798
- path: this.path(accountId, "/symbols")
799
- });
1150
+ async getSymbols(accountId, options) {
1151
+ return this.read(accountId, "/symbols", options);
800
1152
  }
801
- async getAccountInfo(accountId) {
802
- return this.http.request({
803
- method: "GET",
804
- path: this.path(accountId, "/account")
805
- });
1153
+ async getSymbolSpecs(accountId, options) {
1154
+ return this.read(accountId, "/symbols/specs", options);
1155
+ }
1156
+ async getAccountInfo(accountId, options) {
1157
+ return this.read(accountId, "/account", options);
806
1158
  }
807
1159
  // Historical data
808
1160
  async getCandles(accountId, query) {
809
1161
  return this.http.request({
810
1162
  method: "GET",
811
1163
  path: this.path(accountId, "/candles"),
812
- query
1164
+ query: { symbol: query.symbol, timeframe: query.timeframe, startTime: query.startTime, endTime: query.endTime, count: query.count }
813
1165
  });
814
1166
  }
815
1167
  // Margin
1168
+ /** A calculation, not a write: it changes nothing on the terminal. */
816
1169
  async calculateMargin(accountId, body) {
817
1170
  return this.http.request({
818
1171
  method: "POST",
819
1172
  path: this.path(accountId, "/margins"),
820
- body
1173
+ body,
1174
+ idempotent: true
821
1175
  });
822
1176
  }
823
1177
  };
824
1178
 
825
1179
  // src/client.ts
826
1180
  var AtlasClient = class {
1181
+ /** Instances and broker connections on `/api/atlas/instances`. */
827
1182
  instances;
1183
+ /** MT5 terminals by login: deploy, start, stop, remove. */
1184
+ mt5;
828
1185
  eas;
1186
+ backtests;
1187
+ /** MT5 trading on one terminal, by login. */
829
1188
  trading;
830
1189
  subscriptions;
831
1190
  serviceKeys;
@@ -841,7 +1200,9 @@ var AtlasClient = class {
841
1200
  logger: options.logger
842
1201
  });
843
1202
  this.instances = new InstancesResource(this.http);
1203
+ this.mt5 = new Mt5Resource(this.http);
844
1204
  this.eas = new EasResource(this.http);
1205
+ this.backtests = new BacktestsResource(this.http);
845
1206
  this.trading = new TradingResource(this.http);
846
1207
  this.subscriptions = new SubscriptionsResource(this.http);
847
1208
  this.serviceKeys = new ServiceKeysResource(this.http);
@@ -849,9 +1210,11 @@ var AtlasClient = class {
849
1210
  this.v2 = {
850
1211
  instruments: new InstrumentsV2(this.http),
851
1212
  market: new MarketV2(this.http),
1213
+ scanner: new ScannerV2(this.http),
852
1214
  connections: (connectionId) => new ConnectionsV2(this.http, connectionId)
853
1215
  };
854
1216
  }
1217
+ /** A broker connection's own API, by broker name and the connection's `externalRef`. */
855
1218
  broker(brokerName, connectionId) {
856
1219
  return this.brokersResource.connection(brokerName, connectionId);
857
1220
  }
@@ -957,8 +1320,14 @@ var AtlasWebSocket = class extends EventEmitter {
957
1320
  }
958
1321
  this.authenticated = false;
959
1322
  }
1323
+ /** Add channels and filters. The server merges every subscribe on a socket,
1324
+ * and so does the reconnect replay. Its `subscribed` reply names anything
1325
+ * refused; `subscribe_failed` means the account's standing refused it whole. */
960
1326
  subscribe(options) {
961
- this.activeSubscriptions = options;
1327
+ this.activeSubscriptions = mergeSubscriptions(this.activeSubscriptions, options);
1328
+ this.send(options);
1329
+ }
1330
+ send(options) {
962
1331
  this.sendJson({
963
1332
  type: "subscribe",
964
1333
  channels: options.channels,
@@ -971,14 +1340,17 @@ var AtlasWebSocket = class extends EventEmitter {
971
1340
  chains: options.chains
972
1341
  });
973
1342
  }
974
- unsubscribe(channels) {
975
- this.sendJson({ type: "unsubscribe", channels });
976
- if (this.activeSubscriptions) {
977
- this.activeSubscriptions.channels = this.activeSubscriptions.channels.filter((c) => !channels.includes(c));
978
- if (this.activeSubscriptions.channels.length === 0) {
979
- this.activeSubscriptions = null;
980
- }
981
- }
1343
+ /** Drop channels, or only some instrumentKeys / chains while the channels
1344
+ * stay subscribed. Passing an array is the same as `{ channels }`. */
1345
+ unsubscribe(options) {
1346
+ const { channels = [], instrumentKeys, chains } = Array.isArray(options) ? { channels: options } : options;
1347
+ this.sendJson({ type: "unsubscribe", channels, instrumentKeys, chains });
1348
+ const active = this.activeSubscriptions;
1349
+ if (!active) return;
1350
+ active.channels = active.channels.filter((c) => !channels.includes(c));
1351
+ if (instrumentKeys && active.instrumentKeys) active.instrumentKeys = active.instrumentKeys.filter((k) => !instrumentKeys.includes(k));
1352
+ if (chains && active.chains) active.chains = active.chains.filter((c) => !chains.some((d) => d.underlyingKey === c.underlyingKey && d.expiry === c.expiry));
1353
+ if (!active.channels.includes("market.ticks") && !active.channels.includes("market.candles")) active.instrumentKeys = void 0;
982
1354
  }
983
1355
  get isConnected() {
984
1356
  return this.ws !== null && this.ws.readyState === OPEN && this.authenticated;
@@ -998,37 +1370,30 @@ var AtlasWebSocket = class extends EventEmitter {
998
1370
  onAuthSuccess();
999
1371
  this.emit("connected");
1000
1372
  break;
1373
+ // Bad key, IP not allowed, rate limited, insufficient scope, or an
1374
+ // inactive, suspended or out-of-credit account.
1001
1375
  case "service_auth_failed":
1002
1376
  onAuthFailure(new AtlasAuthError(msg.reason ?? "Authentication failed"));
1003
1377
  break;
1004
1378
  case "ping":
1005
1379
  this.sendJson({ type: "pong" });
1006
1380
  break;
1007
- // The server emits `tick` / `candle` on the service WS (the mt5_
1008
- // prefix is stripped in handleMT5Tick/handleMT5Candle); the
1009
- // prefixed cases are kept for any relay that forwards raw frames.
1381
+ case "subscribed":
1382
+ case "subscribe_failed":
1383
+ case "unsubscribed":
1010
1384
  case "tick":
1011
- case "mt5_tick":
1012
- this.emit("tick", msg);
1013
- break;
1014
1385
  case "candle":
1015
- case "mt5_candle":
1016
- this.emit("candle", msg);
1017
- break;
1386
+ case "position_update":
1387
+ case "trade_event":
1388
+ case "heartbeat":
1018
1389
  case "market.tick":
1019
- this.emit("market.tick", msg);
1020
- break;
1021
1390
  case "market.candle":
1022
- this.emit("market.candle", msg);
1023
- break;
1391
+ case "market.chain":
1392
+ case "market.scanner":
1024
1393
  case "trading.order":
1025
- this.emit("trading.order", msg);
1026
- break;
1027
1394
  case "broker_tick":
1028
- this.emit("broker_tick", msg);
1029
- break;
1030
1395
  case "broker_order_update":
1031
- this.emit("broker_order_update", msg);
1396
+ this.emit(type, msg);
1032
1397
  break;
1033
1398
  }
1034
1399
  }
@@ -1048,7 +1413,7 @@ var AtlasWebSocket = class extends EventEmitter {
1048
1413
  try {
1049
1414
  await this.connect();
1050
1415
  if (this.activeSubscriptions) {
1051
- this.subscribe(this.activeSubscriptions);
1416
+ this.send(this.activeSubscriptions);
1052
1417
  }
1053
1418
  } catch {
1054
1419
  }
@@ -1068,7 +1433,25 @@ var AtlasWebSocket = class extends EventEmitter {
1068
1433
  return super.emit(event, ...args);
1069
1434
  }
1070
1435
  };
1436
+ function union(a, b, same = (x, y) => x === y) {
1437
+ if (!a) return b ? [...b] : void 0;
1438
+ if (!b) return a;
1439
+ return [...a, ...b.filter((y) => !a.some((x) => same(x, y)))];
1440
+ }
1441
+ function mergeSubscriptions(current, next) {
1442
+ if (!current) return { ...next, channels: [...next.channels] };
1443
+ return {
1444
+ channels: union(current.channels, next.channels) ?? [],
1445
+ accountIds: union(current.accountIds, next.accountIds),
1446
+ symbols: union(current.symbols, next.symbols),
1447
+ brokerConnectionIds: union(current.brokerConnectionIds, next.brokerConnectionIds),
1448
+ brokerSecurityKeys: union(current.brokerSecurityKeys, next.brokerSecurityKeys),
1449
+ brokerOrderConnectionIds: union(current.brokerOrderConnectionIds, next.brokerOrderConnectionIds),
1450
+ instrumentKeys: union(current.instrumentKeys, next.instrumentKeys),
1451
+ chains: union(current.chains, next.chains, (x, y) => x.underlyingKey === y.underlyingKey && x.expiry === y.expiry)
1452
+ };
1453
+ }
1071
1454
 
1072
- export { AtlasAuthError, AtlasClient, AtlasError, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, ConnectionsV2, MarketV2 };
1455
+ export { AtlasAuthError, AtlasClient, AtlasError, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, BacktestsResource, BrokerConnectionResource, BrokerSubscriptionsResource, ConnectionsV2, EasResource, InstancesResource, InstrumentsV2, MarketV2, Mt5Resource, ScannerV2, ServiceKeysResource, SubscriptionsResource, TradingResource };
1073
1456
  //# sourceMappingURL=index.js.map
1074
1457
  //# sourceMappingURL=index.js.map