nexustrade 0.2.0 → 0.4.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/README.md CHANGED
@@ -87,7 +87,7 @@ const book = nt.portfolio("Momentum", [
87
87
  | **Portfolio state** | `PortfolioValue` `BuyingPower` `MaxDrawdown` `InitialValue` |
88
88
  | **Fundamentals** | `Fundamental` `Economic` `DaysUntilEarnings` `IsIndexMember` `IsIndustry` |
89
89
  | **Options** | `OptionDaysToExpiration` `OptionCollateral` `OptionUnrealizedPnL` `openOption` `closeOption` |
90
- | **Actions** | `buy` `sell` `deposit` `withdraw` `alert` `dynamicRebalance` `rebalanceOption` |
90
+ | **Actions** | `buy` `sell` `alert` `dynamicRebalance` `rebalanceOption` |
91
91
  | **Selection** | `filter` `selectTop` `selectPercentile` `universe` |
92
92
  | **Logic** | `always` `atLeast` `atMost` `exactly` `fewerThan` `multi` `and` `or` |
93
93
 
package/dist/cjs/agent.js CHANGED
@@ -65,6 +65,18 @@ class AgentRun {
65
65
  setCursor(cursor) {
66
66
  this.#cursor = cursor;
67
67
  }
68
+ /** Re-read status without consuming events. */
69
+ async refresh() {
70
+ const response = await this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}`);
71
+ const agent = response.agent;
72
+ if (agent && typeof agent === "object" && !Array.isArray(agent)) {
73
+ const status = agent.status;
74
+ if (typeof status === "string")
75
+ this.status = status;
76
+ this.terminal = Boolean(agent.terminal);
77
+ }
78
+ return this.status;
79
+ }
68
80
  /**
69
81
  * Yield events until the run is terminal.
70
82
  *
@@ -9,13 +9,31 @@
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
11
11
  exports.waitForOperation = waitForOperation;
12
+ exports.clientTransport = clientTransport;
12
13
  exports.createPortfolio = createPortfolio;
13
14
  const agent_ts_1 = require("./agent.js");
14
15
  const env_ts_1 = require("./env.js");
16
+ const portfolio_ts_1 = require("./portfolio.js");
15
17
  /** Boundary adapter: builder output is JSON by construction. */
16
18
  function asJsonObject(value) {
19
+ // PortfolioHandle.toJSON() omits `id`; a bare cast would leak it.
20
+ if (value && typeof value === "object" && "toJSON" in value) {
21
+ const candidate = value;
22
+ if (typeof candidate.toJSON === "function") {
23
+ return candidate.toJSON();
24
+ }
25
+ }
17
26
  return value;
18
27
  }
28
+ function encodeQuery(params) {
29
+ const search = new URLSearchParams();
30
+ for (const [key, value] of Object.entries(params)) {
31
+ if (value !== undefined && value !== "")
32
+ search.set(key, value);
33
+ }
34
+ const encoded = search.toString();
35
+ return encoded ? `?${encoded}` : "";
36
+ }
19
37
  const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
20
38
  const MAX_ERROR_BYTES = 64 * 1024;
21
39
  // Keep in lockstep with _MAX_REDIRECTS in sdk/python/nexustrade/client.py —
@@ -38,11 +56,18 @@ const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
38
56
  class NexusTradeApiError extends Error {
39
57
  status;
40
58
  code;
41
- constructor(status, code, message) {
59
+ /**
60
+ * Set for operation errors (timeout / failure). A timed-out job is still
61
+ * running, so the caller needs the id to resume waiting without resubmitting
62
+ * — reading it out of the message is not an interface.
63
+ */
64
+ operationId;
65
+ constructor(status, code, message, operationId) {
42
66
  super(`${code}: ${message}`);
43
67
  this.name = "NexusTradeApiError";
44
68
  this.status = status;
45
69
  this.code = code;
70
+ this.operationId = operationId;
46
71
  }
47
72
  }
48
73
  exports.NexusTradeApiError = NexusTradeApiError;
@@ -287,7 +312,7 @@ function operationFailure(operation, operationId, status) {
287
312
  if (error.message)
288
313
  message = String(error.message);
289
314
  }
290
- return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message);
315
+ return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message, operationId);
291
316
  }
292
317
  /**
293
318
  * Poll `fetch(operationId)` until the operation reaches a terminal state.
@@ -327,7 +352,7 @@ async function waitForOperation(fetch, operationId, options = {}) {
327
352
  if (remainingMs <= 0) {
328
353
  throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
329
354
  `${timeoutSeconds}s. It is still running — poll again with the ` +
330
- "same id rather than resubmitting.");
355
+ "same id (error.operationId) rather than resubmitting.", operationId);
331
356
  }
332
357
  if (interval > 0) {
333
358
  const delayMs = Math.min(interval * 1000, remainingMs);
@@ -374,6 +399,86 @@ class NexusTradeClient {
374
399
  }
375
400
  return result;
376
401
  }
402
+ /**
403
+ * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
404
+ * `includePositions` defaults off when `search` is set.
405
+ */
406
+ async listPortfolios(options = {}) {
407
+ const query = encodeQuery({
408
+ portfolioIds: options.portfolioIds?.join(","),
409
+ includeInactive: options.includeInactive === undefined
410
+ ? undefined
411
+ : String(options.includeInactive),
412
+ includePaper: options.includePaper === undefined
413
+ ? undefined
414
+ : String(options.includePaper),
415
+ includeLive: options.includeLive === undefined
416
+ ? undefined
417
+ : String(options.includeLive),
418
+ includeChatPortfolios: options.includeChatPortfolios === undefined
419
+ ? undefined
420
+ : String(options.includeChatPortfolios),
421
+ includePositions: options.includePositions === undefined
422
+ ? undefined
423
+ : String(options.includePositions),
424
+ search: options.search,
425
+ limit: options.limit === undefined ? undefined : String(options.limit),
426
+ page: options.page === undefined ? undefined : String(options.page),
427
+ });
428
+ const response = await this.transport.request("GET", `portfolios${query}`);
429
+ const rows = response.portfolios;
430
+ if (!Array.isArray(rows)) {
431
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio list response is missing portfolios.");
432
+ }
433
+ return {
434
+ portfolios: rows.map((row) => (0, portfolio_ts_1.portfolioHandleFromWire)(row, { transport: this.transport })),
435
+ page: typeof response.page === "number" ? response.page : 1,
436
+ limit: typeof response.limit === "number" ? response.limit : 20,
437
+ total: typeof response.total === "number" ? response.total : rows.length,
438
+ totalPages: typeof response.totalPages === "number" ? response.totalPages : 1,
439
+ scopes: isJsonObject(response.scopes) ? response.scopes : undefined,
440
+ };
441
+ }
442
+ async getPortfolio(portfolioId) {
443
+ const response = await this.transport.request("GET", `portfolios/${encodePathSegment(portfolioId)}`);
444
+ const portfolio = response.portfolio;
445
+ if (!isJsonObject(portfolio)) {
446
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
447
+ }
448
+ return (0, portfolio_ts_1.portfolioHandleFromWire)(portfolio, {
449
+ transport: this.transport,
450
+ });
451
+ }
452
+ /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
453
+ async deploy(portfolioId, options = {}) {
454
+ const body = {};
455
+ if (options.frequency !== undefined)
456
+ body.frequency = options.frequency;
457
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/deploy`, { body });
458
+ const result = response.deployment ?? response;
459
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
460
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
461
+ }
462
+ return {
463
+ portfolioId: String(result.portfolioId),
464
+ chatPortfolioId: typeof result.chatPortfolioId === "string"
465
+ ? result.chatPortfolioId
466
+ : undefined,
467
+ name: typeof result.name === "string" ? result.name : "",
468
+ outcome: typeof result.outcome === "string" ? result.outcome : "",
469
+ deploymentType: typeof result.deploymentType === "string"
470
+ ? result.deploymentType
471
+ : undefined,
472
+ };
473
+ }
474
+ async undeploy(portfolioId) {
475
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/undeploy`, { body: {} });
476
+ const result = response.undeployment ?? response;
477
+ if (!isJsonObject(result)) {
478
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
479
+ }
480
+ return result;
481
+ }
377
482
  async createBacktests(backtests, options) {
378
483
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
379
484
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -537,6 +642,11 @@ exports.NexusTradeClient = NexusTradeClient;
537
642
  function backtestInput(item) {
538
643
  const tool = item.tool;
539
644
  if (tool === undefined || tool === null) {
645
+ // Prefer portfolioId over an inline body when both are present.
646
+ if (typeof item.portfolioId === "string" && item.portfolioId) {
647
+ const { portfolio: _ignored, ...rest } = item;
648
+ return { ...rest, portfolioId: item.portfolioId };
649
+ }
540
650
  return { ...item };
541
651
  }
542
652
  if (tool !== "backtest_portfolio") {
@@ -563,6 +673,10 @@ function operationOf(response) {
563
673
  }
564
674
  return operation;
565
675
  }
676
+ /** @internal PortfolioHandle lazy-client attachment. */
677
+ function clientTransport(client) {
678
+ return client.transport;
679
+ }
566
680
  /** Convenience wrapper for scripts that do not need a persistent client. */
567
681
  async function createPortfolio(portfolio, options) {
568
682
  const client = options.client ?? NexusTradeClient.fromEnvironment();
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
- /* eslint-disable */
3
- // GENERATED by src/scripts/codegen/generateNtSdk.ts — do not edit by hand.
4
- // Regenerate: cd server && npx ts-node src/scripts/codegen/generateNtSdk.ts
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.walkForward = exports.backtest = exports.SMA = exports.RSI = exports.PriceStdDev = exports.EMA = exports.BBand = exports.portfolio = exports.sessionFlatten = exports.strategy = exports.closeOption = exports.greeksTrigger = exports.daysHeldTrigger = exports.dteTrigger = exports.pnlTrigger = exports.rebalanceOption = exports.sleeve = exports.structureTemplate = exports.openOption = exports.againstParent = exports.optionsBuilder = exports.leg = exports.dynamicRebalance = exports.launchAgent = exports.alert = exports.withdraw = exports.deposit = exports.sell = exports.buy = exports.selectPercentile = exports.selectTop = exports.filter = exports.always = exports.multi = exports.exactly = exports.fewerThan = exports.atMost = exports.atLeast = exports.or = exports.and = exports.neq = exports.eq = exports.lte = exports.gte = exports.lt = exports.gt = exports.cryptoAsset = exports.stockAsset = exports.PORTFOLIO_WIDE = exports.CANDIDATE = void 0;
7
- exports.geneUniversePipelineFilter = exports.geneSelectTopLimit = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneStructureKind = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = exports.geneSubject = exports.optimization = void 0;
3
+ exports.geneSubject = exports.optimization = exports.walkForward = exports.backtest = exports.SMA = exports.RSI = exports.PriceStdDev = exports.EMA = exports.BBand = exports.portfolio = exports.sessionFlatten = exports.strategy = exports.closeOption = exports.greeksTrigger = exports.daysHeldTrigger = exports.dteTrigger = exports.pnlTrigger = exports.rebalanceOption = exports.sleeve = exports.structureTemplate = exports.openOption = exports.againstParent = exports.optionsBuilder = exports.leg = exports.dynamicRebalance = exports.launchAgent = exports.alert = exports.sell = exports.buy = exports.selectPercentile = exports.selectTop = exports.filter = exports.always = exports.multi = exports.exactly = exports.fewerThan = exports.atMost = exports.atLeast = exports.or = exports.and = exports.neq = exports.eq = exports.lte = exports.gte = exports.lt = exports.gt = exports.cryptoAsset = exports.stockAsset = exports.PORTFOLIO_WIDE = exports.CANDIDATE = void 0;
4
+ exports.geneUniversePipelineFilter = exports.geneSelectTopLimit = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneStructureKind = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = void 0;
8
5
  exports.universe = universe;
9
6
  exports.AbsoluteValue = AbsoluteValue;
10
7
  exports.AverageTrueRange = AverageTrueRange;
@@ -109,6 +106,7 @@ exports.Value = Value;
109
106
  exports.Volume = Volume;
110
107
  exports.VWAP = VWAP;
111
108
  exports.Year = Year;
109
+ const portfolio_ts_1 = require("../portfolio.js");
112
110
  exports.CANDIDATE = { __candidate: true };
113
111
  /** Portfolio-wide targetAssets: [] — rebalance cadence, not per-ticker DCA. */
114
112
  exports.PORTFOLIO_WIDE = { __portfolioWide: true };
@@ -272,10 +270,6 @@ const buy = (target, amount, type = "percent of portfolio") => ({ type: "Buy", t
272
270
  exports.buy = buy;
273
271
  const sell = (target, amount, type = "percent of portfolio") => ({ type: "Sell", targetAsset: toAsset(target), amount: { type, amount } });
274
272
  exports.sell = sell;
275
- const deposit = (amount, type = "dollars") => ({ type: "Deposit", amount: { type, amount } });
276
- exports.deposit = deposit;
277
- const withdraw = (amount, type = "dollars") => ({ type: "Withdraw", amount: { type, amount } });
278
- exports.withdraw = withdraw;
279
273
  const alert = (message) => ({ type: "Alert", message });
280
274
  exports.alert = alert;
281
275
  const launchAgent = (config) => compact({ type: "LaunchAgent", ...config });
@@ -361,7 +355,7 @@ exports.strategy = strategy;
361
355
  */
362
356
  const sessionFlatten = (condition, config = {}, name = "Session flatten") => (0, exports.strategy)(name, condition, (0, exports.closeOption)({ ...config }));
363
357
  exports.sessionFlatten = sessionFlatten;
364
- const portfolio = (name, strategies, options = {}) => compact({ name, initialValue: 10000, ...options, strategies });
358
+ const portfolio = (name, strategies, options = {}) => new portfolio_ts_1.PortfolioHandle(compact({ name, initialValue: 10000, ...options, strategies }));
365
359
  exports.portfolio = portfolio;
366
360
  // ---- generated indicator builders ----
367
361
  /**
package/dist/cjs/index.js CHANGED
@@ -14,7 +14,7 @@ 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.waitForOperation = exports.createPortfolio = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
17
+ exports.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = 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");
@@ -23,4 +23,7 @@ Object.defineProperty(exports, "NexusTradeApiError", { enumerable: true, get: fu
23
23
  Object.defineProperty(exports, "NexusTradeClient", { enumerable: true, get: function () { return client_js_1.NexusTradeClient; } });
24
24
  Object.defineProperty(exports, "createPortfolio", { enumerable: true, get: function () { return client_js_1.createPortfolio; } });
25
25
  Object.defineProperty(exports, "waitForOperation", { enumerable: true, get: function () { return client_js_1.waitForOperation; } });
26
+ var portfolio_js_1 = require("./portfolio.js");
27
+ Object.defineProperty(exports, "PortfolioHandle", { enumerable: true, get: function () { return portfolio_js_1.PortfolioHandle; } });
28
+ Object.defineProperty(exports, "portfolioHandleFromWire", { enumerable: true, get: function () { return portfolio_js_1.portfolioHandleFromWire; } });
26
29
  __exportStar(require("./generated/ntSdk.generated.js"), exports);
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ /**
3
+ * PortfolioHandle — one object you author, save, deploy, fetch, and backtest.
4
+ *
5
+ * Keeps the generated `Portfolio` interface as the shape; this class adds
6
+ * lifecycle methods. `toJSON()` omits `id` so request bodies never leak
7
+ * `"id": null`. Mirrors `portfolio_handle.py`.
8
+ *
9
+ * Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
10
+ * import this module without a cycle through `client.ts`.
11
+ *
12
+ * See designs/2026-07-26-sdk-portfolio-objects.md.
13
+ */
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
27
+ }) : function(o, v) {
28
+ o["default"] = v;
29
+ });
30
+ var __importStar = (this && this.__importStar) || (function () {
31
+ var ownKeys = function(o) {
32
+ ownKeys = Object.getOwnPropertyNames || function (o) {
33
+ var ar = [];
34
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
+ return ar;
36
+ };
37
+ return ownKeys(o);
38
+ };
39
+ return function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ })();
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.PortfolioHandle = void 0;
49
+ exports.portfolioHandleFromWire = portfolioHandleFromWire;
50
+ const client_ts_1 = require("./client.js");
51
+ function isJsonObject(value) {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+ function encodePathSegment(value) {
55
+ return encodeURIComponent(value);
56
+ }
57
+ /** Runtime portfolio object. Implements the generated `Portfolio` shape. */
58
+ class PortfolioHandle {
59
+ name;
60
+ initialValue;
61
+ strategies;
62
+ main;
63
+ supportsFractionalShares;
64
+ supportsCrypto;
65
+ alertsEnabled;
66
+ /** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
67
+ id = null;
68
+ /** Present on list/get summaries: paper | live | chat. */
69
+ type;
70
+ isActive;
71
+ strategyNames;
72
+ createdAt;
73
+ updatedAt;
74
+ brokerage;
75
+ #transport;
76
+ constructor(data, options = {}) {
77
+ const record = { ...data };
78
+ const wireId = options.id ??
79
+ (typeof record.portfolioId === "string" ? record.portfolioId : null) ??
80
+ (typeof record.id === "string" ? record.id : null);
81
+ delete record.portfolioId;
82
+ delete record.id;
83
+ this.name = String(record.name ?? "");
84
+ if (typeof record.initialValue === "number") {
85
+ this.initialValue = record.initialValue;
86
+ }
87
+ this.strategies = Array.isArray(record.strategies)
88
+ ? record.strategies.filter((s) => typeof s === "object" && s !== null && !Array.isArray(s))
89
+ : [];
90
+ if (typeof record.main === "boolean")
91
+ this.main = record.main;
92
+ if (typeof record.supportsFractionalShares === "boolean") {
93
+ this.supportsFractionalShares = record.supportsFractionalShares;
94
+ }
95
+ if (typeof record.supportsCrypto === "boolean") {
96
+ this.supportsCrypto = record.supportsCrypto;
97
+ }
98
+ if (typeof record.alertsEnabled === "boolean") {
99
+ this.alertsEnabled = record.alertsEnabled;
100
+ }
101
+ if (record.type === "paper" ||
102
+ record.type === "live" ||
103
+ record.type === "chat") {
104
+ this.type = record.type;
105
+ }
106
+ if (typeof record.isActive === "boolean")
107
+ this.isActive = record.isActive;
108
+ if (Array.isArray(record.strategyNames)) {
109
+ this.strategyNames = record.strategyNames.map(String);
110
+ }
111
+ if (typeof record.createdAt === "string")
112
+ this.createdAt = record.createdAt;
113
+ if (typeof record.updatedAt === "string")
114
+ this.updatedAt = record.updatedAt;
115
+ if (typeof record.brokerage === "string")
116
+ this.brokerage = record.brokerage;
117
+ for (const [key, value] of Object.entries(record)) {
118
+ if (key === "name" ||
119
+ key === "initialValue" ||
120
+ key === "strategies" ||
121
+ key === "main" ||
122
+ key === "supportsFractionalShares" ||
123
+ key === "supportsCrypto" ||
124
+ key === "alertsEnabled" ||
125
+ key === "type" ||
126
+ key === "isActive" ||
127
+ key === "strategyNames" ||
128
+ key === "createdAt" ||
129
+ key === "updatedAt" ||
130
+ key === "brokerage") {
131
+ continue;
132
+ }
133
+ // `__proto__`/`constructor` arrive as own enumerable keys from
134
+ // JSON.parse; assigning them replaces the instance prototype and the
135
+ // handle silently loses save/deploy/toJSON.
136
+ if (key === "__proto__" || key === "constructor")
137
+ continue;
138
+ Object.defineProperty(this, key, {
139
+ value,
140
+ writable: true,
141
+ enumerable: true,
142
+ configurable: true,
143
+ });
144
+ }
145
+ this.id = wireId;
146
+ this.#transport = options.transport ?? null;
147
+ }
148
+ static from(data, options = {}) {
149
+ return new PortfolioHandle(data, options);
150
+ }
151
+ /** Omit `id` — class fields would otherwise serialize as `"id": null`. */
152
+ toJSON() {
153
+ const body = {
154
+ name: this.name,
155
+ strategies: this.strategies,
156
+ };
157
+ if (this.initialValue !== undefined)
158
+ body.initialValue = this.initialValue;
159
+ if (this.main !== undefined)
160
+ body.main = this.main;
161
+ if (this.supportsFractionalShares !== undefined) {
162
+ body.supportsFractionalShares = this.supportsFractionalShares;
163
+ }
164
+ if (this.supportsCrypto !== undefined) {
165
+ body.supportsCrypto = this.supportsCrypto;
166
+ }
167
+ if (this.alertsEnabled !== undefined) {
168
+ body.alertsEnabled = this.alertsEnabled;
169
+ }
170
+ if (this.type !== undefined)
171
+ body.type = this.type;
172
+ if (this.isActive !== undefined)
173
+ body.isActive = this.isActive;
174
+ if (this.strategyNames !== undefined) {
175
+ body.strategyNames = this.strategyNames;
176
+ }
177
+ if (this.createdAt !== undefined)
178
+ body.createdAt = this.createdAt;
179
+ if (this.updatedAt !== undefined)
180
+ body.updatedAt = this.updatedAt;
181
+ if (this.brokerage !== undefined)
182
+ body.brokerage = this.brokerage;
183
+ return body;
184
+ }
185
+ async #resolveTransport(transport) {
186
+ if (transport)
187
+ return transport;
188
+ if (this.#transport)
189
+ return this.#transport;
190
+ // Lazy: avoids importing NexusTradeClient at module load (cycle with client).
191
+ const { NexusTradeClient, clientTransport } = await Promise.resolve().then(() => __importStar(require("./client.js")));
192
+ this.#transport = clientTransport(NexusTradeClient.fromEnvironment());
193
+ return this.#transport;
194
+ }
195
+ /** Persist as a chat draft. Sets `.id` to the ChatPortfolio id. */
196
+ async save(options) {
197
+ const transport = await this.#resolveTransport(options.transport);
198
+ const response = await transport.request("POST", "portfolios", {
199
+ body: this.toJSON(),
200
+ idempotencyKey: options.idempotencyKey,
201
+ });
202
+ const result = response.portfolio;
203
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
204
+ throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Portfolio save response is missing portfolioId.");
205
+ }
206
+ this.id = result.portfolioId;
207
+ this.#transport = transport;
208
+ return this;
209
+ }
210
+ /**
211
+ * Mint/activate the real paper portfolio.
212
+ * Returns a *different* id than `save()` — see `DeployResult.portfolioId`.
213
+ */
214
+ async deploy(options = {}) {
215
+ if (!this.id) {
216
+ throw new Error("Portfolio must be saved before deploy().");
217
+ }
218
+ const transport = await this.#resolveTransport(options.transport);
219
+ const body = {};
220
+ if (options.frequency !== undefined)
221
+ body.frequency = options.frequency;
222
+ const response = await transport.request("POST", `portfolios/${encodePathSegment(this.id)}/deploy`, { body });
223
+ const result = isJsonObject(response.deployment)
224
+ ? response.deployment
225
+ : response;
226
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
227
+ throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
228
+ }
229
+ return {
230
+ portfolioId: String(result.portfolioId),
231
+ chatPortfolioId: typeof result.chatPortfolioId === "string"
232
+ ? result.chatPortfolioId
233
+ : undefined,
234
+ name: typeof result.name === "string" ? result.name : "",
235
+ outcome: typeof result.outcome === "string" ? result.outcome : "",
236
+ deploymentType: typeof result.deploymentType === "string"
237
+ ? result.deploymentType
238
+ : undefined,
239
+ };
240
+ }
241
+ async undeploy(options = {}) {
242
+ if (!this.id) {
243
+ throw new Error("Portfolio must be saved before undeploy().");
244
+ }
245
+ const transport = await this.#resolveTransport(options.transport);
246
+ const response = await transport.request("POST", `portfolios/${encodePathSegment(this.id)}/undeploy`, { body: {} });
247
+ const result = isJsonObject(response.undeployment)
248
+ ? response.undeployment
249
+ : response;
250
+ if (!isJsonObject(result)) {
251
+ throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
252
+ }
253
+ return result;
254
+ }
255
+ /** By id once saved; inline body before. */
256
+ async backtest(options) {
257
+ const transport = await this.#resolveTransport(options.transport);
258
+ const input = this.id
259
+ ? {
260
+ portfolioId: this.id,
261
+ startDate: options.startDate,
262
+ endDate: options.endDate,
263
+ }
264
+ : {
265
+ portfolio: this.toJSON(),
266
+ startDate: options.startDate,
267
+ endDate: options.endDate,
268
+ };
269
+ if (options.baseline !== undefined)
270
+ input.baseline = options.baseline;
271
+ if (options.interval !== undefined)
272
+ input.interval = options.interval;
273
+ if (options.initialValue !== undefined) {
274
+ input.initialValue = options.initialValue;
275
+ }
276
+ if (options.generateEvents !== undefined) {
277
+ input.generateEvents = options.generateEvents;
278
+ }
279
+ if (options.feeConfig !== undefined)
280
+ input.feeConfig = options.feeConfig;
281
+ const response = await transport.request("POST", "backtests/batch", {
282
+ body: { backtests: [input] },
283
+ idempotencyKey: options.idempotencyKey,
284
+ });
285
+ const operations = response.operations;
286
+ if (!Array.isArray(operations) ||
287
+ operations.length !== 1 ||
288
+ !isJsonObject(operations[0])) {
289
+ throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
290
+ }
291
+ return operations[0];
292
+ }
293
+ }
294
+ exports.PortfolioHandle = PortfolioHandle;
295
+ function portfolioHandleFromWire(data, options = {}) {
296
+ if (!isJsonObject(data)) {
297
+ throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, "invalid_response", "Portfolio response is not an object.");
298
+ }
299
+ return PortfolioHandle.from(data, options);
300
+ }
@@ -64,6 +64,8 @@ export declare class AgentRun {
64
64
  constructor(id: string, transport: Transport, status?: string, options?: AgentRunOptions);
65
65
  /** Resume a run already in flight from a known cursor. */
66
66
  setCursor(cursor: string | null): void;
67
+ /** Re-read status without consuming events. */
68
+ refresh(): Promise<string>;
67
69
  /**
68
70
  * Yield events until the run is terminal.
69
71
  *
package/dist/esm/agent.js CHANGED
@@ -62,6 +62,18 @@ export class AgentRun {
62
62
  setCursor(cursor) {
63
63
  this.#cursor = cursor;
64
64
  }
65
+ /** Re-read status without consuming events. */
66
+ async refresh() {
67
+ const response = await this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}`);
68
+ const agent = response.agent;
69
+ if (agent && typeof agent === "object" && !Array.isArray(agent)) {
70
+ const status = agent.status;
71
+ if (typeof status === "string")
72
+ this.status = status;
73
+ this.terminal = Boolean(agent.terminal);
74
+ }
75
+ return this.status;
76
+ }
65
77
  /**
66
78
  * Yield events until the run is terminal.
67
79
  *
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { AgentRun } from "./agent.ts";
9
9
  import type { JobRequest, Portfolio } from "./generated/ntSdk.generated.js";
10
+ import { PortfolioHandle, type DeployResult, type PortfolioListResult } from "./portfolio.ts";
10
11
  export type JsonValue = string | number | boolean | null | JsonValue[] | {
11
12
  [key: string]: JsonValue;
12
13
  };
@@ -25,6 +26,17 @@ export type JsonObject = {
25
26
  */
