atlaas 0.2.0 → 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 +657 -404
- package/dist/index.d.ts +2029 -123
- package/dist/index.js +632 -250
- package/dist/index.js.map +1 -1
- package/dist/schemas.d.ts +156 -11
- package/dist/schemas.js +125 -13
- package/dist/schemas.js.map +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# atlaas
|
|
2
2
|
|
|
3
|
-
TypeScript SDK for the Atlaas
|
|
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
|
-
|
|
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,553 +25,806 @@ import { AtlasClient } from "atlaas"
|
|
|
25
25
|
|
|
26
26
|
const atlas = new AtlasClient({
|
|
27
27
|
baseUrl: "https://api.atlaas.dev",
|
|
28
|
-
apiKey: "
|
|
28
|
+
apiKey: process.env.ATLAAS_API_KEY ?? ""
|
|
29
29
|
})
|
|
30
30
|
|
|
31
|
-
//
|
|
32
|
-
const
|
|
31
|
+
// Your MT5 terminals
|
|
32
|
+
const terminals = await atlas.mt5.list()
|
|
33
33
|
|
|
34
|
-
//
|
|
35
|
-
const
|
|
36
|
-
|
|
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
|
-
//
|
|
42
|
-
const positions = await atlas.trading.getPositions(
|
|
38
|
+
// Its open positions
|
|
39
|
+
const positions = await atlas.trading.getPositions(login)
|
|
40
|
+
console.log(order.ticket, positions.length)
|
|
43
41
|
```
|
|
44
42
|
|
|
45
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
await atlas.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
70
|
-
await atlas.trading.getOrders(
|
|
71
|
-
await atlas.trading.cancelOrder(
|
|
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(
|
|
75
|
-
await atlas.trading.getPosition(
|
|
76
|
-
|
|
77
|
-
await atlas.trading.
|
|
78
|
-
await atlas.trading.closePosition(
|
|
79
|
-
await atlas.trading.closeBySymbol(
|
|
80
|
-
|
|
81
|
-
//
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
await atlas.trading.
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
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
|
-
//
|
|
95
|
-
await atlas.trading.
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
110
|
-
await atlas.subscriptions.
|
|
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.
|
|
114
|
-
await atlas.subscriptions.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
await atlas.serviceKeys.
|
|
125
|
-
await atlas.serviceKeys.
|
|
126
|
-
|
|
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
|
-
|
|
293
|
+
## Expert Advisors (`atlas.eas`)
|
|
130
294
|
|
|
131
|
-
|
|
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.
|
|
139
|
-
await atlas.eas.get(
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
//
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
await atlas.eas.
|
|
155
|
-
await
|
|
156
|
-
|
|
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
|
-
|
|
160
|
-
|
|
161
|
-
|
|
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)
|
|
393
|
+
|
|
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
|
+
}
|
|
162
403
|
|
|
163
|
-
|
|
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
|
+
```
|
|
164
456
|
|
|
165
|
-
|
|
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",
|
|
493
|
+
const dhan = atlas.broker("dhan", "my-conn-001")
|
|
169
494
|
|
|
170
|
-
await dhan.placeOrder({
|
|
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(
|
|
173
|
-
await dhan.modifyOrder(
|
|
174
|
-
await dhan.cancelOrder(
|
|
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
|
-
//
|
|
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
|
-
|
|
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",
|
|
198
|
-
|
|
520
|
+
const mo = atlas.broker("motilal", "my-mofsl-001")
|
|
199
521
|
await mo.placeOrder({
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
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
|
-
|
|
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
|
-
|
|
546
|
+
## Unified API (`atlas.v2`)
|
|
219
547
|
|
|
220
|
-
|
|
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.
|
|
225
549
|
|
|
226
|
-
Instruments
|
|
227
|
-
|
|
550
|
+
### Instruments (`atlas.v2.instruments`)
|
|
551
|
+
|
|
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",
|
|
233
|
-
segment: "FNO",
|
|
234
|
-
symbol: "NIFTY",
|
|
235
|
-
q: "RELI",
|
|
236
|
-
active: true,
|
|
237
|
-
limit: 100
|
|
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
|
-
|
|
242
|
-
const
|
|
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
|
-
|
|
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
|
|
259
|
-
NSE:IDX:NIFTY
|
|
260
|
-
NSE:FNO:NIFTY:2026-08-27:FUT
|
|
261
|
-
NSE:FNO:NIFTY:2026-08-27:24000:CE
|
|
262
|
-
NSE:FNO:USDINR:2026-08-27:84.25:PE
|
|
263
|
-
FX:XAUUSD
|
|
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
|
|
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.
|
|
287
|
-
|
|
288
|
-
The response shape is exported as `UnifiedInstrument`.
|
|
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.
|
|
289
582
|
|
|
290
|
-
### Connections (`atlas.v2.connections`)
|
|
583
|
+
### Connections (`atlas.v2.connections()`)
|
|
291
584
|
|
|
292
|
-
|
|
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")
|
|
298
|
-
|
|
299
|
-
const { capabilities } = await conn.capabilities()
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
|
|
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
|
-
`
|
|
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
|
-
|
|
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
|
|
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
|
|
366
|
-
await
|
|
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
|
-
//
|
|
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
|
|
639
|
+
await mt5.closePosition({ instrumentKey: "FX:EURUSD", positionId: fx.orderId, lots: 0.02 })
|
|
373
640
|
```
|
|
374
641
|
|
|
375
|
-
Per
|
|
376
|
-
|
|
377
|
-
- **Motilal
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
`
|
|
398
|
-
`
|
|
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
|
-
|
|
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:
|
|
412
|
-
|
|
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",
|
|
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`.
|
|
424
|
-
|
|
425
|
-
Option chains come from the same vendor feed, so they need no broker connection:
|
|
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)
|
|
426
689
|
|
|
427
|
-
|
|
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
|
|
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
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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).
|
|
439
700
|
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
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
|
-
|
|
709
|
+
### Scanner (`atlas.v2.scanner`)
|
|
446
710
|
|
|
447
|
-
|
|
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
|
-
|
|
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
|
-
|
|
453
|
-
|
|
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
|
-
|
|
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
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
})
|
|
725
|
+
| Method | Returns |
|
|
726
|
+
| --- | --- |
|
|
727
|
+
| `board(params?: ScannerBoardParams)` | `ScannerBoard` |
|
|
728
|
+
| `zones(instrumentKey)` | `ScannerZones` |
|
|
465
729
|
|
|
466
|
-
|
|
467
|
-
console.log(`${tick.symbol} bid=${tick.bid} ask=${tick.ask}`)
|
|
468
|
-
})
|
|
730
|
+
## WebSocket stream (`AtlasWebSocket`)
|
|
469
731
|
|
|
470
|
-
ws.
|
|
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
|
-
|
|
475
|
-
|
|
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.
|
|
479
|
-
|
|
480
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
810
|
+
| `autoReconnect` | `true` | Reconnect after a drop |
|
|
495
811
|
| `reconnectDelayMs` | `2000` | Base reconnect delay |
|
|
496
|
-
| `maxReconnectAttempts` | `10` |
|
|
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` |
|
|
812
|
+
| `maxReconnectAttempts` | `10` | Give up after this many |
|
|
507
813
|
|
|
508
|
-
|
|
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
|
-
```
|
|
514
|
-
|
|
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.
|
|
516
|
-
|
|
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.
|
|
814
|
+
## Zod schemas
|
|
520
815
|
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
`ticks`, `candles`, `positions`, `trades`, `orders`, `broker_ticks`
|
|
524
|
-
|
|
525
|
-
## Error Handling
|
|
526
|
-
|
|
527
|
-
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`):
|
|
528
817
|
|
|
529
818
|
```typescript
|
|
530
|
-
import {
|
|
531
|
-
AtlasError,
|
|
532
|
-
AtlasAuthError,
|
|
533
|
-
AtlasRateLimitError,
|
|
534
|
-
AtlasValidationError,
|
|
535
|
-
AtlasNetworkError,
|
|
536
|
-
} from "atlaas"
|
|
819
|
+
import { MT5PositionUpdateSchema, MT5TickSchema, PositionSchema } from "atlaas/schemas"
|
|
537
820
|
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
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
|
-
}
|
|
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)
|
|
554
825
|
```
|
|
555
826
|
|
|
556
|
-
|
|
557
|
-
|
|
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 }`) |
|
|
565
|
-
|
|
566
|
-
## Zod Schemas
|
|
567
|
-
|
|
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:
|
|
569
|
-
|
|
570
|
-
```typescript
|
|
571
|
-
import { PositionSchema, OrderSchema, MT5TickSchema } from "atlaas/schemas"
|
|
572
|
-
|
|
573
|
-
const position = PositionSchema.parse(rawData)
|
|
574
|
-
```
|
|
827
|
+
Exported: `InstanceSchema`, `AtlasInstanceSchema`, `AccountInfoSchema`, `PositionSchema`, `ClosedPositionSchema`, `OrderSchema`, `PriceSchema`, `CandleSchema`, `MarginResultSchema`, `ServiceKeySchema`, `TickSubscriptionsSchema`, `CandleSubscriptionsSchema`, `MT5TickSchema`, `MT5CandleSchema`, `MT5LivePositionSchema`, `MT5PositionUpdateSchema`, `MT5TradeEventSchema`, `MT5HeartbeatSchema`, `BrokerTickSchema`, `BrokerOrderUpdateSchema`.
|
|
575
828
|
|
|
576
829
|
## License
|
|
577
830
|
|