nexustrade 1.35.0 → 1.37.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 CHANGED
@@ -145,6 +145,8 @@ For daily market prices, prefer `lake.query("sec_daily_ohlc", ...)` or the
145
145
  canonical OHLC helper. `daily_ohlc` is a legacy/vendor table and may lag the
146
146
  canonical daily series.
147
147
 
148
+ `client.listOrders({ portfolioId, statuses, page, limit })` lists owned orders with a read key. `client.cancelOrders(orderIds, { idempotencyKey, portfolioId })` cancels explicit IDs with a trade key. Inspect both `canceled` and `rejected`, and reuse the same key/payload for retries. Defaults and status gates are documented in README.
149
+
148
150
  ## Recipes
149
151
 
150
152
  <details open>
package/README.md CHANGED
@@ -508,6 +508,50 @@ approval. The brokerage boundary refuses an unapproved live order regardless of
508
508
  what any caller asks for, so this is a property of the system rather than a
509
509
  promise made by this method. At most 50 orders per request.
510
510
 
511
+ Listing requires a `read` key; cancellation requires a `trade` key. Both
512
+ require a registered account and are unavailable inside compute sandboxes.
513
+
514
+ ```ts
515
+ const page = await client.listOrders({
516
+ portfolioId,
517
+ statuses: ["Accepted", "Pending User Approval"],
518
+ page: 1,
519
+ limit: 50,
520
+ });
521
+ console.log(page.orders, page.totalPages);
522
+
523
+ // Cancel only explicit IDs you selected from the listing.
524
+ const cancellation = await client.cancelOrders(["ORDER_ID"], {
525
+ portfolioId,
526
+ idempotencyKey: "cancel-order-v1",
527
+ });
528
+ console.log(cancellation.canceled, cancellation.rejected);
529
+ ```
530
+
531
+ Listing defaults to `Accepted` and `Pending User Approval`. Request `Pending`,
532
+ `Partially Filled`, `Filled`, or `Canceled` explicitly to inspect other states.
533
+ Pages are 1-based, with a default limit of 50 and a maximum of 100. The response
534
+ includes `orders`, `total`, `returned`, `page`, `limit`, `totalPages`, `truncated`,
535
+ and `ignoredStatuses`; unknown statuses are reported there when valid statuses
536
+ remain, and a wholly invalid filter raises an error. Set
537
+ `includeRebalanceOrders: true`
538
+ for an additional page of pending rebalance actions. Their IDs are separate from
539
+ order IDs and cannot be passed to cancellation.
540
+
541
+ Cancellation accepts at most 50 IDs and returns `canceled` and `rejected` arrays.
542
+ Each success includes `orderId`, `mode` (`db`, `broker`, or `already_canceled`),
543
+ and `canceledOrderIds`, including sibling legs canceled together. Each rejection
544
+ includes `orderId` and `reason`. Inspect both arrays: HTTP success does not mean
545
+ every order was canceled. The optional portfolio ID guards against canceling an
546
+ order from another portfolio. Reuse the same idempotency key and identical
547
+ payload when retrying; an already canceled order returns `already_canceled`.
548
+
549
+ The same cancellation rules as MCP/REST apply: `Accepted` and
550
+ `Pending User Approval` orders can be canceled; `Pending`, `Partially Filled`,
551
+ and `Filled` orders are rejected. Rebalance children must be managed through
552
+ their parent action. Live orders with a broker ID invoke broker cancellation.
553
+ Creation still stages live orders for human approval.
554
+
511
555
  ## Your own data
512
556
 
513
557
  A custom data source is a time series you own — sentiment counts, a proprietary
@@ -716,6 +760,8 @@ is missing here, so this list cannot drift from the code.
716
760
  | `getBrokerage(brokerage)` | Whether one brokerage is linked |
717
761
  | `connectBrokerage(brokerage, { wait })` | Log the connect URL and wait for the link |
718
762
  | `createOrders(portfolioId, orders, { idempotencyKey })` | Stage orders; live ones need approval |
763
+ | `listOrders(options)` | List owned orders by portfolio/status, with pagination |
764
+ | `cancelOrders(orderIds, { idempotencyKey, portfolioId })` | Cancel explicit IDs with a result for each |
719
765
 
720
766
  **Portfolios**
721
767
 
@@ -518,6 +518,7 @@ const BACKTEST_ARG_NAMES = [
518
518
  ["initial_value", "initialValue"],
519
519
  ["generate_events", "generateEvents"],
520
520
  ["fee_config", "feeConfig"],
521
+ ["dividend_policy", "dividendPolicy"],
521
522
  ];
