atlaas 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # atlaas
2
2
 
3
- TypeScript SDK for the Atlaas SaaS API — MT5 instance management, trading, live tick/candle streams, and broker integrations.
3
+ TypeScript SDK for the Atlaas API: MT5 terminals and trading, Expert Advisors and backtests, broker connections, unified instruments and market data, and the live WebSocket stream.
4
+
5
+ Every method here maps to one REST route. The API reference has the full detail of each: [v1](https://atlaas.dev/docs/v1/authentication) for `/api/external` and `/api/atlas`, and [v2](https://atlaas.dev/docs/v2/authentication-scopes) for `/api/v2`. Which key tier can call what is in [Service-key scopes](https://atlaas.dev/docs/v1/service-key-scopes). AI agents can use the same API as tools through the [MCP server](https://atlaas.dev/docs/v1/mcp-server).
4
6
 
5
7
  ## Install
6
8
 
@@ -10,14 +12,12 @@ npm install atlaas
10
12
  bun add atlaas
11
13
  ```
12
14
 
13
- For Node.js WebSocket support, also install `ws`:
15
+ Node.js also needs `ws` for the WebSocket stream (browsers, Bun and Deno use their own):
14
16
 
15
17
  ```bash
16
18
  npm install ws
17
19
  ```
18
20
 
19
- Browser environments use the native WebSocket — no extra dependency needed.
20
-
21
21
  ## Quickstart
22
22
 
23
23
  ```typescript
@@ -25,551 +25,806 @@ import { AtlasClient } from "atlaas"
25
25
 
26
26
  const atlas = new AtlasClient({
27
27
  baseUrl: "https://api.atlaas.dev",
28
- apiKey: "atsk_your_key_here",
28
+ apiKey: process.env.ATLAAS_API_KEY ?? ""
29
29
  })
30
30
 
31
- // List instances
32
- const instances = await atlas.instances.list({ instanceKind: "mt5" })
31
+ // Your MT5 terminals
32
+ const terminals = await atlas.mt5.list()
33
33
 
34
- // Place an order
35
- const order = await atlas.trading.placeOrder("12345", {
36
- symbol: "EURUSD",
37
- type: "BUY",
38
- volume: 0.01,
39
- })
34
+ // Buy 0.01 lots of EURUSD on the first one, by its MT5 login
35
+ const login = terminals[0].accountId
36
+ const order = await atlas.trading.placeOrder(login, { symbol: "EURUSD", type: "BUY", volume: 0.01 })
40
37
 
41
- // Get positions
42
- const positions = await atlas.trading.getPositions("12345")
38
+ // Its open positions
39
+ const positions = await atlas.trading.getPositions(login)
40
+ console.log(order.ticket, positions.length)
43
41
  ```
44
42
 
45
- ## REST API Resources
43
+ The rest of this page assumes an `atlas` client built as above.
44
+
45
+ ## Client options
46
+
47
+ | Option | Default | Description |
48
+ | --- | --- | --- |
49
+ | `baseUrl` | — | Atlaas API base URL |
50
+ | `apiKey` | — | Service key (`atsk_*`) |
51
+ | `timeoutMs` | `30000` | Per-attempt timeout |
52
+ | `maxRetries` | `2` | Retries of a request that is safe to send again (see [Retries](#retries-and-idempotency)) |
53
+ | `logger` | — | Optional `{ debug, info, warn, error }` |
54
+
55
+ ## Errors
46
56
 
47
- ### Instances (`atlas.instances`)
57
+ A failed request throws an `AtlasError` (or a subclass). Besides `message` and `statusCode`, it carries what the server said about the failure:
48
58
 
49
- Manages Atlaas-domain instances via `/api/atlas/instances`.
59
+ | Field | Meaning |
60
+ | --- | --- |
61
+ | `code` | The machine code. On `/api/v2` one of `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`. On `/api/external` some failures carry one too: `TERMINAL_UNAVAILABLE` (503: Atlaas cannot see the terminal right now, so a read is refused rather than answered empty), `COMMAND_UNSUPPORTED` (501: the terminal's connector EA does not implement that read), the idempotency codes, and `FEATURE_UNAVAILABLE` / `FEATURE_PAUSED` |
62
+ | `retryable` | The server's own verdict on retrying (v2) |
63
+ | `brokerCode` | The broker's own error code, when it gave one (v2) |
64
+ | `replayed` | The answer came from the Idempotency-Key store: it is the stored result of an earlier request with the same key |
65
+ | `body` | The parsed error body, for fields such as `requiredScope` on a 403 or `diagnostics` on a failed compile |
50
66
 
51
67
  ```typescript
52
- await atlas.instances.list({ instanceKind: "mt5", state: "RUNNING" })
53
- await atlas.instances.get("instance-id")
54
- await atlas.instances.getByExternalRef("my-ref")
55
- await atlas.instances.getByExternalRefs(["ref1", "ref2"])
56
- await atlas.instances.create({ instanceKind: "mt5", runnerId: "...", credentials: { ... } })
57
- await atlas.instances.update("instance-id", { enabled: true })
58
- await atlas.instances.disable("instance-id") // winddown: runner kills the terminal + deletes the instance folder
59
- await atlas.instances.enable("instance-id") // re-enable: runner redeploys fresh
60
- await atlas.instances.delete("instance-id")
68
+ import { AtlasAuthError, AtlasError, AtlasNetworkError, AtlasRateLimitError, AtlasValidationError } from "atlaas"
69
+
70
+ try {
71
+ await atlas.v2.connections("my-conn-001").place({ instrumentKey: "NSE:EQ:RELIANCE", side: "BUY", orderType: "MARKET", quantity: 1 })
72
+ } catch (err) {
73
+ if (err instanceof AtlasAuthError) {
74
+ // 401: the key is invalid, disabled or expired
75
+ } else if (err instanceof AtlasRateLimitError) {
76
+ console.log(`retry after ${err.retryAfter}s`)
77
+ } else if (err instanceof AtlasValidationError) {
78
+ console.log(err.code, err.message) // 400
79
+ } else if (err instanceof AtlasNetworkError) {
80
+ // no answer: timeout, DNS, connection reset
81
+ } else if (err instanceof AtlasError && err.code === "OUTCOME_UNKNOWN") {
82
+ // 504: the order reached the broker but no answer came back. Read the order book before sending it again.
83
+ } else if (err instanceof AtlasError) {
84
+ console.log(err.statusCode, err.code, err.retryable, err.message)
85
+ }
86
+ }
87
+ ```
88
+
89
+ Status codes and every code are listed in the API reference: [v1 errors](https://atlaas.dev/docs/v1/errors-status-codes) and [v2 errors](https://atlaas.dev/docs/v2/errors).
90
+
91
+ ## Retries and idempotency
92
+
93
+ The SDK retries a failed request (up to `maxRetries`, with backoff, honouring `Retry-After` up to 10 s) only when sending it again cannot act twice:
94
+
95
+ - **Reads** are retried on a network failure, a 408, a 429 or a 5xx other than 501, unless the server says `retryable: false`.
96
+ - **Order writes** are de-duplicated by the server: each call sends one `Idempotency-Key`, every retry reuses it, and the server answers a repeat with the first attempt's stored result. They are retried like reads. These are `trading.placeOrder`, `cancelOrder`, `modifyPosition`, `closePosition` and `closeBySymbol`, the `broker()` order writes, and the `v2.connections()` writes.
97
+ - **Every other write** (creating a terminal, a backtest, an EA version…) is not de-duplicated by the server, so it is sent once. Only the key's own rate limit (a 429 refused before anything ran) is retried.
98
+ - **Never retried:** `OUTCOME_UNKNOWN`, any answer the server replayed from its key store, and any error the server marks `retryable: false`.
99
+
100
+ To retry an order write yourself, across calls or processes, pass your own key. The server keeps it for 24 hours, answers every request with it with the first one's result, and refuses it (`IDEMPOTENCY_KEY_REUSED`) for a different request:
101
+
102
+ ```typescript
103
+ const conn = atlas.v2.connections("my-conn-001")
104
+ const key = "signal-2026-11-12-0915-reliance"
105
+ const placed = await conn.place({ instrumentKey: "NSE:EQ:RELIANCE", side: "BUY", orderType: "MARKET", quantity: 1 }, { idempotencyKey: key })
106
+ await atlas.trading.placeOrder("51234567", { symbol: "EURUSD", type: "BUY", volume: 0.01 }, { idempotencyKey: `${key}-fx` })
107
+ console.log(placed.orderId)
61
108
  ```
62
109
 
63
- ### Trading (`atlas.trading`)
110
+ See [Idempotent order writes](https://atlaas.dev/docs/v1/idempotent-order-writes) (v1) and [Idempotent writes](https://atlaas.dev/docs/v2/idempotent-writes) (v2).
111
+
112
+ ## MT5 terminals (`atlas.mt5`)
113
+
114
+ Deploy, start, stop and remove MT5 terminals, named by MT5 login. Deploying charges the provisioning fee. [API reference](https://atlaas.dev/docs/v1/mt5-instance-lifecycle)
115
+
116
+ ```typescript
117
+ const servers = await atlas.mt5.servers() // [{ serverName, brokerName, displayName, serverType, defaultSymbol }]
118
+ const regions = await atlas.mt5.regions() // [{ id, code, displayName, description }], only regions with room
119
+
120
+ const terminal = await atlas.mt5.create({
121
+ accountId: "51234567",
122
+ password: process.env.MT5_PASSWORD ?? "",
123
+ serverName: servers[0].serverName,
124
+ regionId: regions[0]?.id, // optional
125
+ type: "TICKS_TRADE",
126
+ name: "Gold scalper",
127
+ externalRef: "user-42-gold" // optional, your own id
128
+ })
129
+
130
+ await atlas.mt5.list() // Instance[], newest first
131
+ await atlas.mt5.get(terminal.accountId) // state: PENDING → DEPLOYING → RUNNING
132
+ await atlas.mt5.stop(terminal.accountId)
133
+ await atlas.mt5.start(terminal.accountId)
134
+ await atlas.mt5.delete(terminal.accountId) // no refund
135
+ ```
136
+
137
+ | Method | Returns |
138
+ | --- | --- |
139
+ | `list()` | `Instance[]` |
140
+ | `create(body: CreateInstanceBody)` | `Instance` |
141
+ | `get(accountId: string)` | `Instance` |
142
+ | `delete(accountId: string)` | `void` |
143
+ | `start(accountId: string)` | `Instance` |
144
+ | `stop(accountId: string)` | `Instance` |
145
+ | `servers()` | `DeployServer[]` |
146
+ | `regions()` | `DeployRegion[]` |
147
+
148
+ ## MT5 trading (`atlas.trading`)
64
149
 
65
- MT5 trading operations via `/api/external/instances/:accountId`.
150
+ Trading on one terminal, named by its MT5 login (`/api/external/instances/:accountId`). [Account](https://atlaas.dev/docs/v1/mt5-account), [positions](https://atlaas.dev/docs/v1/mt5-positions), [orders](https://atlaas.dev/docs/v1/mt5-orders), [market data](https://atlaas.dev/docs/v1/mt5-market-data).
66
151
 
67
152
  ```typescript
153
+ const login = "51234567"
154
+
68
155
  // Orders
69
- await atlas.trading.placeOrder(accountId, { symbol: "EURUSD", type: "BUY", volume: 0.1 })
70
- await atlas.trading.getOrders(accountId)
71
- await atlas.trading.cancelOrder(accountId, ticket)
156
+ const order = await atlas.trading.placeOrder(login, { symbol: "EURUSD", type: "BUY_LIMIT", volume: 0.1, price: 1.08, sl: 1.07, tp: 1.1 })
157
+ await atlas.trading.getOrders(login)
158
+ await atlas.trading.cancelOrder(login, order.ticket)
72
159
 
73
160
  // Positions
74
- await atlas.trading.getPositions(accountId)
75
- await atlas.trading.getPosition(accountId, ticket)
76
- await atlas.trading.modifyPosition(accountId, ticket, { sl: 1.07, tp: 1.12 })
77
- await atlas.trading.closePosition(accountId, ticket)
78
- await atlas.trading.closePosition(accountId, ticket, { volume: 0.05 }) // partial
79
- await atlas.trading.closeBySymbol(accountId, { symbol: "EURUSD" })
80
-
81
- // Market data
82
- await atlas.trading.getPrice(accountId, "EURUSD")
83
- await atlas.trading.getSymbols(accountId)
84
- await atlas.trading.getAccountInfo(accountId)
85
-
86
- // Historical candles
87
- await atlas.trading.getCandles(accountId, {
88
- symbol: "EURUSD",
89
- timeframe: "H1",
90
- startTime: "2026-01-01T00:00:00Z",
91
- endTime: "2026-01-02T00:00:00Z",
92
- })
161
+ const open = await atlas.trading.getPositions(login) // what the EA last pushed
162
+ const one = await atlas.trading.getPosition(login, open[0].ticket) // open, or closed from history
163
+ if (one.status === "CLOSED") console.log(one.closePrice, one.closeTime)
164
+ await atlas.trading.modifyPosition(login, open[0].ticket, { sl: 1.07, tp: 1.12 })
165
+ await atlas.trading.closePosition(login, open[0].ticket, { volume: 0.05 }) // partial; omit the body to close it all
166
+ await atlas.trading.closeBySymbol(login, { symbol: "EURUSD" }) // { symbol, closedCount, totalProfit, positions }
167
+
168
+ // Closed positions from the terminal's deal history, paged by close time
169
+ let since = 0
170
+ for (;;) {
171
+ const page = await atlas.trading.getClosedPositions(login, { since, limit: 200 })
172
+ for (const p of page.positions) console.log(p.ticket, p.profit)
173
+ if (!page.hasMore || page.positions.length === 0) break
174
+ since = page.positions[page.positions.length - 1].closeTimeMs
175
+ }
93
176
 
94
- // Margin calculation
95
- await atlas.trading.calculateMargin(accountId, {
96
- symbol: "EURUSD",
97
- type: "ORDER_TYPE_BUY",
98
- volume: 0.1,
99
- openPrice: 1.08,
100
- })
177
+ // Market data and account
178
+ await atlas.trading.getPrice(login, "EURUSD") // { symbol, bid, ask, last?, volume?, timestamp? }
179
+ await atlas.trading.getSymbols(login)
180
+ await atlas.trading.getSymbolSpecs(login) // every symbol's contract spec, raw from the terminal
181
+ await atlas.trading.getAccountInfo(login)
182
+ await atlas.trading.getCandles(login, { symbol: "EURUSD", timeframe: "H1", startTime: "2026-01-01T00:00:00Z", endTime: "2026-01-02T00:00:00Z" })
183
+ await atlas.trading.calculateMargin(login, { symbol: "EURUSD", type: "ORDER_TYPE_BUY", volume: 0.1, openPrice: 1.08 })
184
+ ```
185
+
186
+ Reads that come from the terminal can tell you how fresh they are. Pass `{ withFreshness: true }` to `getOrders`, `getPositions`, `getPosition`, `getPrice`, `getSymbols`, `getSymbolSpecs` or `getAccountInfo`:
187
+
188
+ ```typescript
189
+ const { data, dataAsOf, lastHeartbeatAt } = await atlas.trading.getPositions("51234567", { withFreshness: true })
190
+ const ageMs = Date.now() - Date.parse(dataAsOf)
191
+ if (ageMs > 10_000) console.warn(`positions are ${ageMs} ms old; last EA heartbeat ${lastHeartbeatAt}`)
192
+ console.log(data.length)
101
193
  ```
102
194
 
103
- ### Subscriptions (`atlas.subscriptions`)
195
+ A terminal Atlaas cannot see answers 503 `TERMINAL_UNAVAILABLE`, never an empty list.
196
+
197
+ | Method | Returns |
198
+ | --- | --- |
199
+ | `placeOrder(accountId, body: PlaceOrderBody, options?: WriteOptions)` | `Order` |
200
+ | `getOrders(accountId, options?: FreshnessOption)` | `Order[]` |
201
+ | `cancelOrder(accountId, ticket: number, options?: WriteOptions)` | `void` |
202
+ | `getPositions(accountId, options?: FreshnessOption)` | `Position[]` |
203
+ | `getPosition(accountId, ticket: number, options?: FreshnessOption)` | `PositionDetail` |
204
+ | `getClosedPositions(accountId, query: ClosedPositionsQuery)` | `ClosedPositionsResult` |
205
+ | `modifyPosition(accountId, ticket: number, body: ModifyPositionBody, options?: WriteOptions)` | `ModifyMt5PositionResult` |
206
+ | `closePosition(accountId, ticket: number, body?: ClosePositionBody, options?: WriteOptions)` | `CloseMt5PositionResult` |
207
+ | `closeBySymbol(accountId, body: CloseBySymbolBody, options?: WriteOptions)` | `CloseBySymbolResult` |
208
+ | `getPrice(accountId, symbol: string, options?: FreshnessOption)` | `Price` |
209
+ | `getSymbols(accountId, options?: FreshnessOption)` | `string[]` |
210
+ | `getSymbolSpecs(accountId, options?: FreshnessOption)` | `Mt5SymbolSpec[]` |
211
+ | `getAccountInfo(accountId, options?: FreshnessOption)` | `AccountInfo` |
212
+ | `getCandles(accountId, query: GetCandlesQuery)` | `Candle[]` |
213
+ | `calculateMargin(accountId, body: CalculateMarginBody)` | `MarginResult` |
214
+
215
+ With `{ withFreshness: true }` each read returns `Fresh<T>` (`{ data, dataAsOf, lastHeartbeatAt }`) instead.
104
216
 
105
- Tick and candle data subscriptions via `/api/instances/:accountId`.
217
+ ## MT5 tick and candle subscriptions (`atlas.subscriptions`)
218
+
219
+ Which symbols a terminal streams to the WebSocket, by Atlaas instance id. [API reference](https://atlaas.dev/docs/v1/mt5-real-time-subscriptions-websocket)
106
220
 
107
221
  ```typescript
222
+ const instanceId = "6f1c2a9e-0000-4000-8000-000000000000"
223
+
108
224
  await atlas.subscriptions.subscribeTick(instanceId, { symbol: "EURUSD" })
109
- await atlas.subscriptions.unsubscribeTick(instanceId, { symbol: "EURUSD" })
110
- await atlas.subscriptions.getTickSubscriptions(instanceId)
225
+ await atlas.subscriptions.getTickSubscriptions(instanceId) // { instanceId, accountId, symbols, count }
226
+ await atlas.subscriptions.unsubscribeTick(instanceId, { symbol: "EURUSD" }) // omit the body for every symbol
111
227
 
112
228
  await atlas.subscriptions.subscribeCandle(instanceId, { symbol: "EURUSD", timeframe: "M1" })
113
- await atlas.subscriptions.unsubscribeCandle(instanceId)
114
- await atlas.subscriptions.getCandleSubscriptions(instanceId)
229
+ await atlas.subscriptions.getCandleSubscriptions(instanceId) // { instanceId, accountId, subscriptions, count }
230
+ await atlas.subscriptions.unsubscribeCandle(instanceId, { symbol: "EURUSD", timeframe: "M1" })
231
+ ```
232
+
233
+ ## Instances and broker connections (`atlas.instances`)
234
+
235
+ Every instance on the account, MT5 or broker, keyed by your own `externalRef` (`/api/atlas/instances`). [API reference](https://atlaas.dev/docs/v1/instances-by-id-apiatlas), [identifiers](https://atlaas.dev/docs/v1/identifiers-read-this-first)
236
+
237
+ ```typescript
238
+ // Validate broker credentials before storing them (Dhan logs in and returns the minted token)
239
+ const check = await atlas.instances.validateBrokerCredentials({
240
+ brokerName: "dhan",
241
+ credentials: { clientId: "1100000000", pin: "1234", totpSecret: process.env.DHAN_TOTP ?? "" }
242
+ })
243
+ if (!check.valid) throw new Error(check.error)
244
+
245
+ // Create a broker connection. Brokers need no runnerId: Atlaas places it on a server of its own.
246
+ const created = await atlas.instances.create({
247
+ instanceKind: "dhan",
248
+ externalRef: "my-conn-001",
249
+ credentials: check.credentials
250
+ })
251
+ console.log(created.runnerReady, created.ipAddress) // whitelist ipAddress with the broker
252
+
253
+ const instance = await atlas.instances.get(created.id)
254
+ await atlas.instances.getByExternalRef("my-conn-001")
255
+ await atlas.instances.getByExternalRefs(["my-conn-001", "my-conn-002"])
256
+ await atlas.instances.list({ instanceKind: "dhan", state: "RUNNING", limit: 100 })
257
+ await atlas.instances.update(instance.id, { name: "Dhan main", credentialsPatch: { pin: "4321" } }) // { id }
258
+ await atlas.instances.disable(instance.id) // stops it on its runner; credentials stay stored
259
+ await atlas.instances.enable(instance.id) // redeploys it
260
+ await atlas.instances.delete(instance.id)
115
261
  ```
116
262
 
117
- ### Service Keys (`atlas.serviceKeys`)
263
+ `create` with an `externalRef` you already used updates that instance instead. An MT5 instance here needs a `runnerId`; `atlas.mt5.create` picks one for you.
264
+
265
+ | Method | Returns |
266
+ | --- | --- |
267
+ | `list(query?: ListInstancesQuery)` | `AtlasInstance[]` |
268
+ | `get(id: string)` | `AtlasInstance` |
269
+ | `getByExternalRef(ref: string)` | `AtlasInstance` |
270
+ | `getByExternalRefs(refs: string[])` | `AtlasInstance[]` |
271
+ | `create(body: CreateAtlasInstanceBody)` | `CreateAtlasInstanceResult` |
272
+ | `update(id: string, body: UpdateAtlasInstanceBody)` | `{ id: string }` |
273
+ | `disable(id: string)` | `AtlasInstance \| null` |
274
+ | `enable(id: string)` | `AtlasInstance \| null` |
275
+ | `delete(id: string)` | `void` |
276
+ | `validateBrokerCredentials(body: ValidateBrokerCredentialsBody)` | `ValidateBrokerCredentialsResult` |
118
277
 
119
- Manage API keys via `/api/public/`.
278
+ ## Service keys (`atlas.serviceKeys`)
279
+
280
+ [API reference](https://atlaas.dev/docs/v1/service-keys), [scopes](https://atlaas.dev/docs/v1/service-key-scopes)
120
281
 
121
282
  ```typescript
122
- await atlas.serviceKeys.list(accountId)
123
- await atlas.serviceKeys.create(accountId, { keyName: "prod-key" })
124
- await atlas.serviceKeys.update(keyId, { isActive: false })
125
- await atlas.serviceKeys.regenerate(keyId)
126
- await atlas.serviceKeys.delete(keyId)
283
+ const accountId = "acc_123"
284
+
285
+ await atlas.serviceKeys.list(accountId, { isActive: true })
286
+ const key = await atlas.serviceKeys.create(accountId, { keyName: "prod-bot", rateLimitPerMinute: 600, allowedIpAddresses: ["203.0.113.7"] })
287
+ console.log(key.rawKey) // shown once
288
+ await atlas.serviceKeys.update(key.id, { isActive: false })
289
+ await atlas.serviceKeys.regenerate(key.id) // a new rawKey
290
+ await atlas.serviceKeys.delete(key.id)
127
291
  ```
128
292
 
129
- ### Expert Advisors (`atlas.eas`)
293
+ ## Expert Advisors (`atlas.eas`)
130
294
 
131
- Manage user strategy EAs, their versions, and chart deployments via
132
- `/api/external/eas` and `/api/external/deployments`. Everything is scoped to the
133
- key's account.
295
+ Your EAs, their versions and presets, and their deployments on terminals. [API reference](https://atlaas.dev/docs/v1/eas-deployments-api), [writing an EA for Atlaas](https://atlaas.dev/docs/v1/expert-advisors)
134
296
 
135
297
  ```typescript
298
+ import { createHash } from "node:crypto"
299
+ import { readFile } from "node:fs/promises"
300
+ import { AtlasError, type EaCompileFailure } from "atlaas"
301
+
136
302
  // Registry
303
+ const ea = await atlas.eas.create({ name: "Breakout", description: "London open breakout" })
137
304
  await atlas.eas.list()
138
- await atlas.eas.create({ name: "Breakout", description: "..." })
139
- await atlas.eas.get(eaId) // detail incl. versions[]; each version has an inputManifest
140
- await atlas.eas.update(eaId, { name: "Breakout v2" })
141
- await atlas.eas.remove(eaId)
142
-
143
- // Versions — upload a compiled .ex5 (deployable now) or .mq5 source (compiled for you)
144
- const { url, r2Key } = await atlas.eas.presignVersion(eaId, { version: "1.0.0", sourceType: "MQ5", sizeBytes })
145
- // PUT the file to `url`, then register it:
146
- await atlas.eas.registerVersion(eaId, { r2Key, version: "1.0.0", sourceType: "MQ5", sizeBytes })
147
- await atlas.eas.listVersions(eaId)
148
- await atlas.eas.promoteVersion(eaId, versionId)
149
- await atlas.eas.deleteVersion(eaId, versionId)
150
-
151
- // Deployments — bind a version to a chart on an instance; setBlob is the EA's .set inputs
152
- await atlas.eas.deploy({ versionId, instanceId, symbol: "EURUSD", timeframe: "H1", setBlob })
153
- await atlas.eas.listDeployments({ instanceId })
154
- await atlas.eas.getDeployment(deploymentId)
155
- await atlas.eas.updateDeployment(deploymentId, { setBlob }) // tune inputs / symbol / timeframe / enabled
156
- await atlas.eas.removeDeployment(deploymentId)
305
+ await atlas.eas.update(ea.id, { name: "Breakout v2" })
306
+ const detail = await atlas.eas.get(ea.id) // with versions[], each with its parsed inputManifest
307
+
308
+ // A version from .mq5 source: compile-checked first (the call waits up to 2 minutes), then compiled in the background
309
+ try {
310
+ const saved = await atlas.eas.saveSource(ea.id, { version: "1.0.0", mq5Source: await readFile("Breakout.mq5", "utf8") })
311
+ console.log(saved.compileStatus) // PENDING
312
+ } catch (err) {
313
+ if (err instanceof AtlasError && err.statusCode === 422) {
314
+ for (const d of (err.body as EaCompileFailure).diagnostics) console.log(d.line, d.message)
315
+ }
316
+ }
317
+
318
+ // A version from a compiled .ex5: upload it with its SHA-256, then register it
319
+ const ex5 = await readFile("Breakout.ex5")
320
+ const sha256 = createHash("sha256").update(ex5).digest("hex")
321
+ const upload = await atlas.eas.presignVersion(ea.id, { version: "1.0.1", sourceType: "EX5", sha256, sizeBytes: ex5.byteLength })
322
+ const put = await fetch(upload.url, {
323
+ method: "PUT",
324
+ body: ex5,
325
+ // Signed with the URL: these two headers, and a Content-Length of sizeBytes (fetch sets it from the buffer).
326
+ headers: { "Content-Type": "application/octet-stream", "x-amz-checksum-sha256": Buffer.from(sha256, "hex").toString("base64") }
327
+ })
328
+ if (!put.ok) throw new Error(`upload failed: ${put.status}`)
329
+ const registered = await atlas.eas.registerVersion(ea.id, { r2Key: upload.r2Key, version: "1.0.1", sourceType: "EX5", sha256, sizeBytes: ex5.byteLength })
330
+
331
+ await atlas.eas.listVersions(ea.id, { limit: 20, offset: 0 })
332
+ await atlas.eas.getVersionSource(ea.id, detail.versions[0].id) // { version, sourceType: "MQ5", source }
333
+ await atlas.eas.promoteVersion(ea.id, registered.id) // make it LIVE
334
+ await atlas.eas.deleteVersion(ea.id, registered.id)
335
+
336
+ // Presets: named .set inputs
337
+ const preset = await atlas.eas.createPreset(ea.id, { name: "Conservative", setBlob: "RiskPercent=0.5\nMaxTrades=2" })
338
+ await atlas.eas.listPresets(ea.id)
339
+ await atlas.eas.deletePreset(ea.id, preset.id)
340
+
341
+ // Deployments: a version on a chart of a terminal (instanceId is the Atlaas instance id)
342
+ const deployment = await atlas.eas.deploy({ versionId: registered.id, instanceId: "6f1c2a9e-0000-4000-8000-000000000000", symbol: "EURUSD", timeframe: "H1", setBlob: preset.setBlob })
343
+ await atlas.eas.listDeployments({ instanceId: deployment.instanceId })
344
+ await atlas.eas.getDeployment(deployment.id)
345
+ await atlas.eas.updateDeployment(deployment.id, { enabled: false })
346
+
347
+ // Live against backtest: a backtest of the same window, matched trade by trade
348
+ await atlas.eas.runLiveComparison(deployment.id, { from: "2026-10-01", to: "2026-10-31" }) // { runId, groupId }; billed as a backtest
349
+ const comparison = await atlas.eas.getLiveComparison(deployment.id) // once that backtest is done
350
+ console.log(comparison.summary.matchedPct, comparison.summary.realisedPct)
351
+
352
+ // Monitor: a scheduled re-backtest checked against the live trades
353
+ await atlas.eas.setMonitor(deployment.id, { enabled: true, windowDays: 30 })
354
+ const monitor = await atlas.eas.getMonitor(deployment.id) // verdict: OK | DECAY | SLIPPAGE | NO_LIVE_TRADES | FAILED
355
+ console.log(monitor.verdict)
356
+
357
+ await atlas.eas.removeDeployment(deployment.id)
358
+ await atlas.eas.remove(ea.id)
157
359
  ```
158
360
 
159
- > A version built from `.mq5` source carries a typed `inputManifest` (its parsed
160
- > input parameters) so you can build a settings UI or generate a `.set`. A
161
- > compiled `.ex5` has no readable inputs — supply a `.set` (`setBlob`) yourself.
361
+ A version saved from `.mq5` source carries an `inputManifest` (its parsed inputs) and the `magicInput` Atlaas writes each deployment's `magicNumber` into. A compiled `.ex5` has no readable inputs: give its deployments a `.set` yourself.
362
+
363
+ | Method | Returns |
364
+ | --- | --- |
365
+ | `list()` | `{ items: Ea[] }` |
366
+ | `create(body: CreateEaBody)` | `Ea` |
367
+ | `get(id: string)` | `Ea & { versions: EaVersion[] }` |
368
+ | `update(id: string, body: UpdateEaBody)` | `Ea` |
369
+ | `remove(id: string)` | `{ id: string }` |
370
+ | `listVersions(eaId, query?: ListEaVersionsQuery)` | `ListEaVersionsResult` |
371
+ | `presignVersion(eaId, body: PresignEaVersionBody)` | `PresignEaVersionResult` |
372
+ | `registerVersion(eaId, body: RegisterEaVersionBody)` | `RegisteredEaVersion` |
373
+ | `saveSource(eaId, body: SaveEaSourceBody, options?: { timeoutMs?, signal? })` | `RegisteredEaVersion` |
374
+ | `getVersionSource(eaId, versionId)` | `EaVersionSource` |
375
+ | `promoteVersion(eaId, versionId)` | `{ id, version, status }` |
376
+ | `deleteVersion(eaId, versionId)` | `{ id, version }` |
377
+ | `listPresets(eaId)` | `{ items: EaPreset[] }` |
378
+ | `createPreset(eaId, body: CreateEaPresetBody)` | `EaPreset` |
379
+ | `deletePreset(eaId, presetId)` | `{ id: string }` |
380
+ | `listDeployments(query?: ListDeploymentsQuery)` | `ListDeploymentsResult` |
381
+ | `deploy(body: CreateDeploymentBody)` | `Deployment` |
382
+ | `getDeployment(id)` | `Deployment` |
383
+ | `updateDeployment(id, body: UpdateDeploymentBody)` | `Deployment` |
384
+ | `removeDeployment(id)` | `{ id: string }` |
385
+ | `getLiveComparison(deploymentId)` | `LiveComparison` |
386
+ | `runLiveComparison(deploymentId, body: RunLiveComparisonBody)` | `{ runId, groupId }` |
387
+ | `getMonitor(deploymentId)` | `MonitorStatus` |
388
+ | `setMonitor(deploymentId, body: SetMonitorBody)` | `MonitorStatus` |
389
+
390
+ ## Backtests (`atlas.backtests`)
391
+
392
+ MT5 strategy tester runs on Atlaas hardware, against your terminal's broker history. A backtest is a group of runs: a single test, an optimization, or a walk-forward. Creating one holds credits; `estimate` says how many first. [API reference](https://atlaas.dev/docs/v1/backtests)
162
393
 
163
- ### Broker Trading (`atlas.broker()`)
394
+ ```typescript
395
+ const base = {
396
+ versionId: "ver_123",
397
+ instanceId: "6f1c2a9e-0000-4000-8000-000000000000",
398
+ symbol: "EURUSD",
399
+ timeframe: "H1" as const,
400
+ fromDate: "2025-01-01",
401
+ toDate: "2026-01-01"
402
+ }
164
403
 
165
- Broker-agnostic trading (Dhan, Kite, Motilal Oswal) via `/api/external/brokers/:name/connections/:id`. The broker name is just a string, so any supported broker works through the same surface.
404
+ const estimate = await atlas.backtests.estimate({ fromDate: base.fromDate, toDate: base.toDate, tickMode: "EVERY_TICK" })
405
+ console.log(estimate.credits, estimate.estimatedFinishAt)
406
+
407
+ // One run, with the last two months locked as out-of-sample until you reveal them
408
+ const { group, runs } = await atlas.backtests.create({ ...base, name: "Breakout 2025", tickMode: "EVERY_TICK", oos: { splitDate: "2025-11-01" } })
409
+
410
+ await atlas.backtests.list({ limit: 20 }) // { items, nextCursor }
411
+ await atlas.backtests.get(group.id) // the group with its runs and tester logs
412
+
413
+ const stats = await atlas.backtests.stats(runs[0].id) // 409 until the run is DONE
414
+ console.log(stats.stats.netProfit, stats.analytics?.returns.sharpe)
415
+ const { rows } = await atlas.backtests.trades(runs[0].id, { outcome: "loss", sort: "net", limit: 50 })
416
+ const byHour = await atlas.backtests.trades(runs[0].id, { aggregate: "byHour" })
417
+ console.log(rows[0]?.profit, byHour.rows[0]?.winRatePct)
418
+ const links = await atlas.backtests.result(runs[0].id) // presigned JSON and HTML report, 10 minutes
419
+ await atlas.backtests.peer(runs[0].id)
420
+ await atlas.backtests.summary(runs[0].id) // AI summary, cached
421
+ await atlas.backtests.explainTrade(runs[0].id, rows[0].positionId)
422
+ await atlas.backtests.rerunOnTickModel(runs[0].id, "REAL_TICKS")
423
+ await atlas.backtests.revealOos(group.id) // every reveal is counted
424
+ await atlas.backtests.setNote(group.id, "baseline before the ATR filter")
425
+ await atlas.backtests.setBaseline(group.id)
426
+ await atlas.backtests.clearBaseline(group.id)
427
+ console.log(links.resultUrl)
428
+
429
+ // Optimization, and walk-forward on top of it
430
+ const wf = await atlas.backtests.create({
431
+ ...base,
432
+ name: "Breakout WF",
433
+ optimization: { criterion: "SHARPE", ranges: [{ name: "Period", start: 10, step: 5, stop: 50 }] },
434
+ walkForward: { folds: 5, isRatio: 3 }
435
+ })
436
+ const report = await atlas.backtests.walkForward(wf.group.id)
437
+ console.log(report.wfe)
438
+ const optimizeRun = wf.group.runs[0].id
439
+ await atlas.backtests.passes(optimizeRun, { sort: "-sharpe", limit: 10 })
440
+
441
+ // Several runs at once
442
+ const batch = await atlas.backtests.createBatch({ ...base, name: "Majors", symbols: ["EURUSD", "GBPUSD"], timeframes: ["H1", "H4"] })
443
+ await atlas.backtests.getBatch(batch.batchId)
444
+ await atlas.backtests.createNoiseTest({ groupId: group.id, config: { variants: 8, perturbPct: 10 } })
445
+ await atlas.backtests.createWalkForwardMatrix({ ...base, name: "WF grid", optimization: { ranges: [{ name: "Period", start: 10, step: 5, stop: 50 }] }, isRatios: [2, 3], folds: [4, 6] })
446
+ await atlas.backtests.portfolio({ members: [{ runId: runs[0].id }, { runId: "run_456", weight: 0.5 }] })
447
+
448
+ // Research
449
+ await atlas.backtests.sourceDiff("ver_122", "ver_123")
450
+ await atlas.backtests.swapArbitrage()
451
+ await atlas.backtests.spreadCalibration(base.instanceId, "EURUSD")
452
+
453
+ await atlas.backtests.cancel(runs[0].id)
454
+ await atlas.backtests.delete(group.id)
455
+ ```
456
+
457
+ None of these writes is de-duplicated by the server, so the SDK sends each once. After a timeout, `list()` before you create again.
458
+
459
+ | Method | Returns |
460
+ | --- | --- |
461
+ | `list(query?: ListBacktestsQuery)` | `ListBacktestsResult` |
462
+ | `create(body: CreateBacktestBody)` | `CreateBacktestResult` |
463
+ | `estimate(query: BacktestEstimateQuery)` | `BacktestEstimate` |
464
+ | `get(groupId)` | `BacktestGroup` |
465
+ | `delete(groupId)` | `{ id: string }` |
466
+ | `setNote(groupId, note: string \| null)` | `BacktestGroup` |
467
+ | `setBaseline(groupId)` / `clearBaseline(groupId)` | `{ eaId, baselineGroupId }` |
468
+ | `revealOos(groupId)` | `RevealOosResult` |
469
+ | `walkForward(groupId)` | `WalkForwardReport` |
470
+ | `createBatch(body: CreateBacktestBatchBody)` | `CreateBacktestBatchResult` |
471
+ | `getBatch(batchId)` | `BacktestBatchReport` |
472
+ | `createNoiseTest(body: CreateNoiseTestBody)` | `CreateNoiseTestResult` |
473
+ | `createWalkForwardMatrix(body: CreateWalkForwardMatrixBody)` | `CreateWalkForwardMatrixResult` |
474
+ | `portfolio(body: PortfolioBody)` | `PortfolioReport` |
475
+ | `result(runId)` | `BacktestResultUrls` |
476
+ | `stats(runId)` | `BacktestRunStats` |
477
+ | `trades(runId, query?: BacktestTradesQuery)` | `BacktestTradesResult` (trades, or aggregate rows with `aggregate`) |
478
+ | `passes(runId, query?: BacktestPassesQuery)` | `BacktestPassesResult` |
479
+ | `peer(runId)` | `BacktestPeerContext` |
480
+ | `cancel(runId)` | `CancelBacktestRunResult` |
481
+ | `summary(runId, options?: { refresh?: boolean })` | `{ summary: BacktestAiSummary }` |
482
+ | `explainTrade(runId, positionId)` | `{ explanation: string }` |
483
+ | `rerunOnTickModel(runId, tickMode: BacktestTickMode)` | `CreateBacktestResult` |
484
+ | `sourceDiff(fromVersionId, toVersionId)` | `BacktestSourceDiff` |
485
+ | `swapArbitrage()` | `SwapArbitrageReport` |
486
+ | `spreadCalibration(instanceId, symbol)` | `SpreadCalibration` |
487
+
488
+ ## Broker connections, raw (`atlas.broker()`)
489
+
490
+ A broker's own API through Atlaas (`/api/external/brokers/:broker/connections/:id`), in the broker's own field names. `connectionId` is the connection's `externalRef`. Brokers: `dhan`, `kite`, `motilal`, `angelone`, `fyers`, `upstox`, `shoonya`, `bybit`, `deribit`, `kraken`, `hyperliquid`, `coindcx`, `delta`, `alpaca`, `tastytrade`, `lime`. Prefer the [unified API](#connections-atlasv2connections) unless you need a broker-specific field. [API reference](https://atlaas.dev/docs/v1/broker-connections-raw-routes)
166
491
 
167
492
  ```typescript
168
- const dhan = atlas.broker("dhan", connectionId)
493
+ const dhan = atlas.broker("dhan", "my-conn-001")
169
494
 
170
- await dhan.placeOrder({ order: { ... } })
495
+ const placed = await dhan.placeOrder({ securityId: "11536", exchangeSegment: "NSE_EQ", transactionType: "BUY", quantity: 1, orderType: "MARKET", productType: "INTRADAY" })
171
496
  await dhan.getOrders()
172
- await dhan.getOrder(orderId)
173
- await dhan.modifyOrder(orderId, { changes: { ... } })
174
- await dhan.cancelOrder(orderId)
497
+ await dhan.getOrder("1124091136546")
498
+ await dhan.modifyOrder("1124091136546", { orderType: "LIMIT", price: 2450, quantity: 1, validity: "DAY" })
499
+ await dhan.cancelOrder("1124091136546")
175
500
  await dhan.getTrades()
176
501
  await dhan.getPositions()
177
502
  await dhan.getHoldings()
178
- await dhan.getCandles({ securityId: "1333", exchangeSegment: "NSE_EQ", interval: "5", n: 100 })
503
+ await dhan.getCandles({ securityId: "1333", exchangeSegment: "NSE_EQ", interval: "5", n: 100 }) // Dhan and Kite only
504
+ console.log(placed)
505
+
506
+ // Option chain through your own Dhan connection (Dhan only)
507
+ const expiries = await dhan.getOptionExpiries({ underlyingSecurityId: "13", underlyingSegment: "IDX_I" })
508
+ const chain = await dhan.getOptionChain({ underlyingSymbol: "NIFTY" }, expiries[0])
509
+ console.log(chain.spot, chain.strikes.length)
179
510
 
180
- // Broker tick subscriptions
181
- await dhan.subscriptions.subscribe({ refs: [{ securityId: "1333", exchangeSegment: "NSE_EQ" }] })
511
+ // Tick subscriptions for the broker_ticks channel (Dhan and Kite only)
512
+ await dhan.subscriptions.subscribe({ refs: [{ securityId: "1333", exchangeSegment: "NSE_EQ" }], mode: "quote" })
182
513
  await dhan.subscriptions.list()
183
514
  await dhan.subscriptions.unsubscribe({ refs: [{ securityId: "1333", exchangeSegment: "NSE_EQ" }] })
184
515
  ```
185
516
 
186
- #### Motilal Oswal
187
-
188
- Motilal Oswal (`atlas.broker("motilal", connectionId)`) exposes the order +
189
- order-data surface — `placeOrder`, `modifyOrder`, `cancelOrder`, `getOrders`,
190
- `getOrder`, `getTrades`, `getPositions`, `getHoldings`. Order field names follow
191
- MOFSL (`exchange`, `symboltoken`, `buyorsell`, `ordertype`, `producttype`,
192
- `orderduration`, `price`, `triggerprice`, `quantityinlot` — note **lots, not
193
- shares**). It has **no market/tick data**, so `getCandles` and `subscriptions`
194
- are not supported. Atlaas re-logs in to Motilal automatically each morning.
517
+ Motilal Oswal takes MOFSL fields and sizes in **lots**, not shares. It has no market data, so `getCandles` and `subscriptions` do not apply; Atlaas logs it in again each morning.
195
518
 
196
519
  ```typescript
197
- const mo = atlas.broker("motilal", connectionId)
198
-
520
+ const mo = atlas.broker("motilal", "my-mofsl-001")
199
521
  await mo.placeOrder({
200
- order: {
201
- exchange: "NSE",
202
- symboltoken: 1660,
203
- buyorsell: "BUY",
204
- ordertype: "LIMIT",
205
- producttype: "NORMAL",
206
- orderduration: "DAY",
207
- price: 235.5,
208
- triggerprice: 0,
209
- quantityinlot: 1
210
- }
522
+ exchange: "NSE",
523
+ symboltoken: 1660,
524
+ buyorsell: "BUY",
525
+ ordertype: "LIMIT",
526
+ producttype: "NORMAL",
527
+ orderduration: "DAY",
528
+ price: 235.5,
529
+ triggerprice: 0,
530
+ quantityinlot: 1
211
531
  })
212
- await mo.getOrder(uniqueOrderId) // poll until orderstatus is terminal
213
- await mo.getTrades()
214
532
  ```
215
533
 
216
- See [`docs/integrations/motilal-oswal.md`](../../docs/integrations/motilal-oswal.md) for the full integration guide (provisioning, session init, enums, error handling).
534
+ | Method | Returns |
535
+ | --- | --- |
536
+ | `placeOrder(order: BrokerOrder, options?: WriteOptions)` | broker's reply |
537
+ | `getOrders()` / `getOrder(orderId)` | broker's reply |
538
+ | `modifyOrder(orderId, changes: BrokerOrder, options?: WriteOptions)` | broker's reply |
539
+ | `cancelOrder(orderId, body?: BrokerCancelOrderBody, options?: WriteOptions)` | broker's reply |
540
+ | `getTrades()` / `getPositions()` / `getHoldings()` | broker's reply |
541
+ | `getCandles(query: BrokerCandlesQuery)` | broker's reply |
542
+ | `getOptionExpiries(underlying: DhanUnderlying)` | `string[]` |
543
+ | `getOptionChain(underlying: DhanUnderlying, expiry: string)` | `DhanOptionChain` |
544
+ | `subscriptions.subscribe(body)` / `.unsubscribe(body)` / `.list()` | broker's reply |
217
545
 
218
- ### Instruments (`atlas.v2.instruments`)
546
+ ## Unified API (`atlas.v2`)
219
547
 
220
- Atlaas-owned canonical instrument identity via `/api/v2/instruments`. One
221
- `instrumentKey` per contract, with the per-broker reference ids attached — so
222
- you look an instrument up once and get Dhan's `securityId`, Motilal's
223
- `symboltoken`, the Kite tradingsymbol and the MT5 symbol together, instead of
224
- maintaining a mapping table per broker.
548
+ One shape for every broker: canonical instruments, account-scoped reads and writes on any connection, and market data that needs no connection.
549
+
550
+ ### Instruments (`atlas.v2.instruments`)
225
551
 
226
- Instruments are **global reference data**, identical for every account. Any
227
- valid service key may read any instrument; nothing here is account-scoped.
552
+ Atlaas's canonical `instrumentKey` for each contract, with each broker's reference id attached. Global reference data: any key can read any instrument. [API reference](https://atlaas.dev/docs/v2/instruments)
228
553
 
229
554
  ```typescript
230
- // Browse / search
231
555
  const { instruments, nextCursor } = await atlas.v2.instruments.list({
232
- exchange: "NSE", // NSE | BSE | MCX | FX
233
- segment: "FNO", // EQ | FNO | IDX | CDS | COMM | FX
234
- symbol: "NIFTY", // exact symbol match (upper-cased for you)
235
- q: "RELI", // substring match on instrumentKey (see below)
236
- active: true, // default true; false returns *inactive* rows only
237
- limit: 100, // default 100, max 500
238
- cursor: nextCursor ?? undefined
556
+ exchange: "NSE", // NSE | BSE | MCX | FX | US | CRYPTO
557
+ segment: "FNO", // EQ | FNO | IDX | CDS | COMM | FX | SPOT | PERP
558
+ symbol: "NIFTY", // exact symbol
559
+ q: "RELI", // substring of instrumentKey (not the name)
560
+ active: true, // default true; false lists inactive rows only
561
+ limit: 100 // default 100, max 500
239
562
  })
563
+ const next = nextCursor ? await atlas.v2.instruments.list({ exchange: "NSE", cursor: nextCursor }) : null
240
564
 
241
- // Fetch one by canonical key
242
- const rel = await atlas.v2.instruments.get("NSE:EQ:RELIANCE")
243
-
244
- // Reverse lookup: broker ref id -> canonical instrument
245
- const inst = await atlas.v2.instruments.resolve({
246
- broker: "dhan", // dhan | motilal | kite | mt5
247
- refId: "1333",
248
- segment: "NSE_EQ"
249
- })
250
-
251
- inst.brokerRefs.motilal?.symboltoken // the same contract at another broker
565
+ const reliance = await atlas.v2.instruments.get("NSE:EQ:RELIANCE")
566
+ const fromDhan = await atlas.v2.instruments.resolve({ broker: "dhan", refId: "2885", segment: "NSE_EQ" })
567
+ console.log(instruments.length, next?.instruments.length, reliance.brokerRefs.motilal?.symboltoken, fromDhan.instrumentKey)
252
568
  ```
253
569
 
254
- **`instrumentKey` format** — `EXCHANGE:SEGMENT:SYMBOL` for cash and indices,
255
- plus expiry/strike/right for derivatives:
570
+ Key format: `EXCHANGE:SEGMENT:SYMBOL`, with expiry, strike and right for derivatives:
256
571
 
257
572
  ```
258
- NSE:EQ:RELIANCE (equity)
259
- NSE:IDX:NIFTY (index)
260
- NSE:FNO:NIFTY:2026-08-27:FUT (future — note the :FUT suffix)
261
- NSE:FNO:NIFTY:2026-08-27:24000:CE (option)
262
- NSE:FNO:USDINR:2026-08-27:84.25:PE (fractional strikes keep their decimals)
263
- FX:XAUUSD (forex — no exchange segment)
573
+ NSE:EQ:RELIANCE equity
574
+ NSE:IDX:NIFTY index
575
+ NSE:FNO:NIFTY:2026-08-27:FUT future
576
+ NSE:FNO:NIFTY:2026-08-27:24000:CE option
577
+ NSE:FNO:USDINR:2026-08-27:84.25:PE fractional strike
578
+ FX:XAUUSD forex
264
579
  ```
265
580
 
266
- Expiries are always `YYYY-MM-DD`; symbols may not contain `:`.
267
-
268
- Notes:
269
-
270
- - **`q` matches the `instrumentKey` only**, as an upper-cased substring — not
271
- the company `name`. `q: "RELI"` finds `NSE:EQ:RELIANCE`; `q: "Reliance
272
- Industries"` finds nothing. Use `symbol` when you know the exact ticker.
273
- - **Paging is keyset on `instrumentKey`**, ascending. Pass the returned
274
- `nextCursor` straight back as `cursor`; a `null` cursor means the last page.
275
- - **Kite refs are derived, not synced.** Atlaas has no Kite master; the
276
- `brokerRefs.kite.tradingsymbol` is derived from the Dhan/MOFSL rows using
277
- Kite's naming convention, and `instrumentToken` is absent until the U4 Kite
278
- stream work lands. `resolve({ broker: "kite" })` is therefore not backed by a
279
- synced index.
280
- - **`FX:*` rows come from an MT5 terminal**, populated by the admin
281
- symbol-specs import rather than the daily master sync — expect none until
282
- that has been run for the account.
283
- - NSE/BSE rows refresh daily at 03:00 UTC (08:30 IST) from the Dhan detailed
284
- scrip master and the MOFSL NSEFO master. F&O coverage is the curated index
285
- universe (NIFTY, BANKNIFTY, FINNIFTY, MIDCPNIFTY, SENSEX, BANKEX) within 60
286
- days; equity coverage is all NSE/BSE ES/ETF series.
581
+ Expiries are `YYYY-MM-DD`; symbols never contain `:`. Paging is keyset on `instrumentKey`: pass `nextCursor` back as `cursor` until it is `null`. Kite refs are derived from the Dhan and Motilal rows, not synced from a Kite master. `FX:*` rows come from an MT5 terminal's symbol import.
287
582
 
288
- The response shape is exported as `UnifiedInstrument`.
583
+ ### Connections (`atlas.v2.connections()`)
289
584
 
290
- ### Connections (`atlas.v2.connections`)
291
-
292
- Every connection — Dhan, Zerodha/Kite, Motilal Oswal, MT5 — serves its orders, trades, positions,
293
- holdings, funds, and profile in **one canonical shape**. Unlike `v2.instruments`, this resource is
294
- **account-scoped**: a service key only sees connections it owns.
585
+ Orders, trades, positions, holdings, funds and profile of any connection (Dhan, Kite, Motilal, Angel One, Fyers, Upstox, Shoonya, the crypto and US brokers, MT5) in one shape, and one order shape to write with. Account-scoped: a key only sees its own connections. The id is the Atlaas instance id or its `externalRef`. [API reference](https://atlaas.dev/docs/v2/connections), [what each broker can do](https://atlaas.dev/docs/v2/broker-capabilities)
295
586
 
296
587
  ```typescript
297
- const conn = atlas.v2.connections("my-conn-001") // Atlaas instance id or externalRef
298
-
299
- const { capabilities } = await conn.capabilities()
300
- if (capabilities.closePosition !== "none") {
301
- const { orders, dropped } = await conn.orders({ includeRaw: false })
302
- const { positions, scope } = await conn.positions({ scope: "DAY" })
303
- }
304
-
305
- // Everything in one call — each section reports ok/error independently
588
+ const conn = atlas.v2.connections("my-conn-001")
589
+
590
+ const { broker, capabilities } = await conn.capabilities()
591
+ const { orders, dropped } = await conn.orders()
592
+ const order = await conn.order(orders[0].orderId, { includeRaw: true }) // raw: the broker's own payload
593
+ const { positions, scope } = await conn.positions({ scope: "DAY" }) // NET by default
594
+ const { trades } = await conn.trades({ includeRaw: true })
595
+ const { holdings } = await conn.holdings()
596
+ const funds = await conn.funds()
597
+ const profile = await conn.profile()
598
+ console.log(broker, capabilities.fractionalQuantity, dropped.length, order.status, positions.length, scope, trades.length, holdings.length, funds.availableBalance, profile.clientId)
599
+
600
+ // Everything in one call; each section is ok or an error of its own
306
601
  const snap = await conn.snapshot()
307
602
  if (snap.sections.funds.ok) console.log(snap.sections.funds.funds.availableBalance)
603
+
604
+ // MT5 only: the symbols this terminal lists, with their contract specs
605
+ const { symbols } = await atlas.v2.connections("my-mt5-001").symbols({ symbol: "XAUUSD" })
606
+ console.log(symbols[0]?.contractSize)
308
607
  ```
309
608
 
310
- `orders` and `positions` take an optional `{ includeRaw?: boolean }` — `true` adds the
311
- untranslated broker payload as `raw` on each item; omitted/`false` strips it. `trades()` and
312
- `holdings()` take no params: the server accepts `?includeRaw=true` on trades too (`UnifiedTrade`
313
- rows do carry a `raw` field), but this SDK's typed `trades()` method doesn't expose the flag yet.
314
- `UnifiedHolding` rows never carry a `raw` field, so there's nothing to include for `holdings()`.
315
- `positions({ scope })` defaults to `"NET"`; MT5 and Motilal are net-only and always report
316
- `scope: "NET"` regardless of what you pass. `.order(orderId)` and `.snapshot({ includeRaw })` take
317
- the same `includeRaw` flag; snapshot's positions section is always `scope: "NET"` (the `scope`
318
- param only applies to `.positions()`).
319
-
320
- Every list result carries `dropped: DroppedRow[]` — rows Atlaas couldn't resolve to a canonical
321
- instrument, reported rather than silently omitted (`reason: "INSTRUMENT_UNRESOLVED" |
322
- "UNMAPPABLE"`). A failed call throws with a typed `code` (`BROKER_REJECTED` · `OUTCOME_UNKNOWN` ·
323
- `UNSUPPORTED_CAPABILITY` · `INSTRUMENT_UNRESOLVED` · `SESSION_DOWN` · `RATE_LIMITED` ·
324
- `VALIDATION`) and a `retryable` flag — see [Error Handling](#error-handling). `OUTCOME_UNKNOWN`
325
- (HTTP 504) means the command reached the runner but no reply came back in time: do not blind-retry,
326
- reconcile with a fresh read first.
327
-
328
- Caveats, in brief (full detail in the [API reference](../../apps/backend/docs/README.md#connections-unified-reads)):
329
-
330
- - **Motilal quantities are units** per the MOFSL docs (`lots` is derived from the row's
331
- `lotsize`); order-book **prices** pass through as reported until the scale is confirmed on a
332
- live fill.
333
- - **Kite resolution is derived**, not synced from a Zerodha master — unresolved Kite rows drop
334
- with `INSTRUMENT_UNRESOLVED`.
335
- - **MT5 rows need the FX instrument import** run first, or every MT5 order/position drops with
336
- `INSTRUMENT_UNRESOLVED`; MT5 orders also never populate `placedAt`.
337
-
338
- Types exported: `UnifiedOrder`, `UnifiedPosition`, `UnifiedHolding`, `UnifiedFunds`,
339
- `UnifiedTrade`, `UnifiedProfile`, `UnifiedError`, `DroppedRow`, `BrokerCapabilities`, `V2Snapshot`.
609
+ Every read takes `includeRaw` to add the broker's untranslated row as `raw`. Every list carries `dropped`: rows Atlaas could not map to an instrument (`INSTRUMENT_UNRESOLVED`) or to the unified shape (`UNMAPPABLE`), reported rather than left out. MT5 and Motilal are net-only, so `positions` answers `scope: "NET"` whatever you ask, and `snapshot` positions are always `NET`. A dropped MT5 position or order also carries `mt5: { ticket, symbol, lots?, side? }` as the terminal reported it, so read `dropped` with `positions`: an empty `positions` with a non-empty `dropped` is not a flat account, and the ticket can still be closed by `positionId`.
340
610
 
341
611
  #### Writes
342
612
 
343
- One order shape for every broker. Size it in `quantity` (**units**: Atlaas resolves the broker ref
344
- from `instrumentKey`, converts to MOFSL lots or MT5 volume, and fails closed with `VALIDATION` /
345
- `INSTRUMENT_UNRESOLVED` on a quantity it cannot convert exactly) or, on MT5 and Motilal, in `lots`
346
- (sent to the broker as-is, no contract-size arithmetic; Dhan and Kite refuse it). Exactly one of
347
- the two. `clientTag` is sanitized per broker. Every write is gated on `capabilities` first and
348
- returns `UNSUPPORTED_CAPABILITY` when the matrix says no.
613
+ Size an order in `quantity` (units; Atlaas converts to lots or MT5 volume and refuses a quantity it cannot convert exactly) or, on MT5 and Motilal, in `lots` (sent as is). Exactly one of the two. Every write is checked against `capabilities` first and refused with `UNSUPPORTED_CAPABILITY` when the broker cannot do it. [API reference](https://atlaas.dev/docs/v2/placing-and-managing-orders)
349
614
 
350
615
  ```typescript
616
+ const conn = atlas.v2.connections("my-conn-001")
617
+
351
618
  const placed = await conn.place({
352
619
  instrumentKey: "NSE:FNO:NIFTY:2026-09-24:24000:CE",
353
620
  side: "BUY",
354
621
  orderType: "LIMIT",
355
- quantity: 150, // units; 2 lots of 75 on MOFSL, reported back as `lots`
622
+ quantity: 150, // units: 2 lots of 75
356
623
  price: 120.5,
357
624
  product: "INTRADAY",
358
625
  clientTag: "sig-42"
359
626
  })
360
-
361
627
  await conn.modify(placed.orderId, { price: 121, quantity: 150 })
362
628
  await conn.cancel(placed.orderId)
363
629
 
364
- // MT5 in lots, with the position's SL/TP on the order.
365
- const fx = await conn.place({ instrumentKey: "FX:EURUSD", side: "BUY", orderType: "MARKET", lots: 0.05, stopLoss: 1.08, takeProfit: 1.12 })
366
- await conn.modifyPosition(fx.orderId, { takeProfit: 1.13 }) // SL untouched
630
+ // MT5 in lots, with the position's SL/TP on the order
631
+ const mt5 = atlas.v2.connections("my-mt5-001")
632
+ const fx = await mt5.place({ instrumentKey: "FX:EURUSD", side: "BUY", orderType: "MARKET", lots: 0.05, stopLoss: 1.08, takeProfit: 1.12 })
633
+ const gold = await mt5.place({ instrumentKey: "FX:XAUUSD", side: "BUY", orderType: "MARKET", lots: 0.1, symbol: "XAUUSD.r" }) // pin the terminal's spelling
634
+ console.log(gold.symbol) // "XAUUSD.r"
635
+ await mt5.modifyPosition(fx.orderId, { takeProfit: 1.13 }) // SL untouched; 0 clears a level
367
636
 
368
- // Flatten: MT5 closes every open ticket on the symbol natively (or one, with `positionId`);
369
- // Dhan/Kite place the opposite-side MARKET order for the NET position. `product` is inferred
370
- // from the one open position when omitted.
637
+ // Close: flatten, or part of one MT5 ticket
371
638
  await conn.closePosition({ instrumentKey: "NSE:EQ:RELIANCE" })
372
- await conn.closePosition({ instrumentKey: "FX:EURUSD", positionId: fx.orderId, lots: 0.02 }) // partial, one ticket
639
+ await mt5.closePosition({ instrumentKey: "FX:EURUSD", positionId: fx.orderId, lots: 0.02 })
373
640
  ```
374
641
 
375
- Per-broker notes:
376
-
377
- - **Motilal** — `orderType: "MARKET"` is **synthetic**: Atlaas places a marketable LIMIT priced
378
- off its vendor feed and chases it from ticks (`chase: { maxDriftPct, maxReprices, timeoutMs }`,
379
- defaults 1 / 3 / 60000). The result and the order book carry a `synthetic` block; exhaustion
380
- cancels at the broker with `CHASE_EXHAUSTED`. Vendor feed down → `FEED_UNAVAILABLE`. An explicit
381
- LIMIT price is never chased. `closePosition` reads the NET position and places an opposite-side
382
- synthetic MARKET (partial `quantity` honoured, capped at the open size); `closeOrders[].synthetic`
383
- carries the chase. Book quantities are units (the row's `lotsize` derives `lots`); `modify`
384
- without `quantity` keeps the resting quantity.
385
- - **Kite** — a 2xx with no `order_id` is reported as `BROKER_REJECTED`, never as success.
386
- - **Dhan / Kite** — `quantity` on `closePosition` closes that many units (the runner re-reads the
387
- position and clamps to what is open); omit it to flatten. `lots` is refused, these brokers have
388
- no lots.
389
- - **MT5** — `STOP_LIMIT` is unsupported; `modify` accepts only `price`/`triggerPrice`; a partial
390
- close needs exactly one open ticket on the symbol (name it with `positionId`). `stopLoss` /
391
- `takeProfit` on `place` become the position's levels; `modifyPosition(positionId, { stopLoss?,
392
- takeProfit? })` moves them afterwards, and an omitted side keeps its current level (0 clears it).
393
- Positions report `mt5.volume` in lots; `quantity` on results is units derived from Atlaas's
394
- contract size for the symbol, so prefer `lots` when your own bookkeeping is in lots.
395
-
396
- Types exported: `PlaceOrderV2Body`, `ModifyOrderV2Body`, `ClosePositionV2Body`,
397
- `ModifyPositionV2Body`, `PlaceOrderResult`, `ModifyOrderResult`, `CancelOrderResult`,
398
- `ClosePositionResult`, `ModifyPositionResult`.
642
+ Per broker:
643
+
644
+ - **Motilal**: `orderType: "MARKET"` is synthetic. Atlaas places a marketable LIMIT priced off its feed and chases it (`chase: { maxDriftPct, maxReprices, timeoutMs }`, defaults 1 / 3 / 60000); results and the order book carry a `synthetic` block, and an exhausted chase is cancelled with `CHASE_EXHAUSTED`. A feed that is down answers `FEED_UNAVAILABLE`. `modify` without `quantity` keeps the resting quantity.
645
+ - **Kite**: a 2xx with no `order_id` is reported as `BROKER_REJECTED`.
646
+ - **Dhan / Kite**: `lots` is refused. `quantity` on `closePosition` closes that many units, capped at what is open.
647
+ - **MT5**: no `STOP_LIMIT`; `modify` takes only `price` / `triggerPrice`; a partial close needs one ticket (`positionId`). The terminal's own symbol list decides which spelling an order goes to; when it lists several (`XAUUSD.r`, `XAUUSD.cent`), pin one with `symbol` on `place`, and the result's `symbol` says what was sent. `quantity` converts with that symbol's own contract size and may be fractional on the 0.001-lot grid (`fractionalQuantity` is true); while the terminal's contract size is unknown, a `quantity` place or partial close is refused with `VALIDATION`, so send `lots`. Positions report `mt5.volume` in lots, so prefer `lots` if you keep your books in lots. Rows need the FX instrument import, or they come back in `dropped`. How Atlaas picks the terminal's own spelling of a symbol: [MT5 symbols](https://atlaas.dev/docs/v2/mt5-symbols-the-terminal-decides).
648
+ - **Crypto and fractional shares**: a non-integer `quantity` is accepted where `capabilities.fractionalQuantity` is true. Perpetual positions carry `margin` and `funding`.
649
+
650
+ `OUTCOME_UNKNOWN` (504) means the order reached the broker and no answer came back: read the order book before you send it again.
651
+
652
+ | Method | Returns |
653
+ | --- | --- |
654
+ | `orders(params?: IncludeRawParams)` | `OrdersListResult` |
655
+ | `order(orderId, params?: IncludeRawParams)` | `UnifiedOrder` |
656
+ | `trades(params?: IncludeRawParams)` | `TradesListResult` |
657
+ | `positions(params?: PositionsListParams)` | `PositionsListResult` |
658
+ | `holdings(params?: IncludeRawParams)` | `HoldingsListResult` |
659
+ | `funds(params?: IncludeRawParams)` | `UnifiedFunds` |
660
+ | `profile(params?: IncludeRawParams)` | `UnifiedProfile` |
661
+ | `symbols(params?: { symbol?: string })` | `SymbolSpecsResult` |
662
+ | `capabilities()` | `CapabilitiesResult` |
663
+ | `snapshot(params?: IncludeRawParams)` | `V2Snapshot` |
664
+ | `place(body: PlaceOrderV2Body, options?: V2WriteOptions)` | `PlaceOrderResult` |
665
+ | `modify(orderId, body: ModifyOrderV2Body, options?: V2WriteOptions)` | `ModifyOrderResult` |
666
+ | `cancel(orderId, options?: V2WriteOptions)` | `CancelOrderResult` |
667
+ | `closePosition(body: ClosePositionV2Body, options?: V2WriteOptions)` | `ClosePositionResult` |
668
+ | `modifyPosition(positionId, body: ModifyPositionV2Body, options?: V2WriteOptions)` | `ModifyPositionResult` |
669
+
670
+ `V2WriteOptions` is `{ idempotencyKey?, signal?, includeRaw? }`.
399
671
 
400
672
  ### Market data (`atlas.v2.market`)
401
673
 
402
- Connection-independent quotes and candles by `instrumentKey`. NSE/BSE keys are served by the
403
- Atlaas **data vendor feed** (one Dhan data plan per deployment, opened in-process by the backend);
404
- FX keys by an MT5 connection you own. Nothing is priced off a stale or wrong source: a vendor that
405
- is not configured or disconnected answers `FEED_UNAVAILABLE` (503, retryable), and an MT5 server
406
- without a configured clock offset answers `TIMEZONE_UNCONFIGURED` (409). Closed bars are cached
407
- server-side and kept past Dhan's ~90-day intraday history, so a repeat `candles` call for a window
408
- Atlaas has already seen costs no vendor request.
674
+ Quotes, candles and option chains by `instrumentKey`, with no connection. NSE/BSE keys come from the Atlaas market data feed (they need the account's India access); FX keys from an MT5 terminal you own. A feed that is down answers `FEED_UNAVAILABLE` (503, retryable) and an MT5 server with no clock offset set answers `TIMEZONE_UNCONFIGURED` (409). [API reference](https://atlaas.dev/docs/v2/market-data)
409
675
 
410
676
  ```typescript
411
- const tick = await atlas.v2.market.quote("NSE:FNO:NIFTY:2026-09-24:24000:CE")
412
- // { instrumentKey, ts, mode: "FULL", ltp, bid, ask, volume, oi, source: "dhan" }
677
+ const tick = await atlas.v2.market.quote("NSE:EQ:RELIANCE") // { instrumentKey, ts, mode, ltp, bid?, ask?, ... }
678
+ const { ticks, unresolved } = await atlas.v2.market.quotes(["NSE:EQ:RELIANCE", "NSE:EQ:TCS"]) // up to 200 keys
679
+ console.log(tick.ltp, ticks.length, unresolved)
413
680
 
414
681
  const { candles } = await atlas.v2.market.candles({
415
682
  instrumentKey: "NSE:EQ:RELIANCE",
416
- interval: "5m", // vendor: 1m 5m 15m 1h 1d; MT5: all seven
683
+ interval: "5m",
417
684
  from: "2026-09-07T03:45:00Z",
418
- to: "2026-09-07T10:00:00Z"
685
+ to: new Date("2026-09-07T10:00:00Z")
419
686
  })
420
- ```
421
-
422
- `quote()` on a vendor key nobody has asked for yet opens the subscription and returns a retryable
423
- 404 — call again a moment later. FX candles take an optional `connectionId`.
687
+ const gold = await atlas.v2.market.candles({ instrumentKey: "FX:XAUUSD", interval: "4h", from: "2026-09-01T00:00:00Z", to: "2026-09-07T00:00:00Z", connectionId: "my-mt5-001" })
688
+ console.log(candles.length, gold.source)
424
689
 
425
- Option chains come from the same vendor feed, so they need no broker connection:
426
-
427
- ```typescript
428
- const { expiries } = await atlas.v2.market.expiries("NSE:IDX:NIFTY") // ["2026-09-24", "2026-10-01", …]
690
+ const { expiries } = await atlas.v2.market.expiries("NSE:IDX:NIFTY")
429
691
  const chain = await atlas.v2.market.optionChain("NSE:IDX:NIFTY", expiries[0])
430
- // { underlyingLtp, strikes: [{ strike, ce?: { instrumentKey, ltp, oi, volume, bid?, ask?, iv?, greeks? }, pe? }] }
431
692
  const atm = chain.strikes.reduce((a, b) => (Math.abs(b.strike - chain.underlyingLtp) < Math.abs(a.strike - chain.underlyingLtp) ? b : a))
432
- await conn.place({ instrumentKey: atm.ce!.instrumentKey, side: "BUY", orderType: "MARKET", quantity: 75 })
693
+ if (atm.ce) await atlas.v2.connections("my-conn-001").place({ instrumentKey: atm.ce.instrumentKey, side: "BUY", orderType: "MARKET", quantity: 75 })
433
694
  ```
434
695
 
435
- Dhan meters the chain at about one call per 3 s; Atlaas coalesces identical concurrent calls and
436
- reuses a fresh answer for that window, and reports a vendor refusal as `RATE_LIMITED` (retryable).
696
+ - `quote()` on a key nobody is streaming yet subscribes it and reads the price once from the vendor, so it answers an LTP snapshot (`mode: "LTP"`) straight away. An FX key with no tick yet answers a retryable 404 while its subscription opens.
697
+ - `quotes()` never comes back short: a key it cannot price is listed in `unresolved` with the reason.
698
+ - Candle intervals: NSE/BSE `1m`, `5m`, `15m`, `1h`, `1d`; FX (MT5) all eight (`1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`). Closed bars are cached, so asking again for a window Atlaas has seen costs no vendor call. FX candles take an optional `connectionId`.
699
+ - Option chains are metered at about one call per 3 s per chain; identical calls inside that window share one answer, and a vendor refusal is `RATE_LIMITED` (retryable).
437
700
 
438
- MT5 contract specs are per broker server, not per instrument, so they hang off the connection:
439
-
440
- ```typescript
441
- const { symbols } = await atlas.v2.connections("conn_mt5").symbols({ symbol: "XAUUSD" })
442
- // [{ symbol: "XAUUSD.sc", instrumentKey: "FX:XAUUSD", contractSize: 1, volumeMin, volumeStep, volumeMax, tickSize, digits, tradeMode, … }]
443
- ```
701
+ | Method | Returns |
702
+ | --- | --- |
703
+ | `quote(instrumentKey)` | `UnifiedTick` |
704
+ | `quotes(instrumentKeys: string[])` | `MarketQuotesResult` |
705
+ | `candles(params: MarketCandlesParams)` | `MarketCandlesResult` |
706
+ | `expiries(underlyingKey)` | `UnifiedOptionExpiries` |
707
+ | `optionChain(underlyingKey, expiry)` | `UnifiedOptionChain` |
444
708
 
445
- ## WebSocket Streams
709
+ ### Scanner (`atlas.v2.scanner`)
446
710
 
447
- Real-time tick and candle data via `/ws/service`.
711
+ The NSE intraday strength scanner: every ranked stock, the picks on each side, breadth and sectors, recomputed each minute of the session. Needs the account's India access. [API reference](https://atlaas.dev/docs/v2/scanner)
448
712
 
449
713
  ```typescript
450
- import { AtlasWebSocket } from "atlaas"
714
+ const board = await atlas.v2.scanner.board({ paths: true }) // paths: each stock's move per session minute
715
+ console.log(board.session.state, board.picks.bullish, board.rows[0]?.strength)
451
716
 
452
- const ws = new AtlasWebSocket({
453
- baseUrl: "https://api.atlaas.dev",
454
- apiKey: "atsk_your_key_here",
455
- clientName: "my-bot",
456
- })
717
+ // Later, only the minutes you do not have yet
718
+ const update = await atlas.v2.scanner.board({ paths: true, after: board.session.minute })
457
719
 
458
- await ws.connect()
720
+ // Zones, stops and targets for one ranked stock, on its last two sessions of 5m bars
721
+ const zones = await atlas.v2.scanner.zones(board.picks.bullish[0])
722
+ console.log(update.pathsFrom, zones.rr, zones.stops[0]?.price)
723
+ ```
459
724
 
460
- ws.subscribe({
461
- channels: ["ticks", "candles"],
462
- accountIds: ["12345"],
463
- symbols: ["EURUSD", "GBPUSD"],
464
- })
725
+ | Method | Returns |
726
+ | --- | --- |
727
+ | `board(params?: ScannerBoardParams)` | `ScannerBoard` |
728
+ | `zones(instrumentKey)` | `ScannerZones` |
465
729
 
466
- ws.on("tick", (tick) => {
467
- console.log(`${tick.symbol} bid=${tick.bid} ask=${tick.ask}`)
468
- })
730
+ ## WebSocket stream (`AtlasWebSocket`)
469
731
 
470
- ws.on("candle", (candle) => {
471
- console.log(`${candle.symbol} ${candle.timeframe} close=${candle.close}`)
472
- })
732
+ Live data on `/ws/service`. [Unified channels](https://atlaas.dev/docs/v2/websocket-channels), [MT5 channels](https://atlaas.dev/docs/v1/mt5-real-time-subscriptions-websocket)
473
733
 
474
- ws.on("broker_tick", (tick) => {
475
- console.log(`${tick.brokerName} ${tick.securityId}`, tick.data)
476
- })
734
+ ```typescript
735
+ import { AtlasWebSocket } from "atlaas"
736
+
737
+ const ws = new AtlasWebSocket({ baseUrl: "https://api.atlaas.dev", apiKey: process.env.ATLAAS_API_KEY ?? "", clientName: "my-bot" })
738
+ await ws.connect() // rejects with AtlasAuthError, e.g. "Account has no credits remaining"
739
+ ws.on("subscribe_failed", (f) => console.error("subscribe refused:", f.reason)) // nothing changed
477
740
 
478
- ws.on("disconnected", (reason) => {
479
- console.log("Disconnected:", reason)
480
- // Auto-reconnect is enabled by default
741
+ ws.subscribe({ channels: ["market.ticks", "market.candles", "trading.orders"], instrumentKeys: ["NSE:EQ:RELIANCE", "FX:EURUSD"] })
742
+ ws.on("subscribed", (reply) => {
743
+ for (const r of reply.refusedInstrumentKeys ?? []) console.warn(`${r.instrumentKey} not subscribed: ${r.reason}`)
744
+ if (reply.refusedChannels) console.warn("refused:", reply.refusedChannels)
481
745
  })
482
746
 
483
- // When done
747
+ ws.on("market.tick", (t) => console.log(t.instrumentKey, t.ltp))
748
+ ws.on("market.candle", (c) => c.isFinal && console.log(c.instrumentKey, c.interval, c.candle.c))
749
+ ws.on("trading.order", (o) => console.log(o.connectionId, o.sequence, o.orderId, o.status))
750
+
751
+ // MT5 frames: name the channels you want, narrowed to some terminals and symbols
752
+ ws.subscribe({ channels: ["ticks", "candles", "positions", "trades"], accountIds: ["51234567"], symbols: ["EURUSD"] })
753
+ ws.on("tick", (t) => console.log(t.accountId, t.symbol, t.bid, t.ask))
754
+ ws.on("candle", (c) => console.log(c.symbol, c.timeframe, c.close))
755
+ ws.on("position_update", (p) => console.log(p.accountId, p.equity, p.positions.length))
756
+ ws.on("trade_event", (e) => console.log(e.transType, e.symbol, e.deal))
757
+ ws.on("heartbeat", (h) => console.log(h.accountId, h.balance))
758
+
759
+ // Option chains and the scanner board
760
+ ws.subscribe({ channels: ["market.chain"], chains: [{ underlyingKey: "NSE:IDX:NIFTY", expiry: "2026-11-26" }] })
761
+ ws.subscribe({ channels: ["market.scanner"] })
762
+ ws.on("market.chain", (chain) => console.log(chain.underlyingKey, chain.strikes.length))
763
+ ws.on("market.scanner", (board) => console.log(board.asOf, board.picks.bullish))
764
+
765
+ // Drop one key, one chain, or whole channels
766
+ ws.unsubscribe({ instrumentKeys: ["FX:EURUSD"] })
767
+ ws.unsubscribe({ chains: [{ underlyingKey: "NSE:IDX:NIFTY", expiry: "2026-11-26" }] })
768
+ ws.unsubscribe(["market.scanner"])
769
+
770
+ ws.on("disconnected", (reason) => console.log("disconnected:", reason)) // reconnects and re-subscribes by itself
771
+ ws.on("error", (err) => console.error(err))
772
+ console.log(ws.isConnected)
484
773
  ws.disconnect()
485
774
  ```
486
775
 
487
- ### WebSocket Options
776
+ | Channel | Events | Filter | Scope |
777
+ | --- | --- | --- | --- |
778
+ | `market.ticks` | `market.tick` (`UnifiedTick`) | `instrumentKeys` | `feed:r` |
779
+ | `market.candles` | `market.candle` (`{ instrumentKey, interval, isFinal, candle, source }`) | `instrumentKeys` | `feed:r` |
780
+ | `market.chain` | `market.chain` (`UnifiedOptionChain`) | `chains` | `feed:r`, India |
781
+ | `market.scanner` | `market.scanner` (the scanner board plus `append`) | none | `feed:r`, India |
782
+ | `trading.orders` | `trading.order` (`UnifiedOrder` plus `eventTs`, `sequence`) | `brokerOrderConnectionIds` | `orders:r` |
783
+ | `broker_ticks` | `broker_tick` (Dhan / Kite ticks, untranslated) | `brokerConnectionIds`, `brokerSecurityKeys` (empty: all yours) | `feed:r` |
784
+ | `broker_orders` | `broker_order_update` (the broker's own order alert) | `brokerOrderConnectionIds` (empty: all yours) | `orders:r` |
785
+ | `ticks` | `tick` | `accountIds`, `symbols` | `feed:r` |
786
+ | `candles` | `candle` | `accountIds`, `symbols` | `feed:r` |
787
+ | `positions` | `position_update` | `accountIds` | `orders:r` |
788
+ | `trades` | `trade_event` | `accountIds` | `orders:r` |
789
+
790
+ The MT5 channels (`ticks`, `candles`, `positions`, `trades`) work like this:
791
+
792
+ - Once a subscribe has accepted one of them, the socket gets only the MT5 channels it named, narrowed by `accountIds` (MT5 logins; empty means every terminal you own), with `symbols` narrowing ticks and candles. The terminal `heartbeat` follows `accountIds` only. Unsubscribing all four stops MT5 frames; it does not bring back the unfiltered stream.
793
+ - A socket that never names one of them gets every MT5 frame from every terminal on the account, whatever else it subscribed to.
794
+ - Which symbols a terminal streams at all is set with `atlas.subscriptions`.
795
+ - `orders` is retired: a subscribe naming it gets it back in `refusedChannels` (`"orders (retired: use trading.orders)"`). Follow MT5 orders on `trading.orders`, or as raw `trade_event` frames on `trades`.
796
+
797
+ An inactive, suspended or out-of-credit account is refused at connect (`connect()` rejects with an `AtlasAuthError` carrying the reason, such as `Account has no credits remaining`). If that happens while the socket is open, it keeps streaming what it already subscribed to, but each new `subscribe` is answered with a `subscribe_failed` event (`{ reason }`) and changes nothing until the account is back in good standing. `unsubscribe` always works.
798
+
799
+ - A market channel only carries the keys you name: an empty `instrumentKeys` is nothing, not everything. NSE/BSE keys open a feed subscription; FX keys ride your terminal's own tick subscriptions (`atlas.subscriptions`).
800
+ - An account streams up to 500 instruments across all its sockets. A key over the limit, or one the feed or your access cannot serve, is left out and named in the `subscribed` reply's `refusedInstrumentKeys` with a reason: `account_quota`, `capacity`, `unsupported`, `india_entitlement` or `no_account`. A key read cold through `v2.market.quote` counts toward the limit for 10 minutes.
801
+ - Channels the key's scope cannot read come back in `refusedChannels`, and account or connection ids it does not own in `refusedAccountIds`, `refusedBrokerConnectionIds` and `refusedBrokerOrderConnectionIds`.
802
+ - `trading.orders` is at-least-once; Atlaas dedupes on `(orderId, status, filledQuantity, price)` and stamps a per-connection `sequence` so you can spot gaps.
803
+ - `subscribe` adds to what the socket holds, and a reconnect re-sends all of it. Listen for `subscribed` (and `subscribe_failed`) to see what the server accepted.
488
804
 
489
805
  | Option | Default | Description |
490
- |--------|---------|-------------|
806
+ | --- | --- | --- |
491
807
  | `baseUrl` | — | Atlaas API base URL |
492
- | `apiKey` | — | Service key (`atsk_*`) |
808
+ | `apiKey` | — | Service key (`atsk_*`) with `feed:r` or `orders:r` |
493
809
  | `clientName` | — | Optional name for this client |
494
- | `autoReconnect` | `true` | Reconnect on disconnect |
810
+ | `autoReconnect` | `true` | Reconnect after a drop |
495
811
  | `reconnectDelayMs` | `2000` | Base reconnect delay |
496
- | `maxReconnectAttempts` | `10` | Max reconnect attempts |
497
-
498
- ### Unified channels (v2)
499
-
500
- Three additive channels carry the same canonical shapes as the REST surface:
501
-
502
- | Channel | Event | Payload | Filter |
503
- | --- | --- | --- | --- |
504
- | `market.ticks` | `market.tick` | `UnifiedTick` | `instrumentKeys` (NSE/BSE keys open a vendor subscription on demand) |
505
- | `market.candles` | `market.candle` | `{ instrumentKey, interval, isFinal, candle, source }` from Atlaas's one NSE-grid aggregator (IST 09:15–15:30) or the MT5 stream | `instrumentKeys` |
506
- | `trading.orders` | `trading.order` | `UnifiedOrder + { eventTs, sequence }` from the Dhan order WS, MT5 trade events, and an Atlaas-side poll for Kite/MOFSL | `brokerOrderConnectionIds` |
507
-
508
- ```typescript
509
- ws.subscribe({ channels: ["market.ticks", "market.candles", "trading.orders"], instrumentKeys: ["NSE:EQ:RELIANCE"] })
510
- ws.on("market.tick", (t) => console.log(t.instrumentKey, t.ltp))
511
- ws.on("market.candle", (c) => c.isFinal && console.log(c.interval, c.candle))
512
- ws.on("trading.order", (o) => console.log(o.sequence, o.orderId, o.status))
513
- ```
812
+ | `maxReconnectAttempts` | `10` | Give up after this many |
514
813
 
515
- Delivery on `trading.orders` is at-least-once; Atlaas dedupes on `(orderId, status, filledQuantity,
516
- price)` and stamps a per-connection `sequence`. The raw `ticks` / `candles` / `broker_ticks` /
517
- `broker_orders` channels keep working until their announced retirement.
814
+ ## Zod schemas
518
815
 
519
- ### Channels
520
-
521
- `ticks`, `candles`, `positions`, `trades`, `orders`, `broker_ticks`
522
-
523
- ## Error Handling
524
-
525
- All API errors throw typed exceptions:
816
+ Runtime validation for the v1 shapes and the WebSocket frames, as Zod 4 schemas (compose them with `zod@^4`):
526
817
 
527
818
  ```typescript
528
- import {
529
- AtlasError,
530
- AtlasAuthError,
531
- AtlasRateLimitError,
532
- AtlasValidationError,
533
- AtlasNetworkError,
534
- } from "atlaas"
819
+ import { MT5PositionUpdateSchema, MT5TickSchema, PositionSchema } from "atlaas/schemas"
535
820
 
536
- try {
537
- await atlas.trading.placeOrder(accountId, body)
538
- } catch (err) {
539
- if (err instanceof AtlasAuthError) {
540
- // 401 — invalid or expired API key
541
- } else if (err instanceof AtlasRateLimitError) {
542
- // 429 — retry after err.retryAfter seconds
543
- } else if (err instanceof AtlasValidationError) {
544
- // 400 — bad request
545
- } else if (err instanceof AtlasNetworkError) {
546
- // Network failure or timeout
547
- } else if (err instanceof AtlasError) {
548
- // Other API error (403, 404, 500, etc.)
549
- console.log(err.statusCode, err.message)
550
- }
551
- }
821
+ const tick = MT5TickSchema.parse({ type: "tick", accountId: "51234567", symbol: "EURUSD", bid: 1.1, ask: 1.1002, ts: 1, timestamp: 2 })
822
+ const positions = PositionSchema.array().parse([])
823
+ const update = MT5PositionUpdateSchema.safeParse({})
824
+ console.log(tick.symbol, positions.length, update.success)
552
825
  ```
553
826
 
554
- ## Client Options
555
-
556
- | Option | Default | Description |
557
- |--------|---------|-------------|
558
- | `baseUrl` | — | Atlaas API base URL |
559
- | `apiKey` | — | Service key (`atsk_*`) |
560
- | `timeoutMs` | `30000` | Request timeout |
561
- | `maxRetries` | `2` | Retries on 5xx / network errors |
562
- | `logger` | — | Optional logger (`{ debug, info, warn, error }`) |
563
-
564
- ## Zod Schemas
565
-
566
- For runtime validation, import schemas directly:
567
-
568
- ```typescript
569
- import { PositionSchema, OrderSchema, MT5TickSchema } from "atlaas/schemas"
570
-
571
- const position = PositionSchema.parse(rawData)
572
- ```
827
+ Exported: `InstanceSchema`, `AtlasInstanceSchema`, `AccountInfoSchema`, `PositionSchema`, `ClosedPositionSchema`, `OrderSchema`, `PriceSchema`, `CandleSchema`, `MarginResultSchema`, `ServiceKeySchema`, `TickSubscriptionsSchema`, `CandleSubscriptionsSchema`, `MT5TickSchema`, `MT5CandleSchema`, `MT5LivePositionSchema`, `MT5PositionUpdateSchema`, `MT5TradeEventSchema`, `MT5HeartbeatSchema`, `BrokerTickSchema`, `BrokerOrderUpdateSchema`.
573
828
 
574
829
  ## License
575
830