atlaas 0.2.0 → 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,16 +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
- function isIdempotencyInProgress(status, body) {
63
- const code = typeof body.error === "object" ? body.error.code : body.code;
64
- return status === 409 && code === "IDEMPOTENCY_IN_PROGRESS";
65
- }
66
71
  function jitter(base) {
67
72
  return base * (0.5 + Math.random() * 0.5);
68
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
+ }
69
107
  var HttpTransport = class {
70
108
  baseUrl;
71
109
  apiKey;
@@ -79,74 +117,252 @@ var HttpTransport = class {
79
117
  this.maxRetries = options.maxRetries ?? 2;
80
118
  this.logger = options.logger;
81
119
  }
120
+ /** The `data` of a successful response. */
82
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) {
83
126
  const url = buildUrl(this.baseUrl, options.path, options.query);
84
- const idempotencyKey = options.idempotencyKey ?? (options.method.toUpperCase() === "GET" ? void 0 : globalThis.crypto.randomUUID());
127
+ const idempotencyKey = options.idempotencyKey ?? (isRead(options.method) ? void 0 : globalThis.crypto.randomUUID());
85
128
  let lastError;
86
129
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
87
130
  if (attempt > 0) {
88
- 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);
89
134
  this.logger?.debug?.(`Retry attempt ${attempt} after ${Math.round(delay)}ms`, { url, attempt });
90
135
  await new Promise((resolve) => setTimeout(resolve, delay));
91
136
  }
92
- const controller = new AbortController();
93
- const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
94
137
  try {
95
- const response = await fetch(url, {
96
- method: options.method,
97
- headers: {
98
- "Content-Type": "application/json",
99
- Authorization: `Bearer ${this.apiKey}`,
100
- ...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}
101
- },
102
- body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
103
- signal: options.signal ?? controller.signal
104
- });
105
- clearTimeout(timeout);
106
- if (response.status === 429) {
107
- const retryAfter = response.headers.get("Retry-After");
108
- if (attempt < this.maxRetries) {
109
- lastError = new AtlasRateLimitError("Rate limited", retryAfter ? Number(retryAfter) : void 0);
110
- continue;
111
- }
112
- throw new AtlasRateLimitError("Rate limited", retryAfter ? Number(retryAfter) : void 0);
113
- }
114
- const body = await response.json();
115
- if (!body.success) {
116
- const err = body;
117
- const message = typeof err.error === "object" ? err.error.message ?? "Request failed" : err.error;
118
- if (isIdempotencyInProgress(response.status, err) && attempt < this.maxRetries) {
119
- lastError = this.mapError(response.status, message, err.errorCode);
120
- continue;
121
- }
122
- throw this.mapError(response.status, message, err.errorCode);
123
- }
124
- return body.data;
138
+ return await this.attempt(url, options, idempotencyKey);
125
139
  } catch (error) {
126
- clearTimeout(timeout);
127
- if (error instanceof AtlasError) {
128
- if (isRetryable(error.statusCode) && attempt < this.maxRetries) {
129
- lastError = error;
130
- continue;
131
- }
132
- throw error;
133
- }
134
- if (error instanceof DOMException && error.name === "AbortError") {
135
- lastError = new AtlasNetworkError("Request timed out", error);
136
- if (attempt < this.maxRetries) continue;
137
- throw lastError;
138
- }
139
- lastError = new AtlasNetworkError(error instanceof Error ? error.message : "Network request failed", error);
140
- if (attempt < this.maxRetries) continue;
141
- 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;
142
145
  }
143
146
  }
144
147
  throw lastError ?? new AtlasNetworkError("Request failed after all retries");
145
148
  }
146
- mapError(status, message, errorCode) {
147
- if (status === 401) return new AtlasAuthError(message);
148
- if (status === 400) return new AtlasValidationError(message);
149
- 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 } });
150
366
  }
151
367
  };
152
368
 
@@ -193,11 +409,16 @@ var BrokerConnectionResource = class {
193
409
  this.subscriptions = new BrokerSubscriptionsResource(http, this.basePath);
194
410
  }
195
411
  // Orders