522
523
  function isJsonObject(value) {
523
524
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1264,6 +1265,41 @@ class NexusTradeClient {
1264
1265
  idempotencyKey: options.idempotencyKey,
1265
1266
  });
1266
1267
  }
1268
+ /** List owned orders. Defaults to Accepted and Pending User Approval; pages are 1-based. */
1269
+ async listOrders(options = {}) {
1270
+ if (options.statuses !== undefined && options.statuses.length === 0) {
1271
+ throw new Error("statuses must be a non-empty array.");
1272
+ }
1273
+ const query = encodeQuery({
1274
+ portfolioId: options.portfolioId,
1275
+ statuses: options.statuses?.join(","),
1276
+ page: options.page === undefined ? undefined : String(options.page),
1277
+ limit: options.limit === undefined ? undefined : String(options.limit),
1278
+ includeRebalanceOrders: options.includeRebalanceOrders === undefined
1279
+ ? undefined
1280
+ : String(options.includeRebalanceOrders),
1281
+ });
1282
+ return this.transport.request("GET", `orders${query}`);
1283
+ }
1284
+ /** Cancel explicit order IDs; inspect both canceled and rejected. Live cancellation reaches the broker. */
1285
+ async cancelOrders(orderIds, options) {
1286
+ if (!Array.isArray(orderIds) ||
1287
+ orderIds.length === 0 ||
1288
+ orderIds.some((id) => typeof id !== "string" || !id.trim())) {
1289
+ throw new Error("orderIds must be a non-empty array of non-empty strings.");
1290
+ }
1291
+ if (orderIds.length > 50)
1292
+ throw new Error("at most 50 orders may be canceled per request.");
1293
+ return this.transport.request("POST", "orders/cancel", {
1294
+ body: {
1295
+ orderIds: [...orderIds],
1296
+ ...(options.portfolioId === undefined
1297
+ ? {}
1298
+ : { portfolioId: options.portfolioId }),
1299
+ },
1300
+ idempotencyKey: options.idempotencyKey,
1301
+ });
1302
+ }
1267
1303
  async createBacktests(backtests, options) {
1268
1304
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
1269
1305
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -2096,6 +2096,7 @@ const backtest = (portfolio, config) => ({
2096
2096
  "initial_value": config.initialValue,
2097
2097
  "generate_events": config.generateEvents,
2098
2098
  "fee_config": config.feeConfig,
2099
+ "dividend_policy": config.dividendPolicy,
2099
2100
  }),
2100
2101
  });
2101
2102
  exports.backtest = backtest;
