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.
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * Typed NexusTrade JSON API client.
3
3
  *
4
- * Mirrors the Python client method-for-method; `verifyNtSdk.ts` asserts the two
5
- * surfaces stay identical. Transport-generic: callers pass an API key/base URL,
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,18 @@ 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
+ // Point batches larger than this are uploaded rather than sent inline.
50
+ const MAX_INLINE_POINT_BYTES = 512 * 1024;
51
+ const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
52
+ const POINT_FIELDS = {
53
+ timestamp: "timestamp",
54
+ value: "value",
55
+ ticker: "ticker",
56
+ assetType: "assetType",
57
+ asset_type: "assetType",
58
+ availableAt: "availableAt",
59
+ available_at: "availableAt",
60
+ };
50
61
  export class NexusTradeApiError extends Error {
51
62
  status;
52
63
  code;
@@ -81,6 +92,9 @@ function sameOrigin(left, right) {
81
92
  function supportsBinary(transport) {
82
93
  return (typeof transport.requestBytes === "function");
83
94
  }
95
+ function supportsUpload(transport) {
96
+ return typeof transport.putBytes === "function";
97
+ }
84
98
  function assertValidApiKey(apiKey) {
85
99
  const invalid = typeof apiKey !== "string" ||
86
100
  apiKey.length === 0 ||
@@ -187,6 +201,43 @@ export class HttpTransport {
187
201
  get baseUrl() {
188
202
  return this.#baseUrl;
189
203
  }
204
+ /** PUT a payload to a presigned storage URL. Sends no credential. */
205
+ async putBytes(url, data, options) {
206
+ let parsed;
207
+ try {
208
+ parsed = new URL(url);
209
+ }
210
+ catch {
211
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a malformed upload URL.");
212
+ }
213
+ if (parsed.protocol.toLowerCase() !== "https:") {
214
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a non-HTTPS upload URL.");
215
+ }
216
+ const controller = new AbortController();
217
+ const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
218
+ try {
219
+ let response;
220
+ try {
221
+ response = await fetch(url, {
222
+ method: "PUT",
223
+ headers: { "Content-Type": options.contentType },
224
+ body: new Blob([data], { type: options.contentType }),
225
+ redirect: "manual",
226
+ signal: controller.signal,
227
+ });
228
+ }
229
+ catch (error) {
230
+ const reason = error instanceof Error ? error.message : String(error);
231
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
232
+ }
233
+ if (!response.ok) {
234
+ throw new NexusTradeApiError(response.status, "upload_failed", `Storage rejected the upload: ${response.statusText || `HTTP ${response.status}`}.`);
235
+ }
236
+ }
237
+ finally {
238
+ clearTimeout(timer);
239
+ }
240
+ }
190
241
  async request(method, path, options = {}) {
191
242
  const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
192
243
  const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
@@ -306,18 +357,50 @@ function operationFailure(operation, operationId, status) {
306
357
  }
307
358
  return new NexusTradeApiError(NO_HTTP_STATUS, code, message, operationId);
308
359
  }
360
+ function pointTimestamp(value) {
361
+ return value instanceof Date ? value.toISOString() : value;
362
+ }
309
363
  /**
310
- * Poll `fetch(operationId)` until the operation reaches a terminal state.
364
+ * Normalize one point to its wire shape.
311
365
  *
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`.
315
- *
316
- * Resolves with the terminal operation. Rejects with `NexusTradeApiError` on
317
- * timeout, and on a failed/cancelled operation unless `raiseOnFailure` is
318
- * false. Transport errors from `fetch` propagate — a poller that swallowed
319
- * them would report an infrastructure outage as a still-running job.
366
+ * Accepts snake_case or camelCase field names and Date objects. Throws on an
367
+ * unrecognized field rather than dropping it silently.
320
368
  */
369
+ function customIndicatorPoint(point) {
370
+ const normalized = {};
371
+ for (const [key, value] of Object.entries(point)) {
372
+ const target = POINT_FIELDS[key];
373
+ if (target === undefined) {
374
+ throw new Error(`Unknown custom indicator point field "${key}". Points accept ` +
375
+ "timestamp, value, ticker, assetType, and availableAt.");
376
+ }
377
+ if (value === undefined || value === null)
378
+ continue;
379
+ normalized[target] =
380
+ target === "timestamp" || target === "availableAt"
381
+ ? pointTimestamp(value)
382
+ : value;
383
+ }
384
+ if (normalized.timestamp === undefined) {
385
+ throw new Error("Every custom indicator point needs a timestamp.");
386
+ }
387
+ if (normalized.value === undefined) {
388
+ throw new Error("Every custom indicator point needs a value.");
389
+ }
390
+ return normalized;
391
+ }
392
+ function customIndicatorPoints(points) {
393
+ if (!Array.isArray(points)) {
394
+ throw new Error("points must be an array of point objects.");
395
+ }
396
+ return points.map(customIndicatorPoint);
397
+ }
398
+ function pointsJsonl(points) {
399
+ return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
400
+ }
401
+ function inlinePointBytes(points) {
402
+ return new TextEncoder().encode(JSON.stringify(points)).length;
403
+ }
321
404
  export async function waitForOperation(fetch, operationId, options = {}) {
322
405
  const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
323
406
  const pollIntervalSeconds = options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
@@ -392,7 +475,7 @@ export class NexusTradeClient {
392
475
  return result;
393
476
  }
394
477
  /**
395
- * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
478
+ * List portfolios with optional filters and pagination.
396
479
  * `includePositions` defaults off when `search` is set.
397
480
  */
398
481
  async listPortfolios(options = {}) {
@@ -471,6 +554,190 @@ export class NexusTradeClient {
471
554
  }
472
555
  return result;
473
556
  }
557
+ /**
558
+ * Create a custom data source and return it, including its id.
559
+ *
560
+ * `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
561
+ * every point needs a `ticker`); it defaults to `"global"` and cannot be
562
+ * changed later. `points` is optional and unlimited in size — small batches
563
+ * are sent with the request, larger ones are uploaded, and the returned
564
+ * indicator reflects what landed either way.
565
+ *
566
+ * The id it returns is what a `CustomIndicator` node binds to:
567
+ *
568
+ * ```ts
569
+ * const series = await client.createCustomIndicator(
570
+ * {
571
+ * name: "WSB NVDA Mentions",
572
+ * scope: "asset",
573
+ * points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
574
+ * },
575
+ * { idempotencyKey: "wsb-mentions-v1" },
576
+ * );
577
+ * CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
578
+ * ```
579
+ *
580
+ * Retrying with the same `idempotencyKey` returns the original series rather
581
+ * than creating a second one.
582
+ */
583
+ async createCustomIndicator(indicator, options) {
584
+ const { name, description, scope, points, ...rest } = indicator;
585
+ if (typeof name !== "string" || !name.trim()) {
586
+ throw new Error("createCustomIndicator requires a name.");
587
+ }
588
+ const unknown = Object.keys(rest);
589
+ if (unknown.length > 0) {
590
+ throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
591
+ "Expected name, description, scope, and points.");
592
+ }
593
+ const normalized = points ? customIndicatorPoints(points) : [];
594
+ const body = { name: name.trim() };
595
+ if (description !== undefined)
596
+ body.description = description;
597
+ if (scope !== undefined)
598
+ body.scope = scope;
599
+ const inline = normalized.length > 0 &&
600
+ inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
601
+ if (inline)
602
+ body.points = normalized;
603
+ const created = customIndicatorOf(await this.transport.request("POST", "custom-indicators", {
604
+ body,
605
+ idempotencyKey: options.idempotencyKey,
606
+ }));
607
+ if (inline || normalized.length === 0)
608
+ return created;
609
+ const customIndicatorId = String(created.customIndicatorId);
610
+ // The same key is safe here: the server namespaces an idempotency claim
611
+ // by operation, and deriving a suffixed key could overrun its
612
+ // 160-character limit.
613
+ const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
614
+ return {
615
+ ...(await this.getCustomIndicator(customIndicatorId)),
616
+ upload,
617
+ };
618
+ }
619
+ /** List the custom data sources this account owns. */
620
+ async listCustomIndicators(options = {}) {
621
+ const query = encodeQuery({
622
+ includeArchived: options.includeArchived === undefined
623
+ ? undefined
624
+ : String(options.includeArchived),
625
+ });
626
+ const response = await this.transport.request("GET", `custom-indicators${query}`);
627
+ const indicators = response.indicators;
628
+ if (!Array.isArray(indicators)) {
629
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator list response is missing indicators.");
630
+ }
631
+ return indicators.filter((row) => isJsonObject(row));
632
+ }
633
+ /** Read one custom data source, including its current point count. */
634
+ async getCustomIndicator(customIndicatorId) {
635
+ return customIndicatorOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}`));
636
+ }
637
+ /**
638
+ * Add points to an existing series and return the updated indicator.
639
+ *
640
+ * Recurring collection must append to the same `customIndicatorId` every
641
+ * run; creating a fresh series per run splits the history into fragments a
642
+ * strategy cannot read. Re-sending an identical batch is safe — the
643
+ * duplicate is not written twice.
644
+ *
645
+ * The batch is unlimited in size and, as with creation, is sent inline or
646
+ * uploaded depending on how large it is.
647
+ */
648
+ async appendCustomIndicatorPoints(customIndicatorId, points, options) {
649
+ const normalized = customIndicatorPoints(points);
650
+ if (normalized.length === 0) {
651
+ throw new Error("appendCustomIndicatorPoints needs at least one point.");
652
+ }
653
+ if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
654
+ const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, { body: { points: normalized }, idempotencyKey: options.idempotencyKey });
655
+ const indicator = response.indicator;
656
+ if (!isJsonObject(indicator)) {
657
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
658
+ }
659
+ return indicator;
660
+ }
661
+ const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
662
+ return {
663
+ ...(await this.getCustomIndicator(customIndicatorId)),
664
+ upload,
665
+ };
666
+ }
667
+ /**
668
+ * Open an upload slot and return a presigned `uploadUrl` to PUT to.
669
+ *
670
+ * Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
671
+ * returned URL, then call `completeCustomIndicatorUpload`. Most callers can
672
+ * pass `points` to `createCustomIndicator` or
673
+ * `appendCustomIndicatorPoints` instead and skip all three steps.
674
+ *
675
+ * Retrying with the same `idempotencyKey` re-signs the same job, since the
676
+ * first URL expires in 15 minutes. Once its bytes have arrived the reply
677
+ * carries no `uploadUrl` — there is nothing left to send, so skip the PUT
678
+ * and wait on `jobId`.
679
+ */
680
+ async createCustomIndicatorUpload(customIndicatorId, options) {
681
+ const body = {
682
+ fileName: options.fileName,
683
+ format: options.format ?? "jsonl",
684
+ };
685
+ if (options.contentType !== undefined)
686
+ body.contentType = options.contentType;
687
+ if (options.sizeBytes !== undefined)
688
+ body.sizeBytes = options.sizeBytes;
689
+ const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
690
+ const ticket = response.ticket;
691
+ if (!isJsonObject(ticket) || !ticket.jobId) {
692
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Upload response is missing ticket.");
693
+ }
694
+ return ticket;
695
+ }
696
+ /** Start validation of uploaded bytes and return the operation. */
697
+ async completeCustomIndicatorUpload(customIndicatorId, jobId) {
698
+ return operationOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
699
+ `/uploads/${encodePathSegment(jobId)}/complete`, { body: {} }));
700
+ }
701
+ /** Read an upload operation. `phase` distinguishes the live states. */
702
+ async getCustomIndicatorUpload(customIndicatorId, jobId) {
703
+ return operationOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
704
+ `/uploads/${encodePathSegment(jobId)}`));
705
+ }
706
+ /** Block until an upload is validated. See `waitForOperation`. */
707
+ async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
708
+ return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
709
+ }
710
+ async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
711
+ const payload = pointsJsonl(points);
712
+ if (payload.length > MAX_UPLOAD_BYTES) {
713
+ throw new Error(`${points.length} points serialize to ` +
714
+ `${Math.floor(payload.length / (1024 * 1024))} MB, over the 100 MB ` +
715
+ "upload limit. Send them in several batches.");
716
+ }
717
+ if (!supportsUpload(this.transport)) {
718
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Uploading a large point batch requires HttpTransport.putBytes.");
719
+ }
720
+ const ticket = await this.createCustomIndicatorUpload(customIndicatorId, {
721
+ fileName: `${customIndicatorId}-points.jsonl`,
722
+ format: "jsonl",
723
+ sizeBytes: payload.length,
724
+ idempotencyKey,
725
+ });
726
+ const jobId = String(ticket.jobId);
727
+ // No upload URL means this batch already reached the server on an earlier
728
+ // attempt, so resume at polling instead of re-sending it.
729
+ if (ticket.uploadUrl) {
730
+ const headers = ticket.headers;
731
+ const contentType = isJsonObject(headers) && typeof headers["Content-Type"] === "string"
732
+ ? headers["Content-Type"]
733
+ : "application/x-ndjson";
734
+ await this.transport.putBytes(String(ticket.uploadUrl), payload, {
735
+ contentType,
736
+ });
737
+ await this.completeCustomIndicatorUpload(customIndicatorId, jobId);
738
+ }
739
+ return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
740
+ }
474
741
  async createBacktests(backtests, options) {
475
742
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
476
743
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -657,6 +924,13 @@ function backtestInput(item) {
657
924
  }
658
925
  return normalized;
659
926
  }
927
+ function customIndicatorOf(response) {
928
+ const indicator = response.indicator;
929
+ if (!isJsonObject(indicator) || !indicator.customIndicatorId) {
930
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
931
+ }
932
+ return indicator;
933
+ }
660
934
  function operationOf(response) {
661
935
  const operation = response.operation;
662
936
  if (!isJsonObject(operation)) {
@@ -669,6 +943,13 @@ export function clientTransport(client) {
669
943
  return client.transport;
670
944
  }
671
945
  /** Convenience wrapper for scripts that do not need a persistent client. */
946
+ export async function createCustomIndicator(indicator, options) {
947
+ const client = options.client ?? NexusTradeClient.fromEnvironment();
948
+ return client.createCustomIndicator(indicator, {
949
+ idempotencyKey: options.idempotencyKey,
950
+ });
951
+ }
952
+ /** Convenience wrapper for scripts that do not need a persistent client. */
672
953
  export async function createPortfolio(portfolio, options) {
673
954
  const client = options.client ?? NexusTradeClient.fromEnvironment();
674
955
  return client.createPortfolio(portfolio, {
@@ -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";
@@ -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`. Mirrors `portfolio_handle.py`.
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";
@@ -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`. Mirrors `portfolio_handle.py`.
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) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexustrade",
3
- "version": "0.4.0",
3
+ "version": "1.0.0",
4
4
  "description": "Typed TypeScript SDK for NexusTrade portfolio authoring, backtesting, and optimization",
5
5
  "license": "MIT",
6
6
  "author": "Starks Technology",