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/cjs/client.js
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* Typed NexusTrade JSON API client.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
5
|
+
* Method names and behavior match the Python SDK. Transport-generic: callers
|
|
6
|
+
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
8
7
|
*/
|
|
9
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
-
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;
|
|
11
10
|
exports.waitForOperation = waitForOperation;
|
|
12
11
|
exports.clientTransport = clientTransport;
|
|
12
|
+
exports.createCustomIndicator = createCustomIndicator;
|
|
13
13
|
exports.createPortfolio = createPortfolio;
|
|
14
14
|
const agent_ts_1 = require("./agent.js");
|
|
15
15
|
const env_ts_1 = require("./env.js");
|
|
@@ -53,6 +53,34 @@ 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
|
+
}
|
|
72
|
+
// Point batches larger than this are uploaded rather than sent inline.
|
|
73
|
+
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
74
|
+
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
75
|
+
const POINT_FIELDS = {
|
|
76
|
+
timestamp: "timestamp",
|
|
77
|
+
value: "value",
|
|
78
|
+
ticker: "ticker",
|
|
79
|
+
assetType: "assetType",
|
|
80
|
+
asset_type: "assetType",
|
|
81
|
+
availableAt: "availableAt",
|
|
82
|
+
available_at: "availableAt",
|
|
83
|
+
};
|
|
56
84
|
class NexusTradeApiError extends Error {
|
|
57
85
|
status;
|
|
58
86
|
code;
|
|
@@ -88,6 +116,9 @@ function sameOrigin(left, right) {
|
|
|
88
116
|
function supportsBinary(transport) {
|
|
89
117
|
return (typeof transport.requestBytes === "function");
|
|
90
118
|
}
|
|
119
|
+
function supportsUpload(transport) {
|
|
120
|
+
return typeof transport.putBytes === "function";
|
|
121
|
+
}
|
|
91
122
|
function assertValidApiKey(apiKey) {
|
|
92
123
|
const invalid = typeof apiKey !== "string" ||
|
|
93
124
|
apiKey.length === 0 ||
|
|
@@ -194,6 +225,43 @@ class HttpTransport {
|
|
|
194
225
|
get baseUrl() {
|
|
195
226
|
return this.#baseUrl;
|
|
196
227
|
}
|
|
228
|
+
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
229
|
+
async putBytes(url, data, options) {
|
|
230
|
+
let parsed;
|
|
231
|
+
try {
|
|
232
|
+
parsed = new URL(url);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a malformed upload URL.");
|
|
236
|
+
}
|
|
237
|
+
if (parsed.protocol.toLowerCase() !== "https:") {
|
|
238
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a non-HTTPS upload URL.");
|
|
239
|
+
}
|
|
240
|
+
const controller = new AbortController();
|
|
241
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
|
|
242
|
+
try {
|
|
243
|
+
let response;
|
|
244
|
+
try {
|
|
245
|
+
response = await fetch(url, {
|
|
246
|
+
method: "PUT",
|
|
247
|
+
headers: { "Content-Type": options.contentType },
|
|
248
|
+
body: new Blob([data], { type: options.contentType }),
|
|
249
|
+
redirect: "manual",
|
|
250
|
+
signal: controller.signal,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
255
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "transport_error", reason);
|
|
256
|
+
}
|
|
257
|
+
if (!response.ok) {
|
|
258
|
+
throw new NexusTradeApiError(response.status, "upload_failed", `Storage rejected the upload: ${response.statusText || `HTTP ${response.status}`}.`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
clearTimeout(timer);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
197
265
|
async request(method, path, options = {}) {
|
|
198
266
|
const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
|
|
199
267
|
const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
|
|
@@ -314,18 +382,50 @@ function operationFailure(operation, operationId, status) {
|
|
|
314
382
|
}
|
|
315
383
|
return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message, operationId);
|
|
316
384
|
}
|
|
385
|
+
function pointTimestamp(value) {
|
|
386
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
387
|
+
}
|
|
317
388
|
/**
|
|
318
|
-
*
|
|
319
|
-
*
|
|
320
|
-
* Works for any operation kind because every NexusTrade job reports the same
|
|
321
|
-
* `{id, kind, status, result?, error?}` envelope. Pass any getter with that
|
|
322
|
-
* shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
|
|
389
|
+
* Normalize one point to its wire shape.
|
|
323
390
|
*
|
|
324
|
-
*
|
|
325
|
-
*
|
|
326
|
-
* false. Transport errors from `fetch` propagate — a poller that swallowed
|
|
327
|
-
* them would report an infrastructure outage as a still-running job.
|
|
391
|
+
* Accepts snake_case or camelCase field names and Date objects. Throws on an
|
|
392
|
+
* unrecognized field rather than dropping it silently.
|
|
328
393
|
*/
|
|
394
|
+
function customIndicatorPoint(point) {
|
|
395
|
+
const normalized = {};
|
|
396
|
+
for (const [key, value] of Object.entries(point)) {
|
|
397
|
+
const target = POINT_FIELDS[key];
|
|
398
|
+
if (target === undefined) {
|
|
399
|
+
throw new Error(`Unknown custom indicator point field "${key}". Points accept ` +
|
|
400
|
+
"timestamp, value, ticker, assetType, and availableAt.");
|
|
401
|
+
}
|
|
402
|
+
if (value === undefined || value === null)
|
|
403
|
+
continue;
|
|
404
|
+
normalized[target] =
|
|
405
|
+
target === "timestamp" || target === "availableAt"
|
|
406
|
+
? pointTimestamp(value)
|
|
407
|
+
: value;
|
|
408
|
+
}
|
|
409
|
+
if (normalized.timestamp === undefined) {
|
|
410
|
+
throw new Error("Every custom indicator point needs a timestamp.");
|
|
411
|
+
}
|
|
412
|
+
if (normalized.value === undefined) {
|
|
413
|
+
throw new Error("Every custom indicator point needs a value.");
|
|
414
|
+
}
|
|
415
|
+
return normalized;
|
|
416
|
+
}
|
|
417
|
+
function customIndicatorPoints(points) {
|
|
418
|
+
if (!Array.isArray(points)) {
|
|
419
|
+
throw new Error("points must be an array of point objects.");
|
|
420
|
+
}
|
|
421
|
+
return points.map(customIndicatorPoint);
|
|
422
|
+
}
|
|
423
|
+
function pointsJsonl(points) {
|
|
424
|
+
return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
|
|
425
|
+
}
|
|
426
|
+
function inlinePointBytes(points) {
|
|
427
|
+
return new TextEncoder().encode(JSON.stringify(points)).length;
|
|
428
|
+
}
|
|
329
429
|
async function waitForOperation(fetch, operationId, options = {}) {
|
|
330
430
|
const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
331
431
|
const pollIntervalSeconds = options.pollIntervalSeconds ?? exports.DEFAULT_POLL_INTERVAL_SECONDS;
|
|
@@ -400,7 +500,7 @@ class NexusTradeClient {
|
|
|
400
500
|
return result;
|
|
401
501
|
}
|
|
402
502
|
/**
|
|
403
|
-
* List portfolios
|
|
503
|
+
* List portfolios with optional filters and pagination.
|
|
404
504
|
* `includePositions` defaults off when `search` is set.
|
|
405
505
|
*/
|
|
406
506
|
async listPortfolios(options = {}) {
|
|
@@ -479,6 +579,281 @@ class NexusTradeClient {
|
|
|
479
579
|
}
|
|
480
580
|
return result;
|
|
481
581
|
}
|
|
582
|
+
/**
|
|
583
|
+
* Create a custom data source and return it, including its id.
|
|
584
|
+
*
|
|
585
|
+
* `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
|
|
586
|
+
* every point needs a `ticker`); it defaults to `"global"` and cannot be
|
|
587
|
+
* changed later. `points` is optional and unlimited in size — small batches
|
|
588
|
+
* are sent with the request, larger ones are uploaded, and the returned
|
|
589
|
+
* indicator reflects what landed either way.
|
|
590
|
+
*
|
|
591
|
+
* The id it returns is what a `CustomIndicator` node binds to:
|
|
592
|
+
*
|
|
593
|
+
* ```ts
|
|
594
|
+
* const series = await client.createCustomIndicator(
|
|
595
|
+
* {
|
|
596
|
+
* name: "WSB NVDA Mentions",
|
|
597
|
+
* scope: "asset",
|
|
598
|
+
* points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
|
|
599
|
+
* },
|
|
600
|
+
* { idempotencyKey: "wsb-mentions-v1" },
|
|
601
|
+
* );
|
|
602
|
+
* CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
|
|
603
|
+
* ```
|
|
604
|
+
*
|
|
605
|
+
* Retrying with the same `idempotencyKey` returns the original series rather
|
|
606
|
+
* than creating a second one.
|
|
607
|
+
*/
|
|
608
|
+
async createCustomIndicator(indicator, options) {
|
|
609
|
+
const { name, description, scope, points, ...rest } = indicator;
|
|
610
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
611
|
+
throw new Error("createCustomIndicator requires a name.");
|
|
612
|
+
}
|
|
613
|
+
const unknown = Object.keys(rest);
|
|
614
|
+
if (unknown.length > 0) {
|
|
615
|
+
throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
|
|
616
|
+
"Expected name, description, scope, and points.");
|
|
617
|
+
}
|
|
618
|
+
const normalized = points ? customIndicatorPoints(points) : [];
|
|
619
|
+
const body = { name: name.trim() };
|
|
620
|
+
if (description !== undefined)
|
|
621
|
+
body.description = description;
|
|
622
|
+
if (scope !== undefined)
|
|
623
|
+
body.scope = scope;
|
|
624
|
+
const inline = normalized.length > 0 &&
|
|
625
|
+
inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
|
|
626
|
+
if (inline)
|
|
627
|
+
body.points = normalized;
|
|
628
|
+
const created = customIndicatorOf(await this.transport.request("POST", "custom-indicators", {
|
|
629
|
+
body,
|
|
630
|
+
idempotencyKey: options.idempotencyKey,
|
|
631
|
+
}));
|
|
632
|
+
if (inline || normalized.length === 0)
|
|
633
|
+
return created;
|
|
634
|
+
const customIndicatorId = String(created.customIndicatorId);
|
|
635
|
+
// The same key is safe here: the server namespaces an idempotency claim
|
|
636
|
+
// by operation, and deriving a suffixed key could overrun its
|
|
637
|
+
// 160-character limit.
|
|
638
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
639
|
+
return {
|
|
640
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
641
|
+
upload,
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
/** List the custom data sources this account owns. */
|
|
645
|
+
async listCustomIndicators(options = {}) {
|
|
646
|
+
const query = encodeQuery({
|
|
647
|
+
includeArchived: options.includeArchived === undefined
|
|
648
|
+
? undefined
|
|
649
|
+
: String(options.includeArchived),
|
|
650
|
+
});
|
|
651
|
+
const response = await this.transport.request("GET", `custom-indicators${query}`);
|
|
652
|
+
const indicators = response.indicators;
|
|
653
|
+
if (!Array.isArray(indicators)) {
|
|
654
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator list response is missing indicators.");
|
|
655
|
+
}
|
|
656
|
+
return indicators.filter((row) => isJsonObject(row));
|
|
657
|
+
}
|
|
658
|
+
/** Read one custom data source, including its current point count. */
|
|
659
|
+
async getCustomIndicator(customIndicatorId) {
|
|
660
|
+
return customIndicatorOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}`));
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Add points to an existing series and return the updated indicator.
|
|
664
|
+
*
|
|
665
|
+
* Recurring collection must append to the same `customIndicatorId` every
|
|
666
|
+
* run; creating a fresh series per run splits the history into fragments a
|
|
667
|
+
* strategy cannot read. Re-sending an identical batch is safe — the
|
|
668
|
+
* duplicate is not written twice.
|
|
669
|
+
*
|
|
670
|
+
* The batch is unlimited in size and, as with creation, is sent inline or
|
|
671
|
+
* uploaded depending on how large it is.
|
|
672
|
+
*/
|
|
673
|
+
async appendCustomIndicatorPoints(customIndicatorId, points, options) {
|
|
674
|
+
const normalized = customIndicatorPoints(points);
|
|
675
|
+
if (normalized.length === 0) {
|
|
676
|
+
throw new Error("appendCustomIndicatorPoints needs at least one point.");
|
|
677
|
+
}
|
|
678
|
+
if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
|
|
679
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, { body: { points: normalized }, idempotencyKey: options.idempotencyKey });
|
|
680
|
+
const indicator = response.indicator;
|
|
681
|
+
if (!isJsonObject(indicator)) {
|
|
682
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
683
|
+
}
|
|
684
|
+
return indicator;
|
|
685
|
+
}
|
|
686
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
687
|
+
return {
|
|
688
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
689
|
+
upload,
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
694
|
+
*
|
|
695
|
+
* Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
|
|
696
|
+
* returned URL, then call `completeCustomIndicatorUpload`. Most callers can
|
|
697
|
+
* pass `points` to `createCustomIndicator` or
|
|
698
|
+
* `appendCustomIndicatorPoints` instead and skip all three steps.
|
|
699
|
+
*
|
|
700
|
+
* Retrying with the same `idempotencyKey` re-signs the same job, since the
|
|
701
|
+
* first URL expires in 15 minutes. Once its bytes have arrived the reply
|
|
702
|
+
* carries no `uploadUrl` — there is nothing left to send, so skip the PUT
|
|
703
|
+
* and wait on `jobId`.
|
|
704
|
+
*/
|
|
705
|
+
async createCustomIndicatorUpload(customIndicatorId, options) {
|
|
706
|
+
const body = {
|
|
707
|
+
fileName: options.fileName,
|
|
708
|
+
format: options.format ?? "jsonl",
|
|
709
|
+
};
|
|
710
|
+
if (options.contentType !== undefined)
|
|
711
|
+
body.contentType = options.contentType;
|
|
712
|
+
if (options.sizeBytes !== undefined)
|
|
713
|
+
body.sizeBytes = options.sizeBytes;
|
|
714
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
|
|
715
|
+
const ticket = response.ticket;
|
|
716
|
+
if (!isJsonObject(ticket) || !ticket.jobId) {
|
|
717
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Upload response is missing ticket.");
|
|
718
|
+
}
|
|
719
|
+
return ticket;
|
|
720
|
+
}
|
|
721
|
+
/** Start validation of uploaded bytes and return the operation. */
|
|
722
|
+
async completeCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
723
|
+
return operationOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
724
|
+
`/uploads/${encodePathSegment(jobId)}/complete`, { body: {} }));
|
|
725
|
+
}
|
|
726
|
+
/** Read an upload operation. `phase` distinguishes the live states. */
|
|
727
|
+
async getCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
728
|
+
return operationOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
729
|
+
`/uploads/${encodePathSegment(jobId)}`));
|
|
730
|
+
}
|
|
731
|
+
/** Block until an upload is validated. See `waitForOperation`. */
|
|
732
|
+
async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
|
|
733
|
+
return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
|
|
734
|
+
}
|
|
735
|
+
async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
|
|
736
|
+
const payload = pointsJsonl(points);
|
|
737
|
+
if (payload.length > MAX_UPLOAD_BYTES) {
|
|
738
|
+
throw new Error(`${points.length} points serialize to ` +
|
|
739
|
+
`${Math.floor(payload.length / (1024 * 1024))} MB, over the 100 MB ` +
|
|
740
|
+
"upload limit. Send them in several batches.");
|
|
741
|
+
}
|
|
742
|
+
if (!supportsUpload(this.transport)) {
|
|
743
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsupported_transport", "Uploading a large point batch requires HttpTransport.putBytes.");
|
|
744
|
+
}
|
|
745
|
+
const ticket = await this.createCustomIndicatorUpload(customIndicatorId, {
|
|
746
|
+
fileName: `${customIndicatorId}-points.jsonl`,
|
|
747
|
+
format: "jsonl",
|
|
748
|
+
sizeBytes: payload.length,
|
|
749
|
+
idempotencyKey,
|
|
750
|
+
});
|
|
751
|
+
const jobId = String(ticket.jobId);
|
|
752
|
+
// No upload URL means this batch already reached the server on an earlier
|
|
753
|
+
// attempt, so resume at polling instead of re-sending it.
|
|
754
|
+
if (ticket.uploadUrl) {
|
|
755
|
+
const headers = ticket.headers;
|
|
756
|
+
const contentType = isJsonObject(headers) && typeof headers["Content-Type"] === "string"
|
|
757
|
+
? headers["Content-Type"]
|
|
758
|
+
: "application/x-ndjson";
|
|
759
|
+
await this.transport.putBytes(String(ticket.uploadUrl), payload, {
|
|
760
|
+
contentType,
|
|
761
|
+
});
|
|
762
|
+
await this.completeCustomIndicatorUpload(customIndicatorId, jobId);
|
|
763
|
+
}
|
|
764
|
+
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
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
|
+
}
|
|
482
857
|
async createBacktests(backtests, options) {
|
|
483
858
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
484
859
|
const response = await this.transport.request("POST", "backtests/batch", {
|
|
@@ -666,6 +1041,13 @@ function backtestInput(item) {
|
|
|
666
1041
|
}
|
|
667
1042
|
return normalized;
|
|
668
1043
|
}
|
|
1044
|
+
function customIndicatorOf(response) {
|
|
1045
|
+
const indicator = response.indicator;
|
|
1046
|
+
if (!isJsonObject(indicator) || !indicator.customIndicatorId) {
|
|
1047
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
1048
|
+
}
|
|
1049
|
+
return indicator;
|
|
1050
|
+
}
|
|
669
1051
|
function operationOf(response) {
|
|
670
1052
|
const operation = response.operation;
|
|
671
1053
|
if (!isJsonObject(operation)) {
|
|
@@ -678,6 +1060,13 @@ function clientTransport(client) {
|
|
|
678
1060
|
return client.transport;
|
|
679
1061
|
}
|
|
680
1062
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
1063
|
+
async function createCustomIndicator(indicator, options) {
|
|
1064
|
+
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
1065
|
+
return client.createCustomIndicator(indicator, {
|
|
1066
|
+
idempotencyKey: options.idempotencyKey,
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
681
1070
|
async function createPortfolio(portfolio, options) {
|
|
682
1071
|
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
683
1072
|
return client.createPortfolio(portfolio, {
|
package/dist/cjs/index.js
CHANGED
|
@@ -14,13 +14,14 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
|
|
17
|
+
exports.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = exports.createCustomIndicator = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
|
|
18
18
|
var agent_js_1 = require("./agent.js");
|
|
19
19
|
Object.defineProperty(exports, "AgentRun", { enumerable: true, get: function () { return agent_js_1.AgentRun; } });
|
|
20
20
|
var client_js_1 = require("./client.js");
|
|
21
21
|
Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return client_js_1.HttpTransport; } });
|
|
22
22
|
Object.defineProperty(exports, "NexusTradeApiError", { enumerable: true, get: function () { return client_js_1.NexusTradeApiError; } });
|
|
23
23
|
Object.defineProperty(exports, "NexusTradeClient", { enumerable: true, get: function () { return client_js_1.NexusTradeClient; } });
|
|
24
|
+
Object.defineProperty(exports, "createCustomIndicator", { enumerable: true, get: function () { return client_js_1.createCustomIndicator; } });
|
|
24
25
|
Object.defineProperty(exports, "createPortfolio", { enumerable: true, get: function () { return client_js_1.createPortfolio; } });
|
|
25
26
|
Object.defineProperty(exports, "waitForOperation", { enumerable: true, get: function () { return client_js_1.waitForOperation; } });
|
|
26
27
|
var portfolio_js_1 = require("./portfolio.js");
|
package/dist/cjs/portfolio.js
CHANGED
|
@@ -4,12 +4,10 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Keeps the generated `Portfolio` interface as the shape; this class adds
|
|
6
6
|
* lifecycle methods. `toJSON()` omits `id` so request bodies never leak
|
|
7
|
-
* `"id": null`.
|
|
7
|
+
* `"id": null`.
|
|
8
8
|
*
|
|
9
9
|
* Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
|
|
10
10
|
* import this module without a cycle through `client.ts`.
|
|
11
|
-
*
|
|
12
|
-
* See designs/2026-07-26-sdk-portfolio-objects.md.
|
|
13
11
|
*/
|
|
14
12
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
15
13
|
if (k2 === undefined) k2 = k;
|
package/dist/esm/agent.d.ts
CHANGED
|
@@ -19,8 +19,6 @@
|
|
|
19
19
|
* if (event.needsApproval) await run.approve();
|
|
20
20
|
* }
|
|
21
21
|
* ```
|
|
22
|
-
*
|
|
23
|
-
* Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
|
|
24
22
|
*/
|
|
25
23
|
import { type Transport } from "./client.ts";
|
|
26
24
|
export interface AgentEvent {
|
|
@@ -53,9 +51,8 @@ export declare class AgentRun {
|
|
|
53
51
|
/** Every event yielded so far, in order. */
|
|
54
52
|
readonly events: AgentEvent[];
|
|
55
53
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* they expect to sit blocked for a while.
|
|
54
|
+
* Polling pacing. Mutable so callers can widen the timeout on a run they
|
|
55
|
+
* expect to sit blocked for a while.
|
|
59
56
|
*/
|
|
60
57
|
timeoutSeconds: number;
|
|
61
58
|
pollIntervalSeconds: number;
|
package/dist/esm/agent.js
CHANGED
|
@@ -19,8 +19,6 @@
|
|
|
19
19
|
* if (event.needsApproval) await run.approve();
|
|
20
20
|
* }
|
|
21
21
|
* ```
|
|
22
|
-
*
|
|
23
|
-
* Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
|
|
24
22
|
*/
|
|
25
23
|
import { DEFAULT_POLL_INTERVAL_SECONDS, DEFAULT_POLL_TIMEOUT_SECONDS, MAX_POLL_INTERVAL_SECONDS, NO_HTTP_STATUS, NexusTradeApiError, POLL_BACKOFF_FACTOR, } from "./client.js";
|
|
26
24
|
const DEFAULT_EVENT_LIMIT = 50;
|
|
@@ -35,9 +33,8 @@ export class AgentRun {
|
|
|
35
33
|
/** Every event yielded so far, in order. */
|
|
36
34
|
events = [];
|
|
37
35
|
/**
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* they expect to sit blocked for a while.
|
|
36
|
+
* Polling pacing. Mutable so callers can widen the timeout on a run they
|
|
37
|
+
* expect to sit blocked for a while.
|
|
41
38
|
*/
|
|
42
39
|
timeoutSeconds;
|
|
43
40
|
pollIntervalSeconds;
|
|
@@ -46,6 +43,14 @@ export class AgentRun {
|
|
|
46
43
|
#transport;
|
|
47
44
|
#cursor = null;
|
|
48
45
|
#seen = new Map();
|
|
46
|
+
/**
|
|
47
|
+
* Advances only after a POST is acknowledged, so a retry of a call that
|
|
48
|
+
* failed reuses its key and is deduped, while two different calls never
|
|
49
|
+
* collide. Keying on `events.length` did the latter wrong: two messages sent
|
|
50
|
+
* without iterating between them shared a key and the second was rejected as
|
|
51
|
+
* an idempotency conflict.
|
|
52
|
+
*/
|
|
53
|
+
#actionSeq = 0;
|
|
49
54
|
constructor(id, transport, status = "initializing", options = {}) {
|
|
50
55
|
this.id = id;
|
|
51
56
|
this.status = status;
|
|
@@ -206,8 +211,9 @@ export class AgentRun {
|
|
|
206
211
|
async #post(action, body = {}) {
|
|
207
212
|
const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
|
|
208
213
|
body,
|
|
209
|
-
idempotencyKey: `${this.id}:${action}:${this
|
|
214
|
+
idempotencyKey: `${this.id}:${action}:${this.#actionSeq}`,
|
|
210
215
|
});
|
|
216
|
+
this.#actionSeq += 1;
|
|
211
217
|
const agent = response.agent;
|
|
212
218
|
if (agent && typeof agent === "object" && !Array.isArray(agent)) {
|
|
213
219
|
const status = agent.status;
|