nexustrade 1.0.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 +29 -2
- package/README.md +201 -1
- package/dist/cjs/client.js +108 -1
- package/dist/esm/client.d.ts +49 -0
- package/dist/esm/client.js +107 -0
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -284,12 +284,39 @@ All failures throw `NexusTradeApiError` with a stable `.status`, `.code`, and
|
|
|
284
284
|
`status === 0` means no HTTP status applies: the request never reached the API
|
|
285
285
|
(`transport_error`), or the reply failed an envelope check.
|
|
286
286
|
|
|
287
|
-
##
|
|
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.
|
|
288
303
|
|
|
289
304
|
Not in this SDK. Do not attempt to reach them through it:
|
|
290
305
|
|
|
291
306
|
- **Screener** — MCP only.
|
|
292
|
-
- **
|
|
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.
|
|
293
320
|
|
|
294
321
|
## Verifying your work
|
|
295
322
|
|
package/README.md
CHANGED
|
@@ -165,6 +165,107 @@ const study = await client.createWalkForward(
|
|
|
165
165
|
await client.waitForWalkForward(study.id as string);
|
|
166
166
|
```
|
|
167
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
|
+
|
|
168
269
|
## Your own data
|
|
169
270
|
|
|
170
271
|
A custom data source is a time series you own — sentiment counts, a proprietary
|
|
@@ -316,6 +417,102 @@ tables; your SQL does not change when it does.
|
|
|
316
417
|
> The Python SDK additionally ships `nt.lake.sql(...)`, a DuckDB/pandas
|
|
317
418
|
> convenience layer over these same endpoints.
|
|
318
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
|
+
|
|
319
516
|
## Authentication
|
|
320
517
|
|
|
321
518
|
Create a key at **[nexustrade.io/developers](https://nexustrade.io/developers)**
|
|
@@ -412,7 +609,10 @@ deadline for one request. Neither it nor the poll timeout bounds how long a
|
|
|
412
609
|
|
|
413
610
|
Portfolio drafting, backtesting, optimization, walk-forward studies, and
|
|
414
611
|
read-only SQL over the market-data lake, versioned under `/api/v1/nexustrade`.
|
|
415
|
-
The screener and live
|
|
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.
|
|
416
616
|
|
|
417
617
|
## Requirements
|
|
418
618
|
|
package/dist/cjs/client.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
|
|
9
|
+
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.CONNECT_POLL_INTERVAL_SECONDS = exports.DEFAULT_CONNECT_TIMEOUT_SECONDS = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
|
|
10
10
|
exports.waitForOperation = waitForOperation;
|
|
11
11
|
exports.clientTransport = clientTransport;
|
|
12
12
|
exports.createCustomIndicator = createCustomIndicator;
|
|
@@ -53,6 +53,22 @@ exports.DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
|
53
53
|
exports.MAX_POLL_INTERVAL_SECONDS = 15;
|
|
54
54
|
exports.POLL_BACKOFF_FACTOR = 1.5;
|
|
55
55
|
const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
|
|
56
|
+
// Connecting a brokerage is a human opening a browser. Long enough for that,
|
|
57
|
+
// short enough that a forgotten terminal does not hang all afternoon.
|
|
58
|
+
exports.DEFAULT_CONNECT_TIMEOUT_SECONDS = 300;
|
|
59
|
+
exports.CONNECT_POLL_INTERVAL_SECONDS = 3;
|
|
60
|
+
function sleep(ms) {
|
|
61
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
62
|
+
}
|
|
63
|
+
/** Whether a human is plausibly watching. Never throws on odd streams. */
|
|
64
|
+
function stdoutIsInteractive() {
|
|
65
|
+
try {
|
|
66
|
+
return process.stdout.isTTY === true;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
56
72
|
// Point batches larger than this are uploaded rather than sent inline.
|
|
57
73
|
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
58
74
|
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
@@ -747,6 +763,97 @@ class NexusTradeClient {
|
|
|
747
763
|
}
|
|
748
764
|
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
749
765
|
}
|
|
766
|
+
/**
|
|
767
|
+
* Every connectable brokerage and whether this account has linked it.
|
|
768
|
+
*
|
|
769
|
+
* Reports all of them, connected or not, each with a `connectUrl` — an empty
|
|
770
|
+
* result would say nothing about what to do next.
|
|
771
|
+
*/
|
|
772
|
+
async listBrokerages() {
|
|
773
|
+
const response = await this.transport.request("GET", "brokerages");
|
|
774
|
+
const brokerages = response.brokerages;
|
|
775
|
+
if (!Array.isArray(brokerages)) {
|
|
776
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerages.");
|
|
777
|
+
}
|
|
778
|
+
return brokerages.filter((row) => isJsonObject(row));
|
|
779
|
+
}
|
|
780
|
+
/** Whether one named brokerage is connected. */
|
|
781
|
+
async getBrokerage(brokerage) {
|
|
782
|
+
const response = await this.transport.request("GET", `brokerages/${encodePathSegment(brokerage)}`);
|
|
783
|
+
const result = response.brokerage;
|
|
784
|
+
if (!isJsonObject(result)) {
|
|
785
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerage.");
|
|
786
|
+
}
|
|
787
|
+
return result;
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Resolve once the brokerage is connected, logging where to connect it.
|
|
791
|
+
*
|
|
792
|
+
* Linking a brokerage is an OAuth redirect, so an API key cannot complete it
|
|
793
|
+
* — a human has to open the URL. What this does is make that unmissable and
|
|
794
|
+
* then wait for it.
|
|
795
|
+
*
|
|
796
|
+
* `wait` defaults to whether stdout is a TTY. Interactively it logs the URL
|
|
797
|
+
* and polls until the link appears. Non-interactively — CI, cron, a piped
|
|
798
|
+
* script — it rejects with `brokerage_not_connected` at once rather than
|
|
799
|
+
* stalling for the timeout in front of nobody. Pass `wait` to override.
|
|
800
|
+
*/
|
|
801
|
+
async connectBrokerage(brokerage, options = {}) {
|
|
802
|
+
let current = await this.getBrokerage(brokerage);
|
|
803
|
+
if (current.connected === true)
|
|
804
|
+
return current;
|
|
805
|
+
const connectUrl = String(current.connectUrl ?? "");
|
|
806
|
+
const message = `${brokerage} is not connected. Connect it at ${connectUrl} — ` +
|
|
807
|
+
"linking a brokerage is a browser flow an API key cannot complete.";
|
|
808
|
+
const shouldWait = options.wait ?? stdoutIsInteractive();
|
|
809
|
+
if (!shouldWait) {
|
|
810
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "brokerage_not_connected", message);
|
|
811
|
+
}
|
|
812
|
+
const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_CONNECT_TIMEOUT_SECONDS;
|
|
813
|
+
const pollSeconds = options.pollIntervalSeconds ?? exports.CONNECT_POLL_INTERVAL_SECONDS;
|
|
814
|
+
console.log(message);
|
|
815
|
+
console.log(`Waiting for ${brokerage} to be connected…`);
|
|
816
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
817
|
+
for (;;) {
|
|
818
|
+
const remaining = deadline - Date.now();
|
|
819
|
+
if (remaining <= 0) {
|
|
820
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "brokerage_not_connected", `${brokerage} was still not connected after ${timeoutSeconds}s. ${message}`);
|
|
821
|
+
}
|
|
822
|
+
await sleep(Math.min(pollSeconds * 1000, remaining));
|
|
823
|
+
current = await this.getBrokerage(brokerage);
|
|
824
|
+
if (current.connected === true) {
|
|
825
|
+
console.log(`${brokerage} connected.`);
|
|
826
|
+
return current;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Stage orders against a portfolio.
|
|
832
|
+
*
|
|
833
|
+
* **Paper orders are accepted immediately. Live orders are staged for
|
|
834
|
+
* approval and are never sent to a broker by this call.** A live response
|
|
835
|
+
* carries `requiresApproval: true` and an `approvalUrl`; nothing has traded
|
|
836
|
+
* until a human approves it there. No argument changes that.
|
|
837
|
+
*
|
|
838
|
+
* ```ts
|
|
839
|
+
* const result = await client.createOrders(
|
|
840
|
+
* portfolioId,
|
|
841
|
+
* [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
|
|
842
|
+
* side: "BUY", quantity: 10, orderType: "MARKET" }],
|
|
843
|
+
* { idempotencyKey: "rebalance-2024-04-01" },
|
|
844
|
+
* );
|
|
845
|
+
* if (result.requiresApproval) console.log("approve at", result.approvalUrl);
|
|
846
|
+
* ```
|
|
847
|
+
*/
|
|
848
|
+
async createOrders(portfolioId, orders, options) {
|
|
849
|
+
if (!Array.isArray(orders) || orders.length === 0) {
|
|
850
|
+
throw new Error("createOrders needs at least one order.");
|
|
851
|
+
}
|
|
852
|
+
return this.transport.request("POST", "orders", {
|
|
853
|
+
body: { portfolioId, orders: orders.map((order) => ({ ...order })) },
|
|
854
|
+
idempotencyKey: options.idempotencyKey,
|
|
855
|
+
});
|
|
856
|
+
}
|
|
750
857
|
async createBacktests(backtests, options) {
|
|
751
858
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
752
859
|
const response = await this.transport.request("POST", "backtests/batch", {
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ export declare const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
|
|
|
41
41
|
export declare const DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
42
42
|
export declare const MAX_POLL_INTERVAL_SECONDS = 15;
|
|
43
43
|
export declare const POLL_BACKOFF_FACTOR = 1.5;
|
|
44
|
+
export declare const DEFAULT_CONNECT_TIMEOUT_SECONDS = 300;
|
|
45
|
+
export declare const CONNECT_POLL_INTERVAL_SECONDS = 3;
|
|
44
46
|
export declare class NexusTradeApiError extends Error {
|
|
45
47
|
readonly status: number;
|
|
46
48
|
readonly code: string;
|
|
@@ -230,6 +232,53 @@ export declare class NexusTradeClient {
|
|
|
230
232
|
/** Block until an upload is validated. See `waitForOperation`. */
|
|
231
233
|
waitForCustomIndicatorUpload(customIndicatorId: string, jobId: string, options?: WaitOptions): Promise<JsonObject>;
|
|
232
234
|
private uploadCustomIndicatorPoints;
|
|
235
|
+
/**
|
|
236
|
+
* Every connectable brokerage and whether this account has linked it.
|
|
237
|
+
*
|
|
238
|
+
* Reports all of them, connected or not, each with a `connectUrl` — an empty
|
|
239
|
+
* result would say nothing about what to do next.
|
|
240
|
+
*/
|
|
241
|
+
listBrokerages(): Promise<JsonObject[]>;
|
|
242
|
+
/** Whether one named brokerage is connected. */
|
|
243
|
+
getBrokerage(brokerage: string): Promise<JsonObject>;
|
|
244
|
+
/**
|
|
245
|
+
* Resolve once the brokerage is connected, logging where to connect it.
|
|
246
|
+
*
|
|
247
|
+
* Linking a brokerage is an OAuth redirect, so an API key cannot complete it
|
|
248
|
+
* — a human has to open the URL. What this does is make that unmissable and
|
|
249
|
+
* then wait for it.
|
|
250
|
+
*
|
|
251
|
+
* `wait` defaults to whether stdout is a TTY. Interactively it logs the URL
|
|
252
|
+
* and polls until the link appears. Non-interactively — CI, cron, a piped
|
|
253
|
+
* script — it rejects with `brokerage_not_connected` at once rather than
|
|
254
|
+
* stalling for the timeout in front of nobody. Pass `wait` to override.
|
|
255
|
+
*/
|
|
256
|
+
connectBrokerage(brokerage: string, options?: {
|
|
257
|
+
wait?: boolean;
|
|
258
|
+
timeoutSeconds?: number;
|
|
259
|
+
pollIntervalSeconds?: number;
|
|
260
|
+
}): Promise<JsonObject>;
|
|
261
|
+
/**
|
|
262
|
+
* Stage orders against a portfolio.
|
|
263
|
+
*
|
|
264
|
+
* **Paper orders are accepted immediately. Live orders are staged for
|
|
265
|
+
* approval and are never sent to a broker by this call.** A live response
|
|
266
|
+
* carries `requiresApproval: true` and an `approvalUrl`; nothing has traded
|
|
267
|
+
* until a human approves it there. No argument changes that.
|
|
268
|
+
*
|
|
269
|
+
* ```ts
|
|
270
|
+
* const result = await client.createOrders(
|
|
271
|
+
* portfolioId,
|
|
272
|
+
* [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
|
|
273
|
+
* side: "BUY", quantity: 10, orderType: "MARKET" }],
|
|
274
|
+
* { idempotencyKey: "rebalance-2024-04-01" },
|
|
275
|
+
* );
|
|
276
|
+
* if (result.requiresApproval) console.log("approve at", result.approvalUrl);
|
|
277
|
+
* ```
|
|
278
|
+
*/
|
|
279
|
+
createOrders(portfolioId: string, orders: ReadonlyArray<JsonObject>, options: {
|
|
280
|
+
idempotencyKey: string;
|
|
281
|
+
}): Promise<JsonObject>;
|
|
233
282
|
createBacktests(backtests: ReadonlyArray<JobInput>, options: {
|
|
234
283
|
idempotencyKey: string;
|
|
235
284
|
}): Promise<JsonObject[]>;
|
package/dist/esm/client.js
CHANGED
|
@@ -46,6 +46,22 @@ export const DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
|
46
46
|
export const MAX_POLL_INTERVAL_SECONDS = 15;
|
|
47
47
|
export const POLL_BACKOFF_FACTOR = 1.5;
|
|
48
48
|
const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
|
|
49
|
+
// Connecting a brokerage is a human opening a browser. Long enough for that,
|
|
50
|
+
// short enough that a forgotten terminal does not hang all afternoon.
|
|
51
|
+
export const DEFAULT_CONNECT_TIMEOUT_SECONDS = 300;
|
|
52
|
+
export const CONNECT_POLL_INTERVAL_SECONDS = 3;
|
|
53
|
+
function sleep(ms) {
|
|
54
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
55
|
+
}
|
|
56
|
+
/** Whether a human is plausibly watching. Never throws on odd streams. */
|
|
57
|
+
function stdoutIsInteractive() {
|
|
58
|
+
try {
|
|
59
|
+
return process.stdout.isTTY === true;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
49
65
|
// Point batches larger than this are uploaded rather than sent inline.
|
|
50
66
|
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
51
67
|
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
@@ -738,6 +754,97 @@ export class NexusTradeClient {
|
|
|
738
754
|
}
|
|
739
755
|
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
740
756
|
}
|
|
757
|
+
/**
|
|
758
|
+
* Every connectable brokerage and whether this account has linked it.
|
|
759
|
+
*
|
|
760
|
+
* Reports all of them, connected or not, each with a `connectUrl` — an empty
|
|
761
|
+
* result would say nothing about what to do next.
|
|
762
|
+
*/
|
|
763
|
+
async listBrokerages() {
|
|
764
|
+
const response = await this.transport.request("GET", "brokerages");
|
|
765
|
+
const brokerages = response.brokerages;
|
|
766
|
+
if (!Array.isArray(brokerages)) {
|
|
767
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerages.");
|
|
768
|
+
}
|
|
769
|
+
return brokerages.filter((row) => isJsonObject(row));
|
|
770
|
+
}
|
|
771
|
+
/** Whether one named brokerage is connected. */
|
|
772
|
+
async getBrokerage(brokerage) {
|
|
773
|
+
const response = await this.transport.request("GET", `brokerages/${encodePathSegment(brokerage)}`);
|
|
774
|
+
const result = response.brokerage;
|
|
775
|
+
if (!isJsonObject(result)) {
|
|
776
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerage.");
|
|
777
|
+
}
|
|
778
|
+
return result;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Resolve once the brokerage is connected, logging where to connect it.
|
|
782
|
+
*
|
|
783
|
+
* Linking a brokerage is an OAuth redirect, so an API key cannot complete it
|
|
784
|
+
* — a human has to open the URL. What this does is make that unmissable and
|
|
785
|
+
* then wait for it.
|
|
786
|
+
*
|
|
787
|
+
* `wait` defaults to whether stdout is a TTY. Interactively it logs the URL
|
|
788
|
+
* and polls until the link appears. Non-interactively — CI, cron, a piped
|
|
789
|
+
* script — it rejects with `brokerage_not_connected` at once rather than
|
|
790
|
+
* stalling for the timeout in front of nobody. Pass `wait` to override.
|
|
791
|
+
*/
|
|
792
|
+
async connectBrokerage(brokerage, options = {}) {
|
|
793
|
+
let current = await this.getBrokerage(brokerage);
|
|
794
|
+
if (current.connected === true)
|
|
795
|
+
return current;
|
|
796
|
+
const connectUrl = String(current.connectUrl ?? "");
|
|
797
|
+
const message = `${brokerage} is not connected. Connect it at ${connectUrl} — ` +
|
|
798
|
+
"linking a brokerage is a browser flow an API key cannot complete.";
|
|
799
|
+
const shouldWait = options.wait ?? stdoutIsInteractive();
|
|
800
|
+
if (!shouldWait) {
|
|
801
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "brokerage_not_connected", message);
|
|
802
|
+
}
|
|
803
|
+
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_CONNECT_TIMEOUT_SECONDS;
|
|
804
|
+
const pollSeconds = options.pollIntervalSeconds ?? CONNECT_POLL_INTERVAL_SECONDS;
|
|
805
|
+
console.log(message);
|
|
806
|
+
console.log(`Waiting for ${brokerage} to be connected…`);
|
|
807
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
808
|
+
for (;;) {
|
|
809
|
+
const remaining = deadline - Date.now();
|
|
810
|
+
if (remaining <= 0) {
|
|
811
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "brokerage_not_connected", `${brokerage} was still not connected after ${timeoutSeconds}s. ${message}`);
|
|
812
|
+
}
|
|
813
|
+
await sleep(Math.min(pollSeconds * 1000, remaining));
|
|
814
|
+
current = await this.getBrokerage(brokerage);
|
|
815
|
+
if (current.connected === true) {
|
|
816
|
+
console.log(`${brokerage} connected.`);
|
|
817
|
+
return current;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Stage orders against a portfolio.
|
|
823
|
+
*
|
|
824
|
+
* **Paper orders are accepted immediately. Live orders are staged for
|
|
825
|
+
* approval and are never sent to a broker by this call.** A live response
|
|
826
|
+
* carries `requiresApproval: true` and an `approvalUrl`; nothing has traded
|
|
827
|
+
* until a human approves it there. No argument changes that.
|
|
828
|
+
*
|
|
829
|
+
* ```ts
|
|
830
|
+
* const result = await client.createOrders(
|
|
831
|
+
* portfolioId,
|
|
832
|
+
* [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
|
|
833
|
+
* side: "BUY", quantity: 10, orderType: "MARKET" }],
|
|
834
|
+
* { idempotencyKey: "rebalance-2024-04-01" },
|
|
835
|
+
* );
|
|
836
|
+
* if (result.requiresApproval) console.log("approve at", result.approvalUrl);
|
|
837
|
+
* ```
|
|
838
|
+
*/
|
|
839
|
+
async createOrders(portfolioId, orders, options) {
|
|
840
|
+
if (!Array.isArray(orders) || orders.length === 0) {
|
|
841
|
+
throw new Error("createOrders needs at least one order.");
|
|
842
|
+
}
|
|
843
|
+
return this.transport.request("POST", "orders", {
|
|
844
|
+
body: { portfolioId, orders: orders.map((order) => ({ ...order })) },
|
|
845
|
+
idempotencyKey: options.idempotencyKey,
|
|
846
|
+
});
|
|
847
|
+
}
|
|
741
848
|
async createBacktests(backtests, options) {
|
|
742
849
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
743
850
|
const response = await this.transport.request("POST", "backtests/batch", {
|