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