196
- 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) {
197
415
  return this.http.request({
198
416
  method: "POST",
199
417
  path: `${this.basePath}/orders`,
200
- body
418
+ body: unwrap(order, "order"),
419
+ idempotencyKey: options?.idempotencyKey,
420
+ signal: options?.signal,
421
+ idempotent: true
201
422
  });
202
423
  }
203
424
  async getOrders() {
@@ -212,18 +433,25 @@ var BrokerConnectionResource = class {
212
433
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`
213
434
  });
214
435
  }
215
- async modifyOrder(orderId, body) {
436
+ /** Change a working order, in the broker's own fields. */
437
+ async modifyOrder(orderId, changes, options) {
216
438
  return this.http.request({
217
439
  method: "PUT",
218
440
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
219
- body
441
+ body: unwrap(changes, "changes"),
442
+ idempotencyKey: options?.idempotencyKey,
443
+ signal: options?.signal,
444
+ idempotent: true
220
445
  });
221
446
  }
222
- async cancelOrder(orderId, body) {
447
+ async cancelOrder(orderId, body, options) {
223
448
  return this.http.request({
224
449
  method: "DELETE",
225
450
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
226
- body
451
+ body,
452
+ idempotencyKey: options?.idempotencyKey,
453
+ signal: options?.signal,
454
+ idempotent: true
227
455
  });
228
456
  }
229
457
  // Trades
@@ -256,11 +484,39 @@ var BrokerConnectionResource = class {
256
484
  query
257
485
  });
258
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
+ }
259
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
+ }
260
515
  var BrokersResource = class {
261
516
  constructor(http) {
262
517
  this.http = http;
263
518
  }
519
+ /** `connectionId` is the connection's `externalRef`. */
264
520
  connection(brokerName, connectionId) {
265
521
  return new BrokerConnectionResource(this.http, brokerName, connectionId);
266
522
  }
@@ -272,117 +528,79 @@ var ConnectionsV2 = class {
272
528
  this.http = http;
273
529
  this.connectionId = connectionId;
274
530
  }
275
- 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) {
276
538
  return this.http.request({
277
- method: "GET",
278
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
279
- 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
280
546
  });
281
547
  }
548
+ async orders(params) {
549
+ return this.read("/orders", { includeRaw: params?.includeRaw });
550
+ }
282
551
  async order(orderId, params) {
283
- return this.http.request({
284
- method: "GET",
285
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
286
- query: params
287
- });
552
+ return this.read(`/orders/${encodeURIComponent(orderId)}`, { includeRaw: params?.includeRaw });
288
553
  }
289
- async trades() {
290
- return this.http.request({
291
- method: "GET",
292
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/trades`
293
- });
554
+ async trades(params) {
555
+ return this.read("/trades", { includeRaw: params?.includeRaw });
294
556
  }
