nexustrade 0.4.0 → 1.0.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 +35 -12
- package/README.md +160 -13
- package/dist/cjs/agent.js +12 -6
- package/dist/cjs/client.js +295 -13
- 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 +113 -5
- package/dist/esm/client.js +294 -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
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;
|
|
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,18 @@ 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
|
+
// Point batches larger than this are uploaded rather than sent inline.
|
|
57
|
+
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
58
|
+
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
59
|
+
const POINT_FIELDS = {
|
|
60
|
+
timestamp: "timestamp",
|
|
61
|
+
value: "value",
|
|
62
|
+
ticker: "ticker",
|
|
63
|
+
assetType: "assetType",
|
|
64
|
+
asset_type: "assetType",
|
|
65
|
+
availableAt: "availableAt",
|
|
66
|
+
available_at: "availableAt",
|
|
67
|
+
};
|
|
56
68
|
class NexusTradeApiError extends Error {
|
|
57
69
|
status;
|
|
58
70
|
code;
|
|
@@ -88,6 +100,9 @@ function sameOrigin(left, right) {
|
|
|
88
100
|
function supportsBinary(transport) {
|
|
89
101
|
return (typeof transport.requestBytes === "function");
|
|
90
102
|
}
|
|
103
|
+
function supportsUpload(transport) {
|
|
104
|
+
return typeof transport.putBytes === "function";
|
|
105
|
+
}
|
|
91
106
|
function assertValidApiKey(apiKey) {
|
|
92
107
|
const invalid = typeof apiKey !== "string" ||
|
|
93
108
|
apiKey.length === 0 ||
|
|
@@ -194,6 +209,43 @@ class HttpTransport {
|
|
|
194
209
|
get baseUrl() {
|
|
195
210
|
return this.#baseUrl;
|
|
196
211
|
}
|
|
212
|
+
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
213
|
+
async putBytes(url, data, options) {
|
|
214
|
+
let parsed;
|
|
215
|
+
try {
|
|
216
|
+
parsed = new URL(url);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a malformed upload URL.");
|
|
220
|
+
}
|
|
221
|
+
if (parsed.protocol.toLowerCase() !== "https:") {
|
|
222
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a non-HTTPS upload URL.");
|
|
223
|
+
}
|
|
224
|
+
const controller = new AbortController();
|
|
225
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
|
|
226
|
+
try {
|
|
227
|
+
let response;
|
|
228
|
+
try {
|
|
229
|
+
response = await fetch(url, {
|
|
230
|
+
method: "PUT",
|
|
231
|
+
headers: { "Content-Type": options.contentType },
|
|
232
|
+
body: new Blob([data], { type: options.contentType }),
|
|
233
|
+
redirect: "manual",
|
|
234
|
+
signal: controller.signal,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
239
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "transport_error", reason);
|
|
240
|
+
}
|
|
241
|
+
if (!response.ok) {
|
|
242
|
+
throw new NexusTradeApiError(response.status, "upload_failed", `Storage rejected the upload: ${response.statusText || `HTTP ${response.status}`}.`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
clearTimeout(timer);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
197
249
|
async request(method, path, options = {}) {
|
|
198
250
|
const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
|
|
199
251
|
const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
|
|
@@ -314,18 +366,50 @@ function operationFailure(operation, operationId, status) {
|
|
|
314
366
|
}
|
|
315
367
|
return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message, operationId);
|
|
316
368
|
}
|
|
369
|
+
function pointTimestamp(value) {
|
|
370
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
371
|
+
}
|
|
317
372
|
/**
|
|
318
|
-
*
|
|
373
|
+
* Normalize one point to its wire shape.
|
|
319
374
|
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
* shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
|
|
323
|
-
*
|
|
324
|
-
* Resolves with the terminal operation. Rejects with `NexusTradeApiError` on
|
|
325
|
-
* timeout, and on a failed/cancelled operation unless `raiseOnFailure` is
|
|
326
|
-
* false. Transport errors from `fetch` propagate — a poller that swallowed
|
|
327
|
-
* them would report an infrastructure outage as a still-running job.
|
|
375
|
+
* Accepts snake_case or camelCase field names and Date objects. Throws on an
|
|
376
|
+
* unrecognized field rather than dropping it silently.
|
|
328
377
|
*/
|
|
378
|
+
function customIndicatorPoint(point) {
|
|
379
|
+
const normalized = {};
|
|
380
|
+
for (const [key, value] of Object.entries(point)) {
|
|
381
|
+
const target = POINT_FIELDS[key];
|
|
382
|
+
if (target === undefined) {
|
|
383
|
+
throw new Error(`Unknown custom indicator point field "${key}". Points accept ` +
|
|
384
|
+
"timestamp, value, ticker, assetType, and availableAt.");
|
|
385
|
+
}
|
|
386
|
+
if (value === undefined || value === null)
|
|
387
|
+
continue;
|
|
388
|
+
normalized[target] =
|
|
389
|
+
target === "timestamp" || target === "availableAt"
|
|
390
|
+
? pointTimestamp(value)
|
|
391
|
+
: value;
|
|
392
|
+
}
|
|
393
|
+
if (normalized.timestamp === undefined) {
|
|
394
|
+
throw new Error("Every custom indicator point needs a timestamp.");
|
|
395
|
+
}
|
|
396
|
+
if (normalized.value === undefined) {
|
|
397
|
+
throw new Error("Every custom indicator point needs a value.");
|
|
398
|
+
}
|
|
399
|
+
return normalized;
|
|
400
|
+
}
|
|
401
|
+
function customIndicatorPoints(points) {
|
|
402
|
+
if (!Array.isArray(points)) {
|
|
403
|
+
throw new Error("points must be an array of point objects.");
|
|
404
|
+
}
|
|
405
|
+
return points.map(customIndicatorPoint);
|
|
406
|
+
}
|
|
407
|
+
function pointsJsonl(points) {
|
|
408
|
+
return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
|
|
409
|
+
}
|
|
410
|
+
function inlinePointBytes(points) {
|
|
411
|
+
return new TextEncoder().encode(JSON.stringify(points)).length;
|
|
412
|
+
}
|
|
329
413
|
async function waitForOperation(fetch, operationId, options = {}) {
|
|
330
414
|
const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
331
415
|
const pollIntervalSeconds = options.pollIntervalSeconds ?? exports.DEFAULT_POLL_INTERVAL_SECONDS;
|
|
@@ -400,7 +484,7 @@ class NexusTradeClient {
|
|
|
400
484
|
return result;
|
|
401
485
|
}
|
|
402
486
|
/**
|
|
403
|
-
* List portfolios
|
|
487
|
+
* List portfolios with optional filters and pagination.
|
|
404
488
|
* `includePositions` defaults off when `search` is set.
|
|
405
489
|
*/
|
|
406
490
|
async listPortfolios(options = {}) {
|
|
@@ -479,6 +563,190 @@ class NexusTradeClient {
|
|
|
479
563
|
}
|
|
480
564
|
return result;
|
|
481
565
|
}
|
|
566
|
+
/**
|
|
567
|
+
* Create a custom data source and return it, including its id.
|
|
568
|
+
*
|
|
569
|
+
* `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
|
|
570
|
+
* every point needs a `ticker`); it defaults to `"global"` and cannot be
|
|
571
|
+
* changed later. `points` is optional and unlimited in size — small batches
|
|
572
|
+
* are sent with the request, larger ones are uploaded, and the returned
|
|
573
|
+
* indicator reflects what landed either way.
|
|
574
|
+
*
|
|
575
|
+
* The id it returns is what a `CustomIndicator` node binds to:
|
|
576
|
+
*
|
|
577
|
+
* ```ts
|
|
578
|
+
* const series = await client.createCustomIndicator(
|
|
579
|
+
* {
|
|
580
|
+
* name: "WSB NVDA Mentions",
|
|
581
|
+
* scope: "asset",
|
|
582
|
+
* points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
|
|
583
|
+
* },
|
|
584
|
+
* { idempotencyKey: "wsb-mentions-v1" },
|
|
585
|
+
* );
|
|
586
|
+
* CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
|
|
587
|
+
* ```
|
|
588
|
+
*
|
|
589
|
+
* Retrying with the same `idempotencyKey` returns the original series rather
|
|
590
|
+
* than creating a second one.
|
|
591
|
+
*/
|
|
592
|
+
async createCustomIndicator(indicator, options) {
|
|
593
|
+
const { name, description, scope, points, ...rest } = indicator;
|
|
594
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
595
|
+
throw new Error("createCustomIndicator requires a name.");
|
|
596
|
+
}
|
|
597
|
+
const unknown = Object.keys(rest);
|
|
598
|
+
if (unknown.length > 0) {
|
|
599
|
+
throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
|
|
600
|
+
"Expected name, description, scope, and points.");
|
|
601
|
+
}
|
|
602
|
+
const normalized = points ? customIndicatorPoints(points) : [];
|
|
603
|
+
const body = { name: name.trim() };
|
|
604
|
+
if (description !== undefined)
|
|
605
|
+
body.description = description;
|
|
606
|
+
if (scope !== undefined)
|
|
607
|
+
body.scope = scope;
|
|
608
|
+
const inline = normalized.length > 0 &&
|
|
609
|
+
inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
|
|
610
|
+
if (inline)
|
|
611
|
+
body.points = normalized;
|
|
612
|
+
const created = customIndicatorOf(await this.transport.request("POST", "custom-indicators", {
|
|
613
|
+
body,
|
|
614
|
+
idempotencyKey: options.idempotencyKey,
|
|
615
|
+
}));
|
|
616
|
+
if (inline || normalized.length === 0)
|
|
617
|
+
return created;
|
|
618
|
+
const customIndicatorId = String(created.customIndicatorId);
|
|
619
|
+
// The same key is safe here: the server namespaces an idempotency claim
|
|
620
|
+
// by operation, and deriving a suffixed key could overrun its
|
|
621
|
+
// 160-character limit.
|
|
622
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
623
|
+
return {
|
|
624
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
625
|
+
upload,
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
/** List the custom data sources this account owns. */
|
|
629
|
+
async listCustomIndicators(options = {}) {
|
|
630
|
+
const query = encodeQuery({
|
|
631
|
+
includeArchived: options.includeArchived === undefined
|
|
632
|
+
? undefined
|
|
633
|
+
: String(options.includeArchived),
|
|
634
|
+
});
|
|
635
|
+
const response = await this.transport.request("GET", `custom-indicators${query}`);
|
|
636
|
+
const indicators = response.indicators;
|
|
637
|
+
if (!Array.isArray(indicators)) {
|
|
638
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator list response is missing indicators.");
|
|
639
|
+
}
|
|
640
|
+
return indicators.filter((row) => isJsonObject(row));
|
|
641
|
+
}
|
|
642
|
+
/** Read one custom data source, including its current point count. */
|
|
643
|
+
async getCustomIndicator(customIndicatorId) {
|
|
644
|
+
return customIndicatorOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}`));
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Add points to an existing series and return the updated indicator.
|
|
648
|
+
*
|
|
649
|
+
* Recurring collection must append to the same `customIndicatorId` every
|
|
650
|
+
* run; creating a fresh series per run splits the history into fragments a
|
|
651
|
+
* strategy cannot read. Re-sending an identical batch is safe — the
|
|
652
|
+
* duplicate is not written twice.
|
|
653
|
+
*
|
|
654
|
+
* The batch is unlimited in size and, as with creation, is sent inline or
|
|
655
|
+
* uploaded depending on how large it is.
|
|
656
|
+
*/
|
|
657
|
+
async appendCustomIndicatorPoints(customIndicatorId, points, options) {
|
|
658
|
+
const normalized = customIndicatorPoints(points);
|
|
659
|
+
if (normalized.length === 0) {
|
|
660
|
+
throw new Error("appendCustomIndicatorPoints needs at least one point.");
|
|
661
|
+
}
|
|
662
|
+
if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
|
|
663
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, { body: { points: normalized }, idempotencyKey: options.idempotencyKey });
|
|
664
|
+
const indicator = response.indicator;
|
|
665
|
+
if (!isJsonObject(indicator)) {
|
|
666
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
667
|
+
}
|
|
668
|
+
return indicator;
|
|
669
|
+
}
|
|
670
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
671
|
+
return {
|
|
672
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
673
|
+
upload,
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
678
|
+
*
|
|
679
|
+
* Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
|
|
680
|
+
* returned URL, then call `completeCustomIndicatorUpload`. Most callers can
|
|
681
|
+
* pass `points` to `createCustomIndicator` or
|
|
682
|
+
* `appendCustomIndicatorPoints` instead and skip all three steps.
|
|
683
|
+
*
|
|
684
|
+
* Retrying with the same `idempotencyKey` re-signs the same job, since the
|
|
685
|
+
* first URL expires in 15 minutes. Once its bytes have arrived the reply
|
|
686
|
+
* carries no `uploadUrl` — there is nothing left to send, so skip the PUT
|
|
687
|
+
* and wait on `jobId`.
|
|
688
|
+
*/
|
|
689
|
+
async createCustomIndicatorUpload(customIndicatorId, options) {
|
|
690
|
+
const body = {
|
|
691
|
+
fileName: options.fileName,
|
|
692
|
+
format: options.format ?? "jsonl",
|
|
693
|
+
};
|
|
694
|
+
if (options.contentType !== undefined)
|
|
695
|
+
body.contentType = options.contentType;
|
|
696
|
+
if (options.sizeBytes !== undefined)
|
|
697
|
+
body.sizeBytes = options.sizeBytes;
|
|
698
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
|
|
699
|
+
const ticket = response.ticket;
|
|
700
|
+
if (!isJsonObject(ticket) || !ticket.jobId) {
|
|
701
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Upload response is missing ticket.");
|
|
702
|
+
}
|
|
703
|
+
return ticket;
|
|
704
|
+
}
|
|
705
|
+
/** Start validation of uploaded bytes and return the operation. */
|
|
706
|
+
async completeCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
707
|
+
return operationOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
708
|
+
`/uploads/${encodePathSegment(jobId)}/complete`, { body: {} }));
|
|
709
|
+
}
|
|
710
|
+
/** Read an upload operation. `phase` distinguishes the live states. */
|
|
711
|
+
async getCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
712
|
+
return operationOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
713
|
+
`/uploads/${encodePathSegment(jobId)}`));
|
|
714
|
+
}
|
|
715
|
+
/** Block until an upload is validated. See `waitForOperation`. */
|
|
716
|
+
async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
|
|
717
|
+
return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
|
|
718
|
+
}
|
|
719
|
+
async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
|
|
720
|
+
const payload = pointsJsonl(points);
|
|
721
|
+
if (payload.length > MAX_UPLOAD_BYTES) {
|
|
722
|
+
throw new Error(`${points.length} points serialize to ` +
|
|
723
|
+
`${Math.floor(payload.length / (1024 * 1024))} MB, over the 100 MB ` +
|
|
724
|
+
"upload limit. Send them in several batches.");
|
|
725
|
+
}
|
|
726
|
+
if (!supportsUpload(this.transport)) {
|
|
727
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsupported_transport", "Uploading a large point batch requires HttpTransport.putBytes.");
|
|
728
|
+
}
|
|
729
|
+
const ticket = await this.createCustomIndicatorUpload(customIndicatorId, {
|
|
730
|
+
fileName: `${customIndicatorId}-points.jsonl`,
|
|
731
|
+
format: "jsonl",
|
|
732
|
+
sizeBytes: payload.length,
|
|
733
|
+
idempotencyKey,
|
|
734
|
+
});
|
|
735
|
+
const jobId = String(ticket.jobId);
|
|
736
|
+
// No upload URL means this batch already reached the server on an earlier
|
|
737
|
+
// attempt, so resume at polling instead of re-sending it.
|
|
738
|
+
if (ticket.uploadUrl) {
|
|
739
|
+
const headers = ticket.headers;
|
|
740
|
+
const contentType = isJsonObject(headers) && typeof headers["Content-Type"] === "string"
|
|
741
|
+
? headers["Content-Type"]
|
|
742
|
+
: "application/x-ndjson";
|
|
743
|
+
await this.transport.putBytes(String(ticket.uploadUrl), payload, {
|
|
744
|
+
contentType,
|
|
745
|
+
});
|
|
746
|
+
await this.completeCustomIndicatorUpload(customIndicatorId, jobId);
|
|
747
|
+
}
|
|
748
|
+
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
749
|
+
}
|
|
482
750
|
async createBacktests(backtests, options) {
|
|
483
751
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
484
752
|
const response = await this.transport.request("POST", "backtests/batch", {
|
|
@@ -666,6 +934,13 @@ function backtestInput(item) {
|
|
|
666
934
|
}
|
|
667
935
|
return normalized;
|
|
668
936
|
}
|
|
937
|
+
function customIndicatorOf(response) {
|
|
938
|
+
const indicator = response.indicator;
|
|
939
|
+
if (!isJsonObject(indicator) || !indicator.customIndicatorId) {
|
|
940
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
941
|
+
}
|
|
942
|
+
return indicator;
|
|
943
|
+
}
|
|
669
944
|
function operationOf(response) {
|
|
670
945
|
const operation = response.operation;
|
|
671
946
|
if (!isJsonObject(operation)) {
|
|
@@ -678,6 +953,13 @@ function clientTransport(client) {
|
|
|
678
953
|
return client.transport;
|
|
679
954
|
}
|
|
680
955
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
956
|
+
async function createCustomIndicator(indicator, options) {
|
|
957
|
+
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
958
|
+
return client.createCustomIndicator(indicator, {
|
|
959
|
+
idempotencyKey: options.idempotencyKey,
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
681
963
|
async function createPortfolio(portfolio, options) {
|
|
682
964
|
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
683
965
|
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;
|
package/dist/esm/client.d.ts
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.ts";
|
|
9
8
|
import type { JobRequest, Portfolio } from "./generated/ntSdk.generated.js";
|
|
@@ -74,15 +73,29 @@ export interface BinaryTransport extends Transport {
|
|
|
74
73
|
maxBytes?: number;
|
|
75
74
|
}): Promise<Uint8Array>;
|
|
76
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Transports that can PUT bytes to a presigned storage URL.
|
|
78
|
+
*
|
|
79
|
+
* The URL is absolute and the call carries no credential.
|
|
80
|
+
*/
|
|
81
|
+
export interface UploadTransport extends Transport {
|
|
82
|
+
putBytes(url: string, data: Uint8Array<ArrayBuffer>, options: {
|
|
83
|
+
contentType: string;
|
|
84
|
+
}): Promise<void>;
|
|
85
|
+
}
|
|
77
86
|
export interface HttpTransportOptions {
|
|
78
87
|
apiKey: string;
|
|
79
88
|
baseUrl: string;
|
|
80
89
|
timeoutSeconds?: number;
|
|
81
90
|
}
|
|
82
|
-
export declare class HttpTransport implements Transport {
|
|
91
|
+
export declare class HttpTransport implements Transport, UploadTransport {
|
|
83
92
|
#private;
|
|
84
93
|
constructor(options: HttpTransportOptions);
|
|
85
94
|
get baseUrl(): string;
|
|
95
|
+
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
96
|
+
putBytes(url: string, data: Uint8Array<ArrayBuffer>, options: {
|
|
97
|
+
contentType: string;
|
|
98
|
+
}): Promise<void>;
|
|
86
99
|
request(method: string, path: string, options?: RequestOptions): Promise<JsonObject>;
|
|
87
100
|
}
|
|
88
101
|
export interface NexusTradeClientOptions {
|
|
@@ -108,6 +121,20 @@ export interface WaitOptions {
|
|
|
108
121
|
* false. Transport errors from `fetch` propagate — a poller that swallowed
|
|
109
122
|
* them would report an infrastructure outage as a still-running job.
|
|
110
123
|
*/
|
|
124
|
+
export interface CustomIndicatorPointInput {
|
|
125
|
+
timestamp: string | Date;
|
|
126
|
+
value: number;
|
|
127
|
+
ticker?: string;
|
|
128
|
+
assetType?: string;
|
|
129
|
+
availableAt?: string | Date;
|
|
130
|
+
[field: string]: unknown;
|
|
131
|
+
}
|
|
132
|
+
export interface CustomIndicatorInput {
|
|
133
|
+
name: string;
|
|
134
|
+
description?: string;
|
|
135
|
+
scope?: "global" | "asset";
|
|
136
|
+
points?: ReadonlyArray<CustomIndicatorPointInput>;
|
|
137
|
+
}
|
|
111
138
|
export declare function waitForOperation(fetch: (operationId: string) => Promise<JsonObject>, operationId: string, options?: WaitOptions): Promise<JsonObject>;
|
|
112
139
|
export declare class NexusTradeClient {
|
|
113
140
|
private readonly transport;
|
|
@@ -117,7 +144,7 @@ export declare class NexusTradeClient {
|
|
|
117
144
|
idempotencyKey: string;
|
|
118
145
|
}): Promise<JsonObject>;
|
|
119
146
|
/**
|
|
120
|
-
* List portfolios
|
|
147
|
+
* List portfolios with optional filters and pagination.
|
|
121
148
|
* `includePositions` defaults off when `search` is set.
|
|
122
149
|
*/
|
|
123
150
|
listPortfolios(options?: ListPortfoliosOptions): Promise<PortfolioListResult>;
|
|
@@ -127,6 +154,82 @@ export declare class NexusTradeClient {
|
|
|
127
154
|
frequency?: string;
|
|
128
155
|
}): Promise<DeployResult>;
|
|
129
156
|
undeploy(portfolioId: string): Promise<JsonObject>;
|
|
157
|
+
/**
|
|
158
|
+
* Create a custom data source and return it, including its id.
|
|
159
|
+
*
|
|
160
|
+
* `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
|
|
161
|
+
* every point needs a `ticker`); it defaults to `"global"` and cannot be
|
|
162
|
+
* changed later. `points` is optional and unlimited in size — small batches
|
|
163
|
+
* are sent with the request, larger ones are uploaded, and the returned
|
|
164
|
+
* indicator reflects what landed either way.
|
|
165
|
+
*
|
|
166
|
+
* The id it returns is what a `CustomIndicator` node binds to:
|
|
167
|
+
*
|
|
168
|
+
* ```ts
|
|
169
|
+
* const series = await client.createCustomIndicator(
|
|
170
|
+
* {
|
|
171
|
+
* name: "WSB NVDA Mentions",
|
|
172
|
+
* scope: "asset",
|
|
173
|
+
* points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
|
|
174
|
+
* },
|
|
175
|
+
* { idempotencyKey: "wsb-mentions-v1" },
|
|
176
|
+
* );
|
|
177
|
+
* CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
|
|
178
|
+
* ```
|
|
179
|
+
*
|
|
180
|
+
* Retrying with the same `idempotencyKey` returns the original series rather
|
|
181
|
+
* than creating a second one.
|
|
182
|
+
*/
|
|
183
|
+
createCustomIndicator(indicator: CustomIndicatorInput, options: {
|
|
184
|
+
idempotencyKey: string;
|
|
185
|
+
}): Promise<JsonObject>;
|
|
186
|
+
/** List the custom data sources this account owns. */
|
|
187
|
+
listCustomIndicators(options?: {
|
|
188
|
+
includeArchived?: boolean;
|
|
189
|
+
}): Promise<JsonObject[]>;
|
|
190
|
+
/** Read one custom data source, including its current point count. */
|
|
191
|
+
getCustomIndicator(customIndicatorId: string): Promise<JsonObject>;
|
|
192
|
+
/**
|
|
193
|
+
* Add points to an existing series and return the updated indicator.
|
|
194
|
+
*
|
|
195
|
+
* Recurring collection must append to the same `customIndicatorId` every
|
|
196
|
+
* run; creating a fresh series per run splits the history into fragments a
|
|
197
|
+
* strategy cannot read. Re-sending an identical batch is safe — the
|
|
198
|
+
* duplicate is not written twice.
|
|
199
|
+
*
|
|
200
|
+
* The batch is unlimited in size and, as with creation, is sent inline or
|
|
201
|
+
* uploaded depending on how large it is.
|
|
202
|
+
*/
|
|
203
|
+
appendCustomIndicatorPoints(customIndicatorId: string, points: ReadonlyArray<CustomIndicatorPointInput>, options: {
|
|
204
|
+
idempotencyKey: string;
|
|
205
|
+
}): Promise<JsonObject>;
|
|
206
|
+
/**
|
|
207
|
+
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
208
|
+
*
|
|
209
|
+
* Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
|
|
210
|
+
* returned URL, then call `completeCustomIndicatorUpload`. Most callers can
|
|
211
|
+
* pass `points` to `createCustomIndicator` or
|
|
212
|
+
* `appendCustomIndicatorPoints` instead and skip all three steps.
|
|
213
|
+
*
|
|
214
|
+
* Retrying with the same `idempotencyKey` re-signs the same job, since the
|
|
215
|
+
* first URL expires in 15 minutes. Once its bytes have arrived the reply
|
|
216
|
+
* carries no `uploadUrl` — there is nothing left to send, so skip the PUT
|
|
217
|
+
* and wait on `jobId`.
|
|
218
|
+
*/
|
|
219
|
+
createCustomIndicatorUpload(customIndicatorId: string, options: {
|
|
220
|
+
fileName: string;
|
|
221
|
+
idempotencyKey: string;
|
|
222
|
+
format?: "csv" | "json" | "jsonl";
|
|
223
|
+
contentType?: string;
|
|
224
|
+
sizeBytes?: number;
|
|
225
|
+
}): Promise<JsonObject>;
|
|
226
|
+
/** Start validation of uploaded bytes and return the operation. */
|
|
227
|
+
completeCustomIndicatorUpload(customIndicatorId: string, jobId: string): Promise<JsonObject>;
|
|
228
|
+
/** Read an upload operation. `phase` distinguishes the live states. */
|
|
229
|
+
getCustomIndicatorUpload(customIndicatorId: string, jobId: string): Promise<JsonObject>;
|
|
230
|
+
/** Block until an upload is validated. See `waitForOperation`. */
|
|
231
|
+
waitForCustomIndicatorUpload(customIndicatorId: string, jobId: string, options?: WaitOptions): Promise<JsonObject>;
|
|
232
|
+
private uploadCustomIndicatorPoints;
|
|
130
233
|
createBacktests(backtests: ReadonlyArray<JobInput>, options: {
|
|
131
234
|
idempotencyKey: string;
|
|
132
235
|
}): Promise<JsonObject[]>;
|
|
@@ -192,6 +295,11 @@ export declare class NexusTradeClient {
|
|
|
192
295
|
/** @internal PortfolioHandle lazy-client attachment. */
|
|
193
296
|
export declare function clientTransport(client: NexusTradeClient): Transport;
|
|
194
297
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
298
|
+
export declare function createCustomIndicator(indicator: CustomIndicatorInput, options: {
|
|
299
|
+
idempotencyKey: string;
|
|
300
|
+
client?: NexusTradeClient;
|
|
301
|
+
}): Promise<JsonObject>;
|
|
302
|
+
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
195
303
|
export declare function createPortfolio(portfolio: JsonObject, options: {
|
|
196
304
|
idempotencyKey: string;
|
|
197
305
|
client?: NexusTradeClient;
|