atlaas 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,1074 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ // src/errors.ts
4
+ var AtlasError = class extends Error {
5
+ statusCode;
6
+ errorCode;
7
+ requestId;
8
+ constructor(message, statusCode = 0, errorCode, requestId) {
9
+ super(message);
10
+ this.name = "AtlasError";
11
+ this.statusCode = statusCode;
12
+ this.errorCode = errorCode;
13
+ this.requestId = requestId;
14
+ }
15
+ };
16
+ var AtlasAuthError = class extends AtlasError {
17
+ constructor(message, requestId) {
18
+ super(message, 401, void 0, requestId);
19
+ this.name = "AtlasAuthError";
20
+ }
21
+ };
22
+ var AtlasRateLimitError = class extends AtlasError {
23
+ retryAfter;
24
+ constructor(message, retryAfter, requestId) {
25
+ super(message, 429, void 0, requestId);
26
+ this.name = "AtlasRateLimitError";
27
+ this.retryAfter = retryAfter;
28
+ }
29
+ };
30
+ var AtlasValidationError = class extends AtlasError {
31
+ fields;
32
+ constructor(message, fields, requestId) {
33
+ super(message, 400, void 0, requestId);
34
+ this.name = "AtlasValidationError";
35
+ this.fields = fields;
36
+ }
37
+ };
38
+ var AtlasNetworkError = class extends AtlasError {
39
+ cause;
40
+ constructor(message, cause) {
41
+ super(message, 0);
42
+ this.name = "AtlasNetworkError";
43
+ this.cause = cause;
44
+ }
45
+ };
46
+
47
+ // src/http.ts
48
+ function buildUrl(baseUrl, path, query) {
49
+ const url = new URL(path, baseUrl);
50
+ if (query) {
51
+ for (const [key, value] of Object.entries(query)) {
52
+ if (value !== void 0) {
53
+ url.searchParams.set(key, String(value));
54
+ }
55
+ }
56
+ }
57
+ return url.toString();
58
+ }
59
+ function isRetryable(status) {
60
+ return status >= 500 || status === 408 || status === 429;
61
+ }
62
+ function jitter(base) {
63
+ return base * (0.5 + Math.random() * 0.5);
64
+ }
65
+ var HttpTransport = class {
66
+ baseUrl;
67
+ apiKey;
68
+ timeoutMs;
69
+ maxRetries;
70
+ logger;
71
+ constructor(options) {
72
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
73
+ this.apiKey = options.apiKey;
74
+ this.timeoutMs = options.timeoutMs ?? 3e4;
75
+ this.maxRetries = options.maxRetries ?? 2;
76
+ this.logger = options.logger;
77
+ }
78
+ async request(options) {
79
+ const url = buildUrl(this.baseUrl, options.path, options.query);
80
+ let lastError;
81
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
82
+ if (attempt > 0) {
83
+ const delay = jitter(Math.min(1e3 * 2 ** (attempt - 1), 1e4));
84
+ this.logger?.debug?.(`Retry attempt ${attempt} after ${Math.round(delay)}ms`, { url, attempt });
85
+ await new Promise((resolve) => setTimeout(resolve, delay));
86
+ }
87
+ const controller = new AbortController();
88
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
89
+ try {
90
+ const response = await fetch(url, {
91
+ method: options.method,
92
+ headers: {
93
+ "Content-Type": "application/json",
94
+ Authorization: `Bearer ${this.apiKey}`
95
+ },
96
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0,
97
+ signal: options.signal ?? controller.signal
98
+ });
99
+ clearTimeout(timeout);
100
+ if (response.status === 429) {
101
+ const retryAfter = response.headers.get("Retry-After");
102
+ if (attempt < this.maxRetries) {
103
+ lastError = new AtlasRateLimitError("Rate limited", retryAfter ? Number(retryAfter) : void 0);
104
+ continue;
105
+ }
106
+ throw new AtlasRateLimitError("Rate limited", retryAfter ? Number(retryAfter) : void 0);
107
+ }
108
+ const body = await response.json();
109
+ if (!body.success) {
110
+ const err = body;
111
+ throw this.mapError(response.status, err.error, err.errorCode);
112
+ }
113
+ return body.data;
114
+ } catch (error) {
115
+ clearTimeout(timeout);
116
+ if (error instanceof AtlasError) {
117
+ if (isRetryable(error.statusCode) && attempt < this.maxRetries) {
118
+ lastError = error;
119
+ continue;
120
+ }
121
+ throw error;
122
+ }
123
+ if (error instanceof DOMException && error.name === "AbortError") {
124
+ lastError = new AtlasNetworkError("Request timed out", error);
125
+ if (attempt < this.maxRetries) continue;
126
+ throw lastError;
127
+ }
128
+ lastError = new AtlasNetworkError(error instanceof Error ? error.message : "Network request failed", error);
129
+ if (attempt < this.maxRetries) continue;
130
+ throw lastError;
131
+ }
132
+ }
133
+ throw lastError ?? new AtlasNetworkError("Request failed after all retries");
134
+ }
135
+ mapError(status, message, errorCode) {
136
+ if (status === 401) return new AtlasAuthError(message);
137
+ if (status === 400) return new AtlasValidationError(message);
138
+ return new AtlasError(message, status, errorCode);
139
+ }
140
+ };
141
+
142
+ // src/resources/brokers.ts
143
+ var BrokerSubscriptionsResource = class {
144
+ /** @internal */
145
+ http;
146
+ /** @internal */
147
+ basePath;
148
+ constructor(http, basePath) {
149
+ this.http = http;
150
+ this.basePath = basePath;
151
+ }
152
+ async subscribe(body) {
153
+ return this.http.request({
154
+ method: "POST",
155
+ path: `${this.basePath}/subscriptions`,
156
+ body
157
+ });
158
+ }
159
+ async unsubscribe(body) {
160
+ return this.http.request({
161
+ method: "DELETE",
162
+ path: `${this.basePath}/subscriptions`,
163
+ body
164
+ });
165
+ }
166
+ async list() {
167
+ return this.http.request({
168
+ method: "GET",
169
+ path: `${this.basePath}/subscriptions`
170
+ });
171
+ }
172
+ };
173
+ var BrokerConnectionResource = class {
174
+ subscriptions;
175
+ /** @internal */
176
+ basePath;
177
+ /** @internal */
178
+ http;
179
+ constructor(http, brokerName, connectionId) {
180
+ this.http = http;
181
+ this.basePath = `/api/external/brokers/${encodeURIComponent(brokerName)}/connections/${encodeURIComponent(connectionId)}`;
182
+ this.subscriptions = new BrokerSubscriptionsResource(http, this.basePath);
183
+ }
184
+ // Orders
185
+ async placeOrder(body) {
186
+ return this.http.request({
187
+ method: "POST",
188
+ path: `${this.basePath}/orders`,
189
+ body
190
+ });
191
+ }
192
+ async getOrders() {
193
+ return this.http.request({
194
+ method: "GET",
195
+ path: `${this.basePath}/orders`
196
+ });
197
+ }
198
+ async getOrder(orderId) {
199
+ return this.http.request({
200
+ method: "GET",
201
+ path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`
202
+ });
203
+ }
204
+ async modifyOrder(orderId, body) {
205
+ return this.http.request({
206
+ method: "PUT",
207
+ path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
208
+ body
209
+ });
210
+ }
211
+ async cancelOrder(orderId, body) {
212
+ return this.http.request({
213
+ method: "DELETE",
214
+ path: `${this.basePath}/orders/${encodeURIComponent(orderId)}`,
215
+ body
216
+ });
217
+ }
218
+ // Trades
219
+ /** Trade book (fills). Currently served by Motilal Oswal; brokers whose
220
+ * runner adapter doesn't implement it return an "unsupported command" error. */
221
+ async getTrades() {
222
+ return this.http.request({
223
+ method: "GET",
224
+ path: `${this.basePath}/trades`
225
+ });
226
+ }
227
+ // Positions & Holdings
228
+ async getPositions() {
229
+ return this.http.request({
230
+ method: "GET",
231
+ path: `${this.basePath}/positions`
232
+ });
233
+ }
234
+ async getHoldings() {
235
+ return this.http.request({
236
+ method: "GET",
237
+ path: `${this.basePath}/holdings`
238
+ });
239
+ }
240
+ // Candles
241
+ async getCandles(query) {
242
+ return this.http.request({
243
+ method: "GET",
244
+ path: `${this.basePath}/candles`,
245
+ query
246
+ });
247
+ }
248
+ };
249
+ var BrokersResource = class {
250
+ constructor(http) {
251
+ this.http = http;
252
+ }
253
+ http;
254
+ connection(brokerName, connectionId) {
255
+ return new BrokerConnectionResource(this.http, brokerName, connectionId);
256
+ }
257
+ };
258
+
259
+ // src/resources/connections-v2.ts
260
+ var ConnectionsV2 = class {
261
+ constructor(http, connectionId) {
262
+ this.http = http;
263
+ this.connectionId = connectionId;
264
+ }
265
+ http;
266
+ connectionId;
267
+ async orders(params) {
268
+ return this.http.request({
269
+ method: "GET",
270
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
271
+ query: params
272
+ });
273
+ }
274
+ async order(orderId, params) {
275
+ return this.http.request({
276
+ method: "GET",
277
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
278
+ query: params
279
+ });
280
+ }
281
+ async trades() {
282
+ return this.http.request({
283
+ method: "GET",
284
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/trades`
285
+ });
286
+ }
287
+ async positions(params) {
288
+ return this.http.request({
289
+ method: "GET",
290
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions`,
291
+ query: params
292
+ });
293
+ }
294
+ async holdings() {
295
+ return this.http.request({
296
+ method: "GET",
297
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/holdings`
298
+ });
299
+ }
300
+ async funds() {
301
+ return this.http.request({
302
+ method: "GET",
303
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/funds`
304
+ });
305
+ }
306
+ async profile() {
307
+ return this.http.request({
308
+ method: "GET",
309
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/profile`
310
+ });
311
+ }
312
+ /** MT5 only: the broker server's contract specs (contract size, volume limits, tick size…),
313
+ * keyed to instruments where a ref exists. Held server-side for ~10 min; `symbol` filters. */
314
+ async symbols(params) {
315
+ return this.http.request({
316
+ method: "GET",
317
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/symbols`,
318
+ query: params
319
+ });
320
+ }
321
+ async capabilities() {
322
+ return this.http.request({
323
+ method: "GET",
324
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/capabilities`
325
+ });
326
+ }
327
+ async snapshot(params) {
328
+ return this.http.request({
329
+ method: "GET",
330
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/snapshot`,
331
+ query: params
332
+ });
333
+ }
334
+ // ── Writes (U3) ──────────────────────────────────────────────────────
335
+ async place(body, params) {
336
+ return this.http.request({
337
+ method: "POST",
338
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders`,
339
+ body,
340
+ query: params
341
+ });
342
+ }
343
+ async modify(orderId, body, params) {
344
+ return this.http.request({
345
+ method: "PUT",
346
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
347
+ body,
348
+ query: params
349
+ });
350
+ }
351
+ async cancel(orderId, params) {
352
+ return this.http.request({
353
+ method: "DELETE",
354
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/orders/${encodeURIComponent(orderId)}`,
355
+ query: params
356
+ });
357
+ }
358
+ async closePosition(body, params) {
359
+ return this.http.request({
360
+ method: "POST",
361
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions/close`,
362
+ body,
363
+ query: params
364
+ });
365
+ }
366
+ /** SL / TP on a live position (MT5). An omitted side keeps its level; 0 clears it. */
367
+ async modifyPosition(positionId, body, params) {
368
+ return this.http.request({
369
+ method: "PUT",
370
+ path: `/api/v2/connections/${encodeURIComponent(this.connectionId)}/positions/${encodeURIComponent(positionId)}`,
371
+ body,
372
+ query: params
373
+ });
374
+ }
375
+ };
376
+
377
+ // src/resources/eas.ts
378
+ var EasResource = class {
379
+ constructor(http) {
380
+ this.http = http;
381
+ }
382
+ http;
383
+ // ── Registry ──────────────────────────────────────────────────────────
384
+ async list() {
385
+ return this.http.request({
386
+ method: "GET",
387
+ path: "/api/external/eas"
388
+ });
389
+ }
390
+ async create(body) {
391
+ return this.http.request({
392
+ method: "POST",
393
+ path: "/api/external/eas",
394
+ body
395
+ });
396
+ }
397
+ async get(id) {
398
+ return this.http.request({
399
+ method: "GET",
400
+ path: `/api/external/eas/${encodeURIComponent(id)}`
401
+ });
402
+ }
403
+ async update(id, body) {
404
+ return this.http.request({
405
+ method: "PATCH",
406
+ path: `/api/external/eas/${encodeURIComponent(id)}`,
407
+ body
408
+ });
409
+ }
410
+ async remove(id) {
411
+ return this.http.request({
412
+ method: "DELETE",
413
+ path: `/api/external/eas/${encodeURIComponent(id)}`
414
+ });
415
+ }
416
+ // ── Versions ──────────────────────────────────────────────────────────
417
+ async listVersions(eaId, query) {
418
+ return this.http.request({
419
+ method: "GET",
420
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions`,
421
+ query
422
+ });
423
+ }
424
+ /** Issue a short-lived R2 upload URL for a new .ex5/.mq5 build. */
425
+ async presignVersion(eaId, body) {
426
+ return this.http.request({
427
+ method: "POST",
428
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/presigned`,
429
+ body
430
+ });
431
+ }
432
+ /** Register an already-uploaded build (the r2Key returned by presignVersion). */
433
+ async registerVersion(eaId, body) {
434
+ return this.http.request({
435
+ method: "POST",
436
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions`,
437
+ body
438
+ });
439
+ }
440
+ /** Mark a version LIVE (rollback) without re-uploading. */
441
+ async promoteVersion(eaId, versionId) {
442
+ return this.http.request({
443
+ method: "POST",
444
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}/promote`
445
+ });
446
+ }
447
+ async deleteVersion(eaId, versionId) {
448
+ return this.http.request({
449
+ method: "DELETE",
450
+ path: `/api/external/eas/${encodeURIComponent(eaId)}/versions/${encodeURIComponent(versionId)}`
451
+ });
452
+ }
453
+ // ── Deployments ───────────────────────────────────────────────────────
454
+ async listDeployments(query) {
455
+ return this.http.request({
456
+ method: "GET",
457
+ path: "/api/external/deployments",
458
+ query
459
+ });
460
+ }
461
+ /** Bind a version to a chart inside one of the caller's instances. The
462
+ * setBlob is the .set input-override text; edit it via updateDeployment. */
463
+ async deploy(body) {
464
+ return this.http.request({
465
+ method: "POST",
466
+ path: "/api/external/deployments",
467
+ body
468
+ });
469
+ }
470
+ async getDeployment(id) {
471
+ return this.http.request({
472
+ method: "GET",
473
+ path: `/api/external/deployments/${encodeURIComponent(id)}`
474
+ });
475
+ }
476
+ async updateDeployment(id, body) {
477
+ return this.http.request({
478
+ method: "PATCH",
479
+ path: `/api/external/deployments/${encodeURIComponent(id)}`,
480
+ body
481
+ });
482
+ }
483
+ async removeDeployment(id) {
484
+ return this.http.request({
485
+ method: "DELETE",
486
+ path: `/api/external/deployments/${encodeURIComponent(id)}`
487
+ });
488
+ }
489
+ };
490
+
491
+ // src/resources/instances.ts
492
+ var InstancesResource = class {
493
+ constructor(http) {
494
+ this.http = http;
495
+ }
496
+ http;
497
+ async list(query) {
498
+ return this.http.request({
499
+ method: "GET",
500
+ path: "/api/atlas/instances",
501
+ query
502
+ });
503
+ }
504
+ async get(id) {
505
+ return this.http.request({
506
+ method: "GET",
507
+ path: `/api/atlas/instances/${encodeURIComponent(id)}`
508
+ });
509
+ }
510
+ async getByExternalRef(ref) {
511
+ return this.http.request({
512
+ method: "GET",
513
+ path: `/api/atlas/instances/by-external-ref/${encodeURIComponent(ref)}`
514
+ });
515
+ }
516
+ async getByExternalRefs(refs) {
517
+ return this.http.request({
518
+ method: "POST",
519
+ path: "/api/atlas/instances/by-external-refs",
520
+ body: { refs }
521
+ });
522
+ }
523
+ async create(body) {
524
+ return this.http.request({
525
+ method: "POST",
526
+ path: "/api/atlas/instances",
527
+ body
528
+ });
529
+ }
530
+ async update(id, body) {
531
+ return this.http.request({
532
+ method: "PATCH",
533
+ path: `/api/atlas/instances/${encodeURIComponent(id)}`,
534
+ body
535
+ });
536
+ }
537
+ /**
538
+ * Wind an instance down: the host runner kills the terminal process and
539
+ * deletes the instance folder. Credentials stay stored, so the instance
540
+ * can be re-enabled later. Returns the updated instance.
541
+ */
542
+ async disable(id) {
543
+ return this.http.request({
544
+ method: "POST",
545
+ path: `/api/atlas/instances/${encodeURIComponent(id)}/disable`
546
+ });
547
+ }
548
+ /**
549
+ * Re-enable a wound-down instance: resets it to PENDING so the runner
550
+ * redeploys it fresh. Returns the updated instance.
551
+ */
552
+ async enable(id) {
553
+ return this.http.request({
554
+ method: "POST",
555
+ path: `/api/atlas/instances/${encodeURIComponent(id)}/enable`
556
+ });
557
+ }
558
+ async delete(id) {
559
+ await this.http.request({
560
+ method: "DELETE",
561
+ path: `/api/atlas/instances/${encodeURIComponent(id)}`
562
+ });
563
+ }
564
+ };
565
+
566
+ // src/resources/instruments-v2.ts
567
+ var InstrumentsV2 = class {
568
+ constructor(http) {
569
+ this.http = http;
570
+ }
571
+ http;
572
+ async list(params = {}) {
573
+ return this.http.request({
574
+ method: "GET",
575
+ path: "/api/v2/instruments",
576
+ query: params
577
+ });
578
+ }
579
+ async get(instrumentKey) {
580
+ return this.http.request({
581
+ method: "GET",
582
+ path: `/api/v2/instruments/${encodeURIComponent(instrumentKey)}`
583
+ });
584
+ }
585
+ async resolve(params) {
586
+ return this.http.request({
587
+ method: "GET",
588
+ path: "/api/v2/instruments/resolve",
589
+ query: params
590
+ });
591
+ }
592
+ };
593
+
594
+ // src/resources/market-v2.ts
595
+ var MarketV2 = class {
596
+ constructor(http) {
597
+ this.http = http;
598
+ }
599
+ http;
600
+ /** Latest tick. A vendor key nobody is watching is subscribed and read
601
+ * once from the vendor's REST endpoint, so this answers with a
602
+ * `mode: "LTP"` snapshot rather than a retry-later 404. */
603
+ async quote(instrumentKey) {
604
+ return this.http.request({ method: "GET", path: "/api/v2/market/quote", query: { instrumentKey } });
605
+ }
606
+ /** Latest tick for up to 200 keys, with the cold ones read in one vendor
607
+ * call. `unresolved` names the keys that could not be priced and why —
608
+ * it is never silently short. */
609
+ async quotes(instrumentKeys) {
610
+ return this.http.request({ method: "GET", path: "/api/v2/market/quote", query: { instrumentKeys: instrumentKeys.join(",") } });
611
+ }
612
+ async candles(params) {
613
+ const iso = (v) => v instanceof Date ? v.toISOString() : v;
614
+ return this.http.request({
615
+ method: "GET",
616
+ path: "/api/v2/market/candles",
617
+ query: { instrumentKey: params.instrumentKey, interval: params.interval, from: iso(params.from), to: iso(params.to), connectionId: params.connectionId }
618
+ });
619
+ }
620
+ /** Option expiries for an index or equity underlying (`NSE:IDX:NIFTY`, `NSE:EQ:RELIANCE`), served by the vendor feed. */
621
+ async expiries(underlyingKey) {
622
+ return this.http.request({ method: "GET", path: "/api/v2/market/expiries", query: { underlyingKey } });
623
+ }
624
+ /** Full option chain for one expiry (`YYYY-MM-DD`). Every leg carries its
625
+ * canonical instrumentKey. Identical calls within ~3 s share one vendor request. */
626
+ async optionChain(underlyingKey, expiry) {
627
+ return this.http.request({ method: "GET", path: "/api/v2/market/option-chain", query: { underlyingKey, expiry } });
628
+ }
629
+ };
630
+
631
+ // src/resources/service-keys.ts
632
+ var ServiceKeysResource = class {
633
+ constructor(http) {
634
+ this.http = http;
635
+ }
636
+ http;
637
+ async list(accountId, query) {
638
+ return this.http.request({
639
+ method: "GET",
640
+ path: `/api/public/atlas-accounts/${encodeURIComponent(accountId)}/service-keys`,
641
+ query
642
+ });
643
+ }
644
+ async create(accountId, body) {
645
+ return this.http.request({
646
+ method: "POST",
647
+ path: `/api/public/atlas-accounts/${encodeURIComponent(accountId)}/service-keys`,
648
+ body
649
+ });
650
+ }
651
+ async update(keyId, body) {
652
+ return this.http.request({
653
+ method: "PATCH",
654
+ path: `/api/public/service-keys/${encodeURIComponent(keyId)}`,
655
+ body
656
+ });
657
+ }
658
+ async delete(keyId) {
659
+ await this.http.request({
660
+ method: "DELETE",
661
+ path: `/api/public/service-keys/${encodeURIComponent(keyId)}`
662
+ });
663
+ }
664
+ async regenerate(keyId) {
665
+ return this.http.request({
666
+ method: "POST",
667
+ path: `/api/public/service-keys/${encodeURIComponent(keyId)}/regenerate`
668
+ });
669
+ }
670
+ };
671
+
672
+ // src/resources/subscriptions.ts
673
+ var SubscriptionsResource = class {
674
+ constructor(http) {
675
+ this.http = http;
676
+ }
677
+ http;
678
+ path(instanceId, suffix) {
679
+ return `/api/instances/${encodeURIComponent(instanceId)}${suffix}`;
680
+ }
681
+ // Tick subscriptions
682
+ async subscribeTick(instanceId, body) {
683
+ return this.http.request({
684
+ method: "POST",
685
+ path: this.path(instanceId, "/subscribe-tick"),
686
+ body
687
+ });
688
+ }
689
+ async unsubscribeTick(instanceId, body) {
690
+ return this.http.request({
691
+ method: "POST",
692
+ path: this.path(instanceId, "/unsubscribe-tick"),
693
+ body
694
+ });
695
+ }
696
+ async getTickSubscriptions(instanceId) {
697
+ return this.http.request({
698
+ method: "GET",
699
+ path: this.path(instanceId, "/tick-subscriptions")
700
+ });
701
+ }
702
+ // Candle subscriptions
703
+ async subscribeCandle(instanceId, body) {
704
+ return this.http.request({
705
+ method: "POST",
706
+ path: this.path(instanceId, "/subscribe-candle"),
707
+ body
708
+ });
709
+ }
710
+ async unsubscribeCandle(instanceId, body) {
711
+ return this.http.request({
712
+ method: "POST",
713
+ path: this.path(instanceId, "/unsubscribe-candle"),
714
+ body
715
+ });
716
+ }
717
+ async getCandleSubscriptions(instanceId) {
718
+ return this.http.request({
719
+ method: "GET",
720
+ path: this.path(instanceId, "/candle-subscriptions")
721
+ });
722
+ }
723
+ };
724
+
725
+ // src/resources/trading.ts
726
+ var TradingResource = class {
727
+ constructor(http) {
728
+ this.http = http;
729
+ }
730
+ http;
731
+ path(accountId, suffix) {
732
+ return `/api/external/instances/${encodeURIComponent(accountId)}${suffix}`;
733
+ }
734
+ // Orders
735
+ async placeOrder(accountId, body) {
736
+ return this.http.request({
737
+ method: "POST",
738
+ path: this.path(accountId, "/orders"),
739
+ body
740
+ });
741
+ }
742
+ async getOrders(accountId) {
743
+ return this.http.request({
744
+ method: "GET",
745
+ path: this.path(accountId, "/orders")
746
+ });
747
+ }
748
+ async cancelOrder(accountId, ticket) {
749
+ await this.http.request({
750
+ method: "DELETE",
751
+ path: this.path(accountId, `/orders/${ticket}`)
752
+ });
753
+ }
754
+ // Positions
755
+ async getPositions(accountId) {
756
+ return this.http.request({
757
+ method: "GET",
758
+ path: this.path(accountId, "/positions")
759
+ });
760
+ }
761
+ async getPosition(accountId, ticket) {
762
+ return this.http.request({
763
+ method: "GET",
764
+ path: this.path(accountId, `/positions/${ticket}`)
765
+ });
766
+ }
767
+ async modifyPosition(accountId, ticket, body) {
768
+ return this.http.request({
769
+ method: "PATCH",
770
+ path: this.path(accountId, `/positions/${ticket}`),
771
+ body
772
+ });
773
+ }
774
+ async closePosition(accountId, ticket, body) {
775
+ return this.http.request({
776
+ method: "POST",
777
+ path: this.path(accountId, `/positions/${ticket}/close`),
778
+ body
779
+ });
780
+ }
781
+ async closeBySymbol(accountId, body) {
782
+ return this.http.request({
783
+ method: "POST",
784
+ path: this.path(accountId, "/positions/close-by-symbol"),
785
+ body
786
+ });
787
+ }
788
+ // Market data
789
+ async getPrice(accountId, symbol) {
790
+ return this.http.request({
791
+ method: "GET",
792
+ path: this.path(accountId, `/price/${encodeURIComponent(symbol)}`)
793
+ });
794
+ }
795
+ async getSymbols(accountId) {
796
+ return this.http.request({
797
+ method: "GET",
798
+ path: this.path(accountId, "/symbols")
799
+ });
800
+ }
801
+ async getAccountInfo(accountId) {
802
+ return this.http.request({
803
+ method: "GET",
804
+ path: this.path(accountId, "/account")
805
+ });
806
+ }
807
+ // Historical data
808
+ async getCandles(accountId, query) {
809
+ return this.http.request({
810
+ method: "GET",
811
+ path: this.path(accountId, "/candles"),
812
+ query
813
+ });
814
+ }
815
+ // Margin
816
+ async calculateMargin(accountId, body) {
817
+ return this.http.request({
818
+ method: "POST",
819
+ path: this.path(accountId, "/margins"),
820
+ body
821
+ });
822
+ }
823
+ };
824
+
825
+ // src/client.ts
826
+ var AtlasClient = class {
827
+ instances;
828
+ eas;
829
+ trading;
830
+ subscriptions;
831
+ serviceKeys;
832
+ v2;
833
+ http;
834
+ brokersResource;
835
+ constructor(options) {
836
+ this.http = new HttpTransport({
837
+ baseUrl: options.baseUrl,
838
+ apiKey: options.apiKey,
839
+ timeoutMs: options.timeoutMs,
840
+ maxRetries: options.maxRetries,
841
+ logger: options.logger
842
+ });
843
+ this.instances = new InstancesResource(this.http);
844
+ this.eas = new EasResource(this.http);
845
+ this.trading = new TradingResource(this.http);
846
+ this.subscriptions = new SubscriptionsResource(this.http);
847
+ this.serviceKeys = new ServiceKeysResource(this.http);
848
+ this.brokersResource = new BrokersResource(this.http);
849
+ this.v2 = {
850
+ instruments: new InstrumentsV2(this.http),
851
+ market: new MarketV2(this.http),
852
+ connections: (connectionId) => new ConnectionsV2(this.http, connectionId)
853
+ };
854
+ }
855
+ broker(brokerName, connectionId) {
856
+ return this.brokersResource.connection(brokerName, connectionId);
857
+ }
858
+ };
859
+ var OPEN = 1;
860
+ async function createWebSocket(url) {
861
+ if (typeof globalThis.WebSocket !== "undefined") {
862
+ return new globalThis.WebSocket(url);
863
+ }
864
+ try {
865
+ const { default: WS } = await import('ws');
866
+ return new WS(url);
867
+ } catch {
868
+ throw new AtlasNetworkError("WebSocket not available. Install the 'ws' package for Node.js: npm install ws");
869
+ }
870
+ }
871
+ var AtlasWebSocket = class extends EventEmitter {
872
+ ws = null;
873
+ authenticated = false;
874
+ reconnectAttempts = 0;
875
+ reconnectTimer = null;
876
+ activeSubscriptions = null;
877
+ url;
878
+ apiKey;
879
+ clientName;
880
+ autoReconnect;
881
+ reconnectDelayMs;
882
+ maxReconnectAttempts;
883
+ intentionalClose = false;
884
+ constructor(options) {
885
+ super();
886
+ const base = options.baseUrl.replace(/^http/, "ws").replace(/\/$/, "");
887
+ this.url = `${base}/ws/service`;
888
+ this.apiKey = options.apiKey;
889
+ this.clientName = options.clientName;
890
+ this.autoReconnect = options.autoReconnect ?? true;
891
+ this.reconnectDelayMs = options.reconnectDelayMs ?? 2e3;
892
+ this.maxReconnectAttempts = options.maxReconnectAttempts ?? 10;
893
+ }
894
+ async connect() {
895
+ this.intentionalClose = false;
896
+ return new Promise((resolve, reject) => {
897
+ createWebSocket(this.url).then((ws) => {
898
+ this.ws = ws;
899
+ let settled = false;
900
+ ws.onopen = () => {
901
+ this.reconnectAttempts = 0;
902
+ };
903
+ ws.onmessage = (event) => {
904
+ const raw = typeof event.data === "string" ? event.data : String(event.data);
905
+ let msg;
906
+ try {
907
+ msg = JSON.parse(raw);
908
+ } catch {
909
+ return;
910
+ }
911
+ this.handleMessage(
912
+ msg,
913
+ () => {
914
+ if (!settled) {
915
+ settled = true;
916
+ resolve();
917
+ }
918
+ },
919
+ (err) => {
920
+ if (!settled) {
921
+ settled = true;
922
+ reject(err);
923
+ }
924
+ }
925
+ );
926
+ };
927
+ ws.onclose = (event) => {
928
+ this.authenticated = false;
929
+ this.ws = null;
930
+ if (!settled) {
931
+ settled = true;
932
+ reject(new AtlasNetworkError(`WebSocket closed before auth: ${event.reason || event.code}`));
933
+ }
934
+ this.emit("disconnected", event.reason || String(event.code));
935
+ if (this.autoReconnect && !this.intentionalClose) {
936
+ this.scheduleReconnect();
937
+ }
938
+ };
939
+ ws.onerror = () => {
940
+ if (!settled) {
941
+ settled = true;
942
+ reject(new AtlasNetworkError("WebSocket connection failed"));
943
+ }
944
+ };
945
+ }).catch(reject);
946
+ });
947
+ }
948
+ disconnect() {
949
+ this.intentionalClose = true;
950
+ if (this.reconnectTimer) {
951
+ clearTimeout(this.reconnectTimer);
952
+ this.reconnectTimer = null;
953
+ }
954
+ if (this.ws) {
955
+ this.ws.close(1e3, "client disconnect");
956
+ this.ws = null;
957
+ }
958
+ this.authenticated = false;
959
+ }
960
+ subscribe(options) {
961
+ this.activeSubscriptions = options;
962
+ this.sendJson({
963
+ type: "subscribe",
964
+ channels: options.channels,
965
+ accountIds: options.accountIds,
966
+ symbols: options.symbols,
967
+ brokerConnectionIds: options.brokerConnectionIds,
968
+ brokerSecurityKeys: options.brokerSecurityKeys,
969
+ brokerOrderConnectionIds: options.brokerOrderConnectionIds,
970
+ instrumentKeys: options.instrumentKeys,
971
+ chains: options.chains
972
+ });
973
+ }
974
+ unsubscribe(channels) {
975
+ this.sendJson({ type: "unsubscribe", channels });
976
+ if (this.activeSubscriptions) {
977
+ this.activeSubscriptions.channels = this.activeSubscriptions.channels.filter((c) => !channels.includes(c));
978
+ if (this.activeSubscriptions.channels.length === 0) {
979
+ this.activeSubscriptions = null;
980
+ }
981
+ }
982
+ }
983
+ get isConnected() {
984
+ return this.ws !== null && this.ws.readyState === OPEN && this.authenticated;
985
+ }
986
+ handleMessage(msg, onAuthSuccess, onAuthFailure) {
987
+ const type = msg.type;
988
+ switch (type) {
989
+ case "hello_from_atlas":
990
+ this.sendJson({
991
+ type: "service_auth",
992
+ apiKey: this.apiKey,
993
+ clientName: this.clientName
994
+ });
995
+ break;
996
+ case "service_auth_success":
997
+ this.authenticated = true;
998
+ onAuthSuccess();
999
+ this.emit("connected");
1000
+ break;
1001
+ case "service_auth_failed":
1002
+ onAuthFailure(new AtlasAuthError(msg.reason ?? "Authentication failed"));
1003
+ break;
1004
+ case "ping":
1005
+ this.sendJson({ type: "pong" });
1006
+ break;
1007
+ // The server emits `tick` / `candle` on the service WS (the mt5_
1008
+ // prefix is stripped in handleMT5Tick/handleMT5Candle); the
1009
+ // prefixed cases are kept for any relay that forwards raw frames.
1010
+ case "tick":
1011
+ case "mt5_tick":
1012
+ this.emit("tick", msg);
1013
+ break;
1014
+ case "candle":
1015
+ case "mt5_candle":
1016
+ this.emit("candle", msg);
1017
+ break;
1018
+ case "market.tick":
1019
+ this.emit("market.tick", msg);
1020
+ break;
1021
+ case "market.candle":
1022
+ this.emit("market.candle", msg);
1023
+ break;
1024
+ case "trading.order":
1025
+ this.emit("trading.order", msg);
1026
+ break;
1027
+ case "broker_tick":
1028
+ this.emit("broker_tick", msg);
1029
+ break;
1030
+ case "broker_order_update":
1031
+ this.emit("broker_order_update", msg);
1032
+ break;
1033
+ }
1034
+ }
1035
+ sendJson(data) {
1036
+ if (this.ws && this.ws.readyState === OPEN) {
1037
+ this.ws.send(JSON.stringify(data));
1038
+ }
1039
+ }
1040
+ scheduleReconnect() {
1041
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
1042
+ this.emit("error", new AtlasNetworkError(`Max reconnect attempts (${this.maxReconnectAttempts}) exceeded`));
1043
+ return;
1044
+ }
1045
+ const delay = this.reconnectDelayMs * 2 ** this.reconnectAttempts * (0.5 + Math.random() * 0.5);
1046
+ this.reconnectAttempts++;
1047
+ this.reconnectTimer = setTimeout(async () => {
1048
+ try {
1049
+ await this.connect();
1050
+ if (this.activeSubscriptions) {
1051
+ this.subscribe(this.activeSubscriptions);
1052
+ }
1053
+ } catch {
1054
+ }
1055
+ }, delay);
1056
+ }
1057
+ // Typed event emitter overloads
1058
+ on(event, listener) {
1059
+ return super.on(event, listener);
1060
+ }
1061
+ once(event, listener) {
1062
+ return super.once(event, listener);
1063
+ }
1064
+ off(event, listener) {
1065
+ return super.off(event, listener);
1066
+ }
1067
+ emit(event, ...args) {
1068
+ return super.emit(event, ...args);
1069
+ }
1070
+ };
1071
+
1072
+ export { AtlasAuthError, AtlasClient, AtlasError, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, ConnectionsV2, MarketV2 };
1073
+ //# sourceMappingURL=index.js.map
1074
+ //# sourceMappingURL=index.js.map