atlaas 0.2.0 → 0.4.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 the usage balance is short. */
225
+ async create(body) {
226
+ return this.http.request({ method: "POST", path: "/api/external/backtests", body });
227
+ }
228
+ /** Time and cost (from the usage balance, in its currency) 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
 
@@ -160,6 +376,7 @@ var BrokerSubscriptionsResource = class {
160
376
  this.http = http;
161
377
  this.basePath = basePath;
162
378
  }
379
+ /** @deprecated Subscribe NSE, BSE and MCX keys on the `market.ticks` WebSocket channel instead (it needs India access). */
163
380
  async subscribe(body) {
164
381
  return this.http.request({
165
382
  method: "POST",
@@ -167,6 +384,7 @@ var BrokerSubscriptionsResource = class {
167
384
  body
168
385
  });
169
386
  }
387
+ /** @deprecated Unsubscribe from the `market.ticks` WebSocket channel instead. */
170
388
  async unsubscribe(body) {
171
389
  return this.http.request({
172
390
  method: "DELETE",
@@ -174,6 +392,7 @@ var BrokerSubscriptionsResource = class {
174
392
  body
175
393
  });
176
394
  }
395
+ /** @deprecated The `subscribed` reply on the `market.ticks` WebSocket channel lists what streams. */
177
396
  async list() {
178
397
  return this.http.request({
179
398
  method: "GET",
@@ -193,42 +412,66 @@ var BrokerConnectionResource = class {
193
412
  this.subscriptions = new BrokerSubscriptionsResource(http, this.basePath);
194
413
  }
195
414
  // Orders
196
- async placeOrder(body) {
415
+ /**
416
+ * Place an order in the broker's own fields. Runs at most once per
417
+ * Idempotency-Key, so a retry never places twice.
418
+ * @deprecated Use `atlas.v2.connections(id).placeOrder()` (`POST /api/v2/connections/{id}/orders`).
419
+ */
420
+ async placeOrder(order, options) {
197
421
  return this.http.request({
198
422
  method: "POST",
199
423
  path: `${this.basePath}/orders`,
200
- body
424
+ body: unwrap(order, "order"),
425
+ idempotencyKey: options?.idempotencyKey,
426
+ signal: options?.signal,
427
+ idempotent: true
201
428
  });
202
429
  }
430
+ /** @deprecated Use `atlas.v2.connections(id).orders()` (`GET /api/v2/connections/{id}/orders`). */
203
431
  async getOrders() {
204
432
  return this.http.request({
205
433
  method: "GET",
206
434
  path: `${this.basePath}/orders`
207
435
  });
208
436
  }
437
+ /** @deprecated Use `atlas.v2.connections(id).order(orderId)` (`GET /api/v2/connections/{id}/orders/{orderId}`). */
209
438
  async getOrder(orderId) {
210
439
  return this.http.request({
211
440
  method: "GET",
212
441
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`
213
442
  });
214
443
  }
215
- async modifyOrder(orderId, body) {
444
+ /**
445
+ * Change a working order, in the broker's own fields.
446
+ * @deprecated Use `atlas.v2.connections(id).modifyOrder()` (`PUT /api/v2/connections/{id}/orders/{orderId}`).
447
+ */
448
+ async modifyOrder(orderId, changes, options) {
216
449
  return this.http.request({
217
450
  method: "PUT",
218
451
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
219
- body
452
+ body: unwrap(changes, "changes"),
453
+ idempotencyKey: options?.idempotencyKey,
454
+ signal: options?.signal,
455
+ idempotent: true
220
456
  });
221
457
  }
222
- async cancelOrder(orderId, body) {
458
+ /** @deprecated Use `atlas.v2.connections(id).cancelOrder(orderId)` (`DELETE /api/v2/connections/{id}/orders/{orderId}`). */
459
+ async cancelOrder(orderId, body, options) {
223
460
  return this.http.request({
224
461
  method: "DELETE",
225
462
  path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
226
- body
463
+ body,
464
+ idempotencyKey: options?.idempotencyKey,
465
+ signal: options?.signal,
466
+ idempotent: true
227
467
  });
228
468
  }
229
469
  // Trades
230
- /** Trade book (fills). Currently served by Motilal Oswal; brokers whose
231
- * runner adapter doesn't implement it return an "unsupported command" error. */
470
+ /**
471
+ * Trade book (fills). Currently served by Motilal Oswal; brokers whose
472
+ * runner adapter doesn't implement it return an "unsupported command" error.
473
+ * @deprecated Use `atlas.v2.connections(id).trades()` (`GET /api/v2/connections/{id}/trades`).
474
+ */
232
475
  async getTrades() {
233
476
  return this.http.request({
234
477
  method: "GET",
@@ -236,12 +479,14 @@ var BrokerConnectionResource = class {
236
479
  });
237
480
  }
238
481
  // Positions & Holdings
482
+ /** @deprecated Use `atlas.v2.connections(id).positions()` (`GET /api/v2/connections/{id}/positions`). */
239
483
  async getPositions() {
240
484
  return this.http.request({
241
485
  method: "GET",
242
486
  path: `${this.basePath}/positions`
243
487
  });
244
488
  }
489
+ /** @deprecated Use `atlas.v2.connections(id).holdings()` (`GET /api/v2/connections/{id}/holdings`). */
245
490
  async getHoldings() {
246
491
  return this.http.request({
247
492
  method: "GET",
@@ -249,6 +494,7 @@ var BrokerConnectionResource = class {
249
494
  });
250
495
  }
251
496
  // Candles
497
+ /** @deprecated Use `atlas.v2.market.candles()` (`GET /api/v2/market/candles`), served from the Atlaas market data feed. */
252
498
  async getCandles(query) {
253
499
  return this.http.request({
254
500
  method: "GET",
@@ -256,11 +502,44 @@ var BrokerConnectionResource = class {
256
502
  query
257
503
  });
258
504
  }
505
+ // Options (Dhan only)
506
+ /**
507
+ * Option expiries for an underlying, through this Dhan connection.
508
+ * @deprecated Use `atlas.v2.market.expiries(underlyingKey)` (`GET /api/v2/market/expiries`).
509
+ */
510
+ async getOptionExpiries(underlying) {
511
+ return this.http.request({
512
+ method: "GET",
513
+ path: `${this.basePath}/option-expiries`,
514
+ query: underlyingQuery(underlying)
515
+ });
516
+ }
517
+ /**
518
+ * Dhan's option chain for one expiry (YYYY-MM-DD), through this Dhan connection.
519
+ * @deprecated Use `atlas.v2.market.optionChain(underlyingKey, expiry)` (`GET /api/v2/market/option-chain`), which serves the same data without a connection.
520
+ */
521
+ async getOptionChain(underlying, expiry) {
522
+ return this.http.request({
523
+ method: "GET",
524
+ path: `${this.basePath}/option-chain`,
525
+ query: { ...underlyingQuery(underlying), expiry }
526
+ });
527
+ }
259
528
  };
529
+ function unwrap(body, key) {
530
+ const keys = Object.keys(body);
531
+ const inner = body[key];
532
+ return keys.length === 1 && keys[0] === key && typeof inner === "object" && inner !== null && !Array.isArray(inner) ? inner : body;
533
+ }
534
+ function underlyingQuery(underlying) {
535
+ if ("underlyingSymbol" in underlying) return { underlyingSymbol: underlying.underlyingSymbol };
536
+ return { underlyingSecurityId: underlying.underlyingSecurityId, underlyingSegment: underlying.underlyingSegment };
537
+ }
260
538
  var BrokersResource = class {
261
539
  constructor(http) {
262
540
  this.http = http;
263
541
  }
542
+ /** `connectionId` is the connection's `externalRef`. */
264
543
  connection(brokerName, connectionId) {
265
544
  return new BrokerConnectionResource(this.http, brokerName, connectionId);
266
545
  }
@@ -272,117 +551,93 @@ var ConnectionsV2 = class {
272
551
  this.http = http;
273
552
  this.connectionId = connectionId;
274
553
  }
275
- async orders(params) {
554
+ path(suffix) {
555
+ return `/api/v2/connections/${encodeURIComponent(this.connectionId)}${suffix}`;
556
+ }
557
+ read(suffix, query) {
558
+ return this.http.request({ method: "GET", path: this.path(suffix), query });
559
+ }
560
+ write(method, suffix, body, options) {
276
561
  return this.http.request({
277
- method: "GET",
278
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
279
- query: params
562
+ method,
563
+ path: this.path(suffix),
564
+ body,
565
+ query: { includeRaw: options?.includeRaw },
566
+ idempotencyKey: options?.idempotencyKey,
567
+ signal: options?.signal,
568
+ idempotent: true
280
569
  });
281
570
  }
571
+ async orders(params) {
572
+ return this.read("/orders", { includeRaw: params?.includeRaw });
573
+ }
282
574
  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
- });
575
+ return this.read(`/orders/${encodeURIComponent(orderId)}`, { includeRaw: params?.includeRaw });
288
576
  }
289
- async trades() {
290
- return this.http.request({
291
- method: "GET",
292
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/trades`
293
- });
577
+ async trades(params) {
578
+ return this.read("/trades", { includeRaw: params?.includeRaw });
294
579
  }
580
+ /** `scope` defaults to `NET`; MT5 and Motilal are net-only and always answer `NET`. */
295
581
  async positions(params) {
296
- return this.http.request({
297
- method: "GET",
298
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions`,
299
- query: params
300
- });
582
+ return this.read("/positions", { scope: params?.scope, includeRaw: params?.includeRaw });
301
583
  }
302
- async holdings() {
303
- return this.http.request({
304
- method: "GET",
305
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/holdings`
306
- });
584
+ async holdings(params) {
585
+ return this.read("/holdings", { includeRaw: params?.includeRaw });
307
586
  }
308
- async funds() {
309
- return this.http.request({
310
- method: "GET",
311
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/funds`
312
- });
587
+ async funds(params) {
588
+ return this.read("/funds", { includeRaw: params?.includeRaw });
313
589
  }
314
- async profile() {
315
- return this.http.request({
316
- method: "GET",
317
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/profile`
318
- });
590
+ async profile(params) {
591
+ return this.read("/profile", { includeRaw: params?.includeRaw });
319
592
  }
320
593
  /** MT5 only: the broker server's contract specs (contract size, volume limits, tick size…),
321
594
  * keyed to instruments where a ref exists. Held server-side for ~10 min; `symbol` filters. */
322
595
  async symbols(params) {
323
- return this.http.request({
324
- method: "GET",
325
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/symbols`,
326
- query: params
327
- });
596
+ return this.read("/symbols", { symbol: params?.symbol });
328
597
  }
329
598
  async capabilities() {
330
- return this.http.request({
331
- method: "GET",
332
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/capabilities`
333
- });
599
+ return this.read("/capabilities");
334
600
  }
601
+ /** Every read in one call; each section reports ok or error on its own. Positions are `NET`. */
335
602
  async snapshot(params) {
336
- return this.http.request({
337
- method: "GET",
338
- path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/snapshot`,
339
- query: params
340
- });
603
+ return this.read("/snapshot", { includeRaw: params?.includeRaw });
341
604
  }
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
- });
605
+ // ── Writes ───────────────────────────────────────────────────────────
606
+ // Each runs at most once per Idempotency-Key, so a retry never acts twice.
607
+ // Named like the v1 and raw broker writes (placeOrder, modifyOrder,
608
+ // cancelOrder, closePosition, modifyPosition).
609
+ async placeOrder(body, options) {
610
+ return this.write("POST", "/orders", body, options);
350
611
  }
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
- });
612
+ async modifyOrder(orderId, body, options) {
613
+ return this.write("PUT", `/orders/${encodeURIComponent(orderId)}`, body, options);
358
614
  }
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
- });
615
+ async cancelOrder(orderId, options) {
616
+ return this.write("DELETE", `/orders/${encodeURIComponent(orderId)}`, void 0, options);
365
617
  }
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
- });
618
+ /** @deprecated Renamed to {@link ConnectionsV2.placeOrder}, which takes the same arguments. */
619
+ async place(body, options) {
620
+ return this.placeOrder(body, options);
621
+ }
622
+ /** @deprecated Renamed to {@link ConnectionsV2.modifyOrder}, which takes the same arguments. */
623
+ async modify(orderId, body, options) {
624
+ return this.modifyOrder(orderId, body, options);
625
+ }
626
+ /** @deprecated Renamed to {@link ConnectionsV2.cancelOrder}, which takes the same arguments. */
627
+ async cancel(orderId, options) {
628
+ return this.cancelOrder(orderId, options);
629
+ }
630
+ async closePosition(body, options) {
631
+ return this.write("POST", "/positions/close", body, options);
373
632
  }
374
633
  /** 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
- });
634
+ async modifyPosition(positionId, body, options) {
635
+ return this.write("PUT", `/positions/${encodeURIComponent(positionId)}`, body, options);
382
636
  }
383
637
  };
384
638
 
385
639
  // src/resources/eas.ts
640
+ var SAVE_SOURCE_TIMEOUT_MS = 12e4;
386
641
  var EasResource = class {
387
642
  constructor(http) {
388
643
  this.http = http;
@@ -444,6 +699,29 @@ var EasResource = class {
444
699
  body
445
700
  });
446
701
  }
702
+ /** Save .mq5 source as a version. Atlaas compile-checks it first (up to a
703
+ * minute): a failure is a 422 whose `AtlasError.body` is an `EaCompileFailure`
704
+ * with the compiler's diagnostics. The saved version then compiles in the
705
+ * background (`compileStatus: "PENDING"`). The request waits up to
706
+ * `SAVE_SOURCE_TIMEOUT_MS` (2 minutes) whatever the client's `timeoutMs`,
707
+ * and like every non-order write it is never sent twice. */
708
+ async saveSource(eaId, body, options) {
709
+ return this.http.request({
710
+ method: "POST",
711
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/source`,
712
+ body,
713
+ // At least the compile window, even on a client with a shorter timeout.
714
+ timeoutMs: options?.timeoutMs ?? SAVE_SOURCE_TIMEOUT_MS,
715
+ signal: options?.signal
716
+ });
717
+ }
718
+ /** The .mq5 source of a version (by version id). 409 for an .ex5-only version. */
719
+ async getVersionSource(eaId, versionId) {
720
+ return this.http.request({
721
+ method: "GET",
722
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}/source`
723
+ });
724
+ }
447
725
  /** Mark a version LIVE (rollback) without re-uploading. */
448
726
  async promoteVersion(eaId, versionId) {
449
727
  return this.http.request({
@@ -457,6 +735,26 @@ var EasResource = class {
457
735
  path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}`
458
736
  });
459
737
  }
738
+ // ── Presets: named .set inputs saved on an EA ──────────────────────────
739
+ async listPresets(eaId) {
740
+ return this.http.request({
741
+ method: "GET",
742
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/presets`
743
+ });
744
+ }
745
+ async createPreset(eaId, body) {
746
+ return this.http.request({
747
+ method: "POST",
748
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/presets`,
749
+ body
750
+ });
751
+ }
752
+ async deletePreset(eaId, presetId) {
753
+ return this.http.request({
754
+ method: "DELETE",
755
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/presets/${encodeURIComponent(presetId)}`
756
+ });
757
+ }
460
758
  // ── Deployments ───────────────────────────────────────────────────────
461
759
  async listDeployments(query) {
462
760
  return this.http.request({
@@ -493,6 +791,38 @@ var EasResource = class {
493
791
  path: `/api/external/deployments/${encodeURIComponent(id)}`
494
792
  });
495
793
  }
794
+ /** The newest live comparison of a deployment: its live trades matched against a backtest of the same window. */
795
+ async getLiveComparison(deploymentId) {
796
+ return this.http.request({
797
+ method: "GET",
798
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/live-comparison`
799
+ });
800
+ }
801
+ /** Queue a backtest of the deployment over `from`..`to` (billed as a
802
+ * backtest); the comparison is ready from `getLiveComparison` once it finishes. */
803
+ async runLiveComparison(deploymentId, body) {
804
+ return this.http.request({
805
+ method: "POST",
806
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/live-comparison`,
807
+ body
808
+ });
809
+ }
810
+ /** The deployment's monitor: a scheduled re-backtest checked against its live trades. */
811
+ async getMonitor(deploymentId) {
812
+ return this.http.request({
813
+ method: "GET",
814
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/monitor`
815
+ });
816
+ }
817
+ async setMonitor(deploymentId, body) {
818
+ return this.http.request({
819
+ method: "PUT",
820
+ path: `/api/external/deployments/${encodeURIComponent(deploymentId)}/monitor`,
821
+ body,
822
+ // Sets the same state each time, so it may be sent again.
823
+ idempotent: true
824
+ });
825
+ }
496
826
  };
497
827
 
498
828
  // src/resources/instances.ts
@@ -523,9 +853,13 @@ var InstancesResource = class {
523
853
  return this.http.request({
524
854
  method: "POST",
525
855
  path: "/api/atlas/instances/by-external-refs",
526
- body: { refs }
856
+ body: { refs },
857
+ // A lookup sent as POST: it changes nothing, so it may be retried.
858
+ idempotent: true
527
859
  });
528
860
  }
861
+ /** Create an instance, or update yours that has the same `externalRef`.
862
+ * Read the whole instance with `get(result.id)`. */
529
863
  async create(body) {
530
864
  return this.http.request({
531
865
  method: "POST",
@@ -543,7 +877,8 @@ var InstancesResource = class {
543
877
  /**
544
878
  * Wind an instance down: the host runner kills the terminal process and
545
879
  * deletes the instance folder. Credentials stay stored, so the instance
546
- * can be re-enabled later. Returns the updated instance.
880
+ * can be re-enabled later. Returns the updated instance (null if it was
881
+ * deleted meanwhile).
547
882
  */
548
883
  async disable(id) {
549
884
  return this.http.request({
@@ -553,7 +888,8 @@ var InstancesResource = class {
553
888
  }
554
889
  /**
555
890
  * Re-enable a wound-down instance: resets it to PENDING so the runner
556
- * redeploys it fresh. Returns the updated instance.
891
+ * redeploys it fresh. Returns the updated instance (null if it was
892
+ * deleted meanwhile).
557
893
  */
558
894
  async enable(id) {
559
895
  return this.http.request({
@@ -567,6 +903,15 @@ var InstancesResource = class {
567
903
  path: `/api/atlas/instances/${encodeURIComponent(id)}`
568
904
  });
569
905
  }
906
+ /** Check broker credentials before you store them. For Dhan this logs in
907
+ * and returns the minted access token; other brokers are not checked. */
908
+ async validateBrokerCredentials(body) {
909
+ return this.http.request({
910
+ method: "POST",
911
+ path: "/api/atlas/broker-credentials/validate",
912
+ body
913
+ });
914
+ }
570
915
  };
571
916
 
572
917
  // src/resources/instruments-v2.ts
@@ -603,7 +948,8 @@ var MarketV2 = class {
603
948
  }
604
949
  /** Latest tick. A vendor key nobody is watching is subscribed and read
605
950
  * once from the vendor's REST endpoint, so this answers with a
606
- * `mode: "LTP"` snapshot rather than a retry-later 404. */
951
+ * `mode: "LTP"` snapshot. An FX key with no tick yet answers a retryable
952
+ * 404 (`VALIDATION`) while its subscription opens. */
607
953
  async quote(instrumentKey) {
608
954
  return this.http.request({ method: "GET", path: "/api/v2/market/quote", query: { instrumentKey } });
609
955
  }
@@ -632,6 +978,67 @@ var MarketV2 = class {
632
978
  }
633
979
  };
634
980
 
981
+ // src/resources/mt5.ts
982
+ var Mt5Resource = class {
983
+ constructor(http) {
984
+ this.http = http;
985
+ }
986
+ path(accountId, suffix = "") {
987
+ return `/api/external/instances/${encodeURIComponent(accountId)}${suffix}`;
988
+ }
989
+ /** Your account's MT5 terminals, newest first. */
990
+ async list() {
991
+ return this.http.request({ method: "GET", path: "/api/external/instances" });
992
+ }
993
+ /** Deploy a terminal. It starts as PENDING and the account is charged the provisioning fee. */
994
+ async create(body) {
995
+ return this.http.request({ method: "POST", path: "/api/external/instances", body });
996
+ }
997
+ async get(accountId) {
998
+ return this.http.request({ method: "GET", path: this.path(accountId) });
999
+ }
1000
+ /** Remove the terminal. Nothing is refunded. */
1001
+ async delete(accountId) {
1002
+ await this.http.request({ method: "DELETE", path: this.path(accountId) });
1003
+ }
1004
+ /** Enable the terminal and queue it to deploy again. */
1005
+ async start(accountId) {
1006
+ return this.http.request({ method: "POST", path: this.path(accountId, "/start") });
1007
+ }
1008
+ /** Disable the terminal. Allowed even while terminals are switched to read-only. */
1009
+ async stop(accountId) {
1010
+ return this.http.request({ method: "POST", path: this.path(accountId, "/stop") });
1011
+ }
1012
+ /** MT5 servers `create` accepts as `serverName`. */
1013
+ async servers() {
1014
+ return this.http.request({ method: "GET", path: "/api/external/servers" });
1015
+ }
1016
+ /** Regions with room for a new terminal, for `create`'s `regionId`. */
1017
+ async regions() {
1018
+ return this.http.request({ method: "GET", path: "/api/external/regions" });
1019
+ }
1020
+ };
1021
+
1022
+ // src/resources/scanner-v2.ts
1023
+ var ScannerV2 = class {
1024
+ constructor(http) {
1025
+ this.http = http;
1026
+ }
1027
+ /** The current board: every ranked stock, the picks on each side, breadth and sectors. */
1028
+ async board(params) {
1029
+ return this.http.request({
1030
+ method: "GET",
1031
+ path: "/api/v2/scanner/board",
1032
+ query: { paths: params?.paths ? "1" : void 0, after: params?.after }
1033
+ });
1034
+ }
1035
+ /** Order-block zones, stops and targets on the last two sessions of 5m
1036
+ * bars, for a stock the scanner ranks (`NSE:EQ:<symbol>`). 404 for any other. */
1037
+ async zones(instrumentKey) {
1038
+ return this.http.request({ method: "GET", path: "/api/v2/scanner/zones", query: { instrumentKey } });
1039
+ }
1040
+ };
1041
+
635
1042
  // src/resources/service-keys.ts
636
1043
  var ServiceKeysResource = class {
637
1044
  constructor(http) {
@@ -732,104 +1139,99 @@ var TradingResource = class {
732
1139
  path(accountId, suffix) {
733
1140
  return `/api/external/instances/${encodeURIComponent(accountId)}${suffix}`;
734
1141
  }
1142
+ async read(accountId, suffix, freshness, query) {
1143
+ const envelope = await this.http.requestEnvelope({ method: "GET", path: this.path(accountId, suffix), query });
1144
+ if (!freshness?.withFreshness) return envelope.data;
1145
+ return { data: envelope.data, dataAsOf: envelope.dataAsOf ?? (/* @__PURE__ */ new Date()).toISOString(), lastHeartbeatAt: envelope.lastHeartbeatAt ?? null };
1146
+ }
1147
+ /** An order write: it runs at most once per Idempotency-Key. */
1148
+ write(method, accountId, suffix, body, options) {
1149
+ return this.http.request({ method, path: this.path(accountId, suffix), body, idempotencyKey: options?.idempotencyKey, signal: options?.signal, idempotent: true });
1150
+ }
735
1151
  // Orders
736
- async placeOrder(accountId, body) {
737
- return this.http.request({
738
- method: "POST",
739
- path: this.path(accountId, "/orders"),
740
- body
741
- });
1152
+ /** @deprecated Use `atlas.v2.connections(id).placeOrder()` (`POST /api/v2/connections/{id}/orders`). */
1153
+ async placeOrder(accountId, body, options) {
1154
+ return this.write("POST", accountId, "/orders", body, options);
742
1155
  }
743
- async getOrders(accountId) {
744
- return this.http.request({
745
- method: "GET",
746
- path: this.path(accountId, "/orders")
747
- });
1156
+ async getOrders(accountId, options) {
1157
+ return this.read(accountId, "/orders", options);
748
1158
  }
749
- async cancelOrder(accountId, ticket) {
750
- await this.http.request({
751
- method: "DELETE",
752
- path: this.path(accountId, `/orders/${ticket}`)
753
- });
1159
+ /** @deprecated Use `atlas.v2.connections(id).cancelOrder(ticket)` (`DELETE /api/v2/connections/{id}/orders/{ticket}`). */
1160
+ async cancelOrder(accountId, ticket, options) {
1161
+ await this.write("DELETE", accountId, `/orders/${ticket}`, void 0, options);
754
1162
  }
755
- // Positions
756
- async getPositions(accountId) {
757
- return this.http.request({
758
- method: "GET",
759
- path: this.path(accountId, "/positions")
760
- });
1163
+ async getPositions(accountId, options) {
1164
+ return this.read(accountId, "/positions", options);
761
1165
  }
762
- async getPosition(accountId, ticket) {
1166
+ async getPosition(accountId, ticket, options) {
1167
+ return this.read(accountId, `/positions/${ticket}`, options);
1168
+ }
1169
+ /** Fully closed positions from the terminal's deal history, oldest first. Page with `since` = the last `closeTimeMs`. */
1170
+ async getClosedPositions(accountId, query) {
763
1171
  return this.http.request({
764
1172
  method: "GET",
765
- path: this.path(accountId, `/positions/${ticket}`)
1173
+ path: this.path(accountId, "/positions/closed"),
1174
+ query: { since: query.since, until: query.until, limit: query.limit }
766
1175
  });
767
1176
  }
768
- async modifyPosition(accountId, ticket, body) {
769
- return this.http.request({
770
- method: "PATCH",
771
- path: this.path(accountId, `/positions/${ticket}`),
772
- body
773
- });
1177
+ /** @deprecated Use `atlas.v2.connections(id).modifyPosition(ticket, { stopLoss, takeProfit })` (`PUT /api/v2/connections/{id}/positions/{ticket}`). */
1178
+ async modifyPosition(accountId, ticket, body, options) {
1179
+ return this.write("PATCH", accountId, `/positions/${ticket}`, body, options);
774
1180
  }
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
- });
1181
+ /** @deprecated Use `atlas.v2.connections(id).closePosition({ instrumentKey, positionId: ticket })` (`POST /api/v2/connections/{id}/positions/close`). */
1182
+ async closePosition(accountId, ticket, body, options) {
1183
+ return this.write("POST", accountId, `/positions/${ticket}/close`, body, options);
781
1184
  }
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
- });
1185
+ /** @deprecated Use `atlas.v2.connections(id).closePosition({ instrumentKey })` (`POST /api/v2/connections/{id}/positions/close`). */
1186
+ async closeBySymbol(accountId, body, options) {
1187
+ return this.write("POST", accountId, "/positions/close-by-symbol", body, options);
788
1188
  }
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
- });
1189
+ async getPrice(accountId, symbol, options) {
1190
+ return this.read(accountId, `/price/${encodeURIComponent(symbol)}`, options);
795
1191
  }
796
- async getSymbols(accountId) {
797
- return this.http.request({
798
- method: "GET",
799
- path: this.path(accountId, "/symbols")
800
- });
1192
+ async getSymbols(accountId, options) {
1193
+ return this.read(accountId, "/symbols", options);
801
1194
  }
802
- async getAccountInfo(accountId) {
803
- return this.http.request({
804
- method: "GET",
805
- path: this.path(accountId, "/account")
806
- });
1195
+ async getSymbolSpecs(accountId, options) {
1196
+ return this.read(accountId, "/symbols/specs", options);
1197
+ }
1198
+ async getAccountInfo(accountId, options) {
1199
+ return this.read(accountId, "/account", options);
807
1200
  }
808
1201
  // Historical data
1202
+ /** @deprecated Use `atlas.v2.market.candles({ instrumentKey, interval, from, to, connectionId })` (`GET /api/v2/market/candles`). */
809
1203
  async getCandles(accountId, query) {
810
1204
  return this.http.request({
811
1205
  method: "GET",
812
1206
  path: this.path(accountId, "/candles"),
813
- query
1207
+ query: { symbol: query.symbol, timeframe: query.timeframe, startTime: query.startTime, endTime: query.endTime, count: query.count }
814
1208
  });
815
1209
  }
816
1210
  // Margin
1211
+ /** A calculation, not a write: it changes nothing on the terminal. */
817
1212
  async calculateMargin(accountId, body) {
818
1213
  return this.http.request({
819
1214
  method: "POST",
820
1215
  path: this.path(accountId, "/margins"),
821
- body
1216
+ body,
1217
+ idempotent: true
822
1218
  });
823
1219
  }
824
1220
  };
825
1221
 
826
1222
  // src/client.ts
827
1223
  var AtlasClient = class {
1224
+ /** MT5 platform (v1): instances and broker connections on `/api/atlas/instances`. */
828
1225
  instances;
1226
+ /** MT5 platform (v1): terminals by login, deploy, start, stop, remove. */
1227
+ mt5;
829
1228
  eas;
1229
+ backtests;
1230
+ /** MT5 trading on one terminal, by login. Mostly deprecated: use `v2.connections(id)` and `v2.market`, which work on every market. */
830
1231
  trading;
831
1232
  subscriptions;
832
1233
  serviceKeys;
1234
+ /** The market-neutral API (`/api/v2`): trading on every connection, instruments, market data and the scanner. */
833
1235
  v2;
834
1236
  http;
835
1237
  brokersResource;
@@ -842,7 +1244,9 @@ var AtlasClient = class {
842
1244
  logger: options.logger
843
1245
  });
844
1246
  this.instances = new InstancesResource(this.http);
1247
+ this.mt5 = new Mt5Resource(this.http);
845
1248
  this.eas = new EasResource(this.http);
1249
+ this.backtests = new BacktestsResource(this.http);
846
1250
  this.trading = new TradingResource(this.http);
847
1251
  this.subscriptions = new SubscriptionsResource(this.http);
848
1252
  this.serviceKeys = new ServiceKeysResource(this.http);
@@ -850,9 +1254,14 @@ var AtlasClient = class {
850
1254
  this.v2 = {
851
1255
  instruments: new InstrumentsV2(this.http),
852
1256
  market: new MarketV2(this.http),
1257
+ scanner: new ScannerV2(this.http),
853
1258
  connections: (connectionId) => new ConnectionsV2(this.http, connectionId)
854
1259
  };
855
1260
  }
1261
+ /**
1262
+ * A broker connection's own API, by broker name and the connection's `externalRef`.
1263
+ * @deprecated Use `v2.connections(connectionId)`, which takes the same `externalRef` and speaks one shape for every broker.
1264
+ */
856
1265
  broker(brokerName, connectionId) {
857
1266
  return this.brokersResource.connection(brokerName, connectionId);
858
1267
  }
@@ -958,8 +1367,14 @@ var AtlasWebSocket = class extends EventEmitter {
958
1367
  }
959
1368
  this.authenticated = false;
960
1369
  }
1370
+ /** Add channels and filters. The server merges every subscribe on a socket,
1371
+ * and so does the reconnect replay. Its `subscribed` reply names anything
1372
+ * refused; `subscribe_failed` means the account's standing refused it whole. */
961
1373
  subscribe(options) {
962
- this.activeSubscriptions = options;
1374
+ this.activeSubscriptions = mergeSubscriptions(this.activeSubscriptions, options);
1375
+ this.send(options);
1376
+ }
1377
+ send(options) {
963
1378
  this.sendJson({
964
1379
  type: "subscribe",
965
1380
  channels: options.channels,
@@ -972,14 +1387,17 @@ var AtlasWebSocket = class extends EventEmitter {
972
1387
  chains: options.chains
973
1388
  });
974
1389
  }
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
- }
1390
+ /** Drop channels, or only some instrumentKeys / chains while the channels
1391
+ * stay subscribed. Passing an array is the same as `{ channels }`. */
1392
+ unsubscribe(options) {
1393
+ const { channels = [], instrumentKeys, chains } = Array.isArray(options) ? { channels: options } : options;
1394
+ this.sendJson({ type: "unsubscribe", channels, instrumentKeys, chains });
1395
+ const active = this.activeSubscriptions;
1396
+ if (!active) return;
1397
+ active.channels = active.channels.filter((c) => !channels.includes(c));
1398
+ if (instrumentKeys && active.instrumentKeys) active.instrumentKeys = active.instrumentKeys.filter((k) => !instrumentKeys.includes(k));
1399
+ if (chains && active.chains) active.chains = active.chains.filter((c) => !chains.some((d) => d.underlyingKey === c.underlyingKey && d.expiry === c.expiry));
1400
+ if (!active.channels.includes("market.ticks") && !active.channels.includes("market.candles")) active.instrumentKeys = void 0;
983
1401
  }
984
1402
  get isConnected() {
985
1403
  return this.ws !== null && this.ws.readyState === OPEN && this.authenticated;
@@ -999,37 +1417,30 @@ var AtlasWebSocket = class extends EventEmitter {
999
1417
  onAuthSuccess();
1000
1418
  this.emit("connected");
1001
1419
  break;
1420
+ // Bad key, IP not allowed, rate limited, insufficient scope, or an
1421
+ // inactive or suspended account.
1002
1422
  case "service_auth_failed":
1003
1423
  onAuthFailure(new AtlasAuthError(msg.reason ?? "Authentication failed"));
1004
1424
  break;
1005
1425
  case "ping":
1006
1426
  this.sendJson({ type: "pong" });
1007
1427
  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.
1428
+ case "subscribed":
1429
+ case "subscribe_failed":
1430
+ case "unsubscribed":
1011
1431
  case "tick":
1012
- case "mt5_tick":
1013
- this.emit("tick", msg);
1014
- break;
1015
1432
  case "candle":
1016
- case "mt5_candle":
1017
- this.emit("candle", msg);
1018
- break;
1433
+ case "position_update":
1434
+ case "trade_event":
1435
+ case "heartbeat":
1019
1436
  case "market.tick":
1020
- this.emit("market.tick", msg);
1021
- break;
1022
1437
  case "market.candle":
1023
- this.emit("market.candle", msg);
1024
- break;
1438
+ case "market.chain":
1439
+ case "market.scanner":
1025
1440
  case "trading.order":
1026
- this.emit("trading.order", msg);
1027
- break;
1028
1441
  case "broker_tick":
1029
- this.emit("broker_tick", msg);
1030
- break;
1031
1442
  case "broker_order_update":
1032
- this.emit("broker_order_update", msg);
1443
+ this.emit(type, msg);
1033
1444
  break;
1034
1445
  }
1035
1446
  }
@@ -1049,7 +1460,7 @@ var AtlasWebSocket = class extends EventEmitter {
1049
1460
  try {
1050
1461
  await this.connect();
1051
1462
  if (this.activeSubscriptions) {
1052
- this.subscribe(this.activeSubscriptions);
1463
+ this.send(this.activeSubscriptions);
1053
1464
  }
1054
1465
  } catch {
1055
1466
  }
@@ -1069,7 +1480,25 @@ var AtlasWebSocket = class extends EventEmitter {
1069
1480
  return super.emit(event, ...args);
1070
1481
  }
1071
1482
  };
1483
+ function union(a, b, same = (x, y) => x === y) {
1484
+ if (!a) return b ? [...b] : void 0;
1485
+ if (!b) return a;
1486
+ return [...a, ...b.filter((y) => !a.some((x) => same(x, y)))];
1487
+ }
1488
+ function mergeSubscriptions(current, next) {
1489
+ if (!current) return { ...next, channels: [...next.channels] };
1490
+ return {
1491
+ channels: union(current.channels, next.channels) ?? [],
1492
+ accountIds: union(current.accountIds, next.accountIds),
1493
+ symbols: union(current.symbols, next.symbols),
1494
+ brokerConnectionIds: union(current.brokerConnectionIds, next.brokerConnectionIds),
1495
+ brokerSecurityKeys: union(current.brokerSecurityKeys, next.brokerSecurityKeys),
1496
+ brokerOrderConnectionIds: union(current.brokerOrderConnectionIds, next.brokerOrderConnectionIds),
1497
+ instrumentKeys: union(current.instrumentKeys, next.instrumentKeys),
1498
+ chains: union(current.chains, next.chains, (x, y) => x.underlyingKey === y.underlyingKey && x.expiry === y.expiry)
1499
+ };
1500
+ }
1072
1501
 
1073
- export { AtlasAuthError, AtlasClient, AtlasError, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, ConnectionsV2, MarketV2 };
1502
+ export { AtlasAuthError, AtlasClient, AtlasError, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, BacktestsResource, BrokerConnectionResource, BrokerSubscriptionsResource, ConnectionsV2, EasResource, InstancesResource, InstrumentsV2, MarketV2, Mt5Resource, ScannerV2, ServiceKeysResource, SubscriptionsResource, TradingResource };
1074
1503
  //# sourceMappingURL=index.js.map
1075
1504
  //# sourceMappingURL=index.js.map