nexustrade 0.4.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -25,7 +25,7 @@ export NEXUSTRADE_API_BASE_URL=https://nexustrade.io/api/v1
25
25
 
26
26
  ```ts
27
27
  import { NexusTradeClient } from "nexustrade";
28
- const nt = new NexusTradeClient(); // reads the environment
28
+ const client = new NexusTradeClient(); // reads the environment
29
29
  ```
30
30
 
31
31
  Keys come from https://nexustrade.io/developers. Never hardcode one into a file
@@ -68,10 +68,10 @@ retry with a new key launches a second paid job.
68
68
 
69
69
  ```ts
70
70
  // Right — same logical run reuses the key across retries
71
- await nt.createBacktest(handle, { idempotencyKey: "momentum-2024-v1" });
71
+ await client.createBacktest(handle, { idempotencyKey: "momentum-2024-v1" });
72
72
 
73
73
  // Wrong — every retry is a new billable job
74
- await nt.createBacktest(handle, { idempotencyKey: `run-${Date.now()}` });
74
+ await client.createBacktest(handle, { idempotencyKey: `run-${Date.now()}` });
75
75
  ```
76
76
 
77
77
  Reusing a key with a *different* payload is a `409 idempotency_conflict`. Version
@@ -80,9 +80,9 @@ the key when the request changes: `momentum-2024-v2`.
80
80
  **4. `create*` does not wait. Poll.**
81
81
 
82
82
  ```ts
83
- const operation = await nt.createBacktest(handle, { idempotencyKey: "k" });
83
+ const operation = await client.createBacktest(handle, { idempotencyKey: "k" });
84
84
  // operation.result is ABSENT here — the job has not run yet.
85
- const finished = await nt.waitForBacktest(operation.id as string);
85
+ const finished = await client.waitForBacktest(operation.id as string);
86
86
  console.log(finished.result);
87
87
  ```
88
88
 
@@ -92,10 +92,10 @@ do not resubmit.
92
92
  **5. Batch when you have several.**
93
93
 
94
94
  ```ts
95
- const operations = await nt.createBacktests([h1, h2, h3], {
95
+ const operations = await client.createBacktests([h1, h2, h3], {
96
96
  idempotencyKey: "sweep-v1",
97
97
  });
98
- const results = await nt.waitForBacktests(operations);
98
+ const results = await client.waitForBacktests(operations);
99
99
  ```
100
100
 
101
101
  One request, one key, one rate-limit slot — instead of three of each.
@@ -114,6 +114,28 @@ write, and never log one. Exported values win over the file.
114
114
  narrow before use (`operation.id as string`). This is deliberate: the envelope is
115
115
  whatever the API returned, not a promise the SDK can statically make.
116
116
 
117
+ **9. Your own data belongs in ONE series.** `createCustomIndicator` mints a new
118
+ series every time it is called with a fresh idempotency key. Recurring
119
+ collection must `appendCustomIndicatorPoints` onto the id it created the first
120
+ time — a new series per run splits the history into fragments no strategy can
121
+ read. Persist the id; never re-create by name.
122
+
123
+ ```ts
124
+ // Right — one series, appended forever
125
+ await client.appendCustomIndicatorPoints(seriesId, todaysPoints, {
126
+ idempotencyKey: `mentions-${today}`,
127
+ });
128
+
129
+ // Wrong — a new, disconnected series every run
130
+ await client.createCustomIndicator(
131
+ { name: "Mentions", points: todaysPoints },
132
+ { idempotencyKey: `mentions-${today}` },
133
+ );
134
+ ```
135
+
136
+ Point batches are unlimited in size; the SDK sends them inline or uploads them.
137
+ Do not chunk by hand.
138
+
117
139
  ## Recipes
118
140
 
119
141
  <details open>
@@ -201,7 +223,7 @@ pair.
201
223
  <summary><b>Query the data lake</b></summary>
202
224
 
