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.d.ts CHANGED
@@ -1,40 +1,5 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
 
3
- interface HttpTransportOptions {
4
- baseUrl: string;
5
- apiKey: string;
6
- timeoutMs?: number;
7
- maxRetries?: number;
8
- logger?: AtlasLogger;
9
- }
10
- interface AtlasLogger {
11
- debug?: (message: string, meta?: Record<string, unknown>) => void;
12
- info?: (message: string, meta?: Record<string, unknown>) => void;
13
- warn?: (message: string, meta?: Record<string, unknown>) => void;
14
- error?: (message: string, meta?: Record<string, unknown>) => void;
15
- }
16
- interface RequestOptions {
17
- method: string;
18
- path: string;
19
- body?: unknown;
20
- query?: Record<string, string | number | boolean | undefined>;
21
- signal?: AbortSignal;
22
- /** Sent as `Idempotency-Key`. Writes get a fresh one per call when omitted,
23
- * and every retry of the call reuses it, so a retried order is never
24
- * placed twice. */
25
- idempotencyKey?: string;
26
- }
27
- declare class HttpTransport {
28
- private readonly baseUrl;
29
- private readonly apiKey;
30
- private readonly timeoutMs;
31
- private readonly maxRetries;
32
- private readonly logger?;
33
- constructor(options: HttpTransportOptions);
34
- request<T>(options: RequestOptions): Promise<T>;
35
- private mapError;
36
- }
37
-
38
3
  type InstanceState = "PENDING" | "DEPLOYING" | "DEPLOYED" | "RUNNING" | "STOPPED" | "ERROR";
39
4
  type InstanceType = "TICK" | "TICKS_TRADE" | "TRADE";
40
5
  type OrderDirection = "BUY" | "SELL";
@@ -59,42 +24,108 @@ interface Instance {
59
24
  createdAt: string;
60
25
  updatedAt: string;
61
26
  }
27
+ /** An instance on `/api/atlas/instances`: an MT5 terminal or a broker connection. */
62
28
  interface AtlasInstance {
63
29
  id: string;
30
+ atlasAccountId: string | null;
64
31
  externalRef: string | null;
65
32
  externalUserId: string | null;
66
33
  instanceKind: string | null;
67
34
  /** Broker-side account identifier: MT5 login or broker clientId (Dhan/Kite). */
68
35
  accountId: string | null;
69
36
  runnerId: string;
37
+ name: string | null;
70
38
  state: InstanceState;
71
39
  enabled: boolean;
40
+ autoRestart: boolean;
41
+ containerCpus: string | null;
42
+ containerMemory: string | null;
43
+ /** The IPv4 address the broker whitelists for this connection. */
72
44
  registeredIp: string | null;
45
+ ipVerifiedAt: string | null;
73
46
  lastActiveAt: string | null;
74
47
  connectedAt: string | null;
75
48
  disconnectedAt: string | null;
49
+ /** A 64-bit counter, sent as a decimal string. */
50
+ ticksReceived: string;
51
+ /** A 64-bit counter, sent as a decimal string. */
52
+ tradesExecuted: string;
53
+ errorCount: number;
54
+ avgLatencyMs: number | null;
76
55
  statusMessage: string | null;
77
56
  errorMessage: string | null;
78
- lastError?: string | null;
79
- lastErrorAt?: string | null;
80
- displayName?: string | null;
81
- metadata?: Record<string, unknown> | null;
82
- createdAt?: string;
83
- updatedAt?: string;
57
+ lastError: string | null;
58
+ lastErrorAt: string | null;
59
+ lastSyncedAt: string | null;
60
+ retryCount: number;
61
+ nextRetryAt: string | null;
62
+ displayName: string | null;
63
+ metadata: Record<string, unknown> | null;
64
+ /** Broker funds, as decimal strings. */
65
+ availableBalance: string | null;
66
+ equity: string | null;
67
+ utilizedAmount: string | null;
68
+ collateralAmount: string | null;
69
+ withdrawableBalance: string | null;
70
+ profileData: unknown;
71
+ fundsSyncedAt: string | null;
72
+ runner: {
73
+ ipAddress: string | null;
74
+ health: "HEALTHY" | "DEGRADED" | "UNHEALTHY";
75
+ lastSeenAt: string | null;
76
+ managedRunner: {
77
+ state: "PROVISIONING" | "ACTIVE" | "FAILED" | "DEPROVISIONING" | "DELETED";
78
+ ipAddress: string | null;
79
+ lastError: string | null;
80
+ } | null;
81
+ };
82
+ createdAt: string;
83
+ updatedAt: string;
84
84
  }
85
+ /** POST /api/external/instances: deploy an MT5 terminal. */
85
86
  interface CreateInstanceBody {
87
+ /** The MT5 login. */
86
88
  accountId: string;
87
89
  password?: string;
90
+ /** A `serverName` from `mt5.servers()`. */
88
91
  serverName: string;
89
92
  brokerName?: string;
90
93
  name?: string;
94
+ /** Default TICK. */
91
95
  type?: InstanceType;
96
+ /** A region `id` from `mt5.regions()`; omitted, Atlaas picks one. */
97
+ regionId?: string;
98
+ /** Your own id for the terminal. */
99
+ externalRef?: string;
100
+ }
101
+ /** An MT5 server the deploy catalogue offers. */
102
+ interface DeployServer {
103
+ /** What `mt5.create()` takes as `serverName`. */
104
+ serverName: string;
105
+ brokerName: string;
106
+ displayName: string | null;
107
+ /** `demo` or `live`. */
108
+ serverType: string | null;
109
+ defaultSymbol: string | null;
110
+ }
111
+ /** A region with room for a new MT5 terminal. */
112
+ interface DeployRegion {
113
+ /** What `mt5.create()` takes as `regionId`. */
114
+ id: string;
115
+ code: string;
116
+ displayName: string;
117
+ description: string | null;
92
118
  }
93
119
  interface CreateAtlasInstanceBody {
120
+ /** Upsert key: an existing instance of yours with this ref is updated instead. */
94
121
  externalRef?: string;
95
122
  externalUserId?: string;
96
123
  instanceKind: string;
97
- runnerId: string;
124
+ /** Omit it for a broker connection (dhan, kite, motilal, angelone, fyers,
125
+ * upstox, shoonya, bybit, deribit, kraken, hyperliquid, coindcx, delta,
126
+ * alpaca, tastytrade, lime): Atlaas places it on a server of its own.
127
+ * Required for every other kind, `mt5` included. */
128
+ runnerId?: string;
98
129
  name?: string;
99
130
  metadata?: Record<string, unknown>;
100
131
  credentials: Record<string, unknown>;
@@ -102,14 +133,53 @@ interface CreateAtlasInstanceBody {
102
133
  * account); only master-key callers set it, and it must be a real AtlasAccount. */
103
134
  atlasAccountId?: string;
104
135
  }
136
+ interface CreateAtlasInstanceResult {
137
+ id: string;
138
+ externalRef: string | null;
139
+ runnerId: string;
140
+ /** False while a managed server is still being built. */
141
+ runnerReady: boolean;
142
+ /** The address the broker sees: the managed server's reserved IP, or the runner's. */
143
+ ipAddress: string | null;
144
+ managedRunnerId: string | null;
145
+ }
105
146
  interface UpdateAtlasInstanceBody {
106
147
  state?: InstanceState;
107
148
  enabled?: boolean;
108
149
  autoRestart?: boolean;
150
+ name?: string;
109
151
  metadata?: Record<string, unknown>;
152
+ /** Replaces the stored credentials. */
110
153
  credentials?: Record<string, unknown>;
154
+ /** Merges into the stored credentials; ignored when `credentials` is sent. */
111
155
  credentialsPatch?: Record<string, unknown>;
112
156
  }