26
27
  export type PortfolioInput = Portfolio | JsonObject;
27
28
  export type JobInput = JobRequest | JsonObject;
29
+ export interface ListPortfoliosOptions {
30
+ portfolioIds?: string[];
31
+ includeInactive?: boolean;
32
+ includePaper?: boolean;
33
+ includeLive?: boolean;
34
+ includeChatPortfolios?: boolean;
35
+ includePositions?: boolean;
36
+ search?: string;
37
+ limit?: number;
38
+ page?: number;
39
+ }
28
40
  export declare const NO_HTTP_STATUS = 0;
29
41
  export declare const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
30
42
  export declare const DEFAULT_POLL_INTERVAL_SECONDS = 2;
@@ -33,7 +45,13 @@ export declare const POLL_BACKOFF_FACTOR = 1.5;
33
45
  export declare class NexusTradeApiError extends Error {
34
46
  readonly status: number;
35
47
  readonly code: string;
36
- constructor(status: number, code: string, message: string);
48
+ /**
49
+ * Set for operation errors (timeout / failure). A timed-out job is still
50
+ * running, so the caller needs the id to resume waiting without resubmitting
51
+ * — reading it out of the message is not an interface.
52
+ */
53
+ readonly operationId?: string;
54
+ constructor(status: number, code: string, message: string, operationId?: string);
37
55
  }