203
225
  ```ts
204
- const query = await nt.createLakeQuery(
226
+ const query = await client.createLakeQuery(
205
227
  {
206
228
  query: "SELECT ticker, date, closingPrice FROM lake.daily_ohlc WHERE ticker = ?",
207
229
  params: ["AAPL"],
@@ -209,8 +231,8 @@ const query = await nt.createLakeQuery(
209
231
  },
210
232
  { idempotencyKey: "aapl-daily-v1" },
211
233
  );
212
- const finished = await nt.waitForLakeQuery(query.id as string);
213
- const manifest = await nt.getLakeQueryManifest(finished.id as string);
234
+ const finished = await client.waitForLakeQuery(query.id as string);
235
+ const manifest = await client.getLakeQueryManifest(finished.id as string);
214
236
  ```
215
237
 
216
238
  Always parameterize with `?` rather than interpolating into the SQL string.
@@ -225,7 +247,7 @@ Agents are the one job kind that is NOT fire-and-poll. Three states —
225
247
  ones the run cannot leave on its own, so the caller is the approver.
226
248
 
227
249
  ```ts
228
- const run = await nt.createAgent("Find momentum names in the S&P 500", {
250
+ const run = await client.createAgent("Find momentum names in the S&P 500", {
229
251
  idempotencyKey: "momentum-scan-v1",
230
252
  });
231
253
 
@@ -238,7 +260,7 @@ for await (const event of run) {
238
260
 
239
261
  Iterating waits. If you never answer a blocked run, iteration throws
240
262
  `agent_awaiting_input` rather than spinning silently — the run keeps going
241
- server-side, so reattach with `nt.attachAgent(run.id)`.
263
+ server-side, so reattach with `client.attachAgent(run.id)`.
242
264
 
243
265
  Approving can place orders, so it needs the `trade` scope; everything else
244
266
  needs `write`. Agent runs are unavailable to `run_compute` sandbox code.
@@ -255,18 +277,46 @@ All failures throw `NexusTradeApiError` with a stable `.status`, `.code`, and
255
277
  | `insufficient_scope` | The key lacks `read` / `write` / `lake`. Do not retry. |
256
278
  | `invalid_portfolio` | The book is malformed — fix the builders, do not retry as-is. |
257
279
  | `idempotency_conflict` | Same key, different payload. Version the key. |
280
+ | `idempotency_in_progress` | Same key, first call still running. Wait and re-read; never resubmit. |
258
281
  | `rate_limit_exceeded` | Back off and retry. |
259
282
  | `operation_timeout` | Job still running. Re-poll the same id; never resubmit. |
260
283
 
261
284
  `status === 0` means no HTTP status applies: the request never reached the API
262
285
  (`transport_error`), or the reply failed an envelope check.
263
286
 
264
- ## Out of scope
287
+ ## What is and is not here
288
+
289
+ **Deploying a portfolio IS supported.** `book.save(...)` persists it and
290
+ `book.deploy(...)` starts paper trading it; `client.deploy(portfolioId)` does
291
+ the same from an id. `save` and `deploy` return *different* ids — deploying
292
+ mints a portfolio rather than converting the draft.
293
+
294
+ **`deploy` is not always paper.** A portfolio this SDK creates is always paper:
295
+ the portfolio spec has no deployment field, so there is no way to ask for a
296
+ live one. But `deploy(portfolioId)` accepts the id of a portfolio that is
297
+ *already deployed*, and then it reactivates that portfolio as whatever it
298
+ already is. Hand it the id of a paused **live** portfolio — `listPortfolios`
299
+ will return one under `includeLive: true` — and it resumes live trading against
300
+ the connected brokerage. `undeploy` is the same in reverse. Read
301
+ `deploymentType` on the response to know which one you got, and treat any id
302
+ you did not create in this session as possibly live.
265
303
 
266
304
  Not in this SDK. Do not attempt to reach them through it:
267
305
 
268
306
  - **Screener** — MCP only.
269
- - **Live trading and order placement** — deliberately excluded.
307
+ - **Submitting a live order** — impossible from anywhere, not just here. Live
308
+ orders are staged `PENDING_USER_APPROVAL` and a human approves them in the
309
+ UI; the brokerage boundary refuses an unapproved live order regardless of
310
+ caller. `createOrders` stages them, it does not send them.
311
+ - **Minting a live portfolio, and connecting a brokerage** — both happen in the
312
+ web app. No route under the SDK prefix creates a live deployment; see above
313
+ for reactivating a live portfolio that already exists.
314
+
315
+ The complete method list — every client and handle method, including the ones
316
+ without a worked example above — is the **Complete method reference** table in
317
+ [README.md](README.md#complete-method-reference). A test fails if any public
318
+ method is missing from it, so it is exhaustive by construction rather than by
319
+ maintenance.
270
320
 
271
321
  ## Verifying your work
272
322
 
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
12
12
  [![Deps](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](package.json)
13
13
 
14
- [Quickstart](#quickstart) · [Authoring](#authoring-strategies) · [Polling](#jobs-run-on-the-engine--you-poll) · [Lake SQL](#lake-sql) · [Auth](#authentication) · [Errors](#errors)
14
+ [Quickstart](#quickstart) · [Authoring](#authoring-strategies) · [Polling](#jobs-run-on-the-engine--you-poll) · [Agents](#agent-runs) · [Lake SQL](#lake-sql) · [Auth](#authentication) · [Errors](#errors)
15
15
 
16
16
  </div>
17
17
 
@@ -30,7 +30,7 @@ import {
30
30
  NexusTradeClient, always, backtest, buy, portfolio, stockAsset, strategy,
31
31
  } from "nexustrade";
32
32
 
33
- const nt = new NexusTradeClient({
33
+ const client = new NexusTradeClient({
34
34
  apiKey: "sk-...",
35
35
  baseUrl: "https://nexustrade.io/api/v1",
36
36
  });
@@ -39,11 +39,11 @@ const book = portfolio("Example", [
39
39
  strategy("Buy SPY", always(), buy(stockAsset("SPY"), 100)),
40
40
  ]);
41
41
 
42
- const operation = await nt.createBacktest(
42
+ const operation = await client.createBacktest(
43
43
  backtest(book, { startDate: "2024-01-01", endDate: "2024-12-31" }),
44
44
  { idempotencyKey: "example-v1" },
45
45
  );
46
- const result = await nt.waitForBacktest(operation.id as string);
46
+ const result = await client.waitForBacktest(operation.id as string);
47
47
  console.log(result.result);
48
48
  ```