157
+ interface ValidateBrokerCredentialsBody {
158
+ brokerName: string;
159
+ /** For Dhan: `{ clientId, pin, totpSecret }`. */
160
+ credentials: Record<string, unknown>;
161
+ }
162
+ /**
163
+ * Validity is data: a well-formed request always answers 200. Only Dhan is
164
+ * checked today, by logging in (which mints a real access token, at most one
165
+ * every two minutes); any other broker's credentials come back unchanged with
166
+ * `validated: false`.
167
+ */
168
+ type ValidateBrokerCredentialsResult = {
169
+ valid: true;
170
+ validated: false;
171
+ credentials: Record<string, unknown>;
172
+ } | {
173
+ valid: true;
174
+ validated: true;
175
+ credentials: Record<string, unknown> & {
176
+ accessToken: string;
177
+ accessTokenExpiry: number;
178
+ };
179
+ } | {
180
+ valid: false;
181
+ error: string;
182
+ };
113
183
  interface ListInstancesQuery {
114
184
  instanceKind?: string;
115
185
  state?: string;
@@ -131,21 +201,137 @@ interface AccountInfo {
131
201
  marginLevel?: number;
132
202
  tradeAllowed?: boolean;
133
203
  }
204
+ /** One open MT5 position, as the EA last pushed it. */
134
205
  interface Position {
135
206
  ticket: number;
207
+ /** POSITION_IDENTIFIER, the id deals carry. Absent from older connector EAs. */
208
+ identifier?: number;
136
209
  symbol: string;
137
210
  type: OrderDirection;
138
211
  volume: number;
139
212
  openPrice: number;
140
213
  currentPrice: number;
214
+ /** 0 is none. */
141
215
  sl: number;
216
+ /** 0 is none. */
142
217
  tp: number;
143
218
  profit: number;
144
219
  swap: number;
220
+ /** Epoch seconds, broker server clock. */
145
221
  openTime: number;
222
+ /** @deprecated Never sent on this route; closed positions carry it. */
146
223
  commission?: number;
147
224
  comment?: string;
225
+ /** 0 is a manual trade. */
148
226
  magic?: number;
227
+ digits?: number;
228
+ point?: number;
229
+ volumeMin?: number;
230
+ volumeStep?: number;
231
+ }
232
+ interface PositionDetailBase {
233
+ ticket: number;
234
+ symbol: string;
235
+ type: OrderDirection;
236
+ volume: number;
237
+ openPrice: number;
238
+ profit: number;
239
+ swap: number;
240
+ /** Epoch seconds, broker server clock. */
241
+ openTime: number;
242
+ comment?: string;
243
+ }
244
+ interface OpenPositionDetail extends PositionDetailBase {
245
+ status: "OPEN";
246
+ currentPrice: number;
247
+ sl: number;
248
+ tp: number;
249
+ closePrice?: undefined;
250
+ closeTime?: undefined;
251
+ }
252
+ interface ClosedPositionDetail extends PositionDetailBase {
253
+ status: "CLOSED";
254
+ closePrice: number;
255
+ /** Epoch seconds, broker server clock. */
256
+ closeTime: number;
257
+ currentPrice?: undefined;
258
+ sl?: undefined;
259
+ tp?: undefined;
260
+ }
261
+ /** One position by ticket: open, or closed from the terminal's history. */
262
+ type PositionDetail = OpenPositionDetail | ClosedPositionDetail;
263
+ interface ClosedPositionsQuery {
264
+ /** Epoch ms, exclusive: pass the last `closeTimeMs` you processed (0 for everything). */
265
+ since: number;
266
+ /** Epoch ms; omitted means now. */
267
+ until?: number;
268
+ /** 1..200, default 200. */
269
+ limit?: number;
270
+ }
271
+ /** A fully closed MT5 position from the terminal's deal history. */
272
+ interface ClosedPosition {
273
+ ticket: number;
274
+ symbol: string;
275
+ status: "CLOSED";
276
+ type: OrderDirection | "";
277
+ volume: number;
278
+ /** Volume-weighted. */
279
+ openPrice: number;
280
+ /** Volume-weighted. */
281
+ closePrice: number;
282
+ profit: number;
283
+ swap: number;
284
+ commission: number;
285
+ /** Epoch seconds, broker server clock. */
286
+ openTime: number;
287
+ /** Epoch seconds, broker server clock. */
288
+ closeTime: number;
289
+ /** Epoch ms: the cursor for the next page. */
290
+ closeTimeMs: number;
291
+ magic: number;
292
+ comment: string;
293
+ }
294
+ interface ClosedPositionsResult {
295
+ /** Oldest close first. */
296
+ positions: ClosedPosition[];
297
+ /** The page is full: ask again from the last `closeTimeMs`. */
298
+ hasMore: boolean;
299
+ }
300
+ /** One symbol's contract spec as the MT5 terminal reports it, for every
301
+ * symbol on the server (not only Market Watch). Raw terminal values. */
302
+ interface Mt5SymbolSpec {
303
+ symbol: string;
304
+ description: string;
305
+ path: string;
306
+ baseCurrency: string;
307
+ profitCurrency: string;
308
+ marginCurrency: string;
309
+ digits: number;
310
+ point: number;
311
+ contractSize: number;
312
+ volumeMin: number;
313
+ volumeMax: number;
314
+ volumeStep: number;
315
+ tickSize: number;
316
+ /** 0 for symbols outside Market Watch. */
317
+ tickValue: number;
318
+ stopsLevel: number;
319
+ /** MQL5 ENUM_SYMBOL_TRADE_MODE as an integer. */
320
+ tradeMode: number;
321
+ /** MQL5 ENUM_SYMBOL_CALC_MODE as an integer. */
322
+ calcMode: number;
323
+ }
324
+ /** A read with the freshness fields the MT5 terminal reads carry. */
325
+ interface Fresh<T> {
326
+ data: T;
327
+ /** When the data was produced (ISO 8601). */
328
+ dataAsOf: string;
329
+ /** The terminal's last EA heartbeat (ISO 8601), null if none was ever seen. */
330
+ lastHeartbeatAt: string | null;
331
+ }
332
+ interface FreshnessOption {
333
+ /** Return `{ data, dataAsOf, lastHeartbeatAt }` instead of the data alone. */
334
+ withFreshness: true;
149
335
  }
150
336
  interface ModifyPositionBody {
151
337
  sl?: number;
@@ -157,6 +343,32 @@ interface ClosePositionBody {
157
343
  interface CloseBySymbolBody {
158
344
  symbol: string;
159
345
  }
346
+ interface ModifyMt5PositionResult {
347
+ ticket: number;
348
+ sl?: number;
349
+ tp?: number;
350
+ }
351
+ interface CloseMt5PositionResult {
352
+ ticket: number;
353
+ /** Absent when the terminal's reply did not carry it. */
354
+ closePrice?: number;
355
+ profit?: number;
356
+ /** The position was already closed; nothing was sent. */
357
+ alreadyClosed: boolean;
358
+ }
359
+ interface CloseBySymbolResult {
360
+ symbol: string;
361
+ closedCount: number;
362
+ totalProfit: number;
363
+ positions: Array<{
364
+ ticket: number;
365
+ symbol: string;
366
+ type: string;
367
+ volume: number;
368
+ profit: number;
369
+ closePrice: number;
370
+ }>;
371
+ }
160
372
  interface Order {
161
373
  ticket: number;
162
374
  symbol: string;
@@ -339,6 +551,152 @@ interface EaVersion {
339
551
  deploymentCount: number;
340
552
  uploadedAt: string;
341
553
  }
554
+ /** What registering or saving a version returns: the version without its
555
+ * parsed inputs. Read the full `EaVersion` with `eas.get()` or `listVersions()`. */
556
+ interface RegisteredEaVersion {
557
+ id: string;
558
+ version: string;
559
+ status: EaVersionStatus;
560
+ sourceType: EaSourceType;
561
+ compileStatus: EaCompileStatus;
562
+ deployable: boolean;
563
+ sha256: string | null;
564
+ sizeBytes: number | null;
565
+ magicInput: string | null;
566
+ magicInputWarning: string | null;
567
+ }
568
+ interface SaveEaSourceBody {
569
+ /** 1 to 40 of `A-Za-z0-9._-`. Saving a label again overwrites it, unless it is deployed. */
570
+ version: string;
571
+ /** The .mq5 text, up to 4 MiB. */
572
+ mq5Source: string;
573
+ }
574
+ /** The body of a 422 from `saveSource`: the compile check failed. Read it from `AtlasError.body`. */
575
+ interface EaCompileFailure {
576
+ success: false;
577
+ error: "Compile check failed";
578
+ /** Errors only, at most 50. */
579
+ diagnostics: Array<{
580
+ line?: number;
581
+ column?: number;
582
+ severity?: string;
583
+ message: string;
584
+ }>;
585
+ /** The end of the raw log, when there are no diagnostics. */
586
+ log?: string;
587
+ }
588
+ interface EaVersionSource {
589
+ version: string;
590
+ sourceType: "MQ5";
591
+ source: string;
592
+ }
593
+ interface EaPreset {
594
+ id: string;
595
+ name: string;
596
+ note: string | null;
597
+ /** .set key=value text. */
598
+ setBlob: string;
599
+ createdAt: string;
600
+ updatedAt: string;
601
+ }
602
+ interface CreateEaPresetBody {
603
+ /** 1 to 120 characters, unique per EA. */
604
+ name: string;
605
+ note?: string | null;
606
+ /** Up to 100,000 characters. */
607
+ setBlob: string;
608
+ }
609
+ interface LiveComparisonMatch {
610
+ livePositionId: string;
611
+ simPositionId: string;
612
+ symbol: string;
613
+ type: "buy" | "sell";
614
+ /** Live open time minus simulated open time, seconds. */
615
+ openDeltaSec: number;
616
+ /** Positive is worse for the trader. */
617
+ openSlippagePts: number;
618
+ closeSlippagePts: number | null;
619
+ liveNet: number;
620
+ simNet: number;
621
+ }
622
+ /** A deployment's live trades matched against a backtest of the same window. */
623
+ interface LiveComparisonSummary {
624
+ liveTrades: number;
625
+ simTrades: number;
626
+ matchedPct: number;
627
+ liveNet: number;
628
+ simNet: number;
629
+ avgOpenSlippagePts: number | null;
630
+ medianOpenSlippagePts: number | null;
631
+ p90OpenSlippagePts: number | null;
632
+ /** Live net as a share of simulated net, percent; null when simNet is 0. */
633
+ realisedPct: number | null;
634
+ }
635
+ interface LiveComparison {
636
+ deploymentId: string;
637
+ runId: string;
638
+ instanceId: string;
639
+ magicNumber: number;
640
+ window: {
641
+ from: string;
642
+ to: string;
643
+ };
644
+ computedAt: string;
645
+ matchToleranceSec: number;
646
+ matched: LiveComparisonMatch[];
647
+ unmatchedLive: Array<{
648
+ positionId: string;
649
+ symbol: string;
650
+ type: "buy" | "sell";
651
+ openTime: string;
652
+ net: number;
653
+ }>;
654
+ unmatchedSim: Array<{
655
+ positionId: string;
656
+ symbol: string;
657
+ type: "buy" | "sell";
658
+ openTime: string;
659
+ net: number;
660
+ }>;
661
+ summary: LiveComparisonSummary;
662
+ equity: {
663
+ live: Array<{
664
+ t: string;
665
+ equity: number;
666
+ }>;
667
+ sim: Array<{
668
+ t: string;
669
+ equity: number;
670
+ }>;
671
+ };
672
+ }
673
+ interface RunLiveComparisonBody {
674
+ /** YYYY-MM-DD. */
675
+ from: string;
676
+ /** YYYY-MM-DD, after `from`. */
677
+ to: string;
678
+ }
679
+ type MonitorVerdict = "OK" | "DECAY" | "SLIPPAGE" | "NO_LIVE_TRADES" | "FAILED";
680
+ /** A deployment's scheduled re-backtest against its live trades. */
681
+ interface MonitorStatus {
682
+ deploymentId: string;
683
+ enabled: boolean;
684
+ windowDays: number;
685
+ lastCheckedAt: string | null;
686
+ lastGroupId: string | null;
687
+ verdict: MonitorVerdict | null;
688
+ detail: string | null;
689
+ liveNet: number | null;
690
+ simNet: number | null;
691
+ simP5Net: number | null;
692
+ simP95Net: number | null;
693
+ medianSlippagePts: number | null;
694
+ }
695
+ interface SetMonitorBody {
696
+ enabled: boolean;
697
+ /** 7..365; default 30, and kept when omitted on an update. */
698
+ windowDays?: number;
699
+ }
342
700
  interface CreateEaBody {
343
701
  name: string;
344
702
  slug?: string;
@@ -367,6 +725,8 @@ interface ListDeploymentsResult {
367
725
  interface PresignEaVersionBody {
368
726
  version: string;
369
727
  sourceType: EaSourceType;
728
+ /** Lowercase hex SHA-256 of the file. Required for EX5: the upload must
729
+ * then send it, base64, as `x-amz-checksum-sha256`. */
370
730
  sha256?: string;
371
731
  sizeBytes: number;
372
732
  contentType?: string;
@@ -380,6 +740,7 @@ interface RegisterEaVersionBody {
380
740
  r2Key: string;
381
741
  version: string;
382
742
  sourceType: EaSourceType;
743
+ /** Required for EX5, the same value given to `presignVersion`. */
383
744
  sha256?: string;
384
745
  sizeBytes?: number;
385
746
  }
@@ -427,9 +788,16 @@ interface UpdateDeploymentBody {
427
788
  timeframe?: EaTimeframe;
428
789
  setBlob?: string | null;
429
790
  }
791
+ /** A broker order in the broker's own fields (Dhan: `securityId`,
792
+ * `exchangeSegment`, `transactionType`, `quantity`, `orderType`,
793
+ * `productType`…; Motilal: `exchange`, `symboltoken`, `buyorsell`,
794
+ * `quantityinlot`…), forwarded to the broker as it is. */
795
+ type BrokerOrder = Record<string, unknown>;
796
+ /** @deprecated Pass the order itself. `{ order }` is still unwrapped for you. */
430
797
  interface BrokerOrderBody {
431
798
  order: Record<string, unknown>;
432
799
  }
800
+ /** @deprecated Pass the changes themselves. `{ changes }` is still unwrapped for you. */
433
801
  interface BrokerModifyOrderBody {
434
802
  changes: Record<string, unknown>;
435
803
  }
@@ -454,10 +822,63 @@ interface BrokerUnsubscribeBody {
454
822
  interface BrokerCandlesQuery {
455
823
  [key: string]: string | number | boolean | undefined;
456
824
  }
457
- type WSChannel = "ticks" | "candles" | "positions" | "trades" | "orders" | "broker_ticks" | "broker_orders" | "market.ticks" | "market.candles" | "market.chain" | "trading.orders";
825
+ type DhanSegment = "IDX_I" | "NSE_EQ" | "NSE_FNO" | "NSE_CURRENCY" | "BSE_EQ" | "MCX_COMM" | "BSE_FNO" | "BSE_CURRENCY";
826
+ /** Name the underlying by Dhan security id and segment, or by symbol. */
827
+ type DhanUnderlying = {
828
+ underlyingSecurityId: string;
829
+ underlyingSegment: DhanSegment;
830
+ } | {
831
+ underlyingSymbol: string;
832
+ };
833
+ interface DhanOptionLeg {
834
+ securityId?: string;
835
+ averagePrice?: number;
836
+ ltp: number;
837
+ volume: number;
838
+ oi: number;
839
+ previousClosePrice?: number;
840
+ previousOi?: number;
841
+ previousVolume?: number;
842
+ topAskPrice?: number;
843
+ topAskQuantity?: number;
844
+ topBidPrice?: number;
845
+ topBidQuantity?: number;
846
+ impliedVolatility?: number;
847
+ /** Same value as `impliedVolatility`. */
848
+ iv?: number;
849
+ delta?: number;
850
+ gamma?: number;
851
+ theta?: number;
852
+ vega?: number;
853
+ }
854
+ /** Dhan's option chain as Dhan reports it, through your own connection. */
855
+ interface DhanOptionChain {
856
+ underlyingSecurityId: string;
857
+ underlyingSegment: DhanSegment;
858
+ expiry: string;
859
+ spot: number;
860
+ /** In Dhan's order, not sorted. */
861
+ strikes: Array<{
862
+ strike: number;
863
+ ce?: DhanOptionLeg;
864
+ pe?: DhanOptionLeg;
865
+ }>;
866
+ }
867
+ /**
868
+ * @deprecated `orders` is retired: the server refuses it in the `subscribed`
869
+ * reply's `refusedChannels`. Follow MT5 orders on `trading.orders`, or as raw
870
+ * `trade_event` frames on `trades`. Kept in `WSChannel` so existing code compiles.
871
+ */
872
+ type RetiredWSChannel = "orders";
873
+ /** A `/ws/service` channel. `orders` is retired (see `RetiredWSChannel`). */
874
+ type WSChannel = "ticks" | "candles" | "positions" | "trades" | RetiredWSChannel | "broker_ticks" | "broker_orders" | "market.ticks" | "market.candles" | "market.chain" | "market.scanner" | "trading.orders";
458
875
  interface WSSubscribeOptions {
459
876
  channels: WSChannel[];
877
+ /** MT5 logins to receive MT5 frames for (empty: every terminal you own).
878
+ * Applies once a subscribe has accepted one of `ticks`, `candles`,
879
+ * `positions` or `trades`; before that every MT5 frame of the account arrives. */
460
880
  accountIds?: string[];
881
+ /** Narrows `ticks` and `candles` to these MT5 symbols (empty: every symbol). */
461
882
  symbols?: string[];
462
883
  brokerConnectionIds?: string[];
463
884
  brokerSecurityKeys?: string[];
@@ -474,13 +895,20 @@ interface WSSubscribeOptions {
474
895
  * deployment-wide each refreshes about every N x 3.2 s. */
475
896
  chains?: ChainSelector[];
476
897
  }
898
+ interface WSUnsubscribeOptions {
899
+ channels?: WSChannel[];
900
+ /** Drop just these keys; the channels stay subscribed. */
901
+ instrumentKeys?: string[];
902
+ /** Drop just these chains; `market.chain` stays subscribed. */
903
+ chains?: ChainSelector[];
904
+ }
477
905
  /** One option chain on the `market.chain` channel. */
478
906
  interface ChainSelector {
479
907
  underlyingKey: string;
480
908
  /** YYYY-MM-DD. */
481
909
  expiry: string;
482
910
  }
483
- type UnifiedInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "1d";
911
+ type UnifiedInterval = "1m" | "3m" | "5m" | "15m" | "30m" | "1h" | "4h" | "1d";
484
912
  interface UnifiedCandle {
485
913
  ts: number;
486
914
  o: number;
@@ -606,29 +1034,183 @@ type TradingOrderMessage = UnifiedOrder & {
606
1034
  eventTs: number;
607
1035
  sequence: number;
608
1036
  };
1037
+ /** `tick` WS message (channel `ticks`): one MT5 bid/ask from a terminal the
1038
+ * account owns, also narrowed by `symbols`. Once a subscribe has accepted one of
1039
+ * `ticks`, `candles`, `positions` or `trades`, only the channels named arrive,
1040
+ * narrowed by `accountIds`; until then every MT5 frame of the account does. */
609
1041
  interface MT5Tick {
610
- type: "mt5_tick";
1042
+ type: "tick";
1043
+ /** The MT5 login. */
611
1044
  accountId: string;
612
1045
  symbol: string;
613
1046
  bid: number;
614
1047
  ask: number;
1048
+ /** Terminal time of the tick (epoch ms). */
615
1049
  ts: number;
1050
+ /** When Atlaas received it (epoch ms). */
616
1051
  timestamp: number;
1052
+ runnerId?: string;
617
1053
  }
1054
+ /** `candle` WS message (channel `candles`): one bar from a terminal's candle
1055
+ * subscription, also narrowed by `symbols`. Once a subscribe has accepted one of
1056
+ * `ticks`, `candles`, `positions` or `trades`, only the channels named arrive,
1057
+ * narrowed by `accountIds`; until then every MT5 frame of the account does. */
618
1058
  interface MT5Candle {
619
- type: "mt5_candle";
1059
+ type: "candle";
620
1060
  accountId: string;
621
1061
  symbol: string;
1062
+ /** MT5 timeframe as the subscription named it (e.g. `M1`, `H1`). */
622
1063
  timeframe: string;
1064
+ /** Bar open time (epoch ms). */
623
1065
  time: number;
624
1066
  open: number;
625
1067
  high: number;
626
1068
  low: number;
627
1069
  close: number;
628
1070
  volume: number;
1071
+ /** True on the first update of a new bar. */
629
1072
  isNew?: boolean;
630
1073
  ts: number;
631
1074
  timestamp: number;
1075
+ runnerId?: string;
1076
+ }
1077
+ /** One open MT5 position inside a `position_update` message. */
1078
+ interface MT5LivePosition {
1079
+ ticket: number;
1080
+ /** POSITION_IDENTIFIER, the id deals carry; differs from the ticket after a
1081
+ * netting reversal. Absent from older connector EAs. */
1082
+ identifier?: number;
1083
+ symbol: string;
1084
+ /** `BUY` or `SELL`, as the terminal reports it. */
1085
+ type: string;
1086
+ volume: number;
1087
+ openPrice: number;
1088
+ currentPrice: number;
1089
+ sl: number;
1090
+ tp: number;
1091
+ profit: number;
1092
+ swap: number;
1093
+ openTime: number;
1094
+ /** 0 is a manual trade. Absent from older connector EAs. */
1095
+ magic?: number;
1096
+ comment?: string;
1097
+ digits?: number;
1098
+ point?: number;
1099
+ volumeMin?: number;
1100
+ volumeStep?: number;
1101
+ }
1102
+ /** `position_update` WS message: the terminal's open positions and funds,
1103
+ * pushed by the EA (channel `positions`). Once a subscribe has accepted one of
1104
+ * `ticks`, `candles`, `positions` or `trades`, only the channels named arrive,
1105
+ * narrowed by `accountIds`; until then every MT5 frame of the account does. */
1106
+ interface MT5PositionUpdate {
1107
+ type: "position_update";
1108
+ accountId: string;
1109
+ balance: number;
1110
+ equity: number;
1111
+ margin: number;
1112
+ freeMargin: number;
1113
+ positions: MT5LivePosition[];
1114
+ ts: number;
1115
+ /** Absent from runners that send the compact frame (0.90.3 and later). */
1116
+ timestamp?: number;
1117
+ }
1118
+ /** `trade_event` WS message: one MT5 trade transaction (order or deal) as the
1119
+ * terminal reported it (channel `trades`). Once a subscribe has accepted one of
1120
+ * `ticks`, `candles`, `positions` or `trades`, only the channels named arrive,
1121
+ * narrowed by `accountIds`; until then every MT5 frame of the account does. */
1122
+ interface MT5TradeEvent {
1123
+ type: "trade_event";
1124
+ accountId: string;
1125
+ /** MQL5 TRADE_TRANSACTION_* name. */
1126
+ transType: string;
1127
+ symbol: string;
1128
+ order: number;
1129
+ orderType: string;
1130
+ orderState: string;
1131
+ dealType: string;
1132
+ deal: number;
1133
+ volume: number;
1134
+ price: number;
1135
+ sl: number;
1136
+ tp: number;
1137
+ ts: number;
1138
+ timestamp: number;
1139
+ }
1140
+ /** `heartbeat` WS message: the EA's periodic heartbeat with the account's
1141
+ * balance and equity. On no channel: it follows `accountIds` once MT5
1142
+ * channels are chosen, and otherwise reaches every socket of the account. */
1143
+ interface MT5Heartbeat {
1144
+ type: "heartbeat";
1145
+ runnerId: string;
1146
+ accountId: string;
1147
+ balance?: number;
1148
+ equity?: number;
1149
+ ts: number;
1150
+ timestamp: number;
1151
+ }
1152
+ /** `market.chain` WS message: a full option chain for one subscribed
1153
+ * (underlying, expiry) pair. */
1154
+ type MarketChainMessage = UnifiedOptionChain & {
1155
+ type: "market.chain";
1156
+ };
1157
+ /** `market.scanner` WS message: the whole NSE scanner board, the same one
1158
+ * `v2.scanner.board()` returns, plus `append`. */
1159
+ type MarketScannerMessage = Omit<ScannerBoard, "paths" | "pathsFrom"> & {
1160
+ type: "market.scanner";
1161
+ /** Each stock's move since the session open, in basis points, for the
1162
+ * minute just computed: append it to the paths you hold. */
1163
+ append: Record<string, number>;
1164
+ };
1165
+ type MarketFeedState = "unconfigured" | "disabled" | "connecting" | "connected" | "disconnected";
1166
+ /** Why an `instrumentKeys` entry was left out of a subscription. */
1167
+ type RefusedInstrumentKeyReason = "account_quota" | "capacity" | "unsupported" | "india_entitlement" | "no_account";
1168
+ /** `subscribed` WS reply: what the subscription now holds. Anything refused
1169
+ * is named here rather than accepted and never delivered. */
1170
+ interface SubscribedMessage {
1171
+ type: "subscribed";
1172
+ /** The channels this subscribe accepted. */
1173
+ channels: WSChannel[];
1174
+ /** Channels refused, with the reason: `"trading.orders (needs orders:r)"`,
1175
+ * `"market.scanner (needs the india entitlement)"`, `"orders (retired: use trading.orders)"`. */
1176
+ refusedChannels?: string[];
1177
+ refusedInstrumentKeys?: Array<{
1178
+ instrumentKey: string;
1179
+ reason: RefusedInstrumentKeyReason;
1180
+ }>;
1181
+ /** The per-account instrument limit, sent with `refusedInstrumentKeys`. */
1182
+ instrumentKeyLimit?: number;
1183
+ /** Ids the key's account does not own. */
1184
+ refusedAccountIds?: string[];
1185
+ refusedBrokerConnectionIds?: string[];
1186
+ refusedBrokerOrderConnectionIds?: string[];
1187
+ /** The whole filter after this subscribe, across every subscribe on the socket. */
1188
+ accountIds: string[];
1189
+ symbols: string[];
1190
+ brokerConnectionIds: string[];
1191
+ brokerSecurityKeys: string[];
1192
+ brokerOrderConnectionIds: string[];
1193
+ instrumentKeys: string[];
1194
+ /** Subscribed chains as `"<underlyingKey>|<expiry>"`. */
1195
+ chains: string[];
1196
+ /** State of the Atlaas market data feed that serves NSE/BSE keys. */
1197
+ feed: MarketFeedState;
1198
+ ts: number;
1199
+ }
1200
+ /** `subscribe_failed` WS reply: the account is inactive or suspended (or
1201
+ * could not be checked), so the subscribe changed nothing. What
1202
+ * the socket already subscribed to keeps streaming. */
1203
+ interface SubscribeFailedMessage {
1204
+ type: "subscribe_failed";
1205
+ /** E.g. `Account is inactive`, `Account is suspended`. */
1206
+ reason: string;
1207
+ ts: number;
1208
+ }
1209
+ /** `unsubscribed` WS reply. */
1210
+ interface UnsubscribedMessage {
1211
+ type: "unsubscribed";
1212
+ channels: WSChannel[];
1213
+ ts: number;
632
1214
  }
633
1215
  interface BrokerTick {
634
1216
  type: "broker_tick";
@@ -653,12 +1235,13 @@ interface BrokerOrderUpdate {
653
1235
  * Standalone copy, field-for-field — the SDK does not import contracts. */
654
1236
  interface UnifiedInstrument {
655
1237
  instrumentKey: string;
656
- exchange: "NSE" | "BSE" | "MCX" | "FX";
657
- segment: "EQ" | "FNO" | "IDX" | "CDS" | "COMM" | "FX";
1238
+ exchange: "NSE" | "BSE" | "MCX" | "FX" | "US" | "CRYPTO";
1239
+ segment: "EQ" | "FNO" | "IDX" | "CDS" | "COMM" | "FX" | "SPOT" | "PERP";
658
1240
  symbol: string;
659
1241
  name?: string;
660
1242
  isin?: string;
661
- instrumentType: "EQUITY" | "INDEX" | "FUTIDX" | "FUTSTK" | "OPTIDX" | "OPTSTK" | "FUTCOM" | "OPTCOM" | "FUTCUR" | "OPTCUR" | "FOREX";
1243
+ instrumentType: "EQUITY" | "INDEX" | "FUTIDX" | "FUTSTK" | "OPTIDX" | "OPTSTK" | "FUTCOM" | "OPTCOM" | "FUTCUR" | "OPTCUR" | "FOREX" | "CRYPTO_SPOT" | "CRYPTO_PERP";
1244
+ /** YYYY-MM-DD, derivatives only. */
662
1245
  expiry?: string;
663
1246
  strike?: number;
664
1247
  optionType?: "CE" | "PE";
@@ -685,8 +1268,21 @@ interface UnifiedInstrument {
685
1268
  symbol: string;
686
1269
  server?: string;
687
1270
  };
1271
+ /** Brokers synced from their own masters: `refId` is the broker's own
1272
+ * instrument id (Angel One / Shoonya token, Fyers symbol, Upstox
1273
+ * instrument_key), `segment` its exchange code. */
1274
+ angelone?: BrokerInstrumentRef;
1275
+ fyers?: BrokerInstrumentRef;
1276
+ upstox?: BrokerInstrumentRef;
1277
+ shoonya?: BrokerInstrumentRef;
688
1278
  };
689
1279
  }
1280
+ /** One broker's own id for an instrument (Angel One, Fyers, Upstox, Shoonya). */
1281
+ interface BrokerInstrumentRef {
1282
+ refId: string;
1283
+ segment?: string;
1284
+ tradingsymbol?: string;
1285
+ }
690
1286
  /** Mirror of @atlaas/contracts UnifiedOrder (packages/contracts/src/schemas.ts).
691
1287
  * Standalone copy, field-for-field — the SDK does not import contracts. */
692
1288
  interface UnifiedOrder {
@@ -753,6 +1349,26 @@ interface UnifiedPosition {
753
1349
  magic?: number;
754
1350
  openTime?: number;
755
1351
  };
1352
+ /** Margined crypto positions (perpetuals): what the exchange reports about
1353
+ * the leverage behind the position. Each venue reports a different subset. */
1354
+ margin?: {
1355
+ leverage?: number;
1356
+ liquidationPrice?: number;
1357
+ mode?: "CROSS" | "ISOLATED";
1358
+ /** Margin locked by the position, in its settlement asset. */
1359
+ used?: number;
1360
+ };
1361
+ /** Perpetuals only: the venue's current funding rate, a fraction per
1362
+ * funding interval (0.0001 = 0.01%). A positive rate means longs pay shorts. */
1363
+ funding?: {
1364
+ rate: number;
1365
+ /** When the current rate is next charged (epoch ms). */
1366
+ nextFundingTime?: number;
1367
+ intervalHours?: number;
1368
+ /** The next payment at the current rate and mark, in the settlement
1369
+ * asset: negative when the position pays, positive when it receives. */
1370
+ estimatedPayment?: number;
1371
+ };
756
1372
  raw?: unknown;
757
1373
  }
758
1374
  /** Mirror of @atlaas/contracts UnifiedHolding (packages/contracts/src/schemas.ts).
@@ -801,8 +1417,9 @@ interface UnifiedProfile {
801
1417
  }
802
1418
  /** Mirror of @atlaas/contracts UnifiedError (packages/contracts/src/errors.ts).
803
1419
  * Standalone copy, field-for-field — the SDK does not import contracts. */
1420
+ type UnifiedErrorCode = "BROKER_REJECTED" | "OUTCOME_UNKNOWN" | "UNSUPPORTED_CAPABILITY" | "INSTRUMENT_UNRESOLVED" | "SESSION_DOWN" | "RATE_LIMITED" | "VALIDATION" | "FEED_UNAVAILABLE" | "TIMEZONE_UNCONFIGURED" | "IDEMPOTENCY_IN_PROGRESS" | "IDEMPOTENCY_KEY_REUSED" | "IDEMPOTENCY_UNAVAILABLE";
804
1421
  interface UnifiedError {
805
- code: "BROKER_REJECTED" | "OUTCOME_UNKNOWN" | "UNSUPPORTED_CAPABILITY" | "INSTRUMENT_UNRESOLVED" | "SESSION_DOWN" | "RATE_LIMITED" | "VALIDATION" | "IDEMPOTENCY_IN_PROGRESS" | "IDEMPOTENCY_KEY_REUSED" | "IDEMPOTENCY_UNAVAILABLE";
1422
+ code: UnifiedErrorCode;
806
1423
  message: string;
807
1424
  brokerCode?: string;
808
1425
  raw?: unknown;
@@ -814,6 +1431,21 @@ interface DroppedRow {
814
1431
  reason: "INSTRUMENT_UNRESOLVED" | "UNMAPPABLE";
815
1432
  refId: string;
816
1433
  detail?: string;
1434
+ /** MT5 only: the open position or pending order behind the dropped row,
1435
+ * so a client that cannot place it under an instrument still sees it is
1436
+ * there and can close it by ticket. */
1437
+ mt5?: DroppedMt5Row;
1438
+ }
1439
+ /** Mirror of @atlaas/broker DroppedMt5Row: what the terminal reported for a
1440
+ * dropped MT5 row, as the terminal spells it. */
1441
+ interface DroppedMt5Row {
1442
+ ticket: number;
1443
+ /** The terminal's own symbol (e.g. `XAUUSD.r`). */
1444
+ symbol: string;
1445
+ /** MT5 volume. Absent when the terminal sent none. */
1446
+ lots?: number;
1447
+ /** MT5 direction: a BUY position is long, a SELL position short. Absent for an order type Atlas does not map. */
1448
+ side?: "BUY" | "SELL";
817
1449
  }
818
1450
  /** Mirror of @atlaas/broker BrokerCapabilities (packages/broker/src/normalizers/capabilities.ts).
819
1451
  * Standalone copy, field-for-field — the SDK does not import broker. */
@@ -827,6 +1459,8 @@ interface BrokerCapabilities {
827
1459
  candles: "native" | "feed" | "none";
828
1460
  holdings: boolean;
829
1461
  amo: boolean;
1462
+ /** Accepts a non-integer `quantity` (crypto amounts, fractional shares). */
1463
+ fractionalQuantity: boolean;
830
1464
  }
831
1465
  /** POST /api/v2/connections/:id/orders. Size it in `quantity` (units; Atlas
832
1466
  * converts to MOFSL lots / MT5 volume and fails closed on a non-multiple) or
@@ -850,6 +1484,10 @@ interface PlaceOrderV2Body {
850
1484
  validity?: "DAY" | "IOC" | "GTC" | "GTD" | "TTL";
851
1485
  /** Sanitized per broker (Dhan 30, Kite 20, MOFSL 10 chars). */
852
1486
  clientTag?: string;
1487
+ /** MT5 only: the terminal's own symbol to trade (`XAUUSD.r`), for when the
1488
+ * terminal lists several spellings of the instrument. It must be listed on
1489
+ * the terminal and be a spelling of `instrumentKey`; other brokers refuse it. */
1490
+ symbol?: string;
853
1491
  /** Synthetic MARKET (Motilal) chase policy. Defaults { maxDriftPct: 1, maxReprices: 3, timeoutMs: 60000 }. */
854
1492
  chase?: {
855
1493
  maxDriftPct?: number;
@@ -897,10 +1535,12 @@ interface PlaceOrderResult {
897
1535
  connectionId: string;
898
1536
  instrumentKey: string;
899
1537
  broker: string;
900
- /** Units. Omitted only for an MT5 order placed by `lots` on a symbol with no contractSize. */
1538
+ /** Units. Omitted only for an MT5 order placed by `lots` on a symbol whose contract size the terminal has not reported. */
901
1539
  quantity?: number;
902
1540
  /** MOFSL lots / MT5 volume actually sent. */
903
1541
  lots?: number;
1542
+ /** MT5: the terminal symbol the order went to. */
1543
+ symbol?: string;
904
1544
  /** Set when the order was synthesized as a chased LIMIT. */
905
1545
  synthetic?: {
906
1546
  restingPrice: number;
@@ -988,45 +1628,1245 @@ interface V2Snapshot {
988
1628
  };
989
1629
  };
990
1630
  }
1631
+ type ScannerSessionState = "pre" | "live" | "closed" | "holiday";
1632
+ interface ScannerSession {
1633
+ /** IST trading date, YYYY-MM-DD. */
1634
+ date: string;
1635
+ state: ScannerSessionState;
1636
+ /** Session minute since 09:15 IST. */
1637
+ minute: number;
1638
+ }
1639
+ interface ScannerRow {
1640
+ instrumentKey: string;
1641
+ symbol: string;
1642
+ sector: string;
1643
+ ltp: number;
1644
+ prevClose: number;
1645
+ /** % change from the previous close. */
1646
+ pct: number;
1647
+ /** % move from the session open. */
1648
+ move: number;
1649
+ hiMove: number;
1650
+ loMove: number;
1651
+ /** 1 bullish, -1 bearish. */
1652
+ side: 1 | -1;
1653
+ strength: number;
1654
+ conviction: number;
1655
+ /** Rank within its side. */
1656
+ sideRank: number;
1657
+ /** Rank among the picks on its side; null when not a pick. */
1658
+ pickRank: number | null;
1659
+ rankDelta: number;
1660
+ percentile: number;
1661
+ /** % change in open interest from the previous day; null without a future. */
1662
+ oiChgPct: number | null;
1663
+ /** Session minutes where an order block formed. */
1664
+ obMinutes: number[];
1665
+ }
1666
+ interface ScannerBoard {
1667
+ /** When the board was computed (ISO 8601). */
1668
+ asOf: string;
1669
+ session: ScannerSession;
1670
+ /** How many stocks were ranked. */
1671
+ universe: number;
1672
+ breadth: {
1673
+ up: number;
1674
+ down: number;
1675
+ bullish: number;
1676
+ bearish: number;
1677
+ medianPct: number;
1678
+ };
1679
+ sectors: Array<{
1680
+ name: string;
1681
+ avgPct: number;
1682
+ avgMove: number;
1683
+ up: number;
1684
+ down: number;
1685
+ }>;
1686
+ rows: ScannerRow[];
1687
+ /** instrumentKeys of the picks on each side. */
1688
+ picks: {
1689
+ bullish: string[];
1690
+ bearish: string[];
1691
+ };
1692
+ /** Move in basis points per session minute since 09:15, per instrumentKey. Only with `paths: true`. */
1693
+ paths?: Record<string, number[]>;
1694
+ /** First minute index in each `paths` array, when `after` was given. */
1695
+ pathsFrom?: number;
1696
+ }
1697
+ interface ScannerZones {
1698
+ instrumentKey: string;
1699
+ interval: "5m";
1700
+ asOf: string;
1701
+ /** The last two sessions of 5m bars. */
1702
+ bars: UnifiedCandle[];
1703
+ /** Session VWAP per bar. */
1704
+ vwap: number[];
1705
+ zones: Array<{
1706
+ side: 1 | -1;
1707
+ formedAt: string;
1708
+ top: number;
1709
+ bot: number;
1710
+ mitigatedAt: string | null;
1711
+ }>;
1712
+ /** Index into `zones` of the active zone. */
1713
+ active: number;
1714
+ /** The entry reference inside the active zone. */
1715
+ z: number;
1716
+ stops: Array<{
1717
+ price: number;
1718
+ formedAt: string;
1719
+ }>;
1720
+ targets: Array<{
1721
+ price: number;
1722
+ formedAt: string;
1723
+ }>;
1724
+ rr: number;
1725
+ riskPct: number;
1726
+ liquidity: Array<{
1727
+ price: number;
1728
+ formedAt: string;
1729
+ kind: "swingHigh" | "swingLow";
1730
+ }>;
1731
+ }
1732
+
1733
+ type BacktestTickMode = "EVERY_TICK" | "M1_OHLC" | "OPEN_PRICES" | "REAL_TICKS";
1734
+ type BacktestStatus = "QUEUED" | "CLAIMED" | "RUNNING" | "DONE" | "FAILED" | "CANCELED";
1735
+ type BacktestWindow = "FULL" | "IS" | "OOS" | "WF_IS" | "WF_OOS";
1736
+ type BacktestRunMode = "SINGLE" | "OPTIMIZE" | "SPEC";
1737
+ type BacktestExecutor = "ATLAS_OPERATED" | "SELF_HOSTED";
1738
+ type BacktestGroupKind = "SINGLE" | "OPTIMIZATION" | "WALK_FORWARD";
1739
+ type BacktestBatchKind = "SYMBOLS" | "NOISE" | "WF_MATRIX";
1740
+ type OptimizationAlgorithm = "COMPLETE" | "GENETIC";
1741
+ type OptimizationCriterion = "BALANCE" | "PROFIT_FACTOR" | "EXPECTED_PAYOFF" | "DRAWDOWN" | "RECOVERY_FACTOR" | "SHARPE" | "CUSTOM" | "COMPLEX";
1742
+ interface OptimizationRange {
1743
+ /** EA input name, as in the .set file. */
1744
+ name: string;
1745
+ start: number;
1746
+ step: number;
1747
+ stop: number;
1748
+ }
1749
+ interface OptimizationConfig {
1750
+ algorithm: OptimizationAlgorithm;
1751
+ criterion: OptimizationCriterion;
1752
+ ranges: OptimizationRange[];
1753
+ }
1754
+ interface WalkForwardConfig {
1755
+ /** 2..10 out-of-sample segments. */
1756
+ folds: number;
1757
+ /** In-sample length as a multiple of one out-of-sample segment, 1..10. */
1758
+ isRatio: number;
1759
+ /** Every in-sample window starts at fromDate; rolling otherwise. */
1760
+ anchored: boolean;
1761
+ }
1762
+ /** Tester report numbers. Fields after `finalEquity` are absent on older runs. */
1763
+ interface BacktestStats {
1764
+ initialDeposit: number;
1765
+ netProfit: number;
1766
+ grossProfit: number;
1767
+ grossLoss: number;
1768
+ profitFactor: number | null;
1769
+ expectedPayoff: number | null;
1770
+ recoveryFactor: number | null;
1771
+ sharpeRatio: number | null;
1772
+ balanceDrawdownAbs: number;
1773
+ balanceDrawdownMaxPct: number;
1774
+ equityDrawdownAbs: number;
1775
+ equityDrawdownMaxPct: number;
1776
+ totalTrades: number;
1777
+ totalDeals: number;
1778
+ shortTrades: number;
1779
+ longTrades: number;
1780
+ shortWinPct: number | null;
1781
+ longWinPct: number | null;
1782
+ profitTrades: number;
1783
+ lossTrades: number;
1784
+ winRatePct: number | null;
1785
+ largestProfitTrade: number;
1786
+ largestLossTrade: number;
1787
+ avgProfitTrade: number | null;
1788
+ avgLossTrade: number | null;
1789
+ maxConsecutiveWins: number;
1790
+ maxConsecutiveLosses: number;
1791
+ historyQualityPct: number | null;
1792
+ bars: number | null;
1793
+ ticks: number | null;
1794
+ finalBalance: number;
1795
+ finalEquity: number;
1796
+ balanceDrawdownMaximalAbs?: number | null;
1797
+ balanceDrawdownMaximalPct?: number | null;
1798
+ equityDrawdownMaximalAbs?: number | null;
1799
+ equityDrawdownMaximalPct?: number | null;
1800
+ zScore?: number | null;
1801
+ zScoreConfidencePct?: number | null;
1802
+ ahpr?: number | null;
1803
+ ghpr?: number | null;
1804
+ lrCorrelation?: number | null;
1805
+ lrStandardError?: number | null;
1806
+ marginLevelPct?: number | null;
1807
+ onTesterResult?: number | null;
1808
+ maxConsecutiveWinsMoney?: number | null;
1809
+ maxConsecutiveLossesMoney?: number | null;
1810
+ maximalConsecutiveProfit?: number | null;
1811
+ maximalConsecutiveProfitCount?: number | null;
1812
+ maximalConsecutiveLoss?: number | null;
1813
+ maximalConsecutiveLossCount?: number | null;
1814
+ avgConsecutiveWins?: number | null;
1815
+ avgConsecutiveLosses?: number | null;
1816
+ correlationProfitsMfe?: number | null;
1817
+ correlationProfitsMae?: number | null;
1818
+ correlationMfeMae?: number | null;
1819
+ minHoldingSec?: number | null;
1820
+ maxHoldingSec?: number | null;
1821
+ avgHoldingSec?: number | null;
1822
+ }
1823
+ /** How a position closed, read from the exit deal's comment. */
1824
+ type BacktestExitReason = "sl" | "tp" | "so" | "end" | "other";
1825
+ /** One closed position of a backtest. */
1826
+ interface BacktestTrade {
1827
+ positionId: string;
1828
+ symbol: string;
1829
+ type: "buy" | "sell";
1830
+ volume: number;
1831
+ openTime: string;
1832
+ openPrice: number;
1833
+ closeTime: string;
1834
+ closePrice: number;
1835
+ sl: number | null;
1836
+ tp: number | null;
1837
+ commission: number;
1838
+ swap: number;
1839
+ profit: number;
1840
+ durationSec: number;
1841
+ comment: string | null;
1842
+ exitComment?: string | null;
1843
+ exitReason?: BacktestExitReason | null;
1844
+ }
1845
+ interface BacktestAiSummary {
1846
+ generatedAt: string;
1847
+ /** The model id, or `atlas-rules` for the rule-based fallback. */
1848
+ model: string;
1849
+ headline: string;
1850
+ workedWell: string[];
1851
+ didNotWork: string[];
1852
+ redFlags: string[];
1853
+ tryNext: string[];
1854
+ }
1855
+ interface BacktestRedFlag {
1856
+ code: string;
1857
+ severity: "info" | "warn" | "critical";
1858
+ title: string;
1859
+ detail: string;
1860
+ }
1861
+ /**
1862
+ * Atlaas's analytics for a finished run. The summary sections are typed; the
1863
+ * long series (daily equity, underwater, rolling windows, distributions,
1864
+ * excursions, Monte Carlo fan) and the optional deeper sections (margin, swap,
1865
+ * sizing, baskets, news, pairs, arbitrage…) come through as they are stored.
1866
+ * `stats` and `walkForward` serve the compact form, which leaves the long
1867
+ * series out; `portfolio` and batch reports serve the full one.
1868
+ */
1869
+ interface BacktestAnalytics {
1870
+ version: number;
1871
+ computedAt: string;
1872
+ sample: {
1873
+ trades: number;
1874
+ days: number;
1875
+ years: number;
1876
+ firstTradeAt: string | null;
1877
+ lastTradeAt: string | null;
1878
+ };
1879
+ returns: {
1880
+ totalReturnPct: number;
1881
+ cagrPct: number | null;
1882
+ annualVolPct: number | null;
1883
+ /** Annualised, risk-free 0, on daily returns. */
1884
+ sharpe: number | null;
1885
+ sortino: number | null;
1886
+ calmar: number | null;
1887
+ skew: number | null;
1888
+ kurtosis: number | null;
1889
+ bestDayPct: number | null;
1890
+ worstDayPct: number | null;
1891
+ positiveDaysPct: number | null;
1892
+ };
1893
+ trades: {
1894
+ netProfit: number;
1895
+ avgTrade: number | null;
1896
+ avgWin: number | null;
1897
+ avgLoss: number | null;
1898
+ payoffRatio: number | null;
1899
+ expectancy: number | null;
1900
+ winRatePct: number | null;
1901
+ profitFactor: number | null;
1902
+ sqn: number | null;
1903
+ tStat: number | null;
1904
+ netExTop1: number;
1905
+ netExTop3: number;
1906
+ netExTop5Pct: number;
1907
+ medianDurationSec: number | null;
1908
+ avgWinDurationSec: number | null;
1909
+ avgLossDurationSec: number | null;
1910
+ exitReasons: Array<{
1911
+ reason: BacktestExitReason;
1912
+ trades: number;
1913
+ net: number;
1914
+ winRatePct: number | null;
1915
+ }>;
1916
+ };
1917
+ drawdown: {
1918
+ maxDdPct: number;
1919
+ maxDdAbs: number;
1920
+ avgDdPct: number;
1921
+ ulcerIndex: number;
1922
+ painIndex: number;
1923
+ recoveryFactor: number | null;
1924
+ longestDdDays: number;
1925
+ avgRecoveryDays: number | null;
1926
+ timeUnderwaterPct: number;
1927
+ currentDdPct: number;
1928
+ episodes: Array<{
1929
+ peakAt: string;
1930
+ troughAt: string;
1931
+ recoveredAt: string | null;
1932
+ depthPct: number;
1933
+ depthAbs: number;
1934
+ durationDays: number;
1935
+ recoveryDays: number | null;
1936
+ }>;
1937
+ };
1938
+ tail: {
1939
+ var95DayPct: number | null;
1940
+ cvar95DayPct: number | null;
1941
+ var99DayPct: number | null;
1942
+ cvar99DayPct: number | null;
1943
+ var95Trade: number | null;
1944
+ cvar95Trade: number | null;
1945
+ var99Trade: number | null;
1946
+ cvar99Trade: number | null;
1947
+ };
1948
+ significance: {
1949
+ sharpeObs: number | null;
1950
+ n: number;
1951
+ skew: number | null;
1952
+ kurtosis: number | null;
1953
+ /** Probability that the true Sharpe is above 0. */
1954
+ psr: number | null;
1955
+ /** Backtests tried on this EA when `dsr` was computed. */
1956
+ trials: number;
1957
+ /** Deflated Sharpe: PSR against the expected best of `trials` tries. */
1958
+ dsr: number | null;
1959
+ };
1960
+ flags: BacktestRedFlag[];
1961
+ [section: string]: unknown;
1962
+ }
1963
+ /** One run of a backtest group, as `/api/external/backtests` serves it. */
1964
+ interface BacktestRun {
1965
+ id: string;
1966
+ groupId: string;
1967
+ atlasAccountId: string;
1968
+ window: BacktestWindow;
1969
+ mode: BacktestRunMode;
1970
+ /** On OPTIMIZE runs. */
1971
+ optimization: OptimizationConfig | null;
1972
+ /** Walk-forward fold, 0-based. */
1973
+ foldIndex: number | null;
1974
+ status: BacktestStatus;
1975
+ /** Why it failed or was canceled; `cancel requested` while a cancel is pending. */
1976
+ statusReason: string | null;
1977
+ versionId: string;
1978
+ /** Null once the terminal is deleted. */
1979
+ instanceId: string | null;
1980
+ symbol: string;
1981
+ timeframe: EaTimeframe;
1982
+ setBlob: string | null;
1983
+ tickMode: BacktestTickMode;
1984
+ fromDate: string;
1985
+ toDate: string;
1986
+ deposit: number;
1987
+ currency: string;
1988
+ leverage: number;
1989
+ runnerId: string | null;
1990
+ assignedRunnerId: string | null;
1991
+ claimedAt: string | null;
1992
+ startedAt: string | null;
1993
+ finishedAt: string | null;
1994
+ estimatedSeconds: number | null;
1995
+ attempt: number;
1996
+ executedOn: BacktestExecutor | null;
1997
+ /** Runner phase while it runs (preparing, downloading-history, testing, uploading). */
1998
+ phase: string | null;
1999
+ progressPct: number | null;
2000
+ /** Set once DONE, and null on a locked out-of-sample run. */
2001
+ statsJson: BacktestStats | null;
2002
+ reportKey: string | null;
2003
+ resultKey: string | null;
2004
+ /** Tester log, up to 64 KB. On `get`, not on `list`. */
2005
+ runnerLog?: string | null;
2006
+ chargedMinutes: number | null;
2007
+ barsKey: string | null;
2008
+ aiSummary: BacktestAiSummary | null;
2009
+ /** MT5 ExecutionMode: 0 instant, -1 random delay, above 0 a fixed delay in ms. */
2010
+ executionMode: number;
2011
+ /** The other run of a tick-model pair. */
2012
+ linkedRunId: string | null;
2013
+ liveComparisonSummary: (LiveComparisonSummary & {
2014
+ deploymentId: string;
2015
+ window: {
2016
+ from: string;
2017
+ to: string;
2018
+ };
2019
+ computedAt: string;
2020
+ }) | null;
2021
+ analyticsVersion: number | null;
2022
+ chartTimeframes: EaTimeframe[];
2023
+ createdAt: string;
2024
+ updatedAt: string;
2025
+ version: {
2026
+ id: string;
2027
+ version: string;
2028
+ ea: {
2029
+ id: string;
2030
+ name: string;
2031
+ baselineGroupId: string | null;
2032
+ };
2033
+ };
2034
+ instance: {
2035
+ id: string;
2036
+ name: string | null;
2037
+ accountId: string | null;
2038
+ } | null;
2039
+ barsTimeframes: EaTimeframe[];
2040
+ hasPasses: boolean;
2041
+ hasSpec: boolean;
2042
+ hasCalendar: boolean;
2043
+ extraSymbols: string[];
2044
+ tickSymbols: string[];
2045
+ /** 1-based queue position while QUEUED. */
2046
+ queuePosition: number | null;
2047
+ estimatedFinishAt: string | null;
2048
+ }
2049
+ interface BacktestGroup {
2050
+ id: string;
2051
+ atlasAccountId: string;
2052
+ createdByUserId: string | null;
2053
+ name: string;
2054
+ oosEnabled: boolean;
2055
+ oosRevealCount: number;
2056
+ oosRevealedAt: string | null;
2057
+ agentSessionId: string | null;
2058
+ kind: BacktestGroupKind;
2059
+ batchId: string | null;
2060
+ batchKind: BacktestBatchKind | null;
2061
+ /** NOISE and WF_MATRIX batches: how the group was made. */
2062
+ batchMeta: Record<string, unknown> | null;
2063
+ /** WALK_FORWARD groups: the fold plan. Dates are YYYY-MM-DD. */
2064
+ walkForward: {
2065
+ config: WalkForwardConfig;
2066
+ optimization: OptimizationConfig;
2067
+ holdout: string | null;
2068
+ toDate: string;
2069
+ folds: Array<{
2070
+ index: number;
2071
+ isFrom: string;
2072
+ isTo: string;
2073
+ oosFrom: string;
2074
+ oosTo: string;
2075
+ oosEstimatedSeconds?: number;
2076
+ }>;
2077
+ holdoutEstimatedSeconds?: number;
2078
+ warning?: string | null;
2079
+ } | null;
2080
+ note: string | null;
2081
+ monitorId: string | null;
2082
+ createdAt: string;
2083
+ /** The pinned baseline group of the EA this group tests. */
2084
+ baselineGroupId: string | null;
2085
+ /** Ordered by fromDate. */
2086
+ runs: BacktestRun[];
2087
+ }
2088
+ interface OptimizationConfigInput {
2089
+ /** Default COMPLETE. */
2090
+ algorithm?: OptimizationAlgorithm;
2091
+ /** Default BALANCE. */
2092
+ criterion?: OptimizationCriterion;
2093
+ /** 1 to 4 inputs; COMPLETE is refused above 10,000 combinations. */
2094
+ ranges: OptimizationRange[];
2095
+ }
2096
+ interface CreateBacktestBody {
2097
+ /** 1 to 120 characters. */
2098
+ name: string;
2099
+ /** An EA version with a compiled build. */
2100
+ versionId: string;
2101
+ /** An MT5 terminal of the account with its server set: the tester uses its broker's history. */
2102
+ instanceId: string;
2103
+ symbol: string;
2104
+ timeframe: EaTimeframe;
2105
+ /** .set inputs, up to 100,000 characters. */
2106
+ setBlob?: string | null;
2107
+ /** Default M1_OHLC. */
2108
+ tickMode?: BacktestTickMode;
2109
+ /** YYYY-MM-DD. */
2110
+ fromDate: string;
2111
+ /** YYYY-MM-DD, after fromDate. */
2112
+ toDate: string;
2113
+ /** Default 10000. */
2114
+ deposit?: number;
2115
+ /** Three letters, default USD. */
2116
+ currency?: string;
2117
+ /** 1..10000, default 100. */
2118
+ leverage?: number;
2119
+ /** Lock the run after `splitDate` as an out-of-sample run until you reveal it. */
2120
+ oos?: {
2121
+ splitDate: string;
2122
+ };
2123
+ /** Extra bar timeframes to export for charts, up to 8. */
2124
+ chartTimeframes?: EaTimeframe[];
2125
+ /** Makes an optimization group. */
2126
+ optimization?: OptimizationConfigInput;
2127
+ /** Makes a walk-forward group; needs `optimization`. */
2128
+ walkForward?: {
2129
+ folds: number;
2130
+ isRatio: number;
2131
+ anchored?: boolean;
2132
+ };
2133
+ /** 0 instant (default), -1 random delay, 1..10000 a fixed delay in ms. */
2134
+ executionMode?: number;
2135
+ /** Export the ticks the tester used. Ignored for optimizations. */
2136
+ exportTicks?: boolean;
2137
+ /** Up to 2000 characters. */
2138
+ note?: string;
2139
+ }
2140
+ interface CreateBacktestResult {
2141
+ group: BacktestGroup;
2142
+ runs: Array<{
2143
+ id: string;
2144
+ window: BacktestWindow;
2145
+ status: BacktestStatus;
2146
+ queuePosition: number | null;
2147
+ estimatedSeconds: number | null;
2148
+ estimatedFinishAt: string | null;
2149
+ }>;
2150
+ }
2151
+ interface ListBacktestsQuery {
2152
+ /** 1..100, default 20. */
2153
+ limit?: number;
2154
+ /** `nextCursor` of the previous page. */
2155
+ cursor?: string;
2156
+ }
2157
+ interface ListBacktestsResult {
2158
+ /** Runs carry no `runnerLog`. */
2159
+ items: BacktestGroup[];
2160
+ nextCursor: string | null;
2161
+ }
2162
+ interface BacktestEstimateQuery {
2163
+ tickMode?: BacktestTickMode;
2164
+ fromDate: string;
2165
+ toDate: string;
2166
+ /** Optimizer passes; omit for a single run. */
2167
+ passes?: number;
2168
+ /** Estimate a whole walk-forward with this many folds (2..10). */
2169
+ folds?: number;
2170
+ /** With `folds`: 1..10, default 3. */
2171
+ isRatio?: number;
2172
+ anchored?: boolean;
2173
+ splitDate?: string;
2174
+ timeframe?: EaTimeframe;
2175
+ /** Runs in a batch, noise test or matrix (1..12), default 1. */
2176
+ runs?: number;
2177
+ }
2178
+ /** An amount of money in the account's usage-balance currency. */
2179
+ interface Money {
2180
+ amount: number;
2181
+ currency: "USD" | "INR";
2182
+ }
2183
+ interface BacktestEstimate {
2184
+ estimatedSeconds: number;
2185
+ queueWaitSeconds: number;
2186
+ estimatedFinishAt: string;
2187
+ /** What one run (a whole walk-forward with `folds`) costs from the usage balance. */
2188
+ costPerRun: Money;
2189
+ runs: number;
2190
+ /** `costPerRun` x `runs`: what the usage balance must cover. */
2191
+ cost: Money;
2192
+ /** With `folds`. */
2193
+ walkForward?: {
2194
+ optimizationSeconds: number;
2195
+ oosSeconds: number;
2196
+ holdoutSeconds: number;
2197
+ totalSeconds: number;
2198
+ estimatedCost: Money;
2199
+ };
2200
+ /** A native estimate: what one run replays (M1 bars, or ticks for REAL_TICKS). */
2201
+ replay?: {
2202
+ kind: "m1" | "ticks";
2203
+ count: number;
2204
+ };
2205
+ }
2206
+ interface PortfolioBody {
2207
+ /** 2 to 20 finished runs. */
2208
+ members: Array<{
2209
+ runId: string /** Lot multiplier, default 1. */;
2210
+ weight?: number;
2211
+ }>;
2212
+ /** Starting capital; default the largest member deposit. */
2213
+ capital?: number;
2214
+ }
2215
+ interface PortfolioReport {
2216
+ capital: number;
2217
+ currency: string;
2218
+ members: Array<{
2219
+ runId: string;
2220
+ label: string;
2221
+ weight: number;
2222
+ net: number;
2223
+ maxDdPct: number;
2224
+ contributionPct: number | null;
2225
+ lossInWorstDd: number;
2226
+ }>;
2227
+ /** Runs left out, with the reason. */
2228
+ excluded: Array<{
2229
+ runId: string;
2230
+ reason: string;
2231
+ }>;
2232
+ /** Pearson correlation of members' daily returns, in `members` order. */
2233
+ correlation: number[][];
2234
+ diversification: {
2235
+ sumMemberMaxDdAbs: number;
2236
+ combinedMaxDdAbs: number;
2237
+ };
2238
+ combinedFloatingDdPct: number | null;
2239
+ equity: Array<{
2240
+ t: string;
2241
+ equity: number;
2242
+ }>;
2243
+ analytics: BacktestAnalytics;
2244
+ }
2245
+ interface CreateBacktestBatchBody extends Omit<CreateBacktestBody, "symbol" | "timeframe" | "optimization" | "walkForward"> {
2246
+ /** 1 to 12. Every symbol runs on every timeframe, up to 12 runs. */
2247
+ symbols: string[];
2248
+ timeframes: EaTimeframe[];
2249
+ }
2250
+ interface CreateBacktestBatchResult {
2251
+ batchId: string;
2252
+ groups: Array<{
2253
+ groupId: string;
2254
+ symbol: string;
2255
+ timeframe: string;
2256
+ }>;
2257
+ }
2258
+ interface NoiseTestConfig {
2259
+ /** 3..12 variants. */
2260
+ variants: number;
2261
+ /** Each numeric input moves by up to this percent (0..50]. */
2262
+ perturbPct: number;
2263
+ /** Default 1. */
2264
+ seed?: number;
2265
+ /** Inputs to leave alone. */
2266
+ skip?: string[];
2267
+ /** Inputs to move even when the default rule would leave them alone. */
2268
+ include?: string[];
2269
+ }
2270
+ interface CreateNoiseTestBody {
2271
+ /** A SINGLE backtest group of the account. */
2272
+ groupId: string;
2273
+ config: NoiseTestConfig;
2274
+ }
2275
+ interface CreateNoiseTestResult {
2276
+ batchId: string;
2277
+ groups: Array<{
2278
+ groupId: string;
2279
+ inputs: Record<string, number>;
2280
+ }>;
2281
+ }
2282
+ interface CreateWalkForwardMatrixBody extends CreateBacktestBody {
2283
+ optimization: OptimizationConfigInput;
2284
+ /** In-sample ratios, each 1..10. */
2285
+ isRatios: number[];
2286
+ /** Fold counts, each 2..10. At most 9 cells in all. */
2287
+ folds: number[];
2288
+ }
2289
+ interface CreateWalkForwardMatrixResult {
2290
+ batchId: string;
2291
+ groups: Array<{
2292
+ groupId: string;
2293
+ isRatio: number;
2294
+ folds: number;
2295
+ }>;
2296
+ }
2297
+ interface BacktestSourceDiff {
2298
+ fromVersionId: string;
2299
+ toVersionId: string;
2300
+ fromVersion: string;
2301
+ toVersion: string;
2302
+ /** Unified diff, empty when identical, at most 200 KB. */
2303
+ unified: string;
2304
+ truncated: boolean;
2305
+ added: number;
2306
+ removed: number;
2307
+ }
2308
+ interface SwapArbRow {
2309
+ symbol: string;
2310
+ longInstanceId: string;
2311
+ longInstanceName: string;
2312
+ shortInstanceId: string;
2313
+ shortInstanceName: string;
2314
+ /** Money per lot per night, account currency. Positive earns. */
2315
+ swapLongPerLot: number;
2316
+ swapShortPerLot: number;
2317
+ dailyCarryPerLot: number;
2318
+ roundTripCostPerLot: number;
2319
+ breakEvenDays: number | null;
2320
+ marginPerLot: number;
2321
+ annualisedPctOnMargin: number | null;
2322
+ specsAt: string;
2323
+ }
2324
+ interface SwapArbitrageReport {
2325
+ /** Best annualised first. */
2326
+ rows: SwapArbRow[];
2327
+ specsMissing: Array<{
2328
+ instanceId: string;
2329
+ instanceName: string | null;
2330
+ }>;
2331
+ assumptions: string[];
2332
+ }
2333
+ interface SpreadCalibration {
2334
+ instanceId: string;
2335
+ symbol: string;
2336
+ computedAt: string;
2337
+ byHour: Array<{
2338
+ hour: number;
2339
+ avgSpreadPts: number;
2340
+ p90SpreadPts: number;
2341
+ samples: number;
2342
+ }>;
2343
+ /** From live comparisons on this terminal and symbol, when any exist. */
2344
+ slippagePts: {
2345
+ median: number;
2346
+ p90: number;
2347
+ samples: number;
2348
+ } | null;
2349
+ /** Execution delay to give the tester, ms. */
2350
+ suggestedExecutionDelayMs: number;
2351
+ }
2352
+ interface BacktestBatchReport {
2353
+ batchId: string;
2354
+ batchKind: BacktestBatchKind;
2355
+ name: string;
2356
+ cells: Array<{
2357
+ groupId: string;
2358
+ runId: string | null;
2359
+ symbol: string;
2360
+ timeframe: string;
2361
+ status: string;
2362
+ netProfit: number | null;
2363
+ profitFactor: number | null;
2364
+ maxDdPct: number | null;
2365
+ trades: number | null;
2366
+ }>;
2367
+ consistency: {
2368
+ finished: number;
2369
+ profitablePct: number | null;
2370
+ medianProfitFactor: number | null;
2371
+ };
2372
+ /** Every finished cell combined as one account; null until two are DONE. */
2373
+ combined: PortfolioReport | null;
2374
+ /** NOISE batches. */
2375
+ noise?: {
2376
+ batchId: string;
2377
+ baseGroupId: string;
2378
+ config: NoiseTestConfig;
2379
+ variants: Array<{
2380
+ groupId: string;
2381
+ runId: string | null;
2382
+ status: string;
2383
+ inputs: Record<string, number>;
2384
+ netProfit: number | null;
2385
+ profitFactor: number | null;
2386
+ maxDdPct: number | null;
2387
+ }>;
2388
+ netProfit: {
2389
+ min: number;
2390
+ median: number;
2391
+ max: number;
2392
+ base: number;
2393
+ } | null;
2394
+ /** Coefficient of variation of net profit; above 0.5 reads as fragile. */
2395
+ fragility: number | null;
2396
+ };
2397
+ /** WF_MATRIX batches. `cells[isRatio index][folds index]`. */
2398
+ wfMatrix?: {
2399
+ batchId: string;
2400
+ isRatios: number[];
2401
+ folds: number[];
2402
+ cells: Array<Array<{
2403
+ groupId: string;
2404
+ wfe: number | null;
2405
+ status: string;
2406
+ }>>;
2407
+ };
2408
+ }
2409
+ interface BacktestResultUrls {
2410
+ /** The BacktestResult JSON, presigned for 10 minutes. */
2411
+ resultUrl: string;
2412
+ /** The MT5 HTML report, presigned for 10 minutes. */
2413
+ reportUrl: string | null;
2414
+ }
2415
+ interface BacktestRunStats {
2416
+ runId: string;
2417
+ window: BacktestWindow;
2418
+ stats: BacktestStats;
2419
+ byMonth: Array<{
2420
+ month: string;
2421
+ trades: number;
2422
+ profit: number;
2423
+ }>;
2424
+ byHour: Array<{
2425
+ hour: number;
2426
+ trades: number;
2427
+ profit: number;
2428
+ }>;
2429
+ /** 0 is Sunday. */
2430
+ byWeekday: Array<{
2431
+ weekday: number;
2432
+ trades: number;
2433
+ profit: number;
2434
+ }>;
2435
+ /** Compact analytics: the long series are left out. */
2436
+ analytics: BacktestAnalytics | null;
2437
+ aiSummary: BacktestAiSummary | null;
2438
+ }
2439
+ type BacktestTradeSort = "openTime" | "-openTime" | "closeTime" | "-closeTime" | "net" | "-net" | "profit" | "-profit" | "durationSec" | "-durationSec" | "volume" | "-volume";
2440
+ type BacktestTradeAggregate = "none" | "byMonth" | "byHour" | "byWeekday" | "bySymbol" | "byExitReason";
2441
+ interface BacktestTradesQuery {
2442
+ type?: "buy" | "sell";
2443
+ outcome?: "win" | "loss";
2444
+ /** Bounds on net P/L (profit + commission + swap). */
2445
+ minProfit?: number;
2446
+ maxProfit?: number;
2447
+ minDurationSec?: number;
2448
+ maxDurationSec?: number;
2449
+ /** Needs per-trade R, which needs the bars the tester exported. */
2450
+ minR?: number;
2451
+ maxR?: number;
2452
+ /** Trades opened at or after (ISO). */
2453
+ from?: string;
2454
+ /** Trades opened at or before (ISO). */
2455
+ to?: string;
2456
+ /** Close weekdays, 0 (Sunday) to 6. */
2457
+ weekdays?: number[];
2458
+ /** Close hours, 0 to 23. */
2459
+ hours?: number[];
2460
+ exitReasons?: BacktestExitReason[];
2461
+ /** Case-insensitive substring of the trade comment. */
2462
+ commentContains?: string;
2463
+ /** Default openTime. */
2464
+ sort?: BacktestTradeSort;
2465
+ /** 1..200, default 50. */
2466
+ limit?: number;
2467
+ aggregate?: BacktestTradeAggregate;
2468
+ }
2469
+ interface BacktestTradeAggregateRow {
2470
+ /** Month `YYYY-MM`, hour, weekday, symbol or exit reason. */
2471
+ key: string | number;
2472
+ trades: number;
2473
+ net: number;
2474
+ avg: number;
2475
+ profitFactor: number | null;
2476
+ winRatePct: number;
2477
+ }
2478
+ interface BacktestTradesResult<Row = BacktestTrade | BacktestTradeAggregateRow> {
2479
+ runId: string;
2480
+ window: BacktestWindow;
2481
+ totalMatched: number;
2482
+ rows: Row[];
2483
+ }
2484
+ interface CancelBacktestRunResult {
2485
+ id: string;
2486
+ /** CANCELED when it was still queued; otherwise a stop was requested. */
2487
+ status: "CANCELED" | "CLAIMED" | "RUNNING";
2488
+ statusReason: "canceled by user" | "cancel requested";
2489
+ }
2490
+ interface OptimizationPass {
2491
+ pass: number;
2492
+ /** The criterion value MT5 ranked the pass by. */
2493
+ result: number;
2494
+ profit: number;
2495
+ expectedPayoff: number | null;
2496
+ profitFactor: number | null;
2497
+ recoveryFactor: number | null;
2498
+ sharpe: number | null;
2499
+ custom: number | null;
2500
+ equityDdPct: number | null;
2501
+ trades: number;
2502
+ params: Record<string, number>;
2503
+ }
2504
+ interface BacktestPassesQuery {
2505
+ /** A field or `-field` among pass, result, profit, expectedPayoff, profitFactor, recoveryFactor, sharpe, custom, equityDdPct, trades. Default `-result`. */
2506
+ sort?: string;
2507
+ /** 1..1000, default 50. */
2508
+ limit?: number;
2509
+ }
2510
+ interface BacktestPassesResult {
2511
+ runId: string;
2512
+ /** Before `limit`. */
2513
+ totalPasses: number;
2514
+ result: {
2515
+ schemaVersion: 1;
2516
+ algorithm: OptimizationAlgorithm;
2517
+ criterion: OptimizationCriterion;
2518
+ passes: OptimizationPass[];
2519
+ };
2520
+ }
2521
+ /** Where a run sits among the account's other finished runs of the same EA. `thisRankPct` 100 is best. */
2522
+ interface BacktestPeerContext {
2523
+ runs: number;
2524
+ pf: {
2525
+ median: number | null;
2526
+ thisRankPct: number | null;
2527
+ };
2528
+ netProfit: {
2529
+ median: number | null;
2530
+ thisRankPct: number | null;
2531
+ };
2532
+ sharpe: {
2533
+ median: number | null;
2534
+ thisRankPct: number | null;
2535
+ };
2536
+ maxDdPct: {
2537
+ median: number | null;
2538
+ thisRankPct: number | null;
2539
+ };
2540
+ }
2541
+ interface WalkForwardReport {
2542
+ groupId: string;
2543
+ config: WalkForwardConfig;
2544
+ folds: Array<{
2545
+ index: number;
2546
+ isFrom: string;
2547
+ isTo: string;
2548
+ oosFrom: string;
2549
+ oosTo: string;
2550
+ isRunId: string;
2551
+ oosRunId: string | null;
2552
+ status: "OPTIMIZING" | "TESTING" | "DONE" | "FAILED";
2553
+ bestPass: OptimizationPass | null;
2554
+ isReturnAnnualPct: number | null;
2555
+ oosReturnAnnualPct: number | null;
2556
+ wfe: number | null;
2557
+ oosNet: number | null;
2558
+ }>;
2559
+ /** Annualised OOS return over annualised IS return. */
2560
+ wfe: number | null;
2561
+ /** The OOS segments chained into one account; compact analytics. */
2562
+ stitched: {
2563
+ equity: Array<{
2564
+ t: string;
2565
+ equity: number;
2566
+ }>;
2567
+ analytics: BacktestAnalytics;
2568
+ } | null;
2569
+ paramStability: Array<{
2570
+ name: string;
2571
+ values: number[];
2572
+ cv: number | null;
2573
+ }>;
2574
+ holdout: {
2575
+ runId: string;
2576
+ status: string;
2577
+ locked: boolean;
2578
+ } | null;
2579
+ }
2580
+ interface RevealOosResult {
2581
+ id: string;
2582
+ oosRevealedAt: string;
2583
+ /** Every reveal is counted. */
2584
+ oosRevealCount: number;
2585
+ }
2586
+
2587
+ /**
2588
+ * The machine-readable code on a failed request. The v2 routes send one of
2589
+ * the `UnifiedErrorCode`s in `error.code`; the /api/external routes send a
2590
+ * `code` beside the message on some failures, such as `TERMINAL_UNAVAILABLE`
2591
+ * (503, the terminal behind a read cannot be seen right now) and
2592
+ * `COMMAND_UNSUPPORTED` (501, the connector EA does not implement the read).
2593
+ */
2594
+ type AtlasErrorCode = UnifiedErrorCode | "TERMINAL_UNAVAILABLE" | "COMMAND_UNSUPPORTED" | (string & {});
2595
+ /** What the server said about a failure beyond its message. */
2596
+ interface AtlasErrorDetails {
2597
+ code?: AtlasErrorCode;
2598
+ /** The server's own verdict on retrying (v2 routes only). */
2599
+ retryable?: boolean;
2600
+ /** The broker's own error code, when the broker gave one (v2 routes only). */
2601
+ brokerCode?: string;
2602
+ /** True when the server answered from its Idempotency-Key store: this is
2603
+ * the stored answer of an earlier request with the same key. */
2604
+ replayed?: boolean;
2605
+ /** The parsed error body, as the server sent it. */
2606
+ body?: unknown;
2607
+ }
2608
+ declare class AtlasError extends Error {
2609
+ readonly statusCode: number;
2610
+ readonly errorCode?: number;
2611
+ readonly requestId?: string;
2612
+ readonly code?: AtlasErrorCode;
2613
+ readonly retryable?: boolean;
2614
+ readonly brokerCode?: string;
2615
+ readonly replayed?: boolean;
2616
+ readonly body?: unknown;
2617
+ constructor(message: string, statusCode?: number, errorCode?: number, requestId?: string, details?: AtlasErrorDetails);
2618
+ }
2619
+ declare class AtlasAuthError extends AtlasError {
2620
+ constructor(message: string, requestId?: string, details?: AtlasErrorDetails);
2621
+ }
2622
+ declare class AtlasRateLimitError extends AtlasError {
2623
+ readonly retryAfter?: number;
2624
+ constructor(message: string, retryAfter?: number, requestId?: string, details?: AtlasErrorDetails);
2625
+ }
2626
+ declare class AtlasValidationError extends AtlasError {
2627
+ readonly fields?: string[];
2628
+ constructor(message: string, fields?: string[], requestId?: string, details?: AtlasErrorDetails);
2629
+ }
2630
+ declare class AtlasNetworkError extends AtlasError {
2631
+ readonly cause?: unknown;
2632
+ constructor(message: string, cause?: unknown);
2633
+ }
2634
+
2635
+ interface HttpTransportOptions {
2636
+ baseUrl: string;
2637
+ apiKey: string;
2638
+ timeoutMs?: number;
2639
+ maxRetries?: number;
2640
+ logger?: AtlasLogger;
2641
+ }
2642
+ interface AtlasLogger {
2643
+ debug?: (message: string, meta?: Record<string, unknown>) => void;
2644
+ info?: (message: string, meta?: Record<string, unknown>) => void;
2645
+ warn?: (message: string, meta?: Record<string, unknown>) => void;
2646
+ error?: (message: string, meta?: Record<string, unknown>) => void;
2647
+ }
2648
+ type QueryValue = string | number | boolean | undefined;
2649
+ interface RequestOptions {
2650
+ method: string;
2651
+ path: string;
2652
+ body?: unknown;
2653
+ query?: Record<string, QueryValue>;
2654
+ signal?: AbortSignal;
2655
+ /** Sent as `Idempotency-Key`. Writes get a fresh one per call when omitted,
2656
+ * and every retry of the call reuses it. */
2657
+ idempotencyKey?: string;
2658
+ /** The request may be sent again: the route runs it at most once per
2659
+ * Idempotency-Key and answers a repeat with the stored result (the order
2660
+ * writes), or a second copy changes nothing more than the first. Any
2661
+ * other write is never retried once it may have reached the server. */
2662
+ idempotent?: boolean;
2663
+ /** This request's own per-attempt timeout, for a route that holds the
2664
+ * request longer than the client's `timeoutMs`. */
2665
+ timeoutMs?: number;
2666
+ }
2667
+ /** What a caller can pass to a write that the server de-duplicates. */
2668
+ interface WriteOptions {
2669
+ /** Send your own key to retry a write safely across calls (and processes):
2670
+ * the server answers every request with the same key with the first
2671
+ * one's result for 24 hours, and refuses the key for a different request.
2672
+ * 1 to 255 printable ASCII characters, no spaces. Omitted, each call
2673
+ * gets a fresh key that only its own retries share. */
2674
+ idempotencyKey?: string;
2675
+ signal?: AbortSignal;
2676
+ }
2677
+ /** A successful body as the server sent it. Some MT5 reads add freshness
2678
+ * fields beside `data`. */
2679
+ interface ApiEnvelope<T> {
2680
+ success: true;
2681
+ data: T;
2682
+ message?: string;
2683
+ /** When the data was produced (ISO 8601). MT5 terminal reads only. */
2684
+ dataAsOf?: string;
2685
+ /** The terminal's last EA heartbeat (ISO 8601), or null if none was ever seen. MT5 terminal reads only. */
2686
+ lastHeartbeatAt?: string | null;
2687
+ }
2688
+ declare class HttpTransport {
2689
+ private readonly baseUrl;
2690
+ private readonly apiKey;
2691
+ private readonly timeoutMs;
2692
+ private readonly maxRetries;
2693
+ private readonly logger?;
2694
+ constructor(options: HttpTransportOptions);
2695
+ /** The `data` of a successful response. */
2696
+ request<T>(options: RequestOptions): Promise<T>;
2697
+ /** The whole successful body, with any freshness fields beside `data`. */
2698
+ requestEnvelope<T>(options: RequestOptions): Promise<ApiEnvelope<T>>;
2699
+ private attempt;
2700
+ private mapError;
2701
+ }
2702
+
2703
+ /**
2704
+ * MT5 strategy tester runs (`/api/external/backtests`). A backtest is a group
2705
+ * of one or more runs: a single test, an optimization, or a walk-forward.
2706
+ *
2707
+ * Creating one queues real work charged to the usage balance, and the server does not
2708
+ * de-duplicate these writes, so the SDK never sends one twice: after a
2709
+ * timeout, `list()` before you create again.
2710
+ */
2711
+ declare class BacktestsResource {
2712
+ private readonly http;
2713
+ constructor(http: HttpTransport);
2714
+ private run;
2715
+ private group;
2716
+ /** Your backtests, newest first. Page with `nextCursor`. */
2717
+ list(query?: ListBacktestsQuery): Promise<ListBacktestsResult>;
2718
+ /** Queue a backtest: a single run, an optimization (`optimization`) or a
2719
+ * walk-forward (`optimization` + `walkForward`). 402 when the usage balance is short. */
2720
+ create(body: CreateBacktestBody): Promise<CreateBacktestResult>;
2721
+ /** Time and cost (from the usage balance, in its currency) a backtest would take. Queues nothing. */
2722
+ estimate(query: BacktestEstimateQuery): Promise<BacktestEstimate>;
2723
+ /** A group with its runs and their tester logs. */
2724
+ get(groupId: string): Promise<BacktestGroup>;
2725
+ /** 409 while a run is still on a terminal: cancel it first. */
2726
+ delete(groupId: string): Promise<{
2727
+ id: string;
2728
+ }>;
2729
+ /** Up to 2000 characters; null clears it. */
2730
+ setNote(groupId: string, note: string | null): Promise<BacktestGroup>;
2731
+ /** Pin this group as its EA's baseline. */
2732
+ setBaseline(groupId: string): Promise<{
2733
+ eaId: string;
2734
+ baselineGroupId: string | null;
2735
+ }>;
2736
+ /** Unpin this group if it is its EA's baseline. */
2737
+ clearBaseline(groupId: string): Promise<{
2738
+ eaId: string;
2739
+ baselineGroupId: string | null;
2740
+ }>;
2741
+ /** Unlock the out-of-sample run. Every call is counted in `oosRevealCount`. */
2742
+ revealOos(groupId: string): Promise<RevealOosResult>;
2743
+ /** Folds, walk-forward efficiency, the stitched OOS equity and parameter stability. */
2744
+ walkForward(groupId: string): Promise<WalkForwardReport>;
2745
+ /** Every symbol on every timeframe as its own backtest (up to 12). */
2746
+ createBatch(body: CreateBacktestBatchBody): Promise<CreateBacktestBatchResult>;
2747
+ getBatch(batchId: string): Promise<BacktestBatchReport>;
2748
+ /** Rerun a single backtest with its numeric inputs nudged at random, to see how fragile it is. */
2749
+ createNoiseTest(body: CreateNoiseTestBody): Promise<CreateNoiseTestResult>;
2750
+ /** One walk-forward per in-sample ratio and fold count (up to 9). */
2751
+ createWalkForwardMatrix(body: CreateWalkForwardMatrixBody): Promise<CreateWalkForwardMatrixResult>;
2752
+ /** Combine 2 to 20 finished runs into one account. Changes nothing. */
2753
+ portfolio(body: PortfolioBody): Promise<PortfolioReport>;
2754
+ /** Presigned links to the result JSON and the MT5 report, valid for 10 minutes. */
2755
+ result(runId: string): Promise<BacktestResultUrls>;
2756
+ /** Report numbers, breakdowns and compact analytics. 409 until the run is DONE. */
2757
+ stats(runId: string): Promise<BacktestRunStats>;
2758
+ /** The run's closed trades, filtered and sorted, or grouped with `aggregate`. */
2759
+ trades(runId: string, query?: BacktestTradesQuery & {
2760
+ aggregate?: "none";
2761
+ }): Promise<BacktestTradesResult<BacktestTrade>>;
2762
+ trades(runId: string, query: BacktestTradesQuery & {
2763
+ aggregate: Exclude<BacktestTradesQuery["aggregate"], "none" | undefined>;
2764
+ }): Promise<BacktestTradesResult<BacktestTradeAggregateRow>>;
2765
+ /** An optimization run's passes, best first by default. */
2766
+ passes(runId: string, query?: BacktestPassesQuery): Promise<BacktestPassesResult>;
2767
+ /** Where the run sits among your other finished runs of the same EA. */
2768
+ peer(runId: string): Promise<BacktestPeerContext>;
2769
+ /** Stop a queued or running run. 409 once it has finished. */
2770
+ cancel(runId: string): Promise<CancelBacktestRunResult>;
2771
+ /** An AI summary of the run, cached; `refresh` makes a new one (at most every 10 minutes). */
2772
+ summary(runId: string, options?: {
2773
+ refresh?: boolean;
2774
+ }): Promise<{
2775
+ summary: BacktestAiSummary;
2776
+ }>;
2777
+ /** A plain-language explanation of one trade of the run. */
2778
+ explainTrade(runId: string, positionId: string): Promise<{
2779
+ explanation: string;
2780
+ }>;
2781
+ /** Rerun a single run on another tick model, as a new linked backtest. */
2782
+ rerunOnTickModel(runId: string, tickMode: BacktestTickMode): Promise<CreateBacktestResult>;
2783
+ /** A unified diff of two EA versions' .mq5 source. */
2784
+ sourceDiff(fromVersionId: string, toVersionId: string): Promise<BacktestSourceDiff>;
2785
+ /** Swap carry across your terminals' brokers: long on one, short on another. */
2786
+ swapArbitrage(): Promise<SwapArbitrageReport>;
2787
+ /** The spread by hour your terminal has seen on a symbol, and the execution delay to test with. */
2788
+ spreadCalibration(instanceId: string, symbol: string): Promise<SpreadCalibration>;
2789
+ }
991
2790
 
992
2791
  /** @internal */
993
2792
  declare class BrokerSubscriptionsResource {
994
2793
  /** @internal */ readonly http: HttpTransport;
995
2794
  /** @internal */ readonly basePath: string;
996
2795
  constructor(http: HttpTransport, basePath: string);
2796
+ /** @deprecated Subscribe NSE, BSE and MCX keys on the `market.ticks` WebSocket channel instead (it needs India access). */
997
2797
  subscribe(body: BrokerSubscribeBody): Promise<unknown>;
2798
+ /** @deprecated Unsubscribe from the `market.ticks` WebSocket channel instead. */
998
2799
  unsubscribe(body: BrokerUnsubscribeBody): Promise<unknown>;
2800
+ /** @deprecated The `subscribed` reply on the `market.ticks` WebSocket channel lists what streams. */
999
2801
  list(): Promise<unknown>;
1000
2802
  }
1001
- /** @internal */
2803
+ /**
2804
+ * One broker connection's own API, in the broker's own field names
2805
+ * (`/api/external/brokers/:broker/connections/:id`). Every method is
2806
+ * deprecated in favour of `atlas.v2.connections(id)` and `atlas.v2.market`,
2807
+ * which speak one shape for every broker; the routes keep working.
2808
+ * @internal
2809
+ */
1002
2810
  declare class BrokerConnectionResource {
1003
2811
  readonly subscriptions: BrokerSubscriptionsResource;
1004
2812
  /** @internal */ readonly basePath: string;
1005
2813
  /** @internal */ readonly http: HttpTransport;
1006
2814
  constructor(http: HttpTransport, brokerName: string, connectionId: string);
1007
- placeOrder(body: BrokerOrderBody): Promise<unknown>;
2815
+ /**
2816
+ * Place an order in the broker's own fields. Runs at most once per
2817
+ * Idempotency-Key, so a retry never places twice.
2818
+ * @deprecated Use `atlas.v2.connections(id).placeOrder()` (`POST /api/v2/connections/{id}/orders`).
2819
+ */
2820
+ placeOrder(order: BrokerOrder | BrokerOrderBody, options?: WriteOptions): Promise<unknown>;
2821
+ /** @deprecated Use `atlas.v2.connections(id).orders()` (`GET /api/v2/connections/{id}/orders`). */
1008
2822
  getOrders(): Promise<unknown>;
2823
+ /** @deprecated Use `atlas.v2.connections(id).order(orderId)` (`GET /api/v2/connections/{id}/orders/{orderId}`). */
1009
2824
  getOrder(orderId: string): Promise<unknown>;
1010
- modifyOrder(orderId: string, body: BrokerModifyOrderBody): Promise<unknown>;
1011
- cancelOrder(orderId: string, body?: BrokerCancelOrderBody): Promise<unknown>;
1012
- /** Trade book (fills). Currently served by Motilal Oswal; brokers whose
1013
- * runner adapter doesn't implement it return an "unsupported command" error. */
2825
+ /**
2826
+ * Change a working order, in the broker's own fields.
2827
+ * @deprecated Use `atlas.v2.connections(id).modifyOrder()` (`PUT /api/v2/connections/{id}/orders/{orderId}`).
2828
+ */
2829
+ modifyOrder(orderId: string, changes: BrokerOrder | BrokerModifyOrderBody, options?: WriteOptions): Promise<unknown>;
2830
+ /** @deprecated Use `atlas.v2.connections(id).cancelOrder(orderId)` (`DELETE /api/v2/connections/{id}/orders/{orderId}`). */
2831
+ cancelOrder(orderId: string, body?: BrokerCancelOrderBody, options?: WriteOptions): Promise<unknown>;
2832
+ /**
2833
+ * Trade book (fills). Currently served by Motilal Oswal; brokers whose
2834
+ * runner adapter doesn't implement it return an "unsupported command" error.
2835
+ * @deprecated Use `atlas.v2.connections(id).trades()` (`GET /api/v2/connections/{id}/trades`).
2836
+ */
1014
2837
  getTrades(): Promise<unknown>;
2838
+ /** @deprecated Use `atlas.v2.connections(id).positions()` (`GET /api/v2/connections/{id}/positions`). */
1015
2839
  getPositions(): Promise<unknown>;
2840
+ /** @deprecated Use `atlas.v2.connections(id).holdings()` (`GET /api/v2/connections/{id}/holdings`). */
1016
2841
  getHoldings(): Promise<unknown>;
2842
+ /** @deprecated Use `atlas.v2.market.candles()` (`GET /api/v2/market/candles`), served from the Atlaas market data feed. */
1017
2843
  getCandles(query: BrokerCandlesQuery): Promise<unknown>;
2844
+ /**
2845
+ * Option expiries for an underlying, through this Dhan connection.
2846
+ * @deprecated Use `atlas.v2.market.expiries(underlyingKey)` (`GET /api/v2/market/expiries`).
2847
+ */
2848
+ getOptionExpiries(underlying: DhanUnderlying): Promise<string[]>;
2849
+ /**
2850
+ * Dhan's option chain for one expiry (YYYY-MM-DD), through this Dhan connection.
2851
+ * @deprecated Use `atlas.v2.market.optionChain(underlyingKey, expiry)` (`GET /api/v2/market/option-chain`), which serves the same data without a connection.
2852
+ */
2853
+ getOptionChain(underlying: DhanUnderlying, expiry: string): Promise<DhanOptionChain>;
1018
2854
  }
1019
2855
 
1020
- interface OrdersListParams {
2856
+ interface IncludeRawParams {
2857
+ /** Add the untranslated broker payload as `raw` on each row. */
1021
2858
  includeRaw?: boolean;
1022
2859
  }
2860
+ type OrdersListParams = IncludeRawParams;
2861
+ /** Options for a v2 write. */
2862
+ interface V2WriteOptions extends WriteOptions, IncludeRawParams {
2863
+ }
1023
2864
  interface OrdersListResult {
1024
2865
  orders: UnifiedOrder[];
1025
2866
  dropped: DroppedRow[];
1026
2867
  }
1027
- interface PositionsListParams {
2868
+ interface PositionsListParams extends IncludeRawParams {
1028
2869
  scope?: "NET" | "DAY";
1029
- includeRaw?: boolean;
1030
2870
  }
1031
2871
  interface PositionsListResult {
1032
2872
  positions: UnifiedPosition[];
@@ -1045,44 +2885,43 @@ interface CapabilitiesResult {
1045
2885
  broker: string;
1046
2886
  capabilities: BrokerCapabilities;
1047
2887
  }
2888
+ /** One connection on the unified v2 surface: `/api/v2/connections/:id`. The
2889
+ * id is the Atlaas instance id or its externalRef. */
1048
2890
  declare class ConnectionsV2 {
1049
2891
  private readonly http;
1050
2892
  private readonly connectionId;
1051
2893
  constructor(http: HttpTransport, connectionId: string);
2894
+ private path;
2895
+ private read;
2896
+ private write;
1052
2897
  orders(params?: OrdersListParams): Promise<OrdersListResult>;
1053
- order(orderId: string, params?: {
1054
- includeRaw?: boolean;
1055
- }): Promise<UnifiedOrder>;
1056
- trades(): Promise<TradesListResult>;
2898
+ order(orderId: string, params?: IncludeRawParams): Promise<UnifiedOrder>;
2899
+ trades(params?: IncludeRawParams): Promise<TradesListResult>;
2900
+ /** `scope` defaults to `NET`; MT5 and Motilal are net-only and always answer `NET`. */
1057
2901
  positions(params?: PositionsListParams): Promise<PositionsListResult>;
1058
- holdings(): Promise<HoldingsListResult>;
1059
- funds(): Promise<UnifiedFunds>;
1060
- profile(): Promise<UnifiedProfile>;
2902
+ holdings(params?: IncludeRawParams): Promise<HoldingsListResult>;
2903
+ funds(params?: IncludeRawParams): Promise<UnifiedFunds>;
2904
+ profile(params?: IncludeRawParams): Promise<UnifiedProfile>;
1061
2905
  /** MT5 only: the broker server's contract specs (contract size, volume limits, tick size…),
1062
2906
  * keyed to instruments where a ref exists. Held server-side for ~10 min; `symbol` filters. */
1063
2907
  symbols(params?: {
1064
2908
  symbol?: string;
1065
2909
  }): Promise<SymbolSpecsResult>;
1066
2910
  capabilities(): Promise<CapabilitiesResult>;
1067
- snapshot(params?: {
1068
- includeRaw?: boolean;
1069
- }): Promise<V2Snapshot>;
1070
- place(body: PlaceOrderV2Body, params?: {
1071
- includeRaw?: boolean;
1072
- }): Promise<PlaceOrderResult>;
1073
- modify(orderId: string, body: ModifyOrderV2Body, params?: {
1074
- includeRaw?: boolean;
1075
- }): Promise<ModifyOrderResult>;
1076
- cancel(orderId: string, params?: {
1077
- includeRaw?: boolean;
1078
- }): Promise<CancelOrderResult>;
1079
- closePosition(body: ClosePositionV2Body, params?: {
1080
- includeRaw?: boolean;
1081
- }): Promise<ClosePositionResult>;
2911
+ /** Every read in one call; each section reports ok or error on its own. Positions are `NET`. */
2912
+ snapshot(params?: IncludeRawParams): Promise<V2Snapshot>;
2913
+ placeOrder(body: PlaceOrderV2Body, options?: V2WriteOptions): Promise<PlaceOrderResult>;
2914
+ modifyOrder(orderId: string, body: ModifyOrderV2Body, options?: V2WriteOptions): Promise<ModifyOrderResult>;
2915
+ cancelOrder(orderId: string, options?: V2WriteOptions): Promise<CancelOrderResult>;
2916
+ /** @deprecated Renamed to {@link ConnectionsV2.placeOrder}, which takes the same arguments. */
2917
+ place(body: PlaceOrderV2Body, options?: V2WriteOptions): Promise<PlaceOrderResult>;
2918
+ /** @deprecated Renamed to {@link ConnectionsV2.modifyOrder}, which takes the same arguments. */
2919
+ modify(orderId: string, body: ModifyOrderV2Body, options?: V2WriteOptions): Promise<ModifyOrderResult>;
2920
+ /** @deprecated Renamed to {@link ConnectionsV2.cancelOrder}, which takes the same arguments. */
2921
+ cancel(orderId: string, options?: V2WriteOptions): Promise<CancelOrderResult>;
2922
+ closePosition(body: ClosePositionV2Body, options?: V2WriteOptions): Promise<ClosePositionResult>;
1082
2923
  /** SL / TP on a live position (MT5). An omitted side keeps its level; 0 clears it. */
1083
- modifyPosition(positionId: string, body: ModifyPositionV2Body, params?: {
1084
- includeRaw?: boolean;
1085
- }): Promise<ModifyPositionResult>;
2924
+ modifyPosition(positionId: string, body: ModifyPositionV2Body, options?: V2WriteOptions): Promise<ModifyPositionResult>;
1086
2925
  }
1087
2926
 
1088
2927
  /**
@@ -1110,7 +2949,19 @@ declare class EasResource {
1110
2949
  /** Issue a short-lived R2 upload URL for a new .ex5/.mq5 build. */
1111
2950
  presignVersion(eaId: string, body: PresignEaVersionBody): Promise<PresignEaVersionResult>;
1112
2951
  /** Register an already-uploaded build (the r2Key returned by presignVersion). */
1113
- registerVersion(eaId: string, body: RegisterEaVersionBody): Promise<EaVersion>;
2952
+ registerVersion(eaId: string, body: RegisterEaVersionBody): Promise<RegisteredEaVersion>;
2953
+ /** Save .mq5 source as a version. Atlaas compile-checks it first (up to a
2954
+ * minute): a failure is a 422 whose `AtlasError.body` is an `EaCompileFailure`
2955
+ * with the compiler's diagnostics. The saved version then compiles in the
2956
+ * background (`compileStatus: "PENDING"`). The request waits up to
2957
+ * `SAVE_SOURCE_TIMEOUT_MS` (2 minutes) whatever the client's `timeoutMs`,
2958
+ * and like every non-order write it is never sent twice. */
2959
+ saveSource(eaId: string, body: SaveEaSourceBody, options?: {
2960
+ timeoutMs?: number;
2961
+ signal?: AbortSignal;
2962
+ }): Promise<RegisteredEaVersion>;
2963
+ /** The .mq5 source of a version (by version id). 409 for an .ex5-only version. */
2964
+ getVersionSource(eaId: string, versionId: string): Promise<EaVersionSource>;
1114
2965
  /** Mark a version LIVE (rollback) without re-uploading. */
1115
2966
  promoteVersion(eaId: string, versionId: string): Promise<{
1116
2967
  id: string;
@@ -1121,6 +2972,13 @@ declare class EasResource {
1121
2972
  id: string;
1122
2973
  version: string;
1123
2974
  }>;
2975
+ listPresets(eaId: string): Promise<{
2976
+ items: EaPreset[];
2977
+ }>;
2978
+ createPreset(eaId: string, body: CreateEaPresetBody): Promise<EaPreset>;
2979
+ deletePreset(eaId: string, presetId: string): Promise<{
2980
+ id: string;
2981
+ }>;
1124
2982
  listDeployments(query?: ListDeploymentsQuery): Promise<ListDeploymentsResult>;
1125
2983
  /** Bind a version to a chart inside one of the caller's instances. The
1126
2984
  * setBlob is the .set input-override text; edit it via updateDeployment. */
@@ -1130,8 +2988,22 @@ declare class EasResource {
1130
2988
  removeDeployment(id: string): Promise<{
1131
2989
  id: string;
1132
2990
  }>;
2991
+ /** The newest live comparison of a deployment: its live trades matched against a backtest of the same window. */
2992
+ getLiveComparison(deploymentId: string): Promise<LiveComparison>;
2993
+ /** Queue a backtest of the deployment over `from`..`to` (billed as a
2994
+ * backtest); the comparison is ready from `getLiveComparison` once it finishes. */
2995
+ runLiveComparison(deploymentId: string, body: RunLiveComparisonBody): Promise<{
2996
+ runId: string;
2997
+ groupId: string;
2998
+ }>;
2999
+ /** The deployment's monitor: a scheduled re-backtest checked against its live trades. */
3000
+ getMonitor(deploymentId: string): Promise<MonitorStatus>;
3001
+ setMonitor(deploymentId: string, body: SetMonitorBody): Promise<MonitorStatus>;
1133
3002
  }
1134
3003
 
3004
+ /** Instances on `/api/atlas/instances`: MT5 terminals and broker connections,
3005
+ * keyed by your own `externalRef`. None of these writes is de-duplicated by
3006
+ * the server, so the SDK never sends one twice. */
1135
3007
  declare class InstancesResource {
1136
3008
  private readonly http;
1137
3009
  constructor(http: HttpTransport);
@@ -1139,25 +3011,34 @@ declare class InstancesResource {
1139
3011
  get(id: string): Promise<AtlasInstance>;
1140
3012
  getByExternalRef(ref: string): Promise<AtlasInstance>;
1141
3013
  getByExternalRefs(refs: string[]): Promise<AtlasInstance[]>;
1142
- create(body: CreateAtlasInstanceBody): Promise<AtlasInstance>;
1143
- update(id: string, body: UpdateAtlasInstanceBody): Promise<AtlasInstance>;
3014
+ /** Create an instance, or update yours that has the same `externalRef`.
3015
+ * Read the whole instance with `get(result.id)`. */
3016
+ create(body: CreateAtlasInstanceBody): Promise<CreateAtlasInstanceResult>;
3017
+ update(id: string, body: UpdateAtlasInstanceBody): Promise<{
3018
+ id: string;
3019
+ }>;
1144
3020
  /**
1145
3021
  * Wind an instance down: the host runner kills the terminal process and
1146
3022
  * deletes the instance folder. Credentials stay stored, so the instance
1147
- * can be re-enabled later. Returns the updated instance.
3023
+ * can be re-enabled later. Returns the updated instance (null if it was
3024
+ * deleted meanwhile).
1148
3025
  */
1149
- disable(id: string): Promise<AtlasInstance>;
3026
+ disable(id: string): Promise<AtlasInstance | null>;
1150
3027
  /**
1151
3028
  * Re-enable a wound-down instance: resets it to PENDING so the runner
1152
- * redeploys it fresh. Returns the updated instance.
3029
+ * redeploys it fresh. Returns the updated instance (null if it was
3030
+ * deleted meanwhile).
1153
3031
  */
1154
- enable(id: string): Promise<AtlasInstance>;
3032
+ enable(id: string): Promise<AtlasInstance | null>;
1155
3033
  delete(id: string): Promise<void>;
3034
+ /** Check broker credentials before you store them. For Dhan this logs in
3035
+ * and returns the minted access token; other brokers are not checked. */
3036
+ validateBrokerCredentials(body: ValidateBrokerCredentialsBody): Promise<ValidateBrokerCredentialsResult>;
1156
3037
  }
1157
3038
 
1158
3039
  interface InstrumentListParams {
1159
- exchange?: string;
1160
- segment?: string;
3040
+ exchange?: UnifiedInstrument["exchange"];
3041
+ segment?: UnifiedInstrument["segment"];
1161
3042
  symbol?: string;
1162
3043
  q?: string;
1163
3044
  active?: boolean;
@@ -1169,7 +3050,7 @@ interface InstrumentListResult {
1169
3050
  nextCursor: string | null;
1170
3051
  }
1171
3052
  interface ResolveInstrumentParams {
1172
- broker: "dhan" | "motilal" | "kite" | "mt5";
3053
+ broker: "dhan" | "motilal" | "kite" | "mt5" | "angelone" | "fyers" | "upstox" | "shoonya";
1173
3054
  refId: string;
1174
3055
  segment?: string;
1175
3056
  }
@@ -1183,6 +3064,7 @@ declare class InstrumentsV2 {
1183
3064
 
1184
3065
  interface MarketCandlesParams {
1185
3066
  instrumentKey: string;
3067
+ /** NSE/BSE (vendor feed): 1m, 5m, 15m, 1h, 1d. FX (MT5): every interval. */
1186
3068
  interval: UnifiedInterval;
1187
3069
  /** ISO 8601 or Date. */
1188
3070
  from: string | Date;
@@ -1211,7 +3093,8 @@ declare class MarketV2 {
1211
3093
  constructor(http: HttpTransport);
1212
3094
  /** Latest tick. A vendor key nobody is watching is subscribed and read
1213
3095
  * once from the vendor's REST endpoint, so this answers with a
1214
- * `mode: "LTP"` snapshot rather than a retry-later 404. */
3096
+ * `mode: "LTP"` snapshot. An FX key with no tick yet answers a retryable
3097
+ * 404 (`VALIDATION`) while its subscription opens. */
1215
3098
  quote(instrumentKey: string): Promise<UnifiedTick>;
1216
3099
  /** Latest tick for up to 200 keys, with the cold ones read in one vendor
1217
3100
  * call. `unresolved` names the keys that could not be priced and why —
@@ -1225,6 +3108,51 @@ declare class MarketV2 {
1225
3108
  optionChain(underlyingKey: string, expiry: string): Promise<UnifiedOptionChain>;
1226
3109
  }
1227
3110
 
3111
+ /**
3112
+ * MT5 terminals by login (`/api/external/instances`): deploy, start, stop and
3113
+ * remove them. Trade on one with `atlas.v2.connections(instance.id)`. None
3114
+ * of these writes is de-duplicated by the server, so the SDK never sends one
3115
+ * twice.
3116
+ */
3117
+ declare class Mt5Resource {
3118
+ private readonly http;
3119
+ constructor(http: HttpTransport);
3120
+ private path;
3121
+ /** Your account's MT5 terminals, newest first. */
3122
+ list(): Promise<Instance[]>;
3123
+ /** Deploy a terminal. It starts as PENDING and the account is charged the provisioning fee. */
3124
+ create(body: CreateInstanceBody): Promise<Instance>;
3125
+ get(accountId: string): Promise<Instance>;
3126
+ /** Remove the terminal. Nothing is refunded. */
3127
+ delete(accountId: string): Promise<void>;
3128
+ /** Enable the terminal and queue it to deploy again. */
3129
+ start(accountId: string): Promise<Instance>;
3130
+ /** Disable the terminal. Allowed even while terminals are switched to read-only. */
3131
+ stop(accountId: string): Promise<Instance>;
3132
+ /** MT5 servers `create` accepts as `serverName`. */
3133
+ servers(): Promise<DeployServer[]>;
3134
+ /** Regions with room for a new terminal, for `create`'s `regionId`. */
3135
+ regions(): Promise<DeployRegion[]>;
3136
+ }
3137
+
3138
+ interface ScannerBoardParams {
3139
+ /** Add each stock's per-minute move since 09:15 IST as `paths`. */
3140
+ paths?: boolean;
3141
+ /** With `paths`: start each path at this session minute, to fetch only what you lack. */
3142
+ after?: number;
3143
+ }
3144
+ /** The NSE intraday scanner (`/api/v2/scanner/*`). Needs the `feed:r` scope
3145
+ * and the account's India entitlement; every row is an NSE equity. */
3146
+ declare class ScannerV2 {
3147
+ private readonly http;
3148
+ constructor(http: HttpTransport);
3149
+ /** The current board: every ranked stock, the picks on each side, breadth and sectors. */
3150
+ board(params?: ScannerBoardParams): Promise<ScannerBoard>;
3151
+ /** Order-block zones, stops and targets on the last two sessions of 5m
3152
+ * bars, for a stock the scanner ranks (`NSE:EQ:<symbol>`). 404 for any other. */
3153
+ zones(instrumentKey: string): Promise<ScannerZones>;
3154
+ }
3155
+
1228
3156
  declare class ServiceKeysResource {
1229
3157
  private readonly http;
1230
3158
  constructor(http: HttpTransport);
@@ -1249,22 +3177,75 @@ declare class SubscriptionsResource {
1249
3177
  getCandleSubscriptions(instanceId: string): Promise<CandleSubscriptions>;
1250
3178
  }
1251
3179
 
3180
+ /**
3181
+ * MT5 trading on one terminal, named by its MT5 login: `/api/external/instances/:accountId`.
3182
+ *
3183
+ * Most of it is deprecated in favour of `atlas.v2.connections(id)` and
3184
+ * `atlas.v2.market`, which work the same on MT5 and every broker; each
3185
+ * deprecated method names its replacement. The routes keep working, and
3186
+ * `getPosition`, `getClosedPositions` and `calculateMargin` have no v2
3187
+ * equivalent yet.
3188
+ *
3189
+ * The reads that come from the terminal can return their freshness too: pass
3190
+ * `{ withFreshness: true }` to get `{ data, dataAsOf, lastHeartbeatAt }`. A
3191
+ * terminal Atlaas cannot see answers 503 with `code: "TERMINAL_UNAVAILABLE"`
3192
+ * rather than an empty list.
3193
+ */
1252
3194
  declare class TradingResource {
1253
3195
  private readonly http;
1254
3196
  constructor(http: HttpTransport);
1255
3197
  private path;
1256
- placeOrder(accountId: string, body: PlaceOrderBody): Promise<Order>;
3198
+ private read;
3199
+ /** An order write: it runs at most once per Idempotency-Key. */
3200
+ private write;
3201
+ /** @deprecated Use `atlas.v2.connections(id).placeOrder()` (`POST /api/v2/connections/{id}/orders`). */
3202
+ placeOrder(accountId: string, body: PlaceOrderBody, options?: WriteOptions): Promise<Order>;
3203
+ /** @deprecated Use `atlas.v2.connections(id).orders()` (`GET /api/v2/connections/{id}/orders`). */
1257
3204
  getOrders(accountId: string): Promise<Order[]>;
1258
- cancelOrder(accountId: string, ticket: number): Promise<void>;
3205
+ /** @deprecated Use `atlas.v2.connections(id).orders()` (`GET /api/v2/connections/{id}/orders`). */
3206
+ getOrders(accountId: string, options: FreshnessOption): Promise<Fresh<Order[]>>;
3207
+ /** @deprecated Use `atlas.v2.connections(id).cancelOrder(ticket)` (`DELETE /api/v2/connections/{id}/orders/{ticket}`). */
3208
+ cancelOrder(accountId: string, ticket: number, options?: WriteOptions): Promise<void>;
3209
+ /**
3210
+ * Open positions, as the EA last pushed them (held for a few seconds).
3211
+ * @deprecated Use `atlas.v2.connections(id).positions()` (`GET /api/v2/connections/{id}/positions`).
3212
+ */
1259
3213
  getPositions(accountId: string): Promise<Position[]>;
1260
- getPosition(accountId: string, ticket: number): Promise<Position>;
1261
- modifyPosition(accountId: string, ticket: number, body: ModifyPositionBody): Promise<unknown>;
1262
- closePosition(accountId: string, ticket: number, body?: ClosePositionBody): Promise<unknown>;
1263
- closeBySymbol(accountId: string, body: CloseBySymbolBody): Promise<unknown>;
3214
+ /** @deprecated Use `atlas.v2.connections(id).positions()` (`GET /api/v2/connections/{id}/positions`). */
3215
+ getPositions(accountId: string, options: FreshnessOption): Promise<Fresh<Position[]>>;
3216
+ /** One position by ticket. A ticket no longer open is read from the terminal's history as `status: "CLOSED"`. */
3217
+ getPosition(accountId: string, ticket: number): Promise<PositionDetail>;
3218
+ getPosition(accountId: string, ticket: number, options: FreshnessOption): Promise<Fresh<PositionDetail>>;
3219
+ /** Fully closed positions from the terminal's deal history, oldest first. Page with `since` = the last `closeTimeMs`. */
3220
+ getClosedPositions(accountId: string, query: ClosedPositionsQuery): Promise<ClosedPositionsResult>;
3221
+ /** @deprecated Use `atlas.v2.connections(id).modifyPosition(ticket, { stopLoss, takeProfit })` (`PUT /api/v2/connections/{id}/positions/{ticket}`). */
3222
+ modifyPosition(accountId: string, ticket: number, body: ModifyPositionBody, options?: WriteOptions): Promise<ModifyMt5PositionResult>;
3223
+ /** @deprecated Use `atlas.v2.connections(id).closePosition({ instrumentKey, positionId: ticket })` (`POST /api/v2/connections/{id}/positions/close`). */
3224
+ closePosition(accountId: string, ticket: number, body?: ClosePositionBody, options?: WriteOptions): Promise<CloseMt5PositionResult>;
3225
+ /** @deprecated Use `atlas.v2.connections(id).closePosition({ instrumentKey })` (`POST /api/v2/connections/{id}/positions/close`). */
3226
+ closeBySymbol(accountId: string, body: CloseBySymbolBody, options?: WriteOptions): Promise<CloseBySymbolResult>;
3227
+ /** @deprecated Use `atlas.v2.market.quote("FX:<SYMBOL>")` (`GET /api/v2/market/quote`). */
1264
3228
  getPrice(accountId: string, symbol: string): Promise<Price>;
3229
+ /** @deprecated Use `atlas.v2.market.quote("FX:<SYMBOL>")` (`GET /api/v2/market/quote`). */
3230
+ getPrice(accountId: string, symbol: string, options: FreshnessOption): Promise<Fresh<Price>>;
3231
+ /** @deprecated Use `atlas.v2.connections(id).symbols()` (`GET /api/v2/connections/{id}/symbols`). */
1265
3232
  getSymbols(accountId: string): Promise<string[]>;
3233
+ /** @deprecated Use `atlas.v2.connections(id).symbols()` (`GET /api/v2/connections/{id}/symbols`). */
3234
+ getSymbols(accountId: string, options: FreshnessOption): Promise<Fresh<string[]>>;
3235
+ /**
3236
+ * Contract specs for every symbol on the terminal's server, raw from the terminal.
3237
+ * @deprecated Use `atlas.v2.connections(id).symbols()` (`GET /api/v2/connections/{id}/symbols`), which carries each symbol's contract spec.
3238
+ */
3239
+ getSymbolSpecs(accountId: string): Promise<Mt5SymbolSpec[]>;
3240
+ /** @deprecated Use `atlas.v2.connections(id).symbols()` (`GET /api/v2/connections/{id}/symbols`), which carries each symbol's contract spec. */
3241
+ getSymbolSpecs(accountId: string, options: FreshnessOption): Promise<Fresh<Mt5SymbolSpec[]>>;
3242
+ /** @deprecated Use `atlas.v2.connections(id).funds()` (`GET /api/v2/connections/{id}/funds`). */
1266
3243
  getAccountInfo(accountId: string): Promise<AccountInfo>;
3244
+ /** @deprecated Use `atlas.v2.connections(id).funds()` (`GET /api/v2/connections/{id}/funds`). */
3245
+ getAccountInfo(accountId: string, options: FreshnessOption): Promise<Fresh<AccountInfo>>;
3246
+ /** @deprecated Use `atlas.v2.market.candles({ instrumentKey, interval, from, to, connectionId })` (`GET /api/v2/market/candles`). */
1267
3247
  getCandles(accountId: string, query: GetCandlesQuery): Promise<Candle[]>;
3248
+ /** A calculation, not a write: it changes nothing on the terminal. */
1268
3249
  calculateMargin(accountId: string, body: CalculateMarginBody): Promise<MarginResult>;
1269
3250
  }
1270
3251
 
@@ -1276,44 +3257,33 @@ interface AtlasClientOptions {
1276
3257
  logger?: AtlasLogger;
1277
3258
  }
1278
3259
  declare class AtlasClient {
3260
+ /** MT5 platform (v1): instances and broker connections on `/api/atlas/instances`. */
1279
3261
  readonly instances: InstancesResource;
3262
+ /** MT5 platform (v1): terminals by login, deploy, start, stop, remove. */
3263
+ readonly mt5: Mt5Resource;
1280
3264
  readonly eas: EasResource;
3265
+ readonly backtests: BacktestsResource;
3266
+ /** MT5 trading on one terminal, by login. Mostly deprecated: use `v2.connections(id)` and `v2.market`, which work on every market. */
1281
3267
  readonly trading: TradingResource;
1282
3268
  readonly subscriptions: SubscriptionsResource;
1283
3269
  readonly serviceKeys: ServiceKeysResource;
3270
+ /** The market-neutral API (`/api/v2`): trading on every connection, instruments, market data and the scanner. */
1284
3271
  readonly v2: {
1285
3272
  instruments: InstrumentsV2;
1286
3273
  market: MarketV2;
3274
+ scanner: ScannerV2;
1287
3275
  connections: (connectionId: string) => ConnectionsV2;
1288
3276
  };
1289
3277
  private readonly http;
1290
3278
  private readonly brokersResource;
1291
3279
  constructor(options: AtlasClientOptions);
3280
+ /**
3281
+ * A broker connection's own API, by broker name and the connection's `externalRef`.
3282
+ * @deprecated Use `v2.connections(connectionId)`, which takes the same `externalRef` and speaks one shape for every broker.
3283
+ */
1292
3284
  broker(brokerName: string, connectionId: string): BrokerConnectionResource;
1293
3285
  }
1294
3286
 
1295
- declare class AtlasError extends Error {
1296
- readonly statusCode: number;
1297
- readonly errorCode?: number;
1298
- readonly requestId?: string;
1299
- constructor(message: string, statusCode?: number, errorCode?: number, requestId?: string);
1300
- }
1301
- declare class AtlasAuthError extends AtlasError {
1302
- constructor(message: string, requestId?: string);
1303
- }
1304
- declare class AtlasRateLimitError extends AtlasError {
1305
- readonly retryAfter?: number;
1306
- constructor(message: string, retryAfter?: number, requestId?: string);
1307
- }
1308
- declare class AtlasValidationError extends AtlasError {
1309
- readonly fields?: string[];
1310
- constructor(message: string, fields?: string[], requestId?: string);
1311
- }
1312
- declare class AtlasNetworkError extends AtlasError {
1313
- readonly cause?: unknown;
1314
- constructor(message: string, cause?: unknown);
1315
- }
1316
-
1317
3287
  interface AtlasWebSocketOptions {
1318
3288
  baseUrl: string;
1319
3289
  apiKey: string;
@@ -1325,11 +3295,21 @@ interface AtlasWebSocketOptions {
1325
3295
  type WSEventMap = {
1326
3296
  tick: [MT5Tick];
1327
3297
  candle: [MT5Candle];
3298
+ position_update: [MT5PositionUpdate];
3299
+ trade_event: [MT5TradeEvent];
3300
+ heartbeat: [MT5Heartbeat];
1328
3301
  broker_tick: [BrokerTick];
1329
3302
  broker_order_update: [BrokerOrderUpdate];
1330
3303
  "market.tick": [MarketTickMessage];
1331
3304
  "market.candle": [MarketCandleMessage];
3305
+ "market.chain": [MarketChainMessage];
3306
+ "market.scanner": [MarketScannerMessage];
1332
3307
  "trading.order": [TradingOrderMessage];
3308
+ /** The server's reply to `subscribe`, naming anything it refused. */
3309
+ subscribed: [SubscribedMessage];
3310
+ /** A subscribe refused on the account's standing; nothing changed. */
3311
+ subscribe_failed: [SubscribeFailedMessage];
3312
+ unsubscribed: [UnsubscribedMessage];
1333
3313
  connected: [];
1334
3314
  disconnected: [string];
1335
3315
  error: [Error];
@@ -1350,8 +3330,14 @@ declare class AtlasWebSocket extends EventEmitter {
1350
3330
  constructor(options: AtlasWebSocketOptions);
1351
3331
  connect(): Promise<void>;
1352
3332
  disconnect(): void;
3333
+ /** Add channels and filters. The server merges every subscribe on a socket,
3334
+ * and so does the reconnect replay. Its `subscribed` reply names anything
3335
+ * refused; `subscribe_failed` means the account's standing refused it whole. */
1353
3336
  subscribe(options: WSSubscribeOptions): void;
1354
- unsubscribe(channels: WSChannel[]): void;
3337
+ private send;
3338
+ /** Drop channels, or only some instrumentKeys / chains while the channels
3339
+ * stay subscribed. Passing an array is the same as `{ channels }`. */
3340
+ unsubscribe(options: WSChannel[] | WSUnsubscribeOptions): void;
1355
3341
  get isConnected(): boolean;
1356
3342
  private handleMessage;
1357
3343
  private sendJson;
@@ -1362,4 +3348,4 @@ declare class AtlasWebSocket extends EventEmitter {
1362
3348
  emit<K extends keyof WSEventMap>(event: K, ...args: WSEventMap[K]): boolean;
1363
3349
  }
1364
3350
 
1365
- export { type AccountInfo, AtlasAuthError, AtlasClient, type AtlasClientOptions, AtlasError, type AtlasInstance, type AtlasLogger, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, type AtlasWebSocketOptions, type BrokerCancelOrderBody, type BrokerCandlesQuery, type BrokerCapabilities, type BrokerModifyOrderBody, type BrokerOrderBody, type BrokerOrderUpdate, type BrokerSubscribeBody, type BrokerTick, type BrokerUnsubscribeBody, type CalculateMarginBody, type CancelOrderResult, type Candle, type CandleSubscriptions, type CloseBySymbolBody, type ClosePositionBody, type ClosePositionResult, type ClosePositionV2Body, ConnectionsV2, type CreateAtlasInstanceBody, type CreateDeploymentBody, type CreateEaBody, type CreateInstanceBody, type CreateServiceKeyBody, type Deployment, type DeploymentState, type DroppedRow, type Ea, type EaCompileStatus, type EaInputManifest, type EaInputParam, type EaInputType, type EaSourceType, type EaTimeframe, type EaVersion, type EaVersionStatus, type GetCandlesQuery, type Instance, type InstanceState, type InstanceType, type ListDeploymentsQuery, type ListDeploymentsResult, type ListEaVersionsQuery, type ListEaVersionsResult, type ListInstancesQuery, type MT5Candle, type MT5Tick, type MarginOrderType, type MarginResult, type MarketCandleMessage, type MarketCandlesParams, type MarketCandlesResult, type MarketQuotesResult, type MarketTickMessage, MarketV2, type ModifyOrderResult, type ModifyOrderV2Body, type ModifyPositionBody, type Order, type OrderDirection, type OrderType, type PlaceOrderBody, type PlaceOrderResult, type PlaceOrderV2Body, type Position, type PresignEaVersionBody, type PresignEaVersionResult, type Price, type RegisterEaVersionBody, type ServiceKey, type ServiceKeyWithRaw, type SubscribeCandleBody, type SubscribeTickBody, type TickSubscriptions, type Timeframe, type TradingOrderMessage, type UnifiedCandle, type UnifiedError, type UnifiedFunds, type UnifiedHolding, type UnifiedInstrument, type UnifiedInterval, type UnifiedOrder, type UnifiedPosition, type UnifiedProfile, type UnifiedTick, type UnifiedTrade, type UnsubscribeCandleBody, type UnsubscribeTickBody, type UpdateAtlasInstanceBody, type UpdateDeploymentBody, type UpdateEaBody, type UpdateServiceKeyBody, type V2Snapshot, type WSChannel, type WSSubscribeOptions };
3351
+ export { type AccountInfo, type ApiEnvelope, AtlasAuthError, AtlasClient, type AtlasClientOptions, AtlasError, type AtlasErrorCode, type AtlasErrorDetails, type AtlasInstance, type AtlasLogger, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError, AtlasWebSocket, type AtlasWebSocketOptions, type BacktestAiSummary, type BacktestAnalytics, type BacktestBatchKind, type BacktestBatchReport, type BacktestEstimate, type BacktestEstimateQuery, type BacktestExecutor, type BacktestExitReason, type BacktestGroup, type BacktestGroupKind, type BacktestPassesQuery, type BacktestPassesResult, type BacktestPeerContext, type BacktestRedFlag, type BacktestResultUrls, type BacktestRun, type BacktestRunMode, type BacktestRunStats, type BacktestSourceDiff, type BacktestStats, type BacktestStatus, type BacktestTickMode, type BacktestTrade, type BacktestTradeAggregate, type BacktestTradeAggregateRow, type BacktestTradeSort, type BacktestTradesQuery, type BacktestTradesResult, type BacktestWindow, BacktestsResource, type BrokerCancelOrderBody, type BrokerCandlesQuery, type BrokerCapabilities, BrokerConnectionResource, type BrokerInstrumentRef, type BrokerModifyOrderBody, type BrokerOrder, type BrokerOrderBody, type BrokerOrderUpdate, type BrokerSubscribeBody, BrokerSubscriptionsResource, type BrokerTick, type BrokerUnsubscribeBody, type CalculateMarginBody, type CancelBacktestRunResult, type CancelOrderResult, type Candle, type CandleSubscription, type CandleSubscriptions, type CapabilitiesResult, type ChainSelector, type CloseBySymbolBody, type CloseBySymbolResult, type CloseMt5PositionResult, type ClosePositionBody, type ClosePositionResult, type ClosePositionV2Body, type ClosedPosition, type ClosedPositionDetail, type ClosedPositionsQuery, type ClosedPositionsResult, ConnectionsV2, type CreateAtlasInstanceBody, type CreateAtlasInstanceResult, type CreateBacktestBatchBody, type CreateBacktestBatchResult, type CreateBacktestBody, type CreateBacktestResult, type CreateDeploymentBody, type CreateEaBody, type CreateEaPresetBody, type CreateInstanceBody, type CreateNoiseTestBody, type CreateNoiseTestResult, type CreateServiceKeyBody, type CreateWalkForwardMatrixBody, type CreateWalkForwardMatrixResult, type DeployRegion, type DeployServer, type Deployment, type DeploymentState, type DhanOptionChain, type DhanOptionLeg, type DhanSegment, type DhanUnderlying, type DroppedMt5Row, type DroppedRow, type Ea, type EaCompileFailure, type EaCompileStatus, type EaInputManifest, type EaInputParam, type EaInputType, type EaPreset, type EaSourceType, type EaTimeframe, type EaVersion, type EaVersionSource, type EaVersionStatus, EasResource, type ExpirationType, type FillingMode, type Fresh, type FreshnessOption, type GetCandlesQuery, type HoldingsListResult, type IncludeRawParams, type Instance, type InstanceState, type InstanceType, InstancesResource, type InstrumentListParams, type InstrumentListResult, InstrumentsV2, type ListBacktestsQuery, type ListBacktestsResult, type ListDeploymentsQuery, type ListDeploymentsResult, type ListEaVersionsQuery, type ListEaVersionsResult, type ListInstancesQuery, type LiveComparison, type LiveComparisonMatch, type LiveComparisonSummary, type MT5Candle, type MT5Heartbeat, type MT5LivePosition, type MT5PositionUpdate, type MT5Tick, type MT5TradeEvent, type MarginOrderType, type MarginResult, type MarketCandleMessage, type MarketCandlesParams, type MarketCandlesResult, type MarketChainMessage, type MarketFeedState, type MarketQuotesResult, type MarketScannerMessage, type MarketTickMessage, MarketV2, type ModifyMt5PositionResult, type ModifyOrderResult, type ModifyOrderV2Body, type ModifyPositionBody, type ModifyPositionResult, type ModifyPositionV2Body, type Money, type MonitorStatus, type MonitorVerdict, Mt5Resource, type Mt5SymbolSpec, type NoiseTestConfig, type OpenPositionDetail, type OptimizationAlgorithm, type OptimizationConfig, type OptimizationConfigInput, type OptimizationCriterion, type OptimizationPass, type OptimizationRange, type Order, type OrderDirection, type OrderType, type OrdersListParams, type OrdersListResult, type PlaceOrderBody, type PlaceOrderResult, type PlaceOrderV2Body, type PortfolioBody, type PortfolioReport, type Position, type PositionDetail, type PositionsListParams, type PositionsListResult, type PresignEaVersionBody, type PresignEaVersionResult, type Price, type RefusedInstrumentKeyReason, type RegisterEaVersionBody, type RegisteredEaVersion, type ResolveInstrumentParams, type RetiredWSChannel, type RevealOosResult, type RunLiveComparisonBody, type SaveEaSourceBody, type ScannerBoard, type ScannerBoardParams, type ScannerRow, type ScannerSession, type ScannerSessionState, ScannerV2, type ScannerZones, type ServiceKey, type ServiceKeyWithRaw, ServiceKeysResource, type SetMonitorBody, type SpreadCalibration, type SubscribeCandleBody, type SubscribeFailedMessage, type SubscribeTickBody, type SubscribedMessage, SubscriptionsResource, type SwapArbRow, type SwapArbitrageReport, type SymbolSpecsResult, type TickSubscriptions, type Timeframe, type TradesListResult, type TradingOrderMessage, TradingResource, type UnifiedCandle, type UnifiedError, type UnifiedErrorCode, type UnifiedFunds, type UnifiedHolding, type UnifiedInstrument, type UnifiedInterval, type UnifiedOptionChain, type UnifiedOptionExpiries, type UnifiedOptionLeg, type UnifiedOrder, type UnifiedPosition, type UnifiedProfile, type UnifiedSymbolSpec, type UnifiedTick, type UnifiedTrade, type UnsubscribeCandleBody, type UnsubscribeTickBody, type UnsubscribedMessage, type UpdateAtlasInstanceBody, type UpdateDeploymentBody, type UpdateEaBody, type UpdateServiceKeyBody, type V2Snapshot, type V2WriteOptions, type ValidateBrokerCredentialsBody, type ValidateBrokerCredentialsResult, type WSChannel, type WSEventMap, type WSSubscribeOptions, type WSUnsubscribeOptions, type WalkForwardConfig, type WalkForwardReport, type WriteOptions };