38
56
  export interface RequestOptions {
39
57
  body?: JsonObject;
@@ -98,6 +116,17 @@ export declare class NexusTradeClient {
98
116
  createPortfolio(portfolio: PortfolioInput, options: {
99
117
  idempotencyKey: string;
100
118
  }): Promise<JsonObject>;
119
+ /**
120
+ * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
121
+ * `includePositions` defaults off when `search` is set.
122
+ */
123
+ listPortfolios(options?: ListPortfoliosOptions): Promise<PortfolioListResult>;
124
+ getPortfolio(portfolioId: string): Promise<PortfolioHandle>;
125
+ /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
126
+ deploy(portfolioId: string, options?: {
127
+ frequency?: string;
128
+ }): Promise<DeployResult>;
129
+ undeploy(portfolioId: string): Promise<JsonObject>;
101
130
  createBacktests(backtests: ReadonlyArray<JobInput>, options: {
102
131
  idempotencyKey: string;
103
132
  }): Promise<JsonObject[]>;
@@ -160,6 +189,8 @@ export declare class NexusTradeClient {
160
189
  waitForBacktests(operations: ReadonlyArray<JsonObject>, options?: WaitOptions): Promise<JsonObject[]>;
161
190
  private createPortfolioJob;
162
191
  }
192
+ /** @internal PortfolioHandle lazy-client attachment. */
193
+ export declare function clientTransport(client: NexusTradeClient): Transport;
163
194
  /** Convenience wrapper for scripts that do not need a persistent client. */
164
195
  export declare function createPortfolio(portfolio: JsonObject, options: {
165
196
  idempotencyKey: string;
@@ -7,10 +7,27 @@
7
7
  */
8
8
  import { AgentRun } from "./agent.js";
9
9
  import { LazyDotenv, environmentValue } from "./env.js";
10
+ import { portfolioHandleFromWire, } from "./portfolio.js";
10
11
  /** Boundary adapter: builder output is JSON by construction. */
11
12
  function asJsonObject(value) {
13
+ // PortfolioHandle.toJSON() omits `id`; a bare cast would leak it.
14
+ if (value && typeof value === "object" && "toJSON" in value) {
15
+ const candidate = value;
16
+ if (typeof candidate.toJSON === "function") {
17
+ return candidate.toJSON();
18
+ }
19
+ }
12
20
  return value;
13
21
  }
22
+ function encodeQuery(params) {
23
+ const search = new URLSearchParams();
24
+ for (const [key, value] of Object.entries(params)) {
25
+ if (value !== undefined && value !== "")
26
+ search.set(key, value);
27
+ }
28
+ const encoded = search.toString();
29
+ return encoded ? `?${encoded}` : "";
30
+ }
14
31
  const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
15
32
  const MAX_ERROR_BYTES = 64 * 1024;
16
33
  // Keep in lockstep with _MAX_REDIRECTS in sdk/python/nexustrade/client.py —
@@ -33,11 +50,18 @@ const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
33
50
  export class NexusTradeApiError extends Error {
34
51
  status;
35
52
  code;
36
- constructor(status, code, message) {
53
+ /**
54
+ * Set for operation errors (timeout / failure). A timed-out job is still
55
+ * running, so the caller needs the id to resume waiting without resubmitting
56
+ * — reading it out of the message is not an interface.
57
+ */
58
+ operationId;
59
+ constructor(status, code, message, operationId) {
37
60
  super(`${code}: ${message}`);
38
61
  this.name = "NexusTradeApiError";
39
62
  this.status = status;
40
63
  this.code = code;
64
+ this.operationId = operationId;
41
65
  }
42
66
  }
43
67
  function origin(url) {
@@ -280,7 +304,7 @@ function operationFailure(operation, operationId, status) {
280
304
  if (error.message)
281
305
  message = String(error.message);
282
306
  }
283
- return new NexusTradeApiError(NO_HTTP_STATUS, code, message);
307
+ return new NexusTradeApiError(NO_HTTP_STATUS, code, message, operationId);
284
308
  }
285
309
  /**
286
310
  * Poll `fetch(operationId)` until the operation reaches a terminal state.
@@ -320,7 +344,7 @@ export async function waitForOperation(fetch, operationId, options = {}) {
320
344
  if (remainingMs <= 0) {
321
345
  throw new NexusTradeApiError(NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
322
346
  `${timeoutSeconds}s. It is still running — poll again with the ` +
323
- "same id rather than resubmitting.");
347
+ "same id (error.operationId) rather than resubmitting.", operationId);
324
348
  }
325
349
  if (interval > 0) {
326
350
  const delayMs = Math.min(interval * 1000, remainingMs);
@@ -367,6 +391,86 @@ export class NexusTradeClient {
367
391
  }
368
392
  return result;
369
393
  }
394
+ /**
395
+ * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
396
+ * `includePositions` defaults off when `search` is set.
397
+ */
398
+ async listPortfolios(options = {}) {
399
+ const query = encodeQuery({
400
+ portfolioIds: options.portfolioIds?.join(","),
401
+ includeInactive: options.includeInactive === undefined
402
+ ? undefined
403
+ : String(options.includeInactive),
404
+ includePaper: options.includePaper === undefined
405
+ ? undefined
406
+ : String(options.includePaper),
407
+ includeLive: options.includeLive === undefined
408
+ ? undefined
409
+ : String(options.includeLive),
410
+ includeChatPortfolios: options.includeChatPortfolios === undefined
411
+ ? undefined
412
+ : String(options.includeChatPortfolios),
413
+ includePositions: options.includePositions === undefined
414
+ ? undefined
415
+ : String(options.includePositions),
416
+ search: options.search,
417
+ limit: options.limit === undefined ? undefined : String(options.limit),
418
+ page: options.page === undefined ? undefined : String(options.page),
419
+ });
420
+ const response = await this.transport.request("GET", `portfolios${query}`);
421
+ const rows = response.portfolios;
422
+ if (!Array.isArray(rows)) {
423
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio list response is missing portfolios.");
424
+ }
425
+ return {
426
+ portfolios: rows.map((row) => portfolioHandleFromWire(row, { transport: this.transport })),
427
+ page: typeof response.page === "number" ? response.page : 1,
428
+ limit: typeof response.limit === "number" ? response.limit : 20,
429
+ total: typeof response.total === "number" ? response.total : rows.length,
430
+ totalPages: typeof response.totalPages === "number" ? response.totalPages : 1,
431
+ scopes: isJsonObject(response.scopes) ? response.scopes : undefined,
432
+ };
433
+ }
434
+ async getPortfolio(portfolioId) {
435
+ const response = await this.transport.request("GET", `portfolios/${encodePathSegment(portfolioId)}`);
436
+ const portfolio = response.portfolio;
437
+ if (!isJsonObject(portfolio)) {
438
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
439
+ }
440
+ return portfolioHandleFromWire(portfolio, {
441
+ transport: this.transport,
442
+ });
443
+ }
444
+ /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
445
+ async deploy(portfolioId, options = {}) {
446
+ const body = {};
447
+ if (options.frequency !== undefined)
448
+ body.frequency = options.frequency;
449
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/deploy`, { body });
450
+ const result = response.deployment ?? response;
451
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
452
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
453
+ }
454
+ return {
455
+ portfolioId: String(result.portfolioId),
456
+ chatPortfolioId: typeof result.chatPortfolioId === "string"
457
+ ? result.chatPortfolioId
458
+ : undefined,
459
+ name: typeof result.name === "string" ? result.name : "",
460
+ outcome: typeof result.outcome === "string" ? result.outcome : "",
461
+ deploymentType: typeof result.deploymentType === "string"
462
+ ? result.deploymentType
463
+ : undefined,
464
+ };
465
+ }
466
+ async undeploy(portfolioId) {
467
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/undeploy`, { body: {} });
468
+ const result = response.undeployment ?? response;
469
+ if (!isJsonObject(result)) {
470
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
471
+ }
472
+ return result;
473
+ }
370
474
  async createBacktests(backtests, options) {
371
475
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
372
476
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -529,6 +633,11 @@ export class NexusTradeClient {
529
633
  function backtestInput(item) {
530
634
  const tool = item.tool;
531
635
  if (tool === undefined || tool === null) {
636
+ // Prefer portfolioId over an inline body when both are present.
637
+ if (typeof item.portfolioId === "string" && item.portfolioId) {
638
+ const { portfolio: _ignored, ...rest } = item;
639
+ return { ...rest, portfolioId: item.portfolioId };
640
+ }
532
641
  return { ...item };
533
642
  }
534
643
  if (tool !== "backtest_portfolio") {
@@ -555,6 +664,10 @@ function operationOf(response) {
555
664
  }
556
665
  return operation;
557
666
  }
667
+ /** @internal PortfolioHandle lazy-client attachment. */
668
+ export function clientTransport(client) {
669
+ return client.transport;
670
+ }
558
671
  /** Convenience wrapper for scripts that do not need a persistent client. */
559
672
  export async function createPortfolio(portfolio, options) {
560
673
  const client = options.client ?? NexusTradeClient.fromEnvironment();
@@ -1,3 +1,4 @@
1
+ import { PortfolioHandle } from "../portfolio.ts";
1
2
  export interface Asset {
2
3
  type: AssetType;
3
4
  symbol: string;
@@ -406,8 +407,6 @@ export declare function universe(source: "ALL_US_STOCKS" | "SP500" | "NASDAQ100"
406
407
  export declare function universe(source: "SPECIFIC_ASSETS", assets: AssetArg[]): Universe;
407
408
  export declare const buy: (target: AssetArg, amount: number, type?: AllocationType) => BuyOrSellAction;
408
409
  export declare const sell: (target: AssetArg, amount: number, type?: AllocationType) => BuyOrSellAction;
409
- export declare const deposit: (amount: number, type?: DepositWithdrawAllocationType) => DepositOrWithdrawAction;
410
- export declare const withdraw: (amount: number, type?: DepositWithdrawAllocationType) => DepositOrWithdrawAction;
411
410
  export declare const alert: (message: string) => AlertAction;
412
411
  export declare const launchAgent: (config: {
413
412
  planningModel: string;
@@ -527,7 +526,7 @@ export declare const portfolio: (name: string, strategies: Strategy[], options?:
527
526
  supportsFractionalShares?: boolean;
528
527
  supportsCrypto?: boolean;
529
528
  alertsEnabled?: boolean;
530
- }) => Portfolio;
529
+ }) => PortfolioHandle;
531
530
  /**
532
531
  * AbsoluteValue indicator.
533
532
  */
@@ -1,6 +1,4 @@
1
- /* eslint-disable */
2
- // GENERATED by src/scripts/codegen/generateNtSdk.ts — do not edit by hand.
3
- // Regenerate: cd server && npx ts-node src/scripts/codegen/generateNtSdk.ts
1
+ import { PortfolioHandle } from "../portfolio.js";
4
2
  export const CANDIDATE = { __candidate: true };
5
3
  /** Portfolio-wide targetAssets: [] — rebalance cadence, not per-ticker DCA. */
6
4
  export const PORTFOLIO_WIDE = { __portfolioWide: true };
@@ -143,8 +141,6 @@ export function universe(source, assets) {
143
141
  // ---- equity + cash actions ----
144
142
  export const buy = (target, amount, type = "percent of portfolio") => ({ type: "Buy", targetAsset: toAsset(target), amount: { type, amount } });
145
143
  export const sell = (target, amount, type = "percent of portfolio") => ({ type: "Sell", targetAsset: toAsset(target), amount: { type, amount } });
146
- export const deposit = (amount, type = "dollars") => ({ type: "Deposit", amount: { type, amount } });
147
- export const withdraw = (amount, type = "dollars") => ({ type: "Withdraw", amount: { type, amount } });
148
144
  export const alert = (message) => ({ type: "Alert", message });
149
145
  export const launchAgent = (config) => compact({ type: "LaunchAgent", ...config });
150
146
  export const dynamicRebalance = (config) => compact({ type: "DynamicRebalance", ...config });
@@ -213,7 +209,7 @@ export const strategy = (name, condition, action, options = {}) => compact({ nam
213
209
  * Book-level only — CandidateCondition is rejected (same as strategy when).
214
210
  */
215
211
  export const sessionFlatten = (condition, config = {}, name = "Session flatten") => strategy(name, condition, closeOption({ ...config }));
216
- export const portfolio = (name, strategies, options = {}) => compact({ name, initialValue: 10000, ...options, strategies });
212
+ export const portfolio = (name, strategies, options = {}) => new PortfolioHandle(compact({ name, initialValue: 10000, ...options, strategies }));
217
213
  // ---- generated indicator builders ----
218
214
  /**
219
215
  * AbsoluteValue indicator.
@@ -1,5 +1,7 @@
1
1
  export { AgentRun } from "./agent.js";
2
2
  export type { AgentEvent, AgentRunOptions } from "./agent.js";
3
3
  export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
4
- export type { HttpTransportOptions, JsonObject, JsonValue, NexusTradeClientOptions, RequestOptions, Transport, WaitOptions, } from "./client.js";
4
+ export type { HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, WaitOptions, } from "./client.js";
5
+ export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
6
+ export type { DeployOutcome, DeployResult, PortfolioHandleOptions, PortfolioListResult, PortfolioType, } from "./portfolio.js";
5
7
  export * from "./generated/ntSdk.generated.js";
package/dist/esm/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { AgentRun } from "./agent.js";
2
2
  export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
3
+ export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
3
4
  export * from "./generated/ntSdk.generated.js";
@@ -0,0 +1,89 @@
1
+ /**
2
+ * PortfolioHandle — one object you author, save, deploy, fetch, and backtest.
3
+ *
4
+ * Keeps the generated `Portfolio` interface as the shape; this class adds
5
+ * lifecycle methods. `toJSON()` omits `id` so request bodies never leak
6
+ * `"id": null`. Mirrors `portfolio_handle.py`.
7
+ *
8
+ * Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
9
+ * import this module without a cycle through `client.ts`.
10
+ *
11
+ * See designs/2026-07-26-sdk-portfolio-objects.md.
12
+ */
13
+ import { type JsonObject, type Transport } from "./client.ts";
14
+ import type { Portfolio, Strategy } from "./generated/ntSdk.generated.js";
15
+ export type PortfolioType = "paper" | "live" | "chat";
16
+ export type DeployOutcome = "minted" | "reactivated" | "already_active" | "seed_recovered";
17
+ export interface DeployResult {
18
+ /** Real paper/live id — different from the draft id set by `save()`. */
19
+ portfolioId: string;
20
+ chatPortfolioId?: string;
21
+ name: string;
22
+ outcome: DeployOutcome | string;
23
+ deploymentType?: string;
24
+ }
25
+ export interface PortfolioListResult {
26
+ portfolios: PortfolioHandle[];
27
+ page: number;
28
+ limit: number;
29
+ total: number;
30
+ totalPages: number;
31
+ scopes?: JsonObject;
32
+ }
33
+ export interface PortfolioHandleOptions {
34
+ id?: string | null;
35
+ transport?: Transport;
36
+ }
37
+ /** Runtime portfolio object. Implements the generated `Portfolio` shape. */
38
+ export declare class PortfolioHandle implements Portfolio {
39
+ #private;
40
+ name: string;
41
+ initialValue?: number;
42
+ strategies: Strategy[];
43
+ main?: boolean;
44
+ supportsFractionalShares?: boolean;
45
+ supportsCrypto?: boolean;
46
+ alertsEnabled?: boolean;
47
+ /** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
48
+ id: string | null;
49
+ /** Present on list/get summaries: paper | live | chat. */
50
+ type?: PortfolioType;
51
+ isActive?: boolean;
52
+ strategyNames?: string[];
53
+ createdAt?: string;
54
+ updatedAt?: string;
55
+ brokerage?: string;
56
+ constructor(data: Portfolio | JsonObject, options?: PortfolioHandleOptions);
57
+ static from(data: Portfolio | JsonObject, options?: PortfolioHandleOptions): PortfolioHandle;
58
+ /** Omit `id` — class fields would otherwise serialize as `"id": null`. */
59
+ toJSON(): JsonObject;
60
+ /** Persist as a chat draft. Sets `.id` to the ChatPortfolio id. */
61
+ save(options: {
62
+ idempotencyKey: string;
63
+ transport?: Transport;
64
+ }): Promise<PortfolioHandle>;
65
+ /**
66
+ * Mint/activate the real paper portfolio.
67
+ * Returns a *different* id than `save()` — see `DeployResult.portfolioId`.
68
+ */
69
+ deploy(options?: {
70
+ frequency?: string;
71
+ transport?: Transport;
72
+ }): Promise<DeployResult>;
73
+ undeploy(options?: {
74
+ transport?: Transport;
75
+ }): Promise<JsonObject>;
76
+ /** By id once saved; inline body before. */
77
+ backtest(options: {
78
+ startDate: string;
79
+ endDate: string;
80
+ idempotencyKey: string;
81
+ baseline?: string;
82
+ interval?: string;
83
+ initialValue?: number;
84
+ generateEvents?: boolean;
85
+ feeConfig?: JsonObject;
86
+ transport?: Transport;
87
+ }): Promise<JsonObject>;
88
+ }
89
+ export declare function portfolioHandleFromWire(data: unknown, options?: PortfolioHandleOptions): PortfolioHandle;
@@ -0,0 +1,262 @@
1
+ /**
2
+ * PortfolioHandle — one object you author, save, deploy, fetch, and backtest.
3
+ *
4
+ * Keeps the generated `Portfolio` interface as the shape; this class adds
5
+ * lifecycle methods. `toJSON()` omits `id` so request bodies never leak
6
+ * `"id": null`. Mirrors `portfolio_handle.py`.
7
+ *
8
+ * Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
9
+ * import this module without a cycle through `client.ts`.
10
+ *
11
+ * See designs/2026-07-26-sdk-portfolio-objects.md.
12
+ */
13
+ import { NexusTradeApiError, NO_HTTP_STATUS, } from "./client.js";
14
+ function isJsonObject(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ function encodePathSegment(value) {
18
+ return encodeURIComponent(value);
19
+ }
20
+ /** Runtime portfolio object. Implements the generated `Portfolio` shape. */
21
+ export class PortfolioHandle {
22
+ name;
23
+ initialValue;
24
+ strategies;
25
+ main;
26
+ supportsFractionalShares;
27
+ supportsCrypto;
28
+ alertsEnabled;
29
+ /** Chat draft id after `save()`, or fetched portfolio id. Not serialized. */
30
+ id = null;
31
+ /** Present on list/get summaries: paper | live | chat. */
32
+ type;
33
+ isActive;
34
+ strategyNames;
35
+ createdAt;
36
+ updatedAt;
37
+ brokerage;
38
+ #transport;
39
+ constructor(data, options = {}) {
40
+ const record = { ...data };
41
+ const wireId = options.id ??
42
+ (typeof record.portfolioId === "string" ? record.portfolioId : null) ??
43
+ (typeof record.id === "string" ? record.id : null);
44
+ delete record.portfolioId;
45
+ delete record.id;
46
+ this.name = String(record.name ?? "");
47
+ if (typeof record.initialValue === "number") {
48
+ this.initialValue = record.initialValue;
49
+ }
50
+ this.strategies = Array.isArray(record.strategies)
51
+ ? record.strategies.filter((s) => typeof s === "object" && s !== null && !Array.isArray(s))
52
+ : [];
53
+ if (typeof record.main === "boolean")
54
+ this.main = record.main;
55
+ if (typeof record.supportsFractionalShares === "boolean") {
56
+ this.supportsFractionalShares = record.supportsFractionalShares;
57
+ }
58
+ if (typeof record.supportsCrypto === "boolean") {
59
+ this.supportsCrypto = record.supportsCrypto;
60
+ }
61
+ if (typeof record.alertsEnabled === "boolean") {
62
+ this.alertsEnabled = record.alertsEnabled;
63
+ }
64
+ if (record.type === "paper" ||
65
+ record.type === "live" ||
66
+ record.type === "chat") {
67
+ this.type = record.type;
68
+ }
69
+ if (typeof record.isActive === "boolean")
70
+ this.isActive = record.isActive;
71
+ if (Array.isArray(record.strategyNames)) {
72
+ this.strategyNames = record.strategyNames.map(String);
73
+ }
74
+ if (typeof record.createdAt === "string")
75
+ this.createdAt = record.createdAt;
76
+ if (typeof record.updatedAt === "string")
77
+ this.updatedAt = record.updatedAt;
78
+ if (typeof record.brokerage === "string")
79
+ this.brokerage = record.brokerage;
80
+ for (const [key, value] of Object.entries(record)) {
81
+ if (key === "name" ||
82
+ key === "initialValue" ||
83
+ key === "strategies" ||
84
+ key === "main" ||
85
+ key === "supportsFractionalShares" ||
86
+ key === "supportsCrypto" ||
87
+ key === "alertsEnabled" ||
88
+ key === "type" ||
89
+ key === "isActive" ||
90
+ key === "strategyNames" ||
91
+ key === "createdAt" ||
92
+ key === "updatedAt" ||
93
+ key === "brokerage") {
94
+ continue;
95
+ }
96
+ // `__proto__`/`constructor` arrive as own enumerable keys from
97
+ // JSON.parse; assigning them replaces the instance prototype and the
98
+ // handle silently loses save/deploy/toJSON.
99
+ if (key === "__proto__" || key === "constructor")
100
+ continue;
101
+ Object.defineProperty(this, key, {
102
+ value,
103
+ writable: true,
104
+ enumerable: true,
105
+ configurable: true,
106
+ });
107
+ }
108
+ this.id = wireId;
109
+ this.#transport = options.transport ?? null;
110
+ }
111
+ static from(data, options = {}) {
112
+ return new PortfolioHandle(data, options);
113
+ }
114
+ /** Omit `id` — class fields would otherwise serialize as `"id": null`. */
115
+ toJSON() {
116
+ const body = {
117
+ name: this.name,
118
+ strategies: this.strategies,
119
+ };
120
+ if (this.initialValue !== undefined)
121
+ body.initialValue = this.initialValue;
122
+ if (this.main !== undefined)
123
+ body.main = this.main;
124
+ if (this.supportsFractionalShares !== undefined) {
125
+ body.supportsFractionalShares = this.supportsFractionalShares;
126
+ }
127
+ if (this.supportsCrypto !== undefined) {
128
+ body.supportsCrypto = this.supportsCrypto;
129
+ }
130
+ if (this.alertsEnabled !== undefined) {
131
+ body.alertsEnabled = this.alertsEnabled;
132
+ }
133
+ if (this.type !== undefined)
134
+ body.type = this.type;
135
+ if (this.isActive !== undefined)
136
+ body.isActive = this.isActive;
137
+ if (this.strategyNames !== undefined) {
138
+ body.strategyNames = this.strategyNames;
139
+ }
140
+ if (this.createdAt !== undefined)
141
+ body.createdAt = this.createdAt;
142
+ if (this.updatedAt !== undefined)
143
+ body.updatedAt = this.updatedAt;
144
+ if (this.brokerage !== undefined)
145
+ body.brokerage = this.brokerage;
146
+ return body;
147
+ }
148
+ async #resolveTransport(transport) {
149
+ if (transport)
150
+ return transport;
151
+ if (this.#transport)
152
+ return this.#transport;
153
+ // Lazy: avoids importing NexusTradeClient at module load (cycle with client).
154
+ const { NexusTradeClient, clientTransport } = await import("./client.js");
155
+ this.#transport = clientTransport(NexusTradeClient.fromEnvironment());
156
+ return this.#transport;
157
+ }
158
+ /** Persist as a chat draft. Sets `.id` to the ChatPortfolio id. */
159
+ async save(options) {
160
+ const transport = await this.#resolveTransport(options.transport);
161
+ const response = await transport.request("POST", "portfolios", {
162
+ body: this.toJSON(),
163
+ idempotencyKey: options.idempotencyKey,
164
+ });
165
+ const result = response.portfolio;
166
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
167
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio save response is missing portfolioId.");
168
+ }
169
+ this.id = result.portfolioId;
170
+ this.#transport = transport;
171
+ return this;
172
+ }
173
+ /**
174
+ * Mint/activate the real paper portfolio.
175
+ * Returns a *different* id than `save()` — see `DeployResult.portfolioId`.
176
+ */
177
+ async deploy(options = {}) {
178
+ if (!this.id) {
179
+ throw new Error("Portfolio must be saved before deploy().");
180
+ }
181
+ const transport = await this.#resolveTransport(options.transport);
182
+ const body = {};
183
+ if (options.frequency !== undefined)
184
+ body.frequency = options.frequency;
185
+ const response = await transport.request("POST", `portfolios/${encodePathSegment(this.id)}/deploy`, { body });
186
+ const result = isJsonObject(response.deployment)
187
+ ? response.deployment
188
+ : response;
189
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
190
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
191
+ }
192
+ return {
193
+ portfolioId: String(result.portfolioId),
194
+ chatPortfolioId: typeof result.chatPortfolioId === "string"
195
+ ? result.chatPortfolioId
196
+ : undefined,
197
+ name: typeof result.name === "string" ? result.name : "",
198
+ outcome: typeof result.outcome === "string" ? result.outcome : "",
199
+ deploymentType: typeof result.deploymentType === "string"
200
+ ? result.deploymentType
201
+ : undefined,
202
+ };
203
+ }
204
+ async undeploy(options = {}) {
205
+ if (!this.id) {
206
+ throw new Error("Portfolio must be saved before undeploy().");
207
+ }
208
+ const transport = await this.#resolveTransport(options.transport);
209
+ const response = await transport.request("POST", `portfolios/${encodePathSegment(this.id)}/undeploy`, { body: {} });
210
+ const result = isJsonObject(response.undeployment)
211
+ ? response.undeployment
212
+ : response;
213
+ if (!isJsonObject(result)) {
214
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
215
+ }
216
+ return result;
217
+ }
218
+ /** By id once saved; inline body before. */
219
+ async backtest(options) {
220
+ const transport = await this.#resolveTransport(options.transport);
221
+ const input = this.id
222
+ ? {
223
+ portfolioId: this.id,
224
+ startDate: options.startDate,
225
+ endDate: options.endDate,
226
+ }
227
+ : {
228
+ portfolio: this.toJSON(),
229
+ startDate: options.startDate,
230
+ endDate: options.endDate,
231
+ };
232
+ if (options.baseline !== undefined)
233
+ input.baseline = options.baseline;
234
+ if (options.interval !== undefined)
235
+ input.interval = options.interval;
236
+ if (options.initialValue !== undefined) {
237
+ input.initialValue = options.initialValue;
238
+ }
239
+ if (options.generateEvents !== undefined) {
240
+ input.generateEvents = options.generateEvents;
241
+ }
242
+ if (options.feeConfig !== undefined)
243
+ input.feeConfig = options.feeConfig;
244
+ const response = await transport.request("POST", "backtests/batch", {
245
+ body: { backtests: [input] },
246
+ idempotencyKey: options.idempotencyKey,
247
+ });
248
+ const operations = response.operations;
249
+ if (!Array.isArray(operations) ||
250
+ operations.length !== 1 ||
251
+ !isJsonObject(operations[0])) {
252
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
253
+ }
254
+ return operations[0];
255
+ }
256
+ }
257
+ export function portfolioHandleFromWire(data, options = {}) {
258
+ if (!isJsonObject(data)) {
259
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio response is not an object.");
260
+ }
261
+ return PortfolioHandle.from(data, options);
262
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexustrade",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Typed TypeScript SDK for NexusTrade portfolio authoring, backtesting, and optimization",
5
5
  "license": "MIT",
6
6
  "author": "Starks Technology",