49
49
 
@@ -100,6 +100,27 @@ Every builder is fully typed — your editor completes the whole surface.
100
100
  `create*` enqueues work and returns immediately. It does **not** resolve when
101
101
  results exist. There are no webhooks today.
102
102
 
103
+ ```mermaid
104
+ sequenceDiagram
105
+ participant You
106
+ participant SDK
107
+ participant Engine
108
+
109
+ You->>SDK: createBacktest(book)
110
+ SDK->>Engine: POST (enqueue)
111
+ Engine-->>SDK: id, status=queued
112
+ SDK-->>You: operation (returns immediately)
113
+
114
+ loop waitForBacktest — backoff 2s→15s
115
+ SDK->>Engine: GET /operations/{id}
116
+ Engine-->>SDK: status update
117
+ end
118
+
119
+ SDK-->>You: result (when completed)
120
+
121
+ Note over You,Engine: Poll timeout throws operation_timeout.<br/>The job keeps running — call wait again with the same id.
122
+ ```
123
+
103
124
  Every job kind reports the same envelope, so one poller serves all of them:
104
125
 
105
126
  ```ts
@@ -113,7 +134,7 @@ Every job kind reports the same envelope, so one poller serves all of them:
113
134
  ```
114
135
 
115
136
  ```ts
116
- const finished = await nt.waitForBacktest(operation.id as string);
137
+ const finished = await client.waitForBacktest(operation.id as string);
117
138
  ```
118
139
 
119
140
  | Option | Default | Meaning |
@@ -133,7 +154,7 @@ over a loop: one request, one idempotency key, one rate-limit slot.
133
154
  **Optimization and walk-forward** follow the identical shape:
134
155
 