@@ -132,6 +132,8 @@ class PortfolioHandle {
132
132
  supportsFractionalShares;
133
133
  supportsCrypto;
134
134
  alertsEnabled;
135
+ /** "cash" (the default when omitted) or "reinvest". */
136
+ dividendPolicy;
135
137
  /** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
136
138
  id = null;
137
139
  /** Present on list/get summaries: paper | live | chat. */
@@ -188,6 +190,9 @@ class PortfolioHandle {
188
190
  if (typeof record.alertsEnabled === "boolean") {
189
191
  this.alertsEnabled = record.alertsEnabled;
190
192
  }
193
+ if (record.dividendPolicy === "cash" || record.dividendPolicy === "reinvest") {
194
+ this.dividendPolicy = record.dividendPolicy;
195
+ }
191
196
  if (record.type === "paper" ||
192
197
  record.type === "live" ||
193
198
  record.type === "chat") {
@@ -218,6 +223,7 @@ class PortfolioHandle {
218
223
  key === "supportsFractionalShares" ||
219
224
  key === "supportsCrypto" ||
220
225
  key === "alertsEnabled" ||
226
+ key === "dividendPolicy" ||
221
227
  key === "type" ||
222
228
  key === "isActive" ||
223
229
  key === "strategyNames" ||
@@ -264,6 +270,9 @@ class PortfolioHandle {
264
270
  if (this.alertsEnabled !== undefined) {
265
271
  body.alertsEnabled = this.alertsEnabled;
266
272
  }
273
+ if (this.dividendPolicy !== undefined) {
274
+ body.dividendPolicy = this.dividendPolicy;
275
+ }
267
276
  if (this.type !== undefined)
268
277
  body.type = this.type;
269
278
  if (this.isActive !== undefined)
@@ -378,6 +387,9 @@ class PortfolioHandle {
378
387
  }
379
388
  if (options.feeConfig !== undefined)
380
389
  input.feeConfig = options.feeConfig;
390
+ if (options.dividendPolicy !== undefined) {
391
+ input.dividendPolicy = options.dividendPolicy;
392
+ }
381
393
  const response = await transport.request("POST", "backtests/batch", {
382
394
  body: { backtests: [input] },
383
395
  idempotencyKey: options.idempotencyKey,
@@ -5,7 +5,7 @@
5
5
  * pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
6
6
  */
7
7
  import { AgentRun } from "./agent.ts";
8
- import type { JobRequest, Portfolio, Strategy } from "./generated/ntSdk.generated.js";
8
+ import type { JobRequest, OrderStatus, Portfolio, Strategy } from "./generated/ntSdk.generated.js";
9
9
  import { PortfolioHandle, type DeployResult, type PortfolioListResult } from "./portfolio.ts";
10
10
  export type JsonValue = string | number | boolean | null | JsonValue[] | {
11
11
  [key: string]: JsonValue;
@@ -78,6 +78,13 @@ export interface ReplaceStrategiesOperation {
78
78
  * this route, so typing them here would only compile a guaranteed 403.
79
79
  */
80
80
  export type PortfolioEditOperation = PortfolioRenameOperation | AddStrategiesOperation | RemoveStrategiesOperation | ReplaceStrategyOperation | ReplaceStrategiesOperation;
81
+ export interface ListOrdersOptions {
82
+ portfolioId?: string;
83
+ statuses?: ReadonlyArray<OrderStatus>;
84
+ page?: number;
85
+ limit?: number;
86
+ includeRebalanceOrders?: boolean;
87
+ }
81
88
  export interface ListPortfoliosOptions {
82
89
  portfolioIds?: string[];
83
90
  includeInactive?: boolean;
@@ -419,6 +426,13 @@ export declare class NexusTradeClient {
419
426
  createOrders(portfolioId: string, orders: ReadonlyArray<JsonObject>, options: {
420
427
  idempotencyKey: string;
421
428
  }): Promise<JsonObject>;
429
+ /** List owned orders. Defaults to Accepted and Pending User Approval; pages are 1-based. */
430
+ listOrders(options?: ListOrdersOptions): Promise<JsonObject>;
431
+ /** Cancel explicit order IDs; inspect both canceled and rejected. Live cancellation reaches the broker. */
432
+ cancelOrders(orderIds: ReadonlyArray<string>, options: {
433
+ idempotencyKey: string;
434
+ portfolioId?: string;
435
+ }): Promise<JsonObject>;
422
436
  createBacktests(backtests: ReadonlyArray<JobInput>, options: {
423
437
  idempotencyKey: string;
424
438
  }): Promise<JsonObject[]>;
@@ -508,6 +508,7 @@ const BACKTEST_ARG_NAMES = [
508
508
  ["initial_value", "initialValue"],
509
509
  ["generate_events", "generateEvents"],
510
510
  ["fee_config", "feeConfig"],
511
+ ["dividend_policy", "dividendPolicy"],
511
512
  ];
512
513
  function isJsonObject(value) {
513
514
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1254,6 +1255,41 @@ export class NexusTradeClient {
1254
1255
  idempotencyKey: options.idempotencyKey,
1255
1256
  });
1256
1257
  }
1258
+ /** List owned orders. Defaults to Accepted and Pending User Approval; pages are 1-based. */
1259
+ async listOrders(options = {}) {
1260
+ if (options.statuses !== undefined && options.statuses.length === 0) {
1261
+ throw new Error("statuses must be a non-empty array.");
1262
+ }
1263
+ const query = encodeQuery({
1264
+ portfolioId: options.portfolioId,
1265
+ statuses: options.statuses?.join(","),
1266
+ page: options.page === undefined ? undefined : String(options.page),
1267
+ limit: options.limit === undefined ? undefined : String(options.limit),
1268
+ includeRebalanceOrders: options.includeRebalanceOrders === undefined
1269
+ ? undefined
1270
+ : String(options.includeRebalanceOrders),
1271
+ });
1272
+ return this.transport.request("GET", `orders${query}`);
1273
+ }
1274
+ /** Cancel explicit order IDs; inspect both canceled and rejected. Live cancellation reaches the broker. */
1275
+ async cancelOrders(orderIds, options) {
1276
+ if (!Array.isArray(orderIds) ||
1277
+ orderIds.length === 0 ||
1278
+ orderIds.some((id) => typeof id !== "string" || !id.trim())) {
1279
+ throw new Error("orderIds must be a non-empty array of non-empty strings.");
1280
+ }
1281
+ if (orderIds.length > 50)
1282
+ throw new Error("at most 50 orders may be canceled per request.");
1283
+ return this.transport.request("POST", "orders/cancel", {
1284
+ body: {
1285
+ orderIds: [...orderIds],
1286
+ ...(options.portfolioId === undefined
1287
+ ? {}
1288
+ : { portfolioId: options.portfolioId }),
1289
+ },
1290
+ idempotencyKey: options.idempotencyKey,
1291
+ });
1292
+ }
1257
1293
  async createBacktests(backtests, options) {
1258
1294
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
1259
1295
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -479,8 +479,11 @@ export interface Portfolio {
479
479
  supportsFractionalShares?: boolean;
480
480
  supportsCrypto?: boolean;
481
481
  alertsEnabled?: boolean;
482
+ /** "cash" (default when omitted) or "reinvest" into the paying stock. */
483
+ dividendPolicy?: DividendPolicy;
482
484
  policy?: AuthoredPortfolioPolicy;
483
485
  }
486
+ export type DividendPolicy = "cash" | "reinvest";
484
487
  export type AssetType = "Stock" | "Cryptocurrency" | "Option" | "Other";
485
488
  export type Interval = "Day" | "Hour" | "Minute";
486
489
  export type Comparator = "lessThan" | "greaterThan" | "lessThanOrEqual" | "greaterThanOrEqual" | "equal" | "notEqual";
@@ -710,6 +713,7 @@ export declare const portfolio: (name: string, strategies: Strategy[], options?:
710
713
  supportsFractionalShares?: boolean;
711
714
  supportsCrypto?: boolean;
712
715
  alertsEnabled?: boolean;
716
+ dividendPolicy?: DividendPolicy;
713
717
  policy?: AuthoredPortfolioPolicy;
714
718
  }) => PortfolioHandle;
715
719
  /**
@@ -1629,6 +1633,8 @@ export interface BacktestConfig {
1629
1633
  generateEvents?: boolean;
1630
1634
  /** Optional fee contract keyed by AssetTypeEnum (Stock/Cryptocurrency/Option) with {amount, type: percent|dollars}. Omit for shared defaults (Option $0.65/contract). For replay of an optimizer/walk-forward study, pass that study's persisted feeConfig. Option fill slippage (OptionSlippageFraction) is not set here — engine default 0.5 applies. */
1631
1635
  feeConfig?: FeeConfig;
1636
+ /** Overrides the portfolio's dividend policy for this run only. Omit to use the portfolio's own setting (cash unless it was set to reinvest). "reinvest" buys more of the paying stock on each pay date, which is what a buy-and-hold comparison against the SPY total-return baseline needs. */
1637
+ dividendPolicy?: "cash" | "reinvest";
1632
1638
  }
1633
1639
  export interface WalkForwardConfig {
1634
1640
  /** Global calendar start for the walk-forward study (ISO date). Each Minute evaluation window cannot exceed 730 days of minute data counting minute-indicator warmup, which is the only cap; the 90-day seed first look is a default for callers who name no dates. */
@@ -1896,6 +1896,7 @@ export const backtest = (portfolio, config) => ({
1896
1896
  "initial_value": config.initialValue,
1897
1897
  "generate_events": config.generateEvents,
1898
1898
  "fee_config": config.feeConfig,
1899
+ "dividend_policy": config.dividendPolicy,
1899
1900
  }),
1900
1901
  });
1901
1902
  /** Submit a walk-forward study (anchored or rolling folds, GA or sweep engine). */
@@ -1,7 +1,7 @@
1
1
  export { AgentRun } from "./agent.js";
2
2
  export type { AgentEvent, AgentRunOptions } from "./agent.js";
3
3
  export { HttpTransport, NexusTradeApiError, NexusTradeClient, NexusTradeWorkspaceSessionExpiredError, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
4
- export type { AddStrategiesOperation, BacktestCollateralStatistics, CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, PortfolioEditOperation, PortfolioRenameOperation, RemoveStrategiesOperation, ReplaceStrategiesOperation, ReplaceStrategyOperation, RequestOptions, Transport, UploadTransport, WaitOptions, WorkspaceSessionTransport, } from "./client.js";
4
+ export type { AddStrategiesOperation, BacktestCollateralStatistics, CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListOrdersOptions, ListPortfoliosOptions, NexusTradeClientOptions, PortfolioEditOperation, PortfolioRenameOperation, RemoveStrategiesOperation, ReplaceStrategiesOperation, ReplaceStrategyOperation, RequestOptions, Transport, UploadTransport, WaitOptions, WorkspaceSessionTransport, } from "./client.js";
5
5
  export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
6
6
  export type { DeployOutcome, DeployResult, PortfolioHandleOptions, PortfolioListResult, PortfolioType, ReadonlyPortfolioPolicy, } from "./portfolio.js";
7
7
  export * from "./generated/ntSdk.generated.js";
@@ -9,7 +9,7 @@
9
9
  * import this module without a cycle through `client.ts`.
10
10
  */
11
11
  import { type JsonObject, type Transport } from "./client.ts";
12
- import type { AuthoredPortfolioPolicy, AuthoredStockEligibility, Portfolio, Strategy } from "./generated/ntSdk.generated.js";
12
+ import type { AuthoredPortfolioPolicy, AuthoredStockEligibility, DividendPolicy, Portfolio, Strategy } from "./generated/ntSdk.generated.js";
13
13
  export type PortfolioType = "paper" | "live" | "chat";
14
14
  export type DeployOutcome = "minted" | "reactivated" | "already_active" | "seed_recovered";
15
15
  export interface DeployResult {
@@ -68,6 +68,8 @@ export declare class PortfolioHandle implements Portfolio {
68
68
  supportsFractionalShares?: boolean;
69
69
  supportsCrypto?: boolean;
70
70
  alertsEnabled?: boolean;
71
+ /** "cash" (the default when omitted) or "reinvest". */
72
+ dividendPolicy?: DividendPolicy;
71
73
  /** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
72
74
  id: string | null;
73
75
  /** Present on list/get summaries: paper | live | chat. */
@@ -112,6 +114,8 @@ export declare class PortfolioHandle implements Portfolio {
112
114
  initialValue?: number;
113
115
  generateEvents?: boolean;
114
116
  feeConfig?: JsonObject;
117
+ /** Overrides the portfolio's own dividend policy for this run only. */
118
+ dividendPolicy?: DividendPolicy;
115
119
  transport?: Transport;
116
120
  }): Promise<JsonObject>;
117
121
  }
@@ -95,6 +95,8 @@ export class PortfolioHandle {
95
95
  supportsFractionalShares;
96
96
  supportsCrypto;
97
97
  alertsEnabled;
98
+ /** "cash" (the default when omitted) or "reinvest". */
99
+ dividendPolicy;
98
100
  /** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
99
101
  id = null;
100
102
  /** Present on list/get summaries: paper | live | chat. */
@@ -151,6 +153,9 @@ export class PortfolioHandle {
151
153
  if (typeof record.alertsEnabled === "boolean") {
152
154
  this.alertsEnabled = record.alertsEnabled;
153
155
  }
156
+ if (record.dividendPolicy === "cash" || record.dividendPolicy === "reinvest") {
157
+ this.dividendPolicy = record.dividendPolicy;
158
+ }
154
159
  if (record.type === "paper" ||
155
160
  record.type === "live" ||
156
161
  record.type === "chat") {
@@ -181,6 +186,7 @@ export class PortfolioHandle {
181
186
  key === "supportsFractionalShares" ||
182
187
  key === "supportsCrypto" ||
183
188
  key === "alertsEnabled" ||
189
+ key === "dividendPolicy" ||
184
190
  key === "type" ||
185
191
  key === "isActive" ||
186
192
  key === "strategyNames" ||
@@ -227,6 +233,9 @@ export class PortfolioHandle {
227
233
  if (this.alertsEnabled !== undefined) {
228
234
  body.alertsEnabled = this.alertsEnabled;
229
235
  }
236
+ if (this.dividendPolicy !== undefined) {
237
+ body.dividendPolicy = this.dividendPolicy;
238
+ }
230
239
  if (this.type !== undefined)
231
240
  body.type = this.type;
232
241
  if (this.isActive !== undefined)
@@ -341,6 +350,9 @@ export class PortfolioHandle {
341
350
  }
342
351
  if (options.feeConfig !== undefined)
343
352
  input.feeConfig = options.feeConfig;
353
+ if (options.dividendPolicy !== undefined) {
354
+ input.dividendPolicy = options.dividendPolicy;
355
+ }
344
356
  const response = await transport.request("POST", "backtests/batch", {
345
357
  body: { backtests: [input] },
346
358
  idempotencyKey: options.idempotencyKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexustrade",
3
- "version": "1.35.0",
3
+ "version": "1.37.0",
4
4
  "description": "Typed TypeScript SDK for NexusTrade portfolio authoring, backtesting, and optimization",
5
5
  "license": "MIT",
6
6
  "author": "Starks Technology",