nexustrade 1.0.0 → 1.2.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.
@@ -41,6 +41,12 @@ export declare const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
41
41
  export declare const DEFAULT_POLL_INTERVAL_SECONDS = 2;
42
42
  export declare const MAX_POLL_INTERVAL_SECONDS = 15;
43
43
  export declare const POLL_BACKOFF_FACTOR = 1.5;
44
+ export declare const DEFAULT_CONNECT_TIMEOUT_SECONDS = 300;
45
+ export declare const CONNECT_POLL_INTERVAL_SECONDS = 3;
46
+ export declare const MAX_UPLOAD_PUT_ATTEMPTS = 5;
47
+ export declare const UPLOAD_PUT_INITIAL_BACKOFF_SECONDS = 0.5;
48
+ export declare const UPLOAD_PUT_MAX_BACKOFF_SECONDS = 8;
49
+ export declare const UPLOAD_PUT_JITTER_SECONDS = 0.25;
44
50
  export declare class NexusTradeApiError extends Error {
45
51
  readonly status: number;
46
52
  readonly code: string;
@@ -133,8 +139,12 @@ export interface CustomIndicatorInput {
133
139
  name: string;
134
140
  description?: string;
135
141
  scope?: "global" | "asset";
142
+ pointKind?: "observation" | "period_aggregate" | "disclosed";
143
+ aggregatePeriod?: "1d" | "1w" | "1mo" | "1q";
136
144
  points?: ReadonlyArray<CustomIndicatorPointInput>;
137
145
  }
146
+ type IndicatorPointKind = NonNullable<CustomIndicatorInput["pointKind"]>;
147
+ type IndicatorAggregatePeriod = NonNullable<CustomIndicatorInput["aggregatePeriod"]>;
138
148
  export declare function waitForOperation(fetch: (operationId: string) => Promise<JsonObject>, operationId: string, options?: WaitOptions): Promise<JsonObject>;
139
149
  export declare class NexusTradeClient {
140
150
  private readonly transport;
@@ -202,7 +212,22 @@ export declare class NexusTradeClient {
202
212
  */
203
213
  appendCustomIndicatorPoints(customIndicatorId: string, points: ReadonlyArray<CustomIndicatorPointInput>, options: {
204
214
  idempotencyKey: string;
215
+ pointKind?: IndicatorPointKind;
216
+ aggregatePeriod?: IndicatorAggregatePeriod;
205
217
  }): Promise<JsonObject>;
218
+ /** Replace the complete series while retaining the same CustomIndicator id. */
219
+ replaceCustomIndicatorPoints(customIndicatorId: string, points: ReadonlyArray<CustomIndicatorPointInput>, options: {
220
+ idempotencyKey: string;
221
+ allowShrink?: boolean;
222
+ pointKind?: IndicatorPointKind;
223
+ aggregatePeriod?: IndicatorAggregatePeriod;
224
+ }): Promise<JsonObject>;
225
+ /** Soft-archive a CustomIndicator. Pass confirm when active portfolios use it. */
226
+ archiveCustomIndicator(customIndicatorId: string, options?: {
227
+ confirm?: boolean;
228
+ }): Promise<JsonObject>;
229
+ /** Restore a soft-archived CustomIndicator. */
230
+ restoreCustomIndicator(customIndicatorId: string): Promise<JsonObject>;
206
231
  /**
207
232
  * Open an upload slot and return a presigned `uploadUrl` to PUT to.
208
233
  *
@@ -222,6 +247,8 @@ export declare class NexusTradeClient {
222
247
  format?: "csv" | "json" | "jsonl";
223
248
  contentType?: string;
224
249
  sizeBytes?: number;
250
+ mode?: "append" | "replace";
251
+ allowShrink?: boolean;
225
252
  }): Promise<JsonObject>;
226
253
  /** Start validation of uploaded bytes and return the operation. */
227
254
  completeCustomIndicatorUpload(customIndicatorId: string, jobId: string): Promise<JsonObject>;
@@ -230,6 +257,53 @@ export declare class NexusTradeClient {
230
257
  /** Block until an upload is validated. See `waitForOperation`. */
231
258
  waitForCustomIndicatorUpload(customIndicatorId: string, jobId: string, options?: WaitOptions): Promise<JsonObject>;
232
259
  private uploadCustomIndicatorPoints;
260
+ /**
261
+ * Every connectable brokerage and whether this account has linked it.
262
+ *
263
+ * Reports all of them, connected or not, each with a `connectUrl` — an empty
264
+ * result would say nothing about what to do next.
265
+ */
266
+ listBrokerages(): Promise<JsonObject[]>;
267
+ /** Whether one named brokerage is connected. */
268
+ getBrokerage(brokerage: string): Promise<JsonObject>;
269
+ /**
270
+ * Resolve once the brokerage is connected, logging where to connect it.
271
+ *
272
+ * Linking a brokerage is an OAuth redirect, so an API key cannot complete it
273
+ * — a human has to open the URL. What this does is make that unmissable and
274
+ * then wait for it.
275
+ *
276
+ * `wait` defaults to whether stdout is a TTY. Interactively it logs the URL
277
+ * and polls until the link appears. Non-interactively — CI, cron, a piped
278
+ * script — it rejects with `brokerage_not_connected` at once rather than
279
+ * stalling for the timeout in front of nobody. Pass `wait` to override.
280
+ */
281
+ connectBrokerage(brokerage: string, options?: {
282
+ wait?: boolean;
283
+ timeoutSeconds?: number;
284
+ pollIntervalSeconds?: number;
285
+ }): Promise<JsonObject>;
286
+ /**
287
+ * Stage orders against a portfolio.
288
+ *
289
+ * **Paper orders are accepted immediately. Live orders are staged for
290
+ * approval and are never sent to a broker by this call.** A live response
291
+ * carries `requiresApproval: true` and an `approvalUrl`; nothing has traded
292
+ * until a human approves it there. No argument changes that.
293
+ *
294
+ * ```ts
295
+ * const result = await client.createOrders(
296
+ * portfolioId,
297
+ * [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
298
+ * side: "BUY", quantity: 10, orderType: "MARKET" }],
299
+ * { idempotencyKey: "rebalance-2024-04-01" },
300
+ * );
301
+ * if (result.requiresApproval) console.log("approve at", result.approvalUrl);
302
+ * ```
303
+ */
304
+ createOrders(portfolioId: string, orders: ReadonlyArray<JsonObject>, options: {
305
+ idempotencyKey: string;
306
+ }): Promise<JsonObject>;
233
307
  createBacktests(backtests: ReadonlyArray<JobInput>, options: {
234
308
  idempotencyKey: string;
235
309
  }): Promise<JsonObject[]>;
@@ -272,6 +346,29 @@ export declare class NexusTradeClient {
272
346
  }): Promise<JsonObject>;
273
347
  getLakeQuery(queryId: string): Promise<JsonObject>;
274
348
  cancelLakeQuery(queryId: string): Promise<JsonObject>;
349
+ /**
350
+ * Submit a natural-language stock screen. Returns immediately; poll it.
351
+ *
352
+ * `returnQuery` keeps the generated SQL, engine and catalog version on the
353
+ * result. It defaults on: the SQL is the audit trail, and without it the rows
354
+ * are a number nobody can re-derive. It is returned on failure regardless,
355
+ * because a rejected query is the most useful thing to read.
356
+ */
357
+ createNlScreen(question: string, options?: {
358
+ returnQuery?: boolean;
359
+ }): Promise<JsonObject>;
360
+ getNlScreen(screenId: string): Promise<JsonObject>;
361
+ cancelNlScreen(screenId: string): Promise<JsonObject>;
362
+ /** Block until a screen is terminal. See `waitForOperation`. */
363
+ waitForNlScreen(screenId: string, options?: WaitOptions): Promise<JsonObject>;
364
+ /**
365
+ * Submit a natural-language lake ask. Returns immediately; poll it.
366
+ */
367
+ createLakeAsk(question: string): Promise<JsonObject>;
368
+ getLakeAsk(askId: string): Promise<JsonObject>;
369
+ cancelLakeAsk(askId: string): Promise<JsonObject>;
370
+ /** Block until a lake ask is terminal. See `waitForOperation`. */
371
+ waitForLakeAsk(askId: string, options?: WaitOptions): Promise<JsonObject>;
275
372
  getLakeQueryManifest(queryId: string): Promise<JsonObject>;
276
373
  getLakeCatalog(): Promise<JsonObject[]>;
277
374
  describeLakeTable(table: string): Promise<JsonObject>;
@@ -304,3 +401,4 @@ export declare function createPortfolio(portfolio: JsonObject, options: {
304
401
  idempotencyKey: string;
305
402
  client?: NexusTradeClient;
306
403
  }): Promise<JsonObject>;
404
+ export {};
@@ -46,9 +46,33 @@ export const DEFAULT_POLL_INTERVAL_SECONDS = 2;
46
46
  export const MAX_POLL_INTERVAL_SECONDS = 15;
47
47
  export const POLL_BACKOFF_FACTOR = 1.5;
48
48
  const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
49
+ // Connecting a brokerage is a human opening a browser. Long enough for that,
50
+ // short enough that a forgotten terminal does not hang all afternoon.
51
+ export const DEFAULT_CONNECT_TIMEOUT_SECONDS = 300;
52
+ export const CONNECT_POLL_INTERVAL_SECONDS = 3;
53
+ function sleep(ms) {
54
+ return new Promise((resolve) => setTimeout(resolve, ms));
55
+ }
56
+ /** Whether a human is plausibly watching. Never throws on odd streams. */
57
+ function stdoutIsInteractive() {
58
+ try {
59
+ return process.stdout.isTTY === true;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
49
65
  // Point batches larger than this are uploaded rather than sent inline.
50
66
  const MAX_INLINE_POINT_BYTES = 512 * 1024;
51
67
  const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
68
+ // A presigned PUT crosses the open internet with no API-side retry behind it, so
69
+ // the client owns transient recovery. Jittered (unlike the poll backoff) because
70
+ // every client retrying a storage blip on the same schedule is the blip.
71
+ // checkSdkClientParity.ts asserts these match the Python SDK.
72
+ export const MAX_UPLOAD_PUT_ATTEMPTS = 5;
73
+ export const UPLOAD_PUT_INITIAL_BACKOFF_SECONDS = 0.5;
74
+ export const UPLOAD_PUT_MAX_BACKOFF_SECONDS = 8.0;
75
+ export const UPLOAD_PUT_JITTER_SECONDS = 0.25;
52
76
  const POINT_FIELDS = {
53
77
  timestamp: "timestamp",
54
78
  value: "value",
@@ -75,6 +99,22 @@ export class NexusTradeApiError extends Error {
75
99
  this.operationId = operationId;
76
100
  }
77
101
  }
102
+ function isRetryableUploadHttpStatus(status) {
103
+ return status === 408 || status === 429 || status >= 500;
104
+ }
105
+ /** Only a transport fault or a storage-side transient earns another PUT. */
106
+ function isRetryableUploadError(error) {
107
+ if (!(error instanceof NexusTradeApiError)) {
108
+ return false;
109
+ }
110
+ if (error.code === "transport_error") {
111
+ return true;
112
+ }
113
+ if (error.code === "upload_failed" && error.status !== NO_HTTP_STATUS) {
114
+ return isRetryableUploadHttpStatus(error.status);
115
+ }
116
+ return false;
117
+ }
78
118
  function origin(url) {
79
119
  const parsed = new URL(url);
80
120
  const scheme = parsed.protocol.replace(":", "").toLowerCase();
@@ -90,7 +130,7 @@ function sameOrigin(left, right) {
90
130
  return a.scheme === b.scheme && a.host === b.host && a.port === b.port;
91
131
  }
92
132
  function supportsBinary(transport) {
93
- return (typeof transport.requestBytes === "function");
133
+ return typeof transport.requestBytes === "function";
94
134
  }
95
135
  function supportsUpload(transport) {
96
136
  return typeof transport.putBytes === "function";
@@ -176,7 +216,9 @@ function decodeJsonObject(bytes, status) {
176
216
  catch {
177
217
  throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned invalid JSON.");
178
218
  }
179
- if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
219
+ if (typeof decoded !== "object" ||
220
+ decoded === null ||
221
+ Array.isArray(decoded)) {
180
222
  throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned a non-object JSON response.");
181
223
  }
182
224
  return decoded;
@@ -203,6 +245,23 @@ export class HttpTransport {
203
245
  }
204
246
  /** PUT a payload to a presigned storage URL. Sends no credential. */
205
247
  async putBytes(url, data, options) {
248
+ let delaySeconds = UPLOAD_PUT_INITIAL_BACKOFF_SECONDS;
249
+ for (let attempt = 0; attempt < MAX_UPLOAD_PUT_ATTEMPTS; attempt++) {
250
+ try {
251
+ await this.#putBytesOnce(url, data, options);
252
+ return;
253
+ }
254
+ catch (error) {
255
+ if (attempt >= MAX_UPLOAD_PUT_ATTEMPTS - 1 ||
256
+ !isRetryableUploadError(error)) {
257
+ throw error;
258
+ }
259
+ }
260
+ delaySeconds = Math.min(delaySeconds * 2, UPLOAD_PUT_MAX_BACKOFF_SECONDS);
261
+ await sleep((delaySeconds + Math.random() * UPLOAD_PUT_JITTER_SECONDS) * 1000);
262
+ }
263
+ }
264
+ async #putBytesOnce(url, data, options) {
206
265
  let parsed;
207
266
  try {
208
267
  parsed = new URL(url);
@@ -395,6 +454,129 @@ function customIndicatorPoints(points) {
395
454
  }
396
455
  return points.map(customIndicatorPoint);
397
456
  }
457
+ function dateOnly(value) {
458
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
459
+ return undefined;
460
+ }
461
+ const parsed = new Date(`${value}T00:00:00.000Z`);
462
+ return Number.isNaN(parsed.getTime()) ||
463
+ parsed.toISOString().slice(0, 10) !== value
464
+ ? undefined
465
+ : parsed;
466
+ }
467
+ function utcMidnight(day) {
468
+ return `${day.toISOString().slice(0, 10)}T00:00:00.000Z`;
469
+ }
470
+ function utcDateTime(value) {
471
+ const day = dateOnly(value);
472
+ if (day)
473
+ return day;
474
+ if (typeof value !== "string")
475
+ return undefined;
476
+ const hasExplicitZone = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/i.test(value);
477
+ if (!hasExplicitZone)
478
+ return undefined;
479
+ const parsed = new Date(value);
480
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
481
+ }
482
+ function addUtcDays(day, days) {
483
+ return new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate() + days));
484
+ }
485
+ function pointKindPoints(points, pointKind, aggregatePeriod) {
486
+ if (!pointKind) {
487
+ if (aggregatePeriod) {
488
+ throw new Error("aggregatePeriod requires pointKind period_aggregate.");
489
+ }
490
+ return points;
491
+ }
492
+ if (pointKind !== "period_aggregate" && aggregatePeriod) {
493
+ throw new Error("aggregatePeriod is only valid for period_aggregate.");
494
+ }
495
+ if (pointKind === "period_aggregate" && !aggregatePeriod) {
496
+ throw new Error("period_aggregate requires aggregatePeriod.");
497
+ }
498
+ return points.map((point, index) => {
499
+ const row = { ...point };
500
+ const eventDay = dateOnly(row.timestamp);
501
+ const availableDay = dateOnly(row.availableAt);
502
+ const eventTime = utcDateTime(row.timestamp);
503
+ const availableTime = utcDateTime(row.availableAt);
504
+ if (pointKind === "observation") {
505
+ if (row.availableAt === undefined) {
506
+ row.availableAt = eventDay ? utcMidnight(eventDay) : row.timestamp;
507
+ }
508
+ else if (eventDay && availableDay?.getTime() === eventDay.getTime()) {
509
+ row.availableAt = utcMidnight(eventDay);
510
+ }
511
+ else if (availableDay) {
512
+ row.availableAt = utcMidnight(addUtcDays(availableDay, 1));
513
+ }
514
+ if (eventTime &&
515
+ availableTime &&
516
+ availableTime.toISOString().slice(0, 10) >
517
+ eventTime.toISOString().slice(0, 10)) {
518
+ throw new Error(`Point ${index + 1}: observation availableAt is after the event date.`);
519
+ }
520
+ return row;
521
+ }
522
+ if (pointKind === "disclosed") {
523
+ if (row.availableAt === undefined) {
524
+ throw new Error(`Point ${index + 1}: disclosed pointKind requires availableAt.`);
525
+ }
526
+ if (availableDay) {
527
+ row.availableAt = utcMidnight(addUtcDays(availableDay, 1));
528
+ }
529
+ return row;
530
+ }
531
+ if (!eventTime) {
532
+ throw new Error(`Point ${index + 1}: aggregate timestamp must be date-only or include an explicit UTC offset.`);
533
+ }
534
+ if (eventTime.getUTCHours() !== 0 ||
535
+ eventTime.getUTCMinutes() !== 0 ||
536
+ eventTime.getUTCSeconds() !== 0 ||
537
+ eventTime.getUTCMilliseconds() !== 0) {
538
+ throw new Error(`Point ${index + 1}: aggregate timestamp must be UTC midnight.`);
539
+ }
540
+ let periodEnd;
541
+ if (aggregatePeriod === "1d") {
542
+ periodEnd = addUtcDays(eventTime, 1);
543
+ }
544
+ else if (aggregatePeriod === "1w") {
545
+ if (eventTime.getUTCDay() !== 1) {
546
+ throw new Error(`Point ${index + 1}: 1w timestamp must be a Monday.`);
547
+ }
548
+ periodEnd = addUtcDays(eventTime, 7);
549
+ }
550
+ else if (aggregatePeriod === "1mo") {
551
+ if (eventTime.getUTCDate() !== 1) {
552
+ throw new Error(`Point ${index + 1}: 1mo timestamp must be month start.`);
553
+ }
554
+ periodEnd = new Date(Date.UTC(eventTime.getUTCFullYear(), eventTime.getUTCMonth() + 1, 1));
555
+ }
556
+ else {
557
+ if (eventTime.getUTCDate() !== 1 ||
558
+ ![0, 3, 6, 9].includes(eventTime.getUTCMonth())) {
559
+ throw new Error(`Point ${index + 1}: 1q timestamp must be quarter start.`);
560
+ }
561
+ periodEnd = new Date(Date.UTC(eventTime.getUTCFullYear(), eventTime.getUTCMonth() + 3, 1));
562
+ }
563
+ const derived = utcMidnight(periodEnd);
564
+ if (row.availableAt === undefined) {
565
+ row.availableAt = derived;
566
+ }
567
+ else if (availableDay) {
568
+ const explicit = utcMidnight(addUtcDays(availableDay, 1));
569
+ if (explicit < derived) {
570
+ throw new Error(`Point ${index + 1}: availableAt precedes the aggregate close.`);
571
+ }
572
+ row.availableAt = explicit;
573
+ }
574
+ else if (availableTime && availableTime.getTime() < periodEnd.getTime()) {
575
+ throw new Error(`Point ${index + 1}: availableAt precedes the aggregate close.`);
576
+ }
577
+ return row;
578
+ });
579
+ }
398
580
  function pointsJsonl(points) {
399
581
  return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
400
582
  }
@@ -581,21 +763,25 @@ export class NexusTradeClient {
581
763
  * than creating a second one.
582
764
  */
583
765
  async createCustomIndicator(indicator, options) {
584
- const { name, description, scope, points, ...rest } = indicator;
766
+ const { name, description, scope, pointKind, aggregatePeriod, points, ...rest } = indicator;
585
767
  if (typeof name !== "string" || !name.trim()) {
586
768
  throw new Error("createCustomIndicator requires a name.");
587
769
  }
588
770
  const unknown = Object.keys(rest);
589
771
  if (unknown.length > 0) {
590
772
  throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
591
- "Expected name, description, scope, and points.");
773
+ "Expected name, description, scope, pointKind, aggregatePeriod, and points.");
592
774
  }
593
- const normalized = points ? customIndicatorPoints(points) : [];
775
+ const normalized = pointKindPoints(points ? customIndicatorPoints(points) : [], pointKind, aggregatePeriod);
594
776
  const body = { name: name.trim() };
595
777
  if (description !== undefined)
596
778
  body.description = description;
597
779
  if (scope !== undefined)
598
780
  body.scope = scope;
781
+ if (pointKind !== undefined)
782
+ body.pointKind = pointKind;
783
+ if (aggregatePeriod !== undefined)
784
+ body.aggregatePeriod = aggregatePeriod;
599
785
  const inline = normalized.length > 0 &&
600
786
  inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
601
787
  if (inline)
@@ -646,12 +832,21 @@ export class NexusTradeClient {
646
832
  * uploaded depending on how large it is.
647
833
  */
648
834
  async appendCustomIndicatorPoints(customIndicatorId, points, options) {
649
- const normalized = customIndicatorPoints(points);
835
+ const normalized = pointKindPoints(customIndicatorPoints(points), options.pointKind, options.aggregatePeriod);
650
836
  if (normalized.length === 0) {
651
837
  throw new Error("appendCustomIndicatorPoints needs at least one point.");
652
838
  }
653
839
  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 });
840
+ const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, {
841
+ body: {
842
+ points: normalized,
843
+ ...(options.pointKind ? { pointKind: options.pointKind } : {}),
844
+ ...(options.aggregatePeriod
845
+ ? { aggregatePeriod: options.aggregatePeriod }
846
+ : {}),
847
+ },
848
+ idempotencyKey: options.idempotencyKey,
849
+ });
655
850
  const indicator = response.indicator;
656
851
  if (!isJsonObject(indicator)) {
657
852
  throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
@@ -664,6 +859,43 @@ export class NexusTradeClient {
664
859
  upload,
665
860
  };
666
861
  }
862
+ /** Replace the complete series while retaining the same CustomIndicator id. */
863
+ async replaceCustomIndicatorPoints(customIndicatorId, points, options) {
864
+ const normalized = pointKindPoints(customIndicatorPoints(points), options.pointKind, options.aggregatePeriod);
865
+ if (normalized.length === 0) {
866
+ throw new Error("replaceCustomIndicatorPoints needs at least one point.");
867
+ }
868
+ if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
869
+ return customIndicatorOf(await this.transport.request("PUT", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, {
870
+ body: {
871
+ points: normalized,
872
+ allowShrink: options.allowShrink === true,
873
+ ...(options.pointKind ? { pointKind: options.pointKind } : {}),
874
+ ...(options.aggregatePeriod
875
+ ? { aggregatePeriod: options.aggregatePeriod }
876
+ : {}),
877
+ },
878
+ idempotencyKey: options.idempotencyKey,
879
+ }));
880
+ }
881
+ const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey, { mode: "replace", allowShrink: options.allowShrink === true });
882
+ return {
883
+ ...(await this.getCustomIndicator(customIndicatorId)),
884
+ upload,
885
+ };
886
+ }
887
+ /** Soft-archive a CustomIndicator. Pass confirm when active portfolios use it. */
888
+ async archiveCustomIndicator(customIndicatorId, options = {}) {
889
+ const response = await this.transport.request("DELETE", `custom-indicators/${encodePathSegment(customIndicatorId)}`, { body: { confirm: options.confirm === true } });
890
+ if (!isJsonObject(response.archive)) {
891
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator archive response is missing archive details.");
892
+ }
893
+ return response.archive;
894
+ }
895
+ /** Restore a soft-archived CustomIndicator. */
896
+ async restoreCustomIndicator(customIndicatorId) {
897
+ return customIndicatorOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/restore`, { body: {} }));
898
+ }
667
899
  /**
668
900
  * Open an upload slot and return a presigned `uploadUrl` to PUT to.
669
901
  *
@@ -686,6 +918,10 @@ export class NexusTradeClient {
686
918
  body.contentType = options.contentType;
687
919
  if (options.sizeBytes !== undefined)
688
920
  body.sizeBytes = options.sizeBytes;
921
+ if (options.mode !== undefined)
922
+ body.mode = options.mode;
923
+ if (options.allowShrink !== undefined)
924
+ body.allowShrink = options.allowShrink;
689
925
  const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
690
926
  const ticket = response.ticket;
691
927
  if (!isJsonObject(ticket) || !ticket.jobId) {
@@ -707,7 +943,7 @@ export class NexusTradeClient {
707
943
  async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
708
944
  return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
709
945
  }
710
- async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
946
+ async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey, options = {}) {
711
947
  const payload = pointsJsonl(points);
712
948
  if (payload.length > MAX_UPLOAD_BYTES) {
713
949
  throw new Error(`${points.length} points serialize to ` +
@@ -722,6 +958,8 @@ export class NexusTradeClient {
722
958
  format: "jsonl",
723
959
  sizeBytes: payload.length,
724
960
  idempotencyKey,
961
+ mode: options.mode,
962
+ allowShrink: options.allowShrink,
725
963
  });
726
964
  const jobId = String(ticket.jobId);
727
965
  // No upload URL means this batch already reached the server on an earlier
@@ -738,6 +976,97 @@ export class NexusTradeClient {
738
976
  }
739
977
  return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
740
978
  }
979
+ /**
980
+ * Every connectable brokerage and whether this account has linked it.
981
+ *
982
+ * Reports all of them, connected or not, each with a `connectUrl` — an empty
983
+ * result would say nothing about what to do next.
984
+ */
985
+ async listBrokerages() {
986
+ const response = await this.transport.request("GET", "brokerages");
987
+ const brokerages = response.brokerages;
988
+ if (!Array.isArray(brokerages)) {
989
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerages.");
990
+ }
991
+ return brokerages.filter((row) => isJsonObject(row));
992
+ }
993
+ /** Whether one named brokerage is connected. */
994
+ async getBrokerage(brokerage) {
995
+ const response = await this.transport.request("GET", `brokerages/${encodePathSegment(brokerage)}`);
996
+ const result = response.brokerage;
997
+ if (!isJsonObject(result)) {
998
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerage.");
999
+ }
1000
+ return result;
1001
+ }
1002
+ /**
1003
+ * Resolve once the brokerage is connected, logging where to connect it.
1004
+ *
1005
+ * Linking a brokerage is an OAuth redirect, so an API key cannot complete it
1006
+ * — a human has to open the URL. What this does is make that unmissable and
1007
+ * then wait for it.
1008
+ *
1009
+ * `wait` defaults to whether stdout is a TTY. Interactively it logs the URL
1010
+ * and polls until the link appears. Non-interactively — CI, cron, a piped
1011
+ * script — it rejects with `brokerage_not_connected` at once rather than
1012
+ * stalling for the timeout in front of nobody. Pass `wait` to override.
1013
+ */
1014
+ async connectBrokerage(brokerage, options = {}) {
1015
+ let current = await this.getBrokerage(brokerage);
1016
+ if (current.connected === true)
1017
+ return current;
1018
+ const connectUrl = String(current.connectUrl ?? "");
1019
+ const message = `${brokerage} is not connected. Connect it at ${connectUrl} — ` +
1020
+ "linking a brokerage is a browser flow an API key cannot complete.";
1021
+ const shouldWait = options.wait ?? stdoutIsInteractive();
1022
+ if (!shouldWait) {
1023
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "brokerage_not_connected", message);
1024
+ }
1025
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_CONNECT_TIMEOUT_SECONDS;
1026
+ const pollSeconds = options.pollIntervalSeconds ?? CONNECT_POLL_INTERVAL_SECONDS;
1027
+ console.log(message);
1028
+ console.log(`Waiting for ${brokerage} to be connected…`);
1029
+ const deadline = Date.now() + timeoutSeconds * 1000;
1030
+ for (;;) {
1031
+ const remaining = deadline - Date.now();
1032
+ if (remaining <= 0) {
1033
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "brokerage_not_connected", `${brokerage} was still not connected after ${timeoutSeconds}s. ${message}`);
1034
+ }
1035
+ await sleep(Math.min(pollSeconds * 1000, remaining));
1036
+ current = await this.getBrokerage(brokerage);
1037
+ if (current.connected === true) {
1038
+ console.log(`${brokerage} connected.`);
1039
+ return current;
1040
+ }
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Stage orders against a portfolio.
1045
+ *
1046
+ * **Paper orders are accepted immediately. Live orders are staged for
1047
+ * approval and are never sent to a broker by this call.** A live response
1048
+ * carries `requiresApproval: true` and an `approvalUrl`; nothing has traded
1049
+ * until a human approves it there. No argument changes that.
1050
+ *
1051
+ * ```ts
1052
+ * const result = await client.createOrders(
1053
+ * portfolioId,
1054
+ * [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
1055
+ * side: "BUY", quantity: 10, orderType: "MARKET" }],
1056
+ * { idempotencyKey: "rebalance-2024-04-01" },
1057
+ * );
1058
+ * if (result.requiresApproval) console.log("approve at", result.approvalUrl);
1059
+ * ```
1060
+ */
1061
+ async createOrders(portfolioId, orders, options) {
1062
+ if (!Array.isArray(orders) || orders.length === 0) {
1063
+ throw new Error("createOrders needs at least one order.");
1064
+ }
1065
+ return this.transport.request("POST", "orders", {
1066
+ body: { portfolioId, orders: orders.map((order) => ({ ...order })) },
1067
+ idempotencyKey: options.idempotencyKey,
1068
+ });
1069
+ }
741
1070
  async createBacktests(backtests, options) {
742
1071
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
743
1072
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -833,6 +1162,50 @@ export class NexusTradeClient {
833
1162
  async cancelLakeQuery(queryId) {
834
1163
  return operationOf(await this.transport.request("POST", `lake/queries/${encodePathSegment(queryId)}/cancel`));
835
1164
  }
1165
+ /**
1166
+ * Submit a natural-language stock screen. Returns immediately; poll it.
1167
+ *
1168
+ * `returnQuery` keeps the generated SQL, engine and catalog version on the
1169
+ * result. It defaults on: the SQL is the audit trail, and without it the rows
1170
+ * are a number nobody can re-derive. It is returned on failure regardless,
1171
+ * because a rejected query is the most useful thing to read.
1172
+ */
1173
+ async createNlScreen(question, options = {}) {
1174
+ return operationOf(await this.transport.request("POST", "nl/screens", {
1175
+ body: {
1176
+ question,
1177
+ returnQuery: options.returnQuery ?? true,
1178
+ },
1179
+ }));
1180
+ }
1181
+ async getNlScreen(screenId) {
1182
+ return operationOf(await this.transport.request("GET", `nl/screens/${encodePathSegment(screenId)}`));
1183
+ }
1184
+ async cancelNlScreen(screenId) {
1185
+ return operationOf(await this.transport.request("POST", `nl/screens/${encodePathSegment(screenId)}/cancel`));
1186
+ }
1187
+ /** Block until a screen is terminal. See `waitForOperation`. */
1188
+ async waitForNlScreen(screenId, options = {}) {
1189
+ return waitForOperation((id) => this.getNlScreen(id), screenId, options);
1190
+ }
1191
+ /**
1192
+ * Submit a natural-language lake ask. Returns immediately; poll it.
1193
+ */
1194
+ async createLakeAsk(question) {
1195
+ return operationOf(await this.transport.request("POST", "lake/ask", {
1196
+ body: { question },
1197
+ }));
1198
+ }
1199
+ async getLakeAsk(askId) {
1200
+ return operationOf(await this.transport.request("GET", `lake/ask/${encodePathSegment(askId)}`));
1201
+ }
1202
+ async cancelLakeAsk(askId) {
1203
+ return operationOf(await this.transport.request("POST", `lake/ask/${encodePathSegment(askId)}/cancel`));
1204
+ }
1205
+ /** Block until a lake ask is terminal. See `waitForOperation`. */
1206
+ async waitForLakeAsk(askId, options = {}) {
1207
+ return waitForOperation((id) => this.getLakeAsk(id), askId, options);
1208
+ }
836
1209
  async getLakeQueryManifest(queryId) {
837
1210
  return operationOf(await this.transport.request("GET", `lake/queries/${encodePathSegment(queryId)}/manifest`));
838
1211
  }