557
+ /** `scope` defaults to `NET`; MT5 and Motilal are net-only and always answer `NET`. */
295
558
  async positions(params) {
296
- return this.http.request({
297
- method: "GET",
298
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions`,
299
- query: params
300
- });
559
+ return this.read("/positions", { scope: params?.scope, includeRaw: params?.includeRaw });
301
560
  }
302
- async holdings() {
303
- return this.http.request({
304
- method: "GET",
305
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/holdings`
306
- });
561
+ async holdings(params) {
562
+ return this.read("/holdings", { includeRaw: params?.includeRaw });
307
563
  }
308
- async funds() {
309
- return this.http.request({
310
- method: "GET",
311
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/funds`
312
- });
564
+ async funds(params) {
565
+ return this.read("/funds", { includeRaw: params?.includeRaw });
313
566
  }
314
- async profile() {
315
- return this.http.request({
316
- method: "GET",
317
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/profile`
318
- });
567
+ async profile(params) {
568
+ return this.read("/profile", { includeRaw: params?.includeRaw });
319
569
  }
320
570
  /** MT5 only: the broker server's contract specs (contract size, volume limits, tick size…),
321
571
  * keyed to instruments where a ref exists. Held server-side for ~10 min; `symbol` filters. */
322
572
  async symbols(params) {
323
- return this.http.request({
324
- method: "GET",
325
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/symbols`,
326
- query: params
327
- });
573
+ return this.read("/symbols", { symbol: params?.symbol });
328
574
  }
329
575
  async capabilities() {
330
- return this.http.request({
331
- method: "GET",
332
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/capabilities`
333
- });
576
+ return this.read("/capabilities");
334
577
  }
578
+ /** Every read in one call; each section reports ok or error on its own. Positions are `NET`. */
335
579
  async snapshot(params) {
336
- return this.http.request({
337
- method: "GET",
338
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/snapshot`,
339
- query: params
340
- });
580
+ return this.read("/snapshot", { includeRaw: params?.includeRaw });
341
581
  }
342
- // ── Writes (U3) ──────────────────────────────────────────────────────
343
- async place(body, params) {
344
- return this.http.request({
345
- method: "POST",
346
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
347
- body,
348
- query: params
349
- });
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);
350
586
  }
351
- async modify(orderId, body, params) {
352
- return this.http.request({
353
- method: "PUT",
354
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
355
- body,
356
- query: params
357
- });
587
+ async modify(orderId, body, options) {
588
+ return this.write("PUT", `/orders/${encodeURIComponent(orderId)}`, body, options);
358
589
  }
359
- async cancel(orderId, params) {
360
- return this.http.request({
361
- method: "DELETE",
362
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
363
- query: params
364
- });
590
+ async cancel(orderId, options) {
591
+ return this.write("DELETE", `/orders/${encodeURIComponent(orderId)}`, void 0, options);
365
592
  }
366
- async closePosition(body, params) {
367
- return this.http.request({
368
- method: "POST",
369
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions/close`,
370
- body,
371
- query: params
372
- });
593
+ async closePosition(body, options) {
594
+ return this.write("POST", "/positions/close", body, options);
373
595
  }
374
596
  /** SL / TP on a live position (MT5). An omitted side keeps its level; 0 clears it. */
375
- async modifyPosition(positionId, body, params) {
376
- return this.http.request({
377
- method: "PUT",
378
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions/${encodeURIComponent(positionId)}`,
379
- body,
380
- query: params
381
- });
597
+ async modifyPosition(positionId, body, options) {
598
+ return this.write("PUT", `/positions/${encodeURIComponent(positionId)}`, body, options);
382
599
  }
383
600
  };
384
601
 
385
602
  // src/resources/eas.ts
603
+ var SAVE_SOURCE_TIMEOUT_MS = 12e4;
386
604
  var EasResource = class {
387
605
  constructor(http) {
388
606
  this.http = http;
@@ -444,6 +662,29 @@ var EasResource = class {
444
662
  body
445
663
  });
446
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
+ }
447
688
  /** Mark a version LIVE (rollback) without re-uploading. */
448
689
  async promoteVersion(eaId, versionId) {
449
690
  return this.http.request({
@@ -457,6 +698,26 @@ var EasResource = class {
457
698
  path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}`
458
699
  });
459
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
+ }
460
721
  // ── Deployments ───────────────────────────────────────────────────────
461
722
  async listDeployments(query) {
462
723
  return this.http.request({
@@ -493,6 +754,38 @@ var EasResource = class {
493
754
  path: `/api/external/deployments/${encodeURIComponent(id)}`
494
755
  });
495
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
+ }
496
789
  };
497
790
 
498
791
  // src/resources/instances.ts
@@ -523,9 +816,13 @@ var InstancesResource = class {
523
816
  return this.http.request({
524
817
  method: "POST",
525
818
  path: "/api/atlas/instances/by-external-refs",
526
- body: { refs }
819
+ body: { refs },
820
+ // A lookup sent as POST: it changes nothing, so it may be retried.
821
+ idempotent: true
527
822
  });
528
823
  }
824
+ /** Create an instance, or update yours that has the same `externalRef`.
825
+ * Read the whole instance with `get(result.id)`. */
529
826
  async create(body) {
530
827
  return this.http.request({
531
828
  method: "POST",
@@ -543,7 +840,8 @@ var InstancesResource = class {
543
840
  /**
544
841
  * Wind an instance down: the host runner kills the terminal process and
545
842
  * deletes the instance folder. Credentials stay stored, so the instance
546
- * 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).
547
845
  */
548
846
  async disable(id) {
549
847
  return this.http.request({
@@ -553,7 +851,8 @@ var InstancesResource = class {
553
851
  }
554
852
  /**
555
853
  * Re-enable a wound-down instance: resets it to PENDING so the runner
556
- * redeploys it fresh. Returns the updated instance.
854
+ * redeploys it fresh. Returns the updated instance (null if it was
855
+ * deleted meanwhile).
557
856
  */
558
857
  async enable(id) {
559
858
  return this.http.request({
@@ -567,6 +866,15 @@ var InstancesResource = class {
567
866
  path: `/api/atlas/instances/${encodeURIComponent(id)}`
568
867
  });
569
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
+ }
570
878
  };
571
879
 
572
880
  // src/resources/instruments-v2.ts
@@ -603,7 +911,8 @@ var MarketV2 = class {
603
911
  }
604
912
  /** Latest tick. A vendor key nobody is watching is subscribed and read
605
913
  * once from the vendor's REST endpoint, so this answers with a
606
- * `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. */
607
916
  async quote(instrumentKey) {
608
917
  return this.http.request({ method: "GET", path: "/api/v2/market/quote", query: { instrumentKey } });
609
918
  }
@@ -632,6 +941,67 @@ var MarketV2 = class {
632
941
  }
633
942
  };
634
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
+
635
1005
  // src/resources/service-keys.ts
636
1006
  var ServiceKeysResource = class {
637
1007
  constructor(http) {
@@ -732,101 +1102,89 @@ var TradingResource = class {
732
1102
  path(accountId, suffix) {
733
1103
  return `/api/external/instances/${encodeURIComponent(accountId)}${suffix}`;
734
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
+ }
735
1114
  // Orders
736
- async placeOrder(accountId, body) {
737
- return this.http.request({
738
- method: "POST",
739
- path: this.path(accountId, "/orders"),
740
- body
741
- });
1115
+ async placeOrder(accountId, body, options) {
1116
+ return this.write("POST", accountId, "/orders", body, options);
742
1117
  }
743
- async getOrders(accountId) {
744
- return this.http.request({
745
- method: "GET",
746
- path: this.path(accountId, "/orders")
747
- });
1118
+ async getOrders(accountId, options) {
1119
+ return this.read(accountId, "/orders", options);
748
1120
  }
749
- async cancelOrder(accountId, ticket) {
750
- await this.http.request({
751
- method: "DELETE",
752
- path: this.path(accountId, `/orders/${ticket}`)
753
- });
1121
+ async cancelOrder(accountId, ticket, options) {
1122
+ await this.write("DELETE", accountId, `/orders/${ticket}`, void 0, options);
754
1123
  }
755
- // Positions
756
- async getPositions(accountId) {
757
- return this.http.request({
758
- method: "GET",
759
- path: this.path(accountId, "/positions")
760
- });
1124
+ async getPositions(accountId, options) {
1125
+ return this.read(accountId, "/positions", options);
761
1126
  }
762
- async getPosition(accountId, ticket) {
1127
+ async getPosition(accountId, ticket, options) {
1128
+ return this.read(accountId, `/positions/${ticket}`, options);
1129
+ }
1130
+ /** Fully closed positions from the terminal's deal history, oldest first. Page with `since` = the last `closeTimeMs`. */
1131
+ async getClosedPositions(accountId, query) {
763
1132
  return this.http.request({
764
1133
  method: "GET",
765
- path: this.path(accountId, `/positions/${ticket}`)
1134
+ path: this.path(accountId, "/positions/closed"),
1135
+ query: { since: query.since, until: query.until, limit: query.limit }
766
1136
  });
767
1137
  }
768
- async modifyPosition(accountId, ticket, body) {
769
- return this.http.request({
770
- method: "PATCH",
771
- path: this.path(accountId, `/positions/${ticket}`),
772
- body
773
- });
1138
+ async modifyPosition(accountId, ticket, body, options) {
1139
+ return this.write("PATCH", accountId, `/positions/${ticket}`, body, options);
774
1140
  }
775
- async closePosition(accountId, ticket, body) {
776
- return this.http.request({
777
- method: "POST",
778
- path: this.path(accountId, `/positions/${ticket}/close`),
779
- body
780
- });
1141
+ async closePosition(accountId, ticket, body, options) {
1142
+ return this.write("POST", accountId, `/positions/${ticket}/close`, body, options);
781
1143
  }
782
- async closeBySymbol(accountId, body) {
783
- return this.http.request({
784
- method: "POST",
785
- path: this.path(accountId, "/positions/close-by-symbol"),
786
- body
787
- });
1144
+ async closeBySymbol(accountId, body, options) {
1145
+ return this.write("POST", accountId, "/positions/close-by-symbol", body, options);
788
1146
  }
789
- // Market data
790
- async getPrice(accountId, symbol) {
791
- return this.http.request({
792
- method: "GET",
793
- path: this.path(accountId, `/price/${encodeURIComponent(symbol)}`)
794
- });
1147
+ async getPrice(accountId, symbol, options) {
1148
+ return this.read(accountId, `/price/${encodeURIComponent(symbol)}`, options);
795
1149
  }
796
- async getSymbols(accountId) {
797
- return this.http.request({
798
- method: "GET",
799
- path: this.path(accountId, "/symbols")
800
- });
1150
+ async getSymbols(accountId, options) {
1151
+ return this.read(accountId, "/symbols", options);
801
1152
  }
802
- async getAccountInfo(accountId) {
803
- return this.http.request({
804
- method: "GET",
805
- path: this.path(accountId, "/account")
806
- });
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);
807
1158
  }
808
1159
  // Historical data
809
1160
  async getCandles(accountId, query) {
810
1161
  return this.http.request({
811
1162
  method: "GET",
812
1163
  path: this.path(accountId, "/candles"),
813
- query
1164
+ query: { symbol: query.symbol, timeframe: query.timeframe, startTime: query.startTime, endTime: query.endTime, count: query.count }
814
1165
  });
815
1166
  }
816
1167
  // Margin
1168
+ /** A calculation, not a write: it changes nothing on the terminal. */
817
1169
  async calculateMargin(accountId, body) {
818
1170
  return this.http.request({
819
1171
  method: "POST",
820
1172
  path: this.path(accountId, "/margins"),
821
- body
1173
+ body,
1174
+ idempotent: true
822
1175
  });
823
1176
  }
824
1177
  };
825
1178
 
826
1179
  // src/client.ts
827
1180
  var AtlasClient = class {
1181
+ /** Instances and broker connections on `/api/atlas/instances`. */
828
1182
  instances;
1183
+ /** MT5 terminals by login: deploy, start, stop, remove. */
1184
+ mt5;
829
1185
  eas;
1186
+ backtests;
1187
+ /** MT5 trading on one terminal, by login. */
830
1188
  trading;
831
1189
  subscriptions;
832
1190
  serviceKeys;
@@ -842,7 +1200,9 @@ var AtlasClient = class {
842
1200
  logger: options.logger
843
1201
  });
844
1202
  this.instances = new InstancesResource(this.http);
1203
+ this.mt5 = new Mt5Resource(this.http);
845
1204
  this.eas = new EasResource(this.http);
1205
+ this.backtests = new BacktestsResource(this.http);
846
1206
  this.trading = new TradingResource(this.http);
847
1207
  this.subscriptions = new SubscriptionsResource(this.http);
848
1208
  this.serviceKeys = new ServiceKeysResource(this.http);
@@ -850,9 +1210,11 @@ var AtlasClient = class {
850
1210
  this.v2 = {
851
1211
  instruments: new InstrumentsV2(this.http),
852
1212
  market: new MarketV2(this.http),
1213
+ scanner: new ScannerV2(this.http),
853
1214
  connections: (connectionId) => new ConnectionsV2(this.http, connectionId)
854
1215
  };
855
1216
  }
1217
+ /** A broker connection's own API, by broker name and the connection's `externalRef`. */
856
1218
  broker(brokerName, connectionId) {
857
1219
  return this.brokersResource.connection(brokerName, connectionId);
858
1220
  }
@@ -958,8 +1320,14 @@ var AtlasWebSocket = class extends EventEmitter {
958
1320
  }
959
1321
  this.authenticated = false;
960
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. */
961
1326
  subscribe(options) {
962
- this.activeSubscriptions = options;
1327
+ this.activeSubscriptions = mergeSubscriptions(this.activeSubscriptions, options);
1328
+ this.send(options);
1329
+ }
1330
+ send(options) {
963
1331
  this.sendJson({
964
1332
  type: "subscribe",
965
1333
  channels: options.channels,
@@ -972,14 +1340,17 @@ var AtlasWebSocket = class extends EventEmitter {
972
1340
  chains: options.chains
973
1341
  });
974
1342
  }
975
- unsubscribe(channels) {
976
- this.sendJson({ type: "unsubscribe", channels });
977
- if (this.activeSubscriptions) {
978
- this.activeSubscriptions.channels = this.activeSubscriptions.channels.filter((c) => !channels.includes(c));
979
- if (this.activeSubscriptions.channels.length === 0) {
980
- this.activeSubscriptions = null;
981
- }
982
- }
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;
983
1354
  }
984
1355
  get isConnected() {
985
1356
  return this.ws !== null && this.ws.readyState === OPEN && this.authenticated;
@@ -999,37 +1370,30 @@ var AtlasWebSocket = class extends EventEmitter {
999
1370
  onAuthSuccess();
1000
1371
  this.emit("connected");
1001
1372
  break;
1373
+ // Bad key, IP not allowed, rate limited, insufficient scope, or an
1374
+ // inactive, suspended or out-of-credit account.
1002
1375
  case "service_auth_failed":
1003
1376
  onAuthFailure(new AtlasAuthError(msg.reason ?? "Authentication failed"));
1004
1377
  break;
1005
1378
  case "ping":
1006
1379
  this.sendJson({ type: "pong" });
1007
1380
  break;
1008
- // The server emits `tick` / `candle` on the service WS (the mt5_
1009
- // prefix is stripped in handleMT5Tick/handleMT5Candle); the
1010
- // prefixed cases are kept for any relay that forwards raw frames.
1381
+ case "subscribed":
1382
+ case "subscribe_failed":
1383
+ case "unsubscribed":
1011
1384
  case "tick":
1012
- case "mt5_tick":
1013
- this.emit("tick", msg);
1014
- break;
1015
1385
  case "candle":
1016
- case "mt5_candle":
1017
- this.emit("candle", msg);
1018
- break;
1386
+ case "position_update":
1387
+ case "trade_event":
1388
+ case "heartbeat":
1019
1389
  case "market.tick":
1020
- this.emit("market.tick", msg);
1021
- break;
1022
1390
  case "market.candle":
1023
- this.emit("market.candle", msg);
1024
- break;
1391
+ case "market.chain":
1392
+ case "market.scanner":
1025
1393
  case "trading.order":
1026
- this.emit("trading.order", msg);
1027
- break;
1028
1394
  case "broker_tick":
1029
- this.emit("broker_tick", msg);
1030
- break;
1031
1395
  case "broker_order_update":
1032
- this.emit("broker_order_update", msg);
1396
+ this.emit(type, msg);
1033
1397
  break;
1034
1398
  }
1035
1399
  }
@@ -1049,7 +1413,7 @@ var AtlasWebSocket = class extends EventEmitter {
1049
1413
  try {
1050
1414
  await this.connect();
1051
1415
  if (this.activeSubscriptions) {
1052
- this.subscribe(this.activeSubscriptions);
1416
+ this.send(this.activeSubscriptions);
1053
1417
  }
1054
1418
  } catch {
1055
1419
  }
@@ -1069,7 +1433,25 @@ var AtlasWebSocket = class extends EventEmitter {
1069
1433
  return super.emit(event, ...args);
1070
1434
  }
1071
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
+ }
1072
1454
 
1073
- 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 };
1074
1456
  //# sourceMappingURL=index.js.map
1075
1457
  //# sourceMappingURL=index.js.map