135
156
  ```ts
136
- const study = await nt.createWalkForward(
157
+ const study = await client.createWalkForward(
137
158
  nt.walkForward(book, {
138
159
  globalStartDate: "2022-01-01",
139
160
  globalEndDate: "2024-12-31",
@@ -141,7 +162,225 @@ const study = await nt.createWalkForward(
141
162
  }),
142
163
  { idempotencyKey: "wf-v1" },
143
164
  );
144
- await nt.waitForWalkForward(study.id as string);
165
+ await client.waitForWalkForward(study.id as string);
166
+ ```
167
+
168
+ ## Deploying a portfolio
169
+
170
+ Authoring and backtesting a book does not persist it. `save` writes it to your
171
+ account; `deploy` starts running it.
172
+
173
+ ```ts
174
+ const book = nt.portfolio("Momentum", [/* … */]);
175
+
176
+ await book.save({ idempotencyKey: "momentum-v1" }); // persists; sets book.id
177
+ const deployment = await book.deploy(); // starts paper trading
178
+ await book.undeploy(); // stops it
179
+ ```
180
+
181
+ **`save` and `deploy` produce different ids, and the distinction matters.**
182
+ `save` persists a *draft* and sets `book.id` to it. `deploy` mints the real
183
+ paper portfolio and returns its own `portfolioId` — deploying creates a
184
+ portfolio rather than converting the draft into one, so the two ids coexist.
185
+ Hold on to `deployment.portfolioId` for anything that reads live state;
186
+ `book.id` addresses the draft.
187
+
188
+ ```ts
189
+ deployment.portfolioId // the running portfolio
190
+ deployment.deploymentType // paper, unless you deployed an existing live one
191
+ deployment.outcome // created | reactivated
192
+ ```
193
+
194
+ Handle methods accept an optional `transport`; omitted, they resolve one from
195
+ the environment. The same operations exist on the client — `client.deploy(id)`,
196
+ `client.undeploy(id)` — when you have an id rather than a handle.
197
+
198
+ ```ts
199
+ await client.listPortfolios({ includePaper: true, includePositions: true });
200
+ await client.getPortfolio(portfolioId);
201
+ ```
202
+
203
+ `listPortfolios` filters with `includePaper`, `includeLive`, `includeInactive`,
204
+ `includeChatPortfolios`, `search`, `limit`, and `page`. `includePositions`
205
+ defaults off when `search` is set.
206
+
207
+ **A portfolio you create here is always paper**, and minting a *live* one still
208
+ happens in the web app. Orders and brokerage status are reachable from here;
209
+ see [Live trading](#live-trading).
210
+
211
+ **But `deploy` can start live trading.** Given the id of a portfolio that is
212
+ already deployed, it reactivates that portfolio as whatever it already is — so
213
+ `client.deploy(id)` on a paused live portfolio resumes live trading against the connected
214
+ brokerage, and `includeLive: true` above will hand you such an id. Check `deployment.deploymentType` before
215
+ treating a deploy as simulated.
216
+
217
+ ## Live trading
218
+
219
+ Live trading needs a brokerage linked to your account. Linking is an OAuth
220
+ redirect, so an API key cannot complete it — a human opens the URL.
221
+
222
+ ```ts
223
+ await client.listBrokerages();
224
+ // [{ brokerage: "Alpaca", connected: false,
225
+ // connectUrl: "https://nexustrade.io/live-trading" }, ...]
226
+
227
+ await client.connectBrokerage("Alpaca"); // logs the URL, waits until connected
228
+ ```
229
+
230
+ `connectBrokerage` waits by default **only when stdout is a TTY**. In CI, cron,
231
+ or `run_compute` it rejects with `brokerage_not_connected` immediately, with the
232
+ URL in the message, rather than stalling for five minutes in front of nobody.
233
+ Pass `{ wait: true }` or `{ wait: false }` to force either.
234
+
235
+ A live-only listing that comes back empty rejects with the same error rather
236
+ than an empty array, since an empty array says nothing about why:
237
+
238
+ ```ts
239
+ await client.listPortfolios({ includeLive: true, includePaper: false });
240
+ // NexusTradeApiError: brokerage_not_connected: No live portfolios, and no
241
+ // brokerage is connected. Connect one at https://nexustrade.io/live-trading
242
+ ```
243
+
244
+ ### Orders
245
+
246
+ ```ts
247
+ const result = await client.createOrders(
248
+ portfolioId,
249
+ [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
250
+ side: "BUY", quantity: 10, orderType: "MARKET" }],
251
+ { idempotencyKey: "rebalance-2024-04-01" },
252
+ );
253
+ ```
254
+
255
+ **Paper orders are accepted immediately. Live orders are staged for approval
256
+ and are never sent to a broker by this call.**
257
+
258
+ ```ts
259
+ if (result.requiresApproval) {
260
+ console.log("nothing has traded yet — approve at", result.approvalUrl);
261
+ }
262
+ ```
263
+
264
+ There is no argument, scope, or flag that submits a live order without
265
+ approval. The brokerage boundary refuses an unapproved live order regardless of
266
+ what any caller asks for, so this is a property of the system rather than a
267
+ promise made by this method. At most 50 orders per request.
268
+
269
+ ## Your own data
270
+
271
+ A custom data source is a time series you own — sentiment counts, a proprietary
272
+ factor, anything the platform does not already carry. Create one, then reference
273
+ it from a strategy with `CustomIndicator`.
274
+
275
+ ```ts
276
+ const series = await client.createCustomIndicator(
277
+ {
278
+ name: "WSB NVDA Mentions",
279
+ scope: "asset",
280
+ description: "Daily r/wallstreetbets mentions",
281
+ points: [
282
+ { timestamp: "2024-04-01", value: 152, ticker: "NVDA" },
283
+ { timestamp: "2024-04-02", value: 90, ticker: "NVDA" },
284
+ ],
285
+ },
286
+ { idempotencyKey: "wsb-mentions-v1" },
287
+ );
288
+
289
+ const busy = nt.gt(
290
+ nt.CustomIndicator(nt.stockAsset("NVDA"), String(series.customIndicatorId)),
291
+ 100,
292
+ );
293
+ const book = nt.portfolio("Attention", [
294
+ nt.strategy("Buy the buzz", busy, nt.buy(nt.stockAsset("NVDA"), 25)),
295
+ ]);
296
+ ```
297
+
298
+ `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so every
299
+ point needs a `ticker`). It cannot be changed after creation.
300
+
301
+ **Size is not a constraint.** `points` is unlimited. A batch that fits the
302
+ request goes with it; a larger one is uploaded to storage and validated before
303
+ the call resolves. Either way the returned indicator reflects what actually
304
+ landed, and an upload that fails validation rejects rather than reporting
305
+ success.
306
+
307
+ **Growing a series.** Append to the same id every run:
308
+
309
+ ```ts
310
+ await client.appendCustomIndicatorPoints(
311
+ String(series.customIndicatorId),
312
+ [{ timestamp: "2024-04-03", value: 118, ticker: "NVDA" }],
313
+ { idempotencyKey: "wsb-mentions-2024-04-03" },
314
+ );
315
+ ```
316
+
317
+ Creating a fresh series per run splits the history into fragments no strategy
318
+ can read. Re-sending an identical batch is safe — the duplicate is not written
319
+ twice.
320
+
321
+ | Call | Purpose |
322
+ | --- | --- |
323
+ | `createCustomIndicator(spec, { idempotencyKey })` | Create, optionally seeded |
324
+ | `appendCustomIndicatorPoints(id, points, { idempotencyKey })` | Add points |
325
+ | `listCustomIndicators()` / `getCustomIndicator(id)` | Discover ids and coverage |
326
+
327
+ Points accept `timestamp`, `value`, `ticker`, `assetType`, and `availableAt`
328
+ — camelCase or snake_case, with `Date` objects allowed. Set `availableAt` when a
329
+ value became knowable later than it is dated: an earnings figure stamped to
330
+ quarter-end but published weeks after. An unrecognized field throws rather than
331
+ being silently dropped.
332
+
333
+ To hand over a file you already have on disk, `createCustomIndicatorUpload` /
334
+ `completeCustomIndicatorUpload` / `waitForCustomIndicatorUpload` expose the
335
+ three steps directly. CSV, JSON, and JSONL up to 100 MB.
336
+
337
+ ## Agent runs
338
+
339
+ Every other job is fire-and-poll. **Agents are not** — three states
340
+ (`pending_plan_approval`, `pending_action_approval`, `awaiting_user_input`)
341
+ cannot advance without you. Iterate the run and answer when it blocks:
342
+
343
+ ```mermaid
344
+ sequenceDiagram
345
+ participant You
346
+ participant Run as AgentRun
347
+ participant Engine
348
+
349
+ You->>Run: createAgent(prompt)
350
+ Run->>Engine: POST /agents
351
+ Engine-->>Run: run id
352
+
353
+ loop for await (const event of run)
354
+ Run->>Engine: GET events (cursor)
355
+ Engine-->>Run: new events
356
+
357
+ alt event.needsApproval
358
+ Run-->>You: plan or action awaiting approval
359
+ You->>Run: approve() or reject()
360
+ Run->>Engine: POST approval
361
+ else event.needsInput
362
+ Run-->>You: awaiting user input
363
+ You->>Run: say("...")
364
+ Run->>Engine: POST message
365
+ else
366
+ Run-->>You: event.text
367
+ end
368
+ end
369
+
370
+ Run-->>You: terminal
371
+
372
+ Note over You,Engine: Without approve/say, the run stalls and bills.<br/>Reattach later with attachAgent(run.id).
373
+ ```
374
+
375
+ ```ts
376
+ const run = await client.createAgent("Find momentum names in the S&P 500", {
377
+ idempotencyKey: "momentum-scan-v1",
378
+ });
379
+ for await (const event of run) {
380
+ console.log(event.text);
381
+ if (event.needsApproval) await run.approve();
382
+ if (event.needsInput) await run.say("Focus on tech");
383
+ }
145
384
  ```
146
385
 
147
386
  ## Lake SQL
@@ -150,8 +389,16 @@ Read-only SQL over the NexusTrade market-data lake, against the server-resolved
150
389
  `lake.*` catalog. Results are durable Parquet parts rather than an implicitly
151
390
  materialized in-memory array.
152
391
 
392
+ ```mermaid
393
+ flowchart LR
394
+ A[createLakeQuery] --> B[waitForLakeQuery]
395
+ B --> C[getLakeQueryManifest]
396
+ C --> D[downloadLakeQueryPart]
397
+ D --> E[Stream Parquet within your memory budget]
398
+ ```
399
+
153
400
  ```ts
154
- const query = await nt.createLakeQuery(
401
+ const query = await client.createLakeQuery(
155
402
  {
156
403
  query: "SELECT ticker, date, closingPrice FROM lake.daily_ohlc WHERE ticker = ?",
157
404
  params: ["AAPL"],
@@ -159,8 +406,8 @@ const query = await nt.createLakeQuery(
159
406
  },
160
407
  { idempotencyKey: "aapl-daily-v1" },
161
408
  );
162
- const finished = await nt.waitForLakeQuery(query.id as string);
163
- const manifest = await nt.getLakeQueryManifest(finished.id as string);
409
+ const finished = await client.waitForLakeQuery(query.id as string);
410
+ const manifest = await client.getLakeQueryManifest(finished.id as string);
164
411
  ```
165
412
 
166
413
  Use the manifest plus `downloadLakeQueryPart` to stream results within your own
@@ -170,13 +417,109 @@ tables; your SQL does not change when it does.
170
417
  > The Python SDK additionally ships `nt.lake.sql(...)`, a DuckDB/pandas
171
418
  > convenience layer over these same endpoints.
172
419
 
420
+ ## Complete method reference
421
+
422
+ Every public method on `NexusTradeClient`. A test in this package fails if one
423
+ is missing here, so this list cannot drift from the code.
424
+
425
+ **Live trading and orders**
426
+
427
+ | Method | Purpose |
428
+ | --- | --- |
429
+ | `listBrokerages()` | Every connectable brokerage and whether it is linked |
430
+ | `getBrokerage(brokerage)` | Whether one brokerage is linked |
431
+ | `connectBrokerage(brokerage, { wait })` | Log the connect URL and wait for the link |
432
+ | `createOrders(portfolioId, orders, { idempotencyKey })` | Stage orders; live ones need approval |
433
+
434
+ **Portfolios**
435
+
436
+ | Method | Purpose |
437
+ | --- | --- |
438
+ | `createPortfolio(book, { idempotencyKey })` | Persist a portfolio definition |
439
+ | `listPortfolios(options)` | List portfolios, with filters and pagination |
440
+ | `getPortfolio(portfolioId)` | Read one portfolio |
441
+ | `deploy(portfolioId, { frequency })` | Start paper trading it |
442
+ | `undeploy(portfolioId)` | Stop it |
443
+
444
+ **Backtests**
445
+
446
+ | Method | Purpose |
447
+ | --- | --- |
448
+ | `createBacktest(handle, { idempotencyKey })` | Submit one backtest |
449
+ | `createBacktests(handles, { idempotencyKey })` | Submit many in one request |
450
+ | `getBacktest(backtestId)` | Read the operation |
451
+ | `waitForBacktest(backtestId, options)` | Block until terminal |
452
+ | `waitForBacktests(operations, options)` | Block on a whole batch |
453
+
454
+ **Optimization and walk-forward**
455
+
456
+ | Method | Purpose |
457
+ | --- | --- |
458
+ | `createOptimization(handle, { idempotencyKey })` | Submit an optimization |
459
+ | `getOptimization(optimizationId)` | Read the operation |
460
+ | `waitForOptimization(optimizationId, options)` | Block until terminal |
461
+ | `createWalkForward(handle, { idempotencyKey })` | Submit a walk-forward study |
462
+ | `getWalkForward(studyId)` | Read the operation |
463
+ | `waitForWalkForward(studyId, options)` | Block until terminal |
464
+
465
+ **Custom data sources**
466
+
467
+ | Method | Purpose |
468
+ | --- | --- |
469
+ | `createCustomIndicator(spec, { idempotencyKey })` | Create a series, optionally seeded |
470
+ | `listCustomIndicators(options)` | List owned series |
471
+ | `getCustomIndicator(id)` | Read one, with its point count and range |
472
+ | `appendCustomIndicatorPoints(id, points, { idempotencyKey })` | Add points |
473
+ | `createCustomIndicatorUpload(id, options)` | Open an upload slot (CSV/JSON/JSONL) |
474
+ | `completeCustomIndicatorUpload(id, jobId)` | Start validating uploaded bytes |
475
+ | `getCustomIndicatorUpload(id, jobId)` | Read the upload operation |
476
+ | `waitForCustomIndicatorUpload(id, jobId, options)` | Block until validated |
477
+
478
+ **Agent runs**
479
+
480
+ | Method | Purpose |
481
+ | --- | --- |
482
+ | `createAgent(prompt, { idempotencyKey })` | Start a run |
483
+ | `getAgent(agentId)` | Read its status |
484
+ | `attachAgent(agentId, { cursor })` | Reattach to a run already in flight |
485
+
486
+ **Lake SQL**
487
+
488
+ | Method | Purpose |
489
+ | --- | --- |
490
+ | `createLakeQuery(request, { idempotencyKey })` | Submit read-only SQL |
491
+ | `getLakeQuery(queryId)` | Read the operation |
492
+ | `waitForLakeQuery(queryId, options)` | Block until terminal |
493
+ | `cancelLakeQuery(queryId)` | Cancel an owned query |
494
+ | `getLakeQueryManifest(queryId)` | Schema, checksums, and part metadata |
495
+ | `downloadLakeQueryPart(queryId, part, options)` | Download one Parquet part |
496
+ | `getLakeCatalog()` | List queryable tables |
497
+ | `describeLakeTable(table)` | Columns and types for one table |
498
+
499
+ **Client construction**
500
+
501
+ | Method | Purpose |
502
+ | --- | --- |
503
+ | `new NexusTradeClient({ apiKey, baseUrl })` | Explicit credentials |
504
+ | `NexusTradeClient.fromEnvironment()` | Read them from the environment or `.env` |
505
+
506
+ **PortfolioHandle** — returned by the `portfolio(...)` builder and by
507
+ `getPortfolio` / `listPortfolios`.
508
+
509
+ | Method | Purpose |
510
+ | --- | --- |
511
+ | `save({ idempotencyKey })` | Persist it as a draft, setting `.id` |
512
+ | `backtest({ startDate, endDate, idempotencyKey })` | Backtest it, preferring the saved id |
513
+ | `deploy({ frequency })` | Mint the real paper portfolio (new id) |
514
+ | `undeploy()` | Deactivate its deployment |
515
+
173
516
  ## Authentication
174
517
 
175
518
  Create a key at **[nexustrade.io/developers](https://nexustrade.io/developers)**
176
519
  (Profile → API Keys). Keys start with `sk-` and are shown once.
177
520
 
178
521
  ```ts
179
- const nt = new NexusTradeClient({
522
+ const client = new NexusTradeClient({
180
523
  apiKey: "sk-...",
181
524
  baseUrl: "https://nexustrade.io/api/v1",
182
525
  });
@@ -223,7 +566,7 @@ the original resource instead of launching a second paid job — so a retry afte
223
566
  a network failure is free.
224
567
 
225
568
  ```ts
226
- await nt.createBacktest(handle, { idempotencyKey: "momentum-2024-v1" });
569
+ await client.createBacktest(handle, { idempotencyKey: "momentum-2024-v1" });
227
570
  ```
228
571
 
229
572
  ## Errors
@@ -232,7 +575,7 @@ await nt.createBacktest(handle, { idempotencyKey: "momentum-2024-v1" });
232
575
  import { NexusTradeApiError } from "nexustrade";
233
576
 
234
577
  try {
235
- await nt.createBacktest(handle, { idempotencyKey: "run-1" });
578
+ await client.createBacktest(handle, { idempotencyKey: "run-1" });
236
579
  } catch (error) {
237
580
  if (error instanceof NexusTradeApiError && error.code === "rate_limit_exceeded") {
238
581
  // back off
@@ -248,6 +591,7 @@ try {
248
591
  | 400 | `invalid_request`, `invalid_portfolio` | Malformed input |
249
592
  | 400 | `invalid_idempotency_key` | Must match `[A-Za-z0-9._:-]{1,160}` |
250
593
  | 409 | `idempotency_conflict` | Key reused with a different payload |
594
+ | 409 | `idempotency_in_progress` | Same key, first call still running. Re-poll, do not resubmit |
251
595
  | 404 | `not_found`, `operation_not_found` | Unknown or not yours |
252
596
  | 429 | `rate_limit_exceeded` | Back off and retry |
253
597
 
@@ -265,7 +609,10 @@ deadline for one request. Neither it nor the poll timeout bounds how long a
265
609
 
266
610
  Portfolio drafting, backtesting, optimization, walk-forward studies, and
267
611
  read-only SQL over the market-data lake, versioned under `/api/v1/nexustrade`.
268
- The screener and live trading remain outside this surface.
612
+ The screener and creating a live deployment remain outside this surface.
613
+ Orders are reachable, but a live order is only ever staged for human approval —
614
+ never submitted. `deploy` and `undeploy` act on whatever an existing id already
615
+ is, live included.
269
616
 
270
617
  ## Requirements
271
618
 
package/dist/cjs/agent.js CHANGED
@@ -20,8 +20,6 @@
20
20
  * if (event.needsApproval) await run.approve();
21
21
  * }
22
22
  * ```
23
- *
24
- * Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
25
23
  */
26
24
  Object.defineProperty(exports, "__esModule", { value: true });
27
25
  exports.AgentRun = void 0;
@@ -38,9 +36,8 @@ class AgentRun {
38
36
  /** Every event yielded so far, in order. */
39
37
  events = [];
40
38
  /**
41
- * Pacing, public and mutable to mirror the Python dataclass fields. Tests
42
- * collapse the backoff through these; callers can widen the timeout on a run
43
- * they expect to sit blocked for a while.
39
+ * Polling pacing. Mutable so callers can widen the timeout on a run they
40
+ * expect to sit blocked for a while.
44
41
  */
45
42
  timeoutSeconds;
46
43
  pollIntervalSeconds;
@@ -49,6 +46,14 @@ class AgentRun {
49
46
  #transport;
50
47
  #cursor = null;
51
48
  #seen = new Map();
49
+ /**
50
+ * Advances only after a POST is acknowledged, so a retry of a call that
51
+ * failed reuses its key and is deduped, while two different calls never
52
+ * collide. Keying on `events.length` did the latter wrong: two messages sent
53
+ * without iterating between them shared a key and the second was rejected as
54
+ * an idempotency conflict.
55
+ */
56
+ #actionSeq = 0;
52
57
  constructor(id, transport, status = "initializing", options = {}) {
53
58
  this.id = id;
54
59
  this.status = status;
@@ -209,8 +214,9 @@ class AgentRun {
209
214
  async #post(action, body = {}) {
210
215
  const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
211
216
  body,
212
- idempotencyKey: `${this.id}:${action}:${this.events.length}`,
217
+ idempotencyKey: `${this.id}:${action}:${this.#actionSeq}`,
213
218
  });
219
+ this.#actionSeq += 1;
214
220
  const agent = response.agent;
215
221
  if (agent && typeof agent === "object" && !Array.isArray(agent)) {
216
222
  const status = agent.status;