nexustrade 1.0.0 → 1.2.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 +49 -3
- package/README.md +361 -63
- package/dist/cjs/client.js +382 -9
- package/dist/cjs/generated/ntSdk.generated.js +51 -0
- package/dist/esm/client.d.ts +98 -0
- package/dist/esm/client.js +381 -8
- package/dist/esm/generated/ntSdk.generated.d.ts +51 -4
- package/dist/esm/generated/ntSdk.generated.js +47 -0
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -136,6 +136,15 @@ await client.createCustomIndicator(
|
|
|
136
136
|
Point batches are unlimited in size; the SDK sends them inline or uploads them.
|
|
137
137
|
Do not chunk by hand.
|
|
138
138
|
|
|
139
|
+
Declare `pointKind: "observation"` for point-in-time samples so date-only rows
|
|
140
|
+
retain same-day UTC availability on both inline and large-upload paths. Use
|
|
141
|
+
`period_aggregate` plus `aggregatePeriod` for closed periods, or `disclosed`
|
|
142
|
+
with per-row publication times.
|
|
143
|
+
|
|
144
|
+
For daily market prices, prefer `lake.query("sec_daily_ohlc", ...)` or the
|
|
145
|
+
canonical OHLC helper. `daily_ohlc` is a legacy/vendor table and may lag the
|
|
146
|
+
canonical daily series.
|
|
147
|
+
|
|
139
148
|
## Recipes
|
|
140
149
|
|
|
141
150
|
<details open>
|
|
@@ -284,12 +293,49 @@ All failures throw `NexusTradeApiError` with a stable `.status`, `.code`, and
|
|
|
284
293
|
`status === 0` means no HTTP status applies: the request never reached the API
|
|
285
294
|
(`transport_error`), or the reply failed an envelope check.
|
|
286
295
|
|
|
287
|
-
##
|
|
296
|
+
## What is and is not here
|
|
297
|
+
|
|
298
|
+
**Deploying a portfolio IS supported.** `book.save(...)` persists it and
|
|
299
|
+
`book.deploy(...)` starts paper trading it; `client.deploy(portfolioId)` does
|
|
300
|
+
the same from an id. `save` and `deploy` return *different* ids — deploying
|
|
301
|
+
mints a portfolio rather than converting the draft.
|
|
302
|
+
|
|
303
|
+
**`deploy` is not always paper.** A portfolio this SDK creates is always paper:
|
|
304
|
+
the portfolio spec has no deployment field, so there is no way to ask for a
|
|
305
|
+
live one. But `deploy(portfolioId)` accepts the id of a portfolio that is
|
|
306
|
+
*already deployed*, and then it reactivates that portfolio as whatever it
|
|
307
|
+
already is. Hand it the id of a paused **live** portfolio — `listPortfolios`
|
|
308
|
+
will return one under `includeLive: true` — and it resumes live trading against
|
|
309
|
+
the connected brokerage. `undeploy` is the same in reverse. Read
|
|
310
|
+
`deploymentType` on the response to know which one you got, and treat any id
|
|
311
|
+
you did not create in this session as possibly live.
|
|
288
312
|
|
|
289
313
|
Not in this SDK. Do not attempt to reach them through it:
|
|
290
314
|
|
|
291
|
-
-
|
|
292
|
-
|
|
315
|
+
- ~~**Screener** — MCP only.~~ **The screener is here now:**
|
|
316
|
+
`client.createNlScreen("...")` + `waitForNlScreen(id)` turns a plain-language
|
|
317
|
+
question into validated `lake.*` SQL, runs it, and returns the rows *and the
|
|
318
|
+
statement*. Prefer it over hand-writing SQL for stock selection — the server
|
|
319
|
+
picks tables from the same catalog the validator enforces, so it cannot name
|
|
320
|
+
a column that does not exist. Fall back to `createLakeQuery` only when
|
|
321
|
+
`outcome === "GENERATION_FAILED"`, or when the question is not a stock
|
|
322
|
+
screen. `EMPTY` is an answer, not a fallback trigger, and `CLARIFICATION`
|
|
323
|
+
means the question was ambiguous — answer it rather than guessing SQL. Always
|
|
324
|
+
report `result.sql`: it is model-generated, so it is the only way anyone can
|
|
325
|
+
check the numbers. Spends LLM credits; the lake API does not.
|
|
326
|
+
- **Submitting a live order** — impossible from anywhere, not just here. Live
|
|
327
|
+
orders are staged `PENDING_USER_APPROVAL` and a human approves them in the
|
|
328
|
+
UI; the brokerage boundary refuses an unapproved live order regardless of
|
|
329
|
+
caller. `createOrders` stages them, it does not send them.
|
|
330
|
+
- **Minting a live portfolio, and connecting a brokerage** — both happen in the
|
|
331
|
+
web app. No route under the SDK prefix creates a live deployment; see above
|
|
332
|
+
for reactivating a live portfolio that already exists.
|
|
333
|
+
|
|
334
|
+
The complete method list — every client and handle method, including the ones
|
|
335
|
+
without a worked example above — is the **Complete method reference** table in
|
|
336
|
+
[README.md](README.md#complete-method-reference). A test fails if any public
|
|
337
|
+
method is missing from it, so it is exhaustive by construction rather than by
|
|
338
|
+
maintenance.
|
|
293
339
|
|
|
294
340
|
## Verifying your work
|
|
295
341
|
|
package/README.md
CHANGED
|
@@ -27,7 +27,13 @@ npm install nexustrade
|
|
|
27
27
|
|
|
28
28
|
```ts
|
|
29
29
|
import {
|
|
30
|
-
NexusTradeClient,
|
|
30
|
+
NexusTradeClient,
|
|
31
|
+
always,
|
|
32
|
+
backtest,
|
|
33
|
+
buy,
|
|
34
|
+
portfolio,
|
|
35
|
+
stockAsset,
|
|
36
|
+
strategy,
|
|
31
37
|
} from "nexustrade";
|
|
32
38
|
|
|
33
39
|
const client = new NexusTradeClient({
|
|
@@ -41,12 +47,16 @@ const book = portfolio("Example", [
|
|
|
41
47
|
|
|
42
48
|
const operation = await client.createBacktest(
|
|
43
49
|
backtest(book, { startDate: "2024-01-01", endDate: "2024-12-31" }),
|
|
44
|
-
{ idempotencyKey: "example-v1" }
|
|
50
|
+
{ idempotencyKey: "example-v1" }
|
|
45
51
|
);
|
|
46
52
|
const result = await client.waitForBacktest(operation.id as string);
|
|
47
53
|
console.log(result.result);
|
|
48
54
|
```
|
|
49
55
|
|
|
56
|
+
Backtest operations may include `warnings: string[]` immediately after
|
|
57
|
+
submission and again in the terminal `result`. Treat them as material caveats;
|
|
58
|
+
they do not change a successful operation into a failure.
|
|
59
|
+
|
|
50
60
|
## Authoring strategies
|
|
51
61
|
|
|
52
62
|
Every builder is generated from the same indicator specification the NexusTrade
|
|
@@ -58,38 +68,42 @@ TypeScript cannot overload comparison operators, so indicators compose through
|
|
|
58
68
|
```ts
|
|
59
69
|
import * as nt from "nexustrade";
|
|
60
70
|
|
|
61
|
-
const book = nt.portfolio(
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
nt.
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
71
|
+
const book = nt.portfolio(
|
|
72
|
+
"Momentum",
|
|
73
|
+
[
|
|
74
|
+
nt.strategy(
|
|
75
|
+
"Rotate into strength",
|
|
76
|
+
nt.always(),
|
|
77
|
+
nt.dynamicRebalance({
|
|
78
|
+
universe: nt.universe("SP500"),
|
|
79
|
+
pipeline: [
|
|
80
|
+
nt.filter(nt.gt(nt.Price(nt.CANDIDATE), nt.SMA(nt.CANDIDATE, 200))),
|
|
81
|
+
nt.selectTop(nt.RSI(nt.CANDIDATE, 14), 10),
|
|
82
|
+
],
|
|
83
|
+
weightIndicator: nt.RSI(nt.CANDIDATE, 14),
|
|
84
|
+
limit: 10,
|
|
85
|
+
deploymentPercent: 80,
|
|
86
|
+
})
|
|
87
|
+
),
|
|
88
|
+
],
|
|
89
|
+
{ initialValue: 100_000 }
|
|
90
|
+
);
|
|
77
91
|
```
|
|
78
92
|
|
|
79
93
|
<details>
|
|
80
94
|
<summary><b>What you can build</b> — 170+ generated builders</summary>
|
|
81
95
|
|
|
82
|
-
| Group
|
|
83
|
-
|
|
|
84
|
-
| **Price & volume**
|
|
85
|
-
| **Technicals**
|
|
86
|
-
| **Position state**
|
|
87
|
-
| **Portfolio state** | `PortfolioValue` `BuyingPower` `MaxDrawdown` `InitialValue`
|
|
88
|
-
| **Fundamentals**
|
|
89
|
-
| **Options**
|
|
90
|
-
| **Actions**
|
|
91
|
-
| **Selection**
|
|
92
|
-
| **Logic**
|
|
96
|
+
| Group | Examples |
|
|
97
|
+
| ------------------- | -------------------------------------------------------------------------------------------- |
|
|
98
|
+
| **Price & volume** | `Price` `OpeningPrice` `HighOfDay` `VWAP` `Volume` `GapPercentage` |
|
|
99
|
+
| **Technicals** | `SMA` `EMA` `RSI` `BollingerBand` `AverageTrueRange` `CrossAbove` |
|
|
100
|
+
| **Position state** | `PositionValue` `PositionPercentChange` `PositionMaxDrawdown` |
|
|
101
|
+
| **Portfolio state** | `PortfolioValue` `BuyingPower` `MaxDrawdown` `InitialValue` |
|
|
102
|
+
| **Fundamentals** | `Fundamental` `Economic` `DaysUntilEarnings` `IsIndexMember` `IsIndustry` |
|
|
103
|
+
| **Options** | `OptionDaysToExpiration` `OptionCollateral` `OptionUnrealizedPnL` `openOption` `closeOption` |
|
|
104
|
+
| **Actions** | `buy` `sell` `alert` `dynamicRebalance` `rebalanceOption` |
|
|
105
|
+
| **Selection** | `filter` `selectTop` `selectPercentile` `universe` |
|
|
106
|
+
| **Logic** | `always` `atLeast` `atMost` `exactly` `fewerThan` `multi` `and` `or` |
|
|
93
107
|
|
|
94
108
|
Every builder is fully typed — your editor completes the whole surface.
|
|
95
109
|
|
|
@@ -137,12 +151,12 @@ Every job kind reports the same envelope, so one poller serves all of them:
|
|
|
137
151
|
const finished = await client.waitForBacktest(operation.id as string);
|
|
138
152
|
```
|
|
139
153
|
|
|
140
|
-
| Option
|
|
141
|
-
|
|
|
142
|
-
| `timeoutSeconds`
|
|
143
|
-
| `pollIntervalSeconds`
|
|
144
|
-
| `maxPollIntervalSeconds` | `15`
|
|
145
|
-
| `throwOnFailure`
|
|
154
|
+
| Option | Default | Meaning |
|
|
155
|
+
| ------------------------ | ------- | -------------------------------------------------- |
|
|
156
|
+
| `timeoutSeconds` | `900` | Give up waiting (the job keeps running) |
|
|
157
|
+
| `pollIntervalSeconds` | `2` | First interval; backs off 1.5× |
|
|
158
|
+
| `maxPollIntervalSeconds` | `15` | Interval ceiling |
|
|
159
|
+
| `throwOnFailure` | `true` | Throw on `failed`/`cancelled` instead of returning |
|
|
146
160
|
|
|
147
161
|
A timeout throws `operation_timeout` and does **not** cancel the job — call the
|
|
148
162
|
waiter again with the same id rather than resubmitting.
|
|
@@ -160,11 +174,134 @@ const study = await client.createWalkForward(
|
|
|
160
174
|
globalEndDate: "2024-12-31",
|
|
161
175
|
foldCount: 4,
|
|
162
176
|
}),
|
|
163
|
-
{ idempotencyKey: "wf-v1" }
|
|
177
|
+
{ idempotencyKey: "wf-v1" }
|
|
164
178
|
);
|
|
165
179
|
await client.waitForWalkForward(study.id as string);
|
|
166
180
|
```
|
|
167
181
|
|
|
182
|
+
## Deploying a portfolio
|
|
183
|
+
|
|
184
|
+
Authoring and backtesting a book does not persist it. `save` writes it to your
|
|
185
|
+
account; `deploy` starts running it.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
const book = nt.portfolio("Momentum", [
|
|
189
|
+
/* … */
|
|
190
|
+
]);
|
|
191
|
+
|
|
192
|
+
await book.save({ idempotencyKey: "momentum-v1" }); // persists; sets book.id
|
|
193
|
+
const deployment = await book.deploy(); // starts paper trading
|
|
194
|
+
await book.undeploy(); // stops it
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
**`save` and `deploy` produce different ids, and the distinction matters.**
|
|
198
|
+
`save` persists a _draft_ and sets `book.id` to it. `deploy` mints the real
|
|
199
|
+
paper portfolio and returns its own `portfolioId` — deploying creates a
|
|
200
|
+
portfolio rather than converting the draft into one, so the two ids coexist.
|
|
201
|
+
Hold on to `deployment.portfolioId` for anything that reads live state;
|
|
202
|
+
`book.id` addresses the draft.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
deployment.portfolioId; // the running portfolio
|
|
206
|
+
deployment.deploymentType; // paper, unless you deployed an existing live one
|
|
207
|
+
deployment.outcome; // created | reactivated
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
Handle methods accept an optional `transport`; omitted, they resolve one from
|
|
211
|
+
the environment. The same operations exist on the client — `client.deploy(id)`,
|
|
212
|
+
`client.undeploy(id)` — when you have an id rather than a handle.
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
await client.listPortfolios({ includePaper: true, includePositions: true });
|
|
216
|
+
await client.getPortfolio(portfolioId);
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`listPortfolios` filters with `includePaper`, `includeLive`, `includeInactive`,
|
|
220
|
+
`includeChatPortfolios`, `search`, `limit`, and `page`. `includePositions`
|
|
221
|
+
defaults off when `search` is set.
|
|
222
|
+
|
|
223
|
+
**A portfolio you create here is always paper**, and minting a _live_ one still
|
|
224
|
+
happens in the web app. Orders and brokerage status are reachable from here;
|
|
225
|
+
see [Live trading](#live-trading).
|
|
226
|
+
|
|
227
|
+
**But `deploy` can start live trading.** Given the id of a portfolio that is
|
|
228
|
+
already deployed, it reactivates that portfolio as whatever it already is — so
|
|
229
|
+
`client.deploy(id)` on a paused live portfolio resumes live trading against the connected
|
|
230
|
+
brokerage, and `includeLive: true` above will hand you such an id. Check `deployment.deploymentType` before
|
|
231
|
+
treating a deploy as simulated.
|
|
232
|
+
|
|
233
|
+
## Live trading
|
|
234
|
+
|
|
235
|
+
Live trading needs a brokerage linked to your account. Linking is an OAuth
|
|
236
|
+
redirect, so an API key cannot complete it — a human opens the URL.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
await client.listBrokerages();
|
|
240
|
+
// [{ brokerage: "Alpaca", connected: false,
|
|
241
|
+
// connectUrl: "https://nexustrade.io/live-trading" }, ...]
|
|
242
|
+
|
|
243
|
+
await client.connectBrokerage("Alpaca"); // logs the URL, waits until connected
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
`connectBrokerage` waits by default **only when stdout is a TTY**. In CI, cron,
|
|
247
|
+
or `run_compute` it rejects with `brokerage_not_connected` immediately, with the
|
|
248
|
+
URL in the message, rather than stalling for five minutes in front of nobody.
|
|
249
|
+
Pass `{ wait: true }` or `{ wait: false }` to force either.
|
|
250
|
+
|
|
251
|
+
A live-only listing that comes back empty rejects with the same error rather
|
|
252
|
+
than an empty array, since an empty array says nothing about why:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
await client.listPortfolios({ includeLive: true, includePaper: false });
|
|
256
|
+
// NexusTradeApiError: brokerage_not_connected: No live portfolios, and no
|
|
257
|
+
// brokerage is connected. Connect one at https://nexustrade.io/live-trading
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### Orders
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
const result = await client.createOrders(
|
|
264
|
+
portfolioId,
|
|
265
|
+
[
|
|
266
|
+
{
|
|
267
|
+
asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
|
|
268
|
+
side: "BUY",
|
|
269
|
+
quantity: 10,
|
|
270
|
+
orderType: "MARKET",
|
|
271
|
+
},
|
|
272
|
+
],
|
|
273
|
+
{ idempotencyKey: "rebalance-2024-04-01" }
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
// Dollar notional (stock/crypto only — options require contract quantity):
|
|
277
|
+
await client.createOrders(
|
|
278
|
+
portfolioId,
|
|
279
|
+
[
|
|
280
|
+
{
|
|
281
|
+
asset: { name: "AAPL", type: "STOCK", symbol: "AAPL" },
|
|
282
|
+
side: "BUY",
|
|
283
|
+
amount: 500,
|
|
284
|
+
orderType: "MARKET",
|
|
285
|
+
},
|
|
286
|
+
],
|
|
287
|
+
{ idempotencyKey: "buy-aapl-500" }
|
|
288
|
+
);
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
**Paper orders are accepted immediately. Live orders are staged for approval
|
|
292
|
+
and are never sent to a broker by this call.**
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
if (result.requiresApproval) {
|
|
296
|
+
console.log("nothing has traded yet — approve at", result.approvalUrl);
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
There is no argument, scope, or flag that submits a live order without
|
|
301
|
+
approval. The brokerage boundary refuses an unapproved live order regardless of
|
|
302
|
+
what any caller asks for, so this is a property of the system rather than a
|
|
303
|
+
promise made by this method. At most 50 orders per request.
|
|
304
|
+
|
|
168
305
|
## Your own data
|
|
169
306
|
|
|
170
307
|
A custom data source is a time series you own — sentiment counts, a proprietary
|
|
@@ -177,17 +314,18 @@ const series = await client.createCustomIndicator(
|
|
|
177
314
|
name: "WSB NVDA Mentions",
|
|
178
315
|
scope: "asset",
|
|
179
316
|
description: "Daily r/wallstreetbets mentions",
|
|
317
|
+
pointKind: "observation",
|
|
180
318
|
points: [
|
|
181
319
|
{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" },
|
|
182
320
|
{ timestamp: "2024-04-02", value: 90, ticker: "NVDA" },
|
|
183
321
|
],
|
|
184
322
|
},
|
|
185
|
-
{ idempotencyKey: "wsb-mentions-v1" }
|
|
323
|
+
{ idempotencyKey: "wsb-mentions-v1" }
|
|
186
324
|
);
|
|
187
325
|
|
|
188
326
|
const busy = nt.gt(
|
|
189
327
|
nt.CustomIndicator(nt.stockAsset("NVDA"), String(series.customIndicatorId)),
|
|
190
|
-
100
|
|
328
|
+
100
|
|
191
329
|
);
|
|
192
330
|
const book = nt.portfolio("Attention", [
|
|
193
331
|
nt.strategy("Buy the buzz", busy, nt.buy(nt.stockAsset("NVDA"), 25)),
|
|
@@ -197,6 +335,13 @@ const book = nt.portfolio("Attention", [
|
|
|
197
335
|
`scope` is `"global"` (one series) or `"asset"` (one series per ticker, so every
|
|
198
336
|
point needs a `ticker`). It cannot be changed after creation.
|
|
199
337
|
|
|
338
|
+
Declare `pointKind` whenever the time semantics are known: `observation` for
|
|
339
|
+
point-in-time samples, `period_aggregate` plus `aggregatePeriod` (`1d`, `1w`,
|
|
340
|
+
`1mo`, or `1q`) for closed-period values, and `disclosed` for values with an
|
|
341
|
+
explicit publication time on every row. The SDK applies this contract before
|
|
342
|
+
both inline and large-upload writes. A same-day date-only observation becomes
|
|
343
|
+
an explicit same-day UTC instant instead of shifting to the next calendar day.
|
|
344
|
+
|
|
200
345
|
**Size is not a constraint.** `points` is unlimited. A batch that fits the
|
|
201
346
|
request goes with it; a larger one is uploaded to storage and validated before
|
|
202
347
|
the call resolves. Either way the returned indicator reflects what actually
|
|
@@ -209,7 +354,7 @@ success.
|
|
|
209
354
|
await client.appendCustomIndicatorPoints(
|
|
210
355
|
String(series.customIndicatorId),
|
|
211
356
|
[{ timestamp: "2024-04-03", value: 118, ticker: "NVDA" }],
|
|
212
|
-
{ idempotencyKey: "wsb-mentions-2024-04-03" }
|
|
357
|
+
{ idempotencyKey: "wsb-mentions-2024-04-03" }
|
|
213
358
|
);
|
|
214
359
|
```
|
|
215
360
|
|
|
@@ -217,11 +362,13 @@ Creating a fresh series per run splits the history into fragments no strategy
|
|
|
217
362
|
can read. Re-sending an identical batch is safe — the duplicate is not written
|
|
218
363
|
twice.
|
|
219
364
|
|
|
220
|
-
| Call
|
|
221
|
-
|
|
|
222
|
-
| `createCustomIndicator(spec, { idempotencyKey })`
|
|
223
|
-
| `appendCustomIndicatorPoints(id, points, { idempotencyKey })` | Add points
|
|
224
|
-
| `
|
|
365
|
+
| Call | Purpose |
|
|
366
|
+
| ------------------------------------------------------------- | ------------------------- |
|
|
367
|
+
| `createCustomIndicator(spec, { idempotencyKey })` | Create, optionally seeded |
|
|
368
|
+
| `appendCustomIndicatorPoints(id, points, { idempotencyKey })` | Add points |
|
|
369
|
+
| `replaceCustomIndicatorPoints(id, points, { idempotencyKey })` | Replace points, retain id |
|
|
370
|
+
| `archiveCustomIndicator(id)` / `restoreCustomIndicator(id)` | Reversible lifecycle |
|
|
371
|
+
| `listCustomIndicators()` / `getCustomIndicator(id)` | Discover ids and coverage |
|
|
225
372
|
|
|
226
373
|
Points accept `timestamp`, `value`, `ticker`, `assetType`, and `availableAt`
|
|
227
374
|
— camelCase or snake_case, with `Date` objects allowed. Set `availableAt` when a
|
|
@@ -299,16 +446,49 @@ flowchart LR
|
|
|
299
446
|
```ts
|
|
300
447
|
const query = await client.createLakeQuery(
|
|
301
448
|
{
|
|
302
|
-
query:
|
|
449
|
+
query:
|
|
450
|
+
"SELECT ticker, date, closingPrice FROM lake.daily_ohlc WHERE ticker = ?",
|
|
303
451
|
params: ["AAPL"],
|
|
304
452
|
limits: { maxRows: 10_000 },
|
|
305
453
|
},
|
|
306
|
-
{ idempotencyKey: "aapl-daily-v1" }
|
|
454
|
+
{ idempotencyKey: "aapl-daily-v1" }
|
|
307
455
|
);
|
|
308
456
|
const finished = await client.waitForLakeQuery(query.id as string);
|
|
309
457
|
const manifest = await client.getLakeQueryManifest(finished.id as string);
|
|
310
458
|
```
|
|
311
459
|
|
|
460
|
+
## Natural language
|
|
461
|
+
|
|
462
|
+
Describe the screen instead of writing the SQL. The server generates it,
|
|
463
|
+
validates it against the same `lake.*` catalog the engine reads, executes it,
|
|
464
|
+
and hands back both the rows and the statement.
|
|
465
|
+
|
|
466
|
+
```ts
|
|
467
|
+
const screen = await client.createNlScreen(
|
|
468
|
+
"technology stocks with a market cap over 100 billion and a PE under 30"
|
|
469
|
+
);
|
|
470
|
+
const done = await client.waitForNlScreen(screen.id as string);
|
|
471
|
+
|
|
472
|
+
const result = done.result as Record<string, unknown>;
|
|
473
|
+
console.log(result.rows);
|
|
474
|
+
console.log(result.sql); // always check the SQL — it is model-generated
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
`returnQuery` defaults to `true` because the SQL is the audit trail: without it
|
|
478
|
+
the rows are a number you cannot re-derive. It is returned on failure whatever
|
|
479
|
+
you pass, since a rejected query is the most useful thing to read.
|
|
480
|
+
|
|
481
|
+
Branch on `result.outcome`, not on status alone:
|
|
482
|
+
|
|
483
|
+
| `outcome` | Meaning |
|
|
484
|
+
| ------------------- | --------------------------------------------------------- |
|
|
485
|
+
| `ROWS` | Matches found |
|
|
486
|
+
| `EMPTY` | Every filter ran and nothing cleared them all — an answer |
|
|
487
|
+
| `CLARIFICATION` | The question was ambiguous; `result.clarification` asks |
|
|
488
|
+
| `GENERATION_FAILED` | The retry budget was spent — the only case worth retrying |
|
|
489
|
+
|
|
490
|
+
This method spends LLM credits. The structured `lake` API below does not.
|
|
491
|
+
|
|
312
492
|
Use the manifest plus `downloadLakeQueryPart` to stream results within your own
|
|
313
493
|
memory budget. NexusTrade picks a compatible backing engine for the referenced
|
|
314
494
|
tables; your SQL does not change when it does.
|
|
@@ -316,6 +496,118 @@ tables; your SQL does not change when it does.
|
|
|
316
496
|
> The Python SDK additionally ships `nt.lake.sql(...)`, a DuckDB/pandas
|
|
317
497
|
> convenience layer over these same endpoints.
|
|
318
498
|
|
|
499
|
+
## Complete method reference
|
|
500
|
+
|
|
501
|
+
Every public method on `NexusTradeClient`. A test in this package fails if one
|
|
502
|
+
is missing here, so this list cannot drift from the code.
|
|
503
|
+
|
|
504
|
+
**Live trading and orders**
|
|
505
|
+
|
|
506
|
+
| Method | Purpose |
|
|
507
|
+
| ------------------------------------------------------- | ---------------------------------------------------- |
|
|
508
|
+
| `listBrokerages()` | Every connectable brokerage and whether it is linked |
|
|
509
|
+
| `getBrokerage(brokerage)` | Whether one brokerage is linked |
|
|
510
|
+
| `connectBrokerage(brokerage, { wait })` | Log the connect URL and wait for the link |
|
|
511
|
+
| `createOrders(portfolioId, orders, { idempotencyKey })` | Stage orders; live ones need approval |
|
|
512
|
+
|
|
513
|
+
**Portfolios**
|
|
514
|
+
|
|
515
|
+
| Method | Purpose |
|
|
516
|
+
| ------------------------------------------- | -------------------------------------------- |
|
|
517
|
+
| `createPortfolio(book, { idempotencyKey })` | Persist a portfolio definition |
|
|
518
|
+
| `listPortfolios(options)` | List portfolios, with filters and pagination |
|
|
519
|
+
| `getPortfolio(portfolioId)` | Read one portfolio |
|
|
520
|
+
| `deploy(portfolioId, { frequency })` | Start paper trading it |
|
|
521
|
+
| `undeploy(portfolioId)` | Stop it |
|
|
522
|
+
|
|
523
|
+
**Backtests**
|
|
524
|
+
|
|
525
|
+
| Method | Purpose |
|
|
526
|
+
| ---------------------------------------------- | -------------------------- |
|
|
527
|
+
| `createBacktest(handle, { idempotencyKey })` | Submit one backtest |
|
|
528
|
+
| `createBacktests(handles, { idempotencyKey })` | Submit many in one request |
|
|
529
|
+
| `getBacktest(backtestId)` | Read the operation |
|
|
530
|
+
| `waitForBacktest(backtestId, options)` | Block until terminal |
|
|
531
|
+
| `waitForBacktests(operations, options)` | Block on a whole batch |
|
|
532
|
+
|
|
533
|
+
**Optimization and walk-forward**
|
|
534
|
+
|
|
535
|
+
| Method | Purpose |
|
|
536
|
+
| ------------------------------------------------ | --------------------------- |
|
|
537
|
+
| `createOptimization(handle, { idempotencyKey })` | Submit an optimization |
|
|
538
|
+
| `getOptimization(optimizationId)` | Read the operation |
|
|
539
|
+
| `waitForOptimization(optimizationId, options)` | Block until terminal |
|
|
540
|
+
| `createWalkForward(handle, { idempotencyKey })` | Submit a walk-forward study |
|
|
541
|
+
| `getWalkForward(studyId)` | Read the operation |
|
|
542
|
+
| `waitForWalkForward(studyId, options)` | Block until terminal |
|
|
543
|
+
|
|
544
|
+
**Custom data sources**
|
|
545
|
+
|
|
546
|
+
| Method | Purpose |
|
|
547
|
+
| --------------------------------------------------------------------------- | -------------------------------------------------- |
|
|
548
|
+
| `createCustomIndicator(spec, { idempotencyKey })` | Create a series, optionally seeded |
|
|
549
|
+
| `listCustomIndicators(options)` | List owned series |
|
|
550
|
+
| `getCustomIndicator(id)` | Read one, with its point count and range |
|
|
551
|
+
| `appendCustomIndicatorPoints(id, points, { idempotencyKey })` | Add points |
|
|
552
|
+
| `replaceCustomIndicatorPoints(id, points, { idempotencyKey, allowShrink })` | Replace the complete series while retaining its id |
|
|
553
|
+
| `archiveCustomIndicator(id, { confirm })` | Soft-archive a series |
|
|
554
|
+
| `restoreCustomIndicator(id)` | Restore an archived series |
|
|
555
|
+
| `createCustomIndicatorUpload(id, options)` | Open an upload slot (CSV/JSON/JSONL) |
|
|
556
|
+
| `completeCustomIndicatorUpload(id, jobId)` | Start validating uploaded bytes |
|
|
557
|
+
| `getCustomIndicatorUpload(id, jobId)` | Read the upload operation |
|
|
558
|
+
| `waitForCustomIndicatorUpload(id, jobId, options)` | Block until validated |
|
|
559
|
+
|
|
560
|
+
**Agent runs**
|
|
561
|
+
|
|
562
|
+
| Method | Purpose |
|
|
563
|
+
| ----------------------------------------- | ----------------------------------- |
|
|
564
|
+
| `createAgent(prompt, { idempotencyKey })` | Start a run |
|
|
565
|
+
| `getAgent(agentId)` | Read its status |
|
|
566
|
+
| `attachAgent(agentId, { cursor })` | Reattach to a run already in flight |
|
|
567
|
+
|
|
568
|
+
**Lake SQL**
|
|
569
|
+
|
|
570
|
+
| Method | Purpose |
|
|
571
|
+
| ----------------------------------------------- | ------------------------------------ |
|
|
572
|
+
| `createLakeQuery(request, { idempotencyKey })` | Submit read-only SQL |
|
|
573
|
+
| `getLakeQuery(queryId)` | Read the operation |
|
|
574
|
+
| `waitForLakeQuery(queryId, options)` | Block until terminal |
|
|
575
|
+
| `cancelLakeQuery(queryId)` | Cancel an owned query |
|
|
576
|
+
| `createLakeAsk(question)` | Ask the lake in plain language |
|
|
577
|
+
| `getLakeAsk(askId)` | Read the operation |
|
|
578
|
+
| `waitForLakeAsk(askId, options)` | Block until terminal |
|
|
579
|
+
| `cancelLakeAsk(askId)` | Cancel an owned ask |
|
|
580
|
+
| `getLakeQueryManifest(queryId)` | Schema, checksums, and part metadata |
|
|
581
|
+
| `downloadLakeQueryPart(queryId, part, options)` | Download one Parquet part |
|
|
582
|
+
| `getLakeCatalog()` | List queryable tables |
|
|
583
|
+
| `describeLakeTable(table)` | Columns and types for one table |
|
|
584
|
+
|
|
585
|
+
**Natural language**
|
|
586
|
+
|
|
587
|
+
| Method | Purpose |
|
|
588
|
+
| ------------------------------------------- | ------------------------------------------- |
|
|
589
|
+
| `createNlScreen(question, { returnQuery })` | Screen stocks from a plain-language question |
|
|
590
|
+
| `getNlScreen(screenId)` | Read the operation |
|
|
591
|
+
| `waitForNlScreen(screenId, options)` | Block until terminal |
|
|
592
|
+
| `cancelNlScreen(screenId)` | Cancel an owned screen |
|
|
593
|
+
|
|
594
|
+
**Client construction**
|
|
595
|
+
|
|
596
|
+
| Method | Purpose |
|
|
597
|
+
| ------------------------------------------- | ---------------------------------------- |
|
|
598
|
+
| `new NexusTradeClient({ apiKey, baseUrl })` | Explicit credentials |
|
|
599
|
+
| `NexusTradeClient.fromEnvironment()` | Read them from the environment or `.env` |
|
|
600
|
+
|
|
601
|
+
**PortfolioHandle** — returned by the `portfolio(...)` builder and by
|
|
602
|
+
`getPortfolio` / `listPortfolios`.
|
|
603
|
+
|
|
604
|
+
| Method | Purpose |
|
|
605
|
+
| -------------------------------------------------- | -------------------------------------- |
|
|
606
|
+
| `save({ idempotencyKey })` | Persist it as a draft, setting `.id` |
|
|
607
|
+
| `backtest({ startDate, endDate, idempotencyKey })` | Backtest it, preferring the saved id |
|
|
608
|
+
| `deploy({ frequency })` | Mint the real paper portfolio (new id) |
|
|
609
|
+
| `undeploy()` | Deactivate its deployment |
|
|
610
|
+
|
|
319
611
|
## Authentication
|
|
320
612
|
|
|
321
613
|
Create a key at **[nexustrade.io/developers](https://nexustrade.io/developers)**
|
|
@@ -344,11 +636,11 @@ The real environment always wins — a `.env` value is used only when the variab
|
|
|
344
636
|
is absent, so a stale file can never override what you exported. Nothing is
|
|
345
637
|
written back to `process.env`. Opt out with `NEXUSTRADE_DISABLE_DOTENV=1`.
|
|
346
638
|
|
|
347
|
-
| Scope
|
|
348
|
-
|
|
|
349
|
-
| `read`
|
|
639
|
+
| Scope | Grants |
|
|
640
|
+
| ------- | --------------------------------------------------------------------------------- |
|
|
641
|
+
| `read` | `getBacktest`, `getOptimization`, `getWalkForward` |
|
|
350
642
|
| `write` | `createPortfolio`, `createBacktest(s)`, `createOptimization`, `createWalkForward` |
|
|
351
|
-
| `lake`
|
|
643
|
+
| `lake` | Lake catalog, query lifecycle, manifests, result parts |
|
|
352
644
|
|
|
353
645
|
A key missing the scope gets `403 insufficient_scope`.
|
|
354
646
|
|
|
@@ -380,23 +672,26 @@ import { NexusTradeApiError } from "nexustrade";
|
|
|
380
672
|
try {
|
|
381
673
|
await client.createBacktest(handle, { idempotencyKey: "run-1" });
|
|
382
674
|
} catch (error) {
|
|
383
|
-
if (
|
|
675
|
+
if (
|
|
676
|
+
error instanceof NexusTradeApiError &&
|
|
677
|
+
error.code === "rate_limit_exceeded"
|
|
678
|
+
) {
|
|
384
679
|
// back off
|
|
385
680
|
}
|
|
386
681
|
throw error;
|
|
387
682
|
}
|
|
388
683
|
```
|
|
389
684
|
|
|
390
|
-
| Status | Code
|
|
391
|
-
|
|
|
392
|
-
| 401
|
|
393
|
-
| 403
|
|
394
|
-
| 400
|
|
395
|
-
| 400
|
|
396
|
-
| 409
|
|
397
|
-
| 409
|
|
398
|
-
| 404
|
|
399
|
-
| 429
|
|
685
|
+
| Status | Code | Meaning |
|
|
686
|
+
| ------ | -------------------------------------- | ------------------------------------------------------------ |
|
|
687
|
+
| 401 | `invalid_token` | Missing, malformed, or expired key (or an OAuth JWT) |
|
|
688
|
+
| 403 | `insufficient_scope` | Key lacks `read`, `write`, or `lake` |
|
|
689
|
+
| 400 | `invalid_request`, `invalid_portfolio` | Malformed input |
|
|
690
|
+
| 400 | `invalid_idempotency_key` | Must match `[A-Za-z0-9._:-]{1,160}` |
|
|
691
|
+
| 409 | `idempotency_conflict` | Key reused with a different payload |
|
|
692
|
+
| 409 | `idempotency_in_progress` | Same key, first call still running. Re-poll, do not resubmit |
|
|
693
|
+
| 404 | `not_found`, `operation_not_found` | Unknown or not yours |
|
|
694
|
+
| 429 | `rate_limit_exceeded` | Back off and retry |
|
|
400
695
|
|
|
401
696
|
`status` is `0` when no HTTP status describes the failure: `transport_error`
|
|
402
697
|
(never reached the API), `unsafe_redirect`, or an `invalid_response` envelope
|
|
@@ -406,13 +701,16 @@ check on an otherwise-successful reply.
|
|
|
406
701
|
|
|
407
702
|
`new HttpTransport({ timeoutSeconds })` (default 30) is a total wall-clock
|
|
408
703
|
deadline for one request. Neither it nor the poll timeout bounds how long a
|
|
409
|
-
|
|
704
|
+
_job_ takes.
|
|
410
705
|
|
|
411
706
|
## Scope
|
|
412
707
|
|
|
413
708
|
Portfolio drafting, backtesting, optimization, walk-forward studies, and
|
|
414
709
|
read-only SQL over the market-data lake, versioned under `/api/v1/nexustrade`.
|
|
415
|
-
The screener and live
|
|
710
|
+
The screener and creating a live deployment remain outside this surface.
|
|
711
|
+
Orders are reachable, but a live order is only ever staged for human approval —
|
|
712
|
+
never submitted. `deploy` and `undeploy` act on whatever an existing id already
|
|
713
|
+
is, live included.
|
|
416
714
|
|
|
417
715
|
## Requirements
|
|
418
716
|
|