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 +64 -14
- package/README.md +361 -14
- package/dist/cjs/agent.js +12 -6
- package/dist/cjs/client.js +403 -14
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/portfolio.js +1 -3
- package/dist/esm/agent.d.ts +2 -5
- package/dist/esm/agent.js +12 -6
- package/dist/esm/client.d.ts +162 -5
- package/dist/esm/client.js +401 -13
- package/dist/esm/index.d.ts +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/portfolio.d.ts +1 -3
- package/dist/esm/portfolio.js +1 -3
- package/package.json +1 -1
package/dist/esm/client.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Typed NexusTrade JSON API client.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
4
|
+
* Method names and behavior match the Python SDK. Transport-generic: callers
|
|
5
|
+
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
7
6
|
*/
|
|
8
7
|
import { AgentRun } from "./agent.js";
|
|
9
8
|
import { LazyDotenv, environmentValue } from "./env.js";
|
|
@@ -47,6 +46,34 @@ export const DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
|
47
46
|
export const MAX_POLL_INTERVAL_SECONDS = 15;
|
|
48
47
|
export const POLL_BACKOFF_FACTOR = 1.5;
|
|
49
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
|
+
}
|
|
65
|
+
// Point batches larger than this are uploaded rather than sent inline.
|
|
66
|
+
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
67
|
+
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
68
|
+
const POINT_FIELDS = {
|
|
69
|
+
timestamp: "timestamp",
|
|
70
|
+
value: "value",
|
|
71
|
+
ticker: "ticker",
|
|
72
|
+
assetType: "assetType",
|
|
73
|
+
asset_type: "assetType",
|
|
74
|
+
availableAt: "availableAt",
|
|
75
|
+
available_at: "availableAt",
|
|
76
|
+
};
|
|
50
77
|
export class NexusTradeApiError extends Error {
|
|
51
78
|
status;
|
|
52
79
|
code;
|
|
@@ -81,6 +108,9 @@ function sameOrigin(left, right) {
|
|
|
81
108
|
function supportsBinary(transport) {
|
|
82
109
|
return (typeof transport.requestBytes === "function");
|
|
83
110
|
}
|
|
111
|
+
function supportsUpload(transport) {
|
|
112
|
+
return typeof transport.putBytes === "function";
|
|
113
|
+
}
|
|
84
114
|
function assertValidApiKey(apiKey) {
|
|
85
115
|
const invalid = typeof apiKey !== "string" ||
|
|
86
116
|
apiKey.length === 0 ||
|
|
@@ -187,6 +217,43 @@ export class HttpTransport {
|
|
|
187
217
|
get baseUrl() {
|
|
188
218
|
return this.#baseUrl;
|
|
189
219
|
}
|
|
220
|
+
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
221
|
+
async putBytes(url, data, options) {
|
|
222
|
+
let parsed;
|
|
223
|
+
try {
|
|
224
|
+
parsed = new URL(url);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a malformed upload URL.");
|
|
228
|
+
}
|
|
229
|
+
if (parsed.protocol.toLowerCase() !== "https:") {
|
|
230
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a non-HTTPS upload URL.");
|
|
231
|
+
}
|
|
232
|
+
const controller = new AbortController();
|
|
233
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
|
|
234
|
+
try {
|
|
235
|
+
let response;
|
|
236
|
+
try {
|
|
237
|
+
response = await fetch(url, {
|
|
238
|
+
method: "PUT",
|
|
239
|
+
headers: { "Content-Type": options.contentType },
|
|
240
|
+
body: new Blob([data], { type: options.contentType }),
|
|
241
|
+
redirect: "manual",
|
|
242
|
+
signal: controller.signal,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
247
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
|
|
248
|
+
}
|
|
249
|
+
if (!response.ok) {
|
|
250
|
+
throw new NexusTradeApiError(response.status, "upload_failed", `Storage rejected the upload: ${response.statusText || `HTTP ${response.status}`}.`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
clearTimeout(timer);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
190
257
|
async request(method, path, options = {}) {
|
|
191
258
|
const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
|
|
192
259
|
const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
|
|
@@ -306,18 +373,50 @@ function operationFailure(operation, operationId, status) {
|
|
|
306
373
|
}
|
|
307
374
|
return new NexusTradeApiError(NO_HTTP_STATUS, code, message, operationId);
|
|
308
375
|
}
|
|
376
|
+
function pointTimestamp(value) {
|
|
377
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
378
|
+
}
|
|
309
379
|
/**
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
* Works for any operation kind because every NexusTrade job reports the same
|
|
313
|
-
* `{id, kind, status, result?, error?}` envelope. Pass any getter with that
|
|
314
|
-
* shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
|
|
380
|
+
* Normalize one point to its wire shape.
|
|
315
381
|
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
* false. Transport errors from `fetch` propagate — a poller that swallowed
|
|
319
|
-
* them would report an infrastructure outage as a still-running job.
|
|
382
|
+
* Accepts snake_case or camelCase field names and Date objects. Throws on an
|
|
383
|
+
* unrecognized field rather than dropping it silently.
|
|
320
384
|
*/
|
|
385
|
+
function customIndicatorPoint(point) {
|
|
386
|
+
const normalized = {};
|
|
387
|
+
for (const [key, value] of Object.entries(point)) {
|
|
388
|
+
const target = POINT_FIELDS[key];
|
|
389
|
+
if (target === undefined) {
|
|
390
|
+
throw new Error(`Unknown custom indicator point field "${key}". Points accept ` +
|
|
391
|
+
"timestamp, value, ticker, assetType, and availableAt.");
|
|
392
|
+
}
|
|
393
|
+
if (value === undefined || value === null)
|
|
394
|
+
continue;
|
|
395
|
+
normalized[target] =
|
|
396
|
+
target === "timestamp" || target === "availableAt"
|
|
397
|
+
? pointTimestamp(value)
|
|
398
|
+
: value;
|
|
399
|
+
}
|
|
400
|
+
if (normalized.timestamp === undefined) {
|
|
401
|
+
throw new Error("Every custom indicator point needs a timestamp.");
|
|
402
|
+
}
|
|
403
|
+
if (normalized.value === undefined) {
|
|
404
|
+
throw new Error("Every custom indicator point needs a value.");
|
|
405
|
+
}
|
|
406
|
+
return normalized;
|
|
407
|
+
}
|
|
408
|
+
function customIndicatorPoints(points) {
|
|
409
|
+
if (!Array.isArray(points)) {
|
|
410
|
+
throw new Error("points must be an array of point objects.");
|
|
411
|
+
}
|
|
412
|
+
return points.map(customIndicatorPoint);
|
|
413
|
+
}
|
|
414
|
+
function pointsJsonl(points) {
|
|
415
|
+
return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
|
|
416
|
+
}
|
|
417
|
+
function inlinePointBytes(points) {
|
|
418
|
+
return new TextEncoder().encode(JSON.stringify(points)).length;
|
|
419
|
+
}
|
|
321
420
|
export async function waitForOperation(fetch, operationId, options = {}) {
|
|
322
421
|
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
323
422
|
const pollIntervalSeconds = options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
|
|
@@ -392,7 +491,7 @@ export class NexusTradeClient {
|
|
|
392
491
|
return result;
|
|
393
492
|
}
|
|
394
493
|
/**
|
|
395
|
-
* List portfolios
|
|
494
|
+
* List portfolios with optional filters and pagination.
|
|
396
495
|
* `includePositions` defaults off when `search` is set.
|
|
397
496
|
*/
|
|
398
497
|
async listPortfolios(options = {}) {
|
|
@@ -471,6 +570,281 @@ export class NexusTradeClient {
|
|
|
471
570
|
}
|
|
472
571
|
return result;
|
|
473
572
|
}
|
|
573
|
+
/**
|
|
574
|
+
* Create a custom data source and return it, including its id.
|
|
575
|
+
*
|
|
576
|
+
* `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
|
|
577
|
+
* every point needs a `ticker`); it defaults to `"global"` and cannot be
|
|
578
|
+
* changed later. `points` is optional and unlimited in size — small batches
|
|
579
|
+
* are sent with the request, larger ones are uploaded, and the returned
|
|
580
|
+
* indicator reflects what landed either way.
|
|
581
|
+
*
|
|
582
|
+
* The id it returns is what a `CustomIndicator` node binds to:
|
|
583
|
+
*
|
|
584
|
+
* ```ts
|
|
585
|
+
* const series = await client.createCustomIndicator(
|
|
586
|
+
* {
|
|
587
|
+
* name: "WSB NVDA Mentions",
|
|
588
|
+
* scope: "asset",
|
|
589
|
+
* points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
|
|
590
|
+
* },
|
|
591
|
+
* { idempotencyKey: "wsb-mentions-v1" },
|
|
592
|
+
* );
|
|
593
|
+
* CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
|
|
594
|
+
* ```
|
|
595
|
+
*
|
|
596
|
+
* Retrying with the same `idempotencyKey` returns the original series rather
|
|
597
|
+
* than creating a second one.
|
|
598
|
+
*/
|
|
599
|
+
async createCustomIndicator(indicator, options) {
|
|
600
|
+
const { name, description, scope, points, ...rest } = indicator;
|
|
601
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
602
|
+
throw new Error("createCustomIndicator requires a name.");
|
|
603
|
+
}
|
|
604
|
+
const unknown = Object.keys(rest);
|
|
605
|
+
if (unknown.length > 0) {
|
|
606
|
+
throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
|
|
607
|
+
"Expected name, description, scope, and points.");
|
|
608
|
+
}
|
|
609
|
+
const normalized = points ? customIndicatorPoints(points) : [];
|
|
610
|
+
const body = { name: name.trim() };
|
|
611
|
+
if (description !== undefined)
|
|
612
|
+
body.description = description;
|
|
613
|
+
if (scope !== undefined)
|
|
614
|
+
body.scope = scope;
|
|
615
|
+
const inline = normalized.length > 0 &&
|
|
616
|
+
inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
|
|
617
|
+
if (inline)
|
|
618
|
+
body.points = normalized;
|
|
619
|
+
const created = customIndicatorOf(await this.transport.request("POST", "custom-indicators", {
|
|
620
|
+
body,
|
|
621
|
+
idempotencyKey: options.idempotencyKey,
|
|
622
|
+
}));
|
|
623
|
+
if (inline || normalized.length === 0)
|
|
624
|
+
return created;
|
|
625
|
+
const customIndicatorId = String(created.customIndicatorId);
|
|
626
|
+
// The same key is safe here: the server namespaces an idempotency claim
|
|
627
|
+
// by operation, and deriving a suffixed key could overrun its
|
|
628
|
+
// 160-character limit.
|
|
629
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
630
|
+
return {
|
|
631
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
632
|
+
upload,
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
/** List the custom data sources this account owns. */
|
|
636
|
+
async listCustomIndicators(options = {}) {
|
|
637
|
+
const query = encodeQuery({
|
|
638
|
+
includeArchived: options.includeArchived === undefined
|
|
639
|
+
? undefined
|
|
640
|
+
: String(options.includeArchived),
|
|
641
|
+
});
|
|
642
|
+
const response = await this.transport.request("GET", `custom-indicators${query}`);
|
|
643
|
+
const indicators = response.indicators;
|
|
644
|
+
if (!Array.isArray(indicators)) {
|
|
645
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator list response is missing indicators.");
|
|
646
|
+
}
|
|
647
|
+
return indicators.filter((row) => isJsonObject(row));
|
|
648
|
+
}
|
|
649
|
+
/** Read one custom data source, including its current point count. */
|
|
650
|
+
async getCustomIndicator(customIndicatorId) {
|
|
651
|
+
return customIndicatorOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}`));
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Add points to an existing series and return the updated indicator.
|
|
655
|
+
*
|
|
656
|
+
* Recurring collection must append to the same `customIndicatorId` every
|
|
657
|
+
* run; creating a fresh series per run splits the history into fragments a
|
|
658
|
+
* strategy cannot read. Re-sending an identical batch is safe — the
|
|
659
|
+
* duplicate is not written twice.
|
|
660
|
+
*
|
|
661
|
+
* The batch is unlimited in size and, as with creation, is sent inline or
|
|
662
|
+
* uploaded depending on how large it is.
|
|
663
|
+
*/
|
|
664
|
+
async appendCustomIndicatorPoints(customIndicatorId, points, options) {
|
|
665
|
+
const normalized = customIndicatorPoints(points);
|
|
666
|
+
if (normalized.length === 0) {
|
|
667
|
+
throw new Error("appendCustomIndicatorPoints needs at least one point.");
|
|
668
|
+
}
|
|
669
|
+
if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
|
|
670
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, { body: { points: normalized }, idempotencyKey: options.idempotencyKey });
|
|
671
|
+
const indicator = response.indicator;
|
|
672
|
+
if (!isJsonObject(indicator)) {
|
|
673
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
674
|
+
}
|
|
675
|
+
return indicator;
|
|
676
|
+
}
|
|
677
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
678
|
+
return {
|
|
679
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
680
|
+
upload,
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
685
|
+
*
|
|
686
|
+
* Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
|
|
687
|
+
* returned URL, then call `completeCustomIndicatorUpload`. Most callers can
|
|
688
|
+
* pass `points` to `createCustomIndicator` or
|
|
689
|
+
* `appendCustomIndicatorPoints` instead and skip all three steps.
|
|
690
|
+
*
|
|
691
|
+
* Retrying with the same `idempotencyKey` re-signs the same job, since the
|
|
692
|
+
* first URL expires in 15 minutes. Once its bytes have arrived the reply
|
|
693
|
+
* carries no `uploadUrl` — there is nothing left to send, so skip the PUT
|
|
694
|
+
* and wait on `jobId`.
|
|
695
|
+
*/
|
|
696
|
+
async createCustomIndicatorUpload(customIndicatorId, options) {
|
|
697
|
+
const body = {
|
|
698
|
+
fileName: options.fileName,
|
|
699
|
+
format: options.format ?? "jsonl",
|
|
700
|
+
};
|
|
701
|
+
if (options.contentType !== undefined)
|
|
702
|
+
body.contentType = options.contentType;
|
|
703
|
+
if (options.sizeBytes !== undefined)
|
|
704
|
+
body.sizeBytes = options.sizeBytes;
|
|
705
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
|
|
706
|
+
const ticket = response.ticket;
|
|
707
|
+
if (!isJsonObject(ticket) || !ticket.jobId) {
|
|
708
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Upload response is missing ticket.");
|
|
709
|
+
}
|
|
710
|
+
return ticket;
|
|
711
|
+
}
|
|
712
|
+
/** Start validation of uploaded bytes and return the operation. */
|
|
713
|
+
async completeCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
714
|
+
return operationOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
715
|
+
`/uploads/${encodePathSegment(jobId)}/complete`, { body: {} }));
|
|
716
|
+
}
|
|
717
|
+
/** Read an upload operation. `phase` distinguishes the live states. */
|
|
718
|
+
async getCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
719
|
+
return operationOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
720
|
+
`/uploads/${encodePathSegment(jobId)}`));
|
|
721
|
+
}
|
|
722
|
+
/** Block until an upload is validated. See `waitForOperation`. */
|
|
723
|
+
async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
|
|
724
|
+
return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
|
|
725
|
+
}
|
|
726
|
+
async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
|
|
727
|
+
const payload = pointsJsonl(points);
|
|
728
|
+
if (payload.length > MAX_UPLOAD_BYTES) {
|
|
729
|
+
throw new Error(`${points.length} points serialize to ` +
|
|
730
|
+
`${Math.floor(payload.length / (1024 * 1024))} MB, over the 100 MB ` +
|
|
731
|
+
"upload limit. Send them in several batches.");
|
|
732
|
+
}
|
|
733
|
+
if (!supportsUpload(this.transport)) {
|
|
734
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Uploading a large point batch requires HttpTransport.putBytes.");
|
|
735
|
+
}
|
|
736
|
+
const ticket = await this.createCustomIndicatorUpload(customIndicatorId, {
|
|
737
|
+
fileName: `${customIndicatorId}-points.jsonl`,
|
|
738
|
+
format: "jsonl",
|
|
739
|
+
sizeBytes: payload.length,
|
|
740
|
+
idempotencyKey,
|
|
741
|
+
});
|
|
742
|
+
const jobId = String(ticket.jobId);
|
|
743
|
+
// No upload URL means this batch already reached the server on an earlier
|
|
744
|
+
// attempt, so resume at polling instead of re-sending it.
|
|
745
|
+
if (ticket.uploadUrl) {
|
|
746
|
+
const headers = ticket.headers;
|
|
747
|
+
const contentType = isJsonObject(headers) && typeof headers["Content-Type"] === "string"
|
|
748
|
+
? headers["Content-Type"]
|
|
749
|
+
: "application/x-ndjson";
|
|
750
|
+
await this.transport.putBytes(String(ticket.uploadUrl), payload, {
|
|
751
|
+
contentType,
|
|
752
|
+
});
|
|
753
|
+
await this.completeCustomIndicatorUpload(customIndicatorId, jobId);
|
|
754
|
+
}
|
|
755
|
+
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
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
|
+
}
|
|
474
848
|
async createBacktests(backtests, options) {
|
|
475
849
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
476
850
|
const response = await this.transport.request("POST", "backtests/batch", {
|
|
@@ -657,6 +1031,13 @@ function backtestInput(item) {
|
|
|
657
1031
|
}
|
|
658
1032
|
return normalized;
|
|
659
1033
|
}
|
|
1034
|
+
function customIndicatorOf(response) {
|
|
1035
|
+
const indicator = response.indicator;
|
|
1036
|
+
if (!isJsonObject(indicator) || !indicator.customIndicatorId) {
|
|
1037
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
1038
|
+
}
|
|
1039
|
+
return indicator;
|
|
1040
|
+
}
|
|
660
1041
|
function operationOf(response) {
|
|
661
1042
|
const operation = response.operation;
|
|
662
1043
|
if (!isJsonObject(operation)) {
|
|
@@ -669,6 +1050,13 @@ export function clientTransport(client) {
|
|
|
669
1050
|
return client.transport;
|
|
670
1051
|
}
|
|
671
1052
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
1053
|
+
export async function createCustomIndicator(indicator, options) {
|
|
1054
|
+
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
1055
|
+
return client.createCustomIndicator(indicator, {
|
|
1056
|
+
idempotencyKey: options.idempotencyKey,
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
672
1060
|
export async function createPortfolio(portfolio, options) {
|
|
673
1061
|
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
674
1062
|
return client.createPortfolio(portfolio, {
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { AgentRun } from "./agent.js";
|
|
2
2
|
export type { AgentEvent, AgentRunOptions } from "./agent.js";
|
|
3
|
-
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
|
|
4
|
-
export type { HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, WaitOptions, } from "./client.js";
|
|
3
|
+
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
4
|
+
export type { CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, UploadTransport, WaitOptions, } from "./client.js";
|
|
5
5
|
export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
|
|
6
6
|
export type { DeployOutcome, DeployResult, PortfolioHandleOptions, PortfolioListResult, PortfolioType, } from "./portfolio.js";
|
|
7
7
|
export * from "./generated/ntSdk.generated.js";
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { AgentRun } from "./agent.js";
|
|
2
|
-
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
|
|
2
|
+
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
3
3
|
export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
|
|
4
4
|
export * from "./generated/ntSdk.generated.js";
|
package/dist/esm/portfolio.d.ts
CHANGED
|
@@ -3,12 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Keeps the generated `Portfolio` interface as the shape; this class adds
|
|
5
5
|
* lifecycle methods. `toJSON()` omits `id` so request bodies never leak
|
|
6
|
-
* `"id": null`.
|
|
6
|
+
* `"id": null`.
|
|
7
7
|
*
|
|
8
8
|
* Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
|
|
9
9
|
* import this module without a cycle through `client.ts`.
|
|
10
|
-
*
|
|
11
|
-
* See designs/2026-07-26-sdk-portfolio-objects.md.
|
|
12
10
|
*/
|
|
13
11
|
import { type JsonObject, type Transport } from "./client.ts";
|
|
14
12
|
import type { Portfolio, Strategy } from "./generated/ntSdk.generated.js";
|
package/dist/esm/portfolio.js
CHANGED
|
@@ -3,12 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Keeps the generated `Portfolio` interface as the shape; this class adds
|
|
5
5
|
* lifecycle methods. `toJSON()` omits `id` so request bodies never leak
|
|
6
|
-
* `"id": null`.
|
|
6
|
+
* `"id": null`.
|
|
7
7
|
*
|
|
8
8
|
* Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
|
|
9
9
|
* import this module without a cycle through `client.ts`.
|
|
10
|
-
*
|
|
11
|
-
* See designs/2026-07-26-sdk-portfolio-objects.md.
|
|
12
10
|
*/
|
|
13
11
|
import { NexusTradeApiError, NO_HTTP_STATUS, } from "./client.js";
|
|
14
12
|
function isJsonObject(value) {
|