nexustrade 0.2.0 → 0.3.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/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 —
@@ -374,6 +392,86 @@ class NexusTradeClient {
374
392
  }
375
393
  return result;
376
394
  }
395
+ /**
396
+ * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
397
+ * `includePositions` defaults off when `search` is set.
398
+ */
399
+ async listPortfolios(options = {}) {
400
+ const query = encodeQuery({
401
+ portfolioIds: options.portfolioIds?.join(","),
402
+ includeInactive: options.includeInactive === undefined
403
+ ? undefined
404
+ : String(options.includeInactive),
405
+ includePaper: options.includePaper === undefined
406
+ ? undefined
407
+ : String(options.includePaper),
408
+ includeLive: options.includeLive === undefined
409
+ ? undefined
410
+ : String(options.includeLive),
411
+ includeChatPortfolios: options.includeChatPortfolios === undefined
412
+ ? undefined
413
+ : String(options.includeChatPortfolios),
414
+ includePositions: options.includePositions === undefined
415
+ ? undefined
416
+ : String(options.includePositions),
417
+ search: options.search,
418
+ limit: options.limit === undefined ? undefined : String(options.limit),
419
+ page: options.page === undefined ? undefined : String(options.page),
420
+ });
421
+ const response = await this.transport.request("GET", `portfolios${query}`);
422
+ const rows = response.portfolios;
423
+ if (!Array.isArray(rows)) {
424
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio list response is missing portfolios.");
425
+ }
426
+ return {
427
+ portfolios: rows.map((row) => (0, portfolio_ts_1.portfolioHandleFromWire)(row, { transport: this.transport })),
428
+ page: typeof response.page === "number" ? response.page : 1,
429
+ limit: typeof response.limit === "number" ? response.limit : 20,
430
+ total: typeof response.total === "number" ? response.total : rows.length,
431
+ totalPages: typeof response.totalPages === "number" ? response.totalPages : 1,
432
+ scopes: isJsonObject(response.scopes) ? response.scopes : undefined,
433
+ };
434
+ }
435
+ async getPortfolio(portfolioId) {
436
+ const response = await this.transport.request("GET", `portfolios/${encodePathSegment(portfolioId)}`);
437
+ const portfolio = response.portfolio;
438
+ if (!isJsonObject(portfolio)) {
439
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
440
+ }
441
+ return (0, portfolio_ts_1.portfolioHandleFromWire)(portfolio, {
442
+ transport: this.transport,
443
+ });
444
+ }
445
+ /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
446
+ async deploy(portfolioId, options = {}) {
447
+ const body = {};
448
+ if (options.frequency !== undefined)
449
+ body.frequency = options.frequency;
450
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/deploy`, { body });
451
+ const result = response.deployment ?? response;
452
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
453
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
454
+ }
455
+ return {
456
+ portfolioId: String(result.portfolioId),
457
+ chatPortfolioId: typeof result.chatPortfolioId === "string"
458
+ ? result.chatPortfolioId
459
+ : undefined,
460
+ name: typeof result.name === "string" ? result.name : "",
461
+ outcome: typeof result.outcome === "string" ? result.outcome : "",
462
+ deploymentType: typeof result.deploymentType === "string"
463
+ ? result.deploymentType
464
+ : undefined,
465
+ };
466
+ }
467
+ async undeploy(portfolioId) {
468
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/undeploy`, { body: {} });
469
+ const result = response.undeployment ?? response;
470
+ if (!isJsonObject(result)) {
471
+ throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
472
+ }
473
+ return result;
474
+ }
377
475
  async createBacktests(backtests, options) {
378
476
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
379
477
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -537,6 +635,11 @@ exports.NexusTradeClient = NexusTradeClient;
537
635
  function backtestInput(item) {
538
636
  const tool = item.tool;
539
637
  if (tool === undefined || tool === null) {
638
+ // Prefer portfolioId over an inline body when both are present.
639
+ if (typeof item.portfolioId === "string" && item.portfolioId) {
640
+ const { portfolio: _ignored, ...rest } = item;
641
+ return { ...rest, portfolioId: item.portfolioId };
642
+ }
540
643
  return { ...item };
541
644
  }
542
645
  if (tool !== "backtest_portfolio") {
@@ -563,6 +666,10 @@ function operationOf(response) {
563
666
  }
564
667
  return operation;
565
668
  }
669
+ /** @internal PortfolioHandle lazy-client attachment. */
670
+ function clientTransport(client) {
671
+ return client.transport;
672
+ }
566
673
  /** Convenience wrapper for scripts that do not need a persistent client. */
567
674
  async function createPortfolio(portfolio, options) {
568
675
  const client = options.client ?? NexusTradeClient.fromEnvironment();
@@ -1,7 +1,4 @@
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
3
  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
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 = exports.geneSubject = exports.optimization = void 0;
@@ -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 };
@@ -361,7 +359,7 @@ exports.strategy = strategy;
361
359
  */
362
360
  const sessionFlatten = (condition, config = {}, name = "Session flatten") => (0, exports.strategy)(name, condition, (0, exports.closeOption)({ ...config }));
363
361
  exports.sessionFlatten = sessionFlatten;
364
- const portfolio = (name, strategies, options = {}) => compact({ name, initialValue: 10000, ...options, strategies });
362
+ const portfolio = (name, strategies, options = {}) => new portfolio_ts_1.PortfolioHandle(compact({ name, initialValue: 10000, ...options, strategies }));
365
363
  exports.portfolio = portfolio;
366
364
  // ---- generated indicator builders ----
367
365
  /**
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;
@@ -98,6 +110,17 @@ export declare class NexusTradeClient {
98
110
  createPortfolio(portfolio: PortfolioInput, options: {
99
111
  idempotencyKey: string;
100
112
  }): Promise<JsonObject>;
113
+ /**
114
+ * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
115
+ * `includePositions` defaults off when `search` is set.
116
+ */
117
+ listPortfolios(options?: ListPortfoliosOptions): Promise<PortfolioListResult>;
118
+ getPortfolio(portfolioId: string): Promise<PortfolioHandle>;
119
+ /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
120
+ deploy(portfolioId: string, options?: {
121
+ frequency?: string;
122
+ }): Promise<DeployResult>;
123
+ undeploy(portfolioId: string): Promise<JsonObject>;
101
124
  createBacktests(backtests: ReadonlyArray<JobInput>, options: {
102
125
  idempotencyKey: string;
103
126
  }): Promise<JsonObject[]>;
@@ -160,6 +183,8 @@ export declare class NexusTradeClient {
160
183
  waitForBacktests(operations: ReadonlyArray<JsonObject>, options?: WaitOptions): Promise<JsonObject[]>;
161
184
  private createPortfolioJob;
162
185
  }
186
+ /** @internal PortfolioHandle lazy-client attachment. */
187
+ export declare function clientTransport(client: NexusTradeClient): Transport;
163
188
  /** Convenience wrapper for scripts that do not need a persistent client. */
164
189
  export declare function createPortfolio(portfolio: JsonObject, options: {
165
190
  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 —
@@ -367,6 +384,86 @@ export class NexusTradeClient {
367
384
  }
368
385
  return result;
369
386
  }
387
+ /**
388
+ * List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
389
+ * `includePositions` defaults off when `search` is set.
390
+ */
391
+ async listPortfolios(options = {}) {
392
+ const query = encodeQuery({
393
+ portfolioIds: options.portfolioIds?.join(","),
394
+ includeInactive: options.includeInactive === undefined
395
+ ? undefined
396
+ : String(options.includeInactive),
397
+ includePaper: options.includePaper === undefined
398
+ ? undefined
399
+ : String(options.includePaper),
400
+ includeLive: options.includeLive === undefined
401
+ ? undefined
402
+ : String(options.includeLive),
403
+ includeChatPortfolios: options.includeChatPortfolios === undefined
404
+ ? undefined
405
+ : String(options.includeChatPortfolios),
406
+ includePositions: options.includePositions === undefined
407
+ ? undefined
408
+ : String(options.includePositions),
409
+ search: options.search,
410
+ limit: options.limit === undefined ? undefined : String(options.limit),
411
+ page: options.page === undefined ? undefined : String(options.page),
412
+ });
413
+ const response = await this.transport.request("GET", `portfolios${query}`);
414
+ const rows = response.portfolios;
415
+ if (!Array.isArray(rows)) {
416
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio list response is missing portfolios.");
417
+ }
418
+ return {
419
+ portfolios: rows.map((row) => portfolioHandleFromWire(row, { transport: this.transport })),
420
+ page: typeof response.page === "number" ? response.page : 1,
421
+ limit: typeof response.limit === "number" ? response.limit : 20,
422
+ total: typeof response.total === "number" ? response.total : rows.length,
423
+ totalPages: typeof response.totalPages === "number" ? response.totalPages : 1,
424
+ scopes: isJsonObject(response.scopes) ? response.scopes : undefined,
425
+ };
426
+ }
427
+ async getPortfolio(portfolioId) {
428
+ const response = await this.transport.request("GET", `portfolios/${encodePathSegment(portfolioId)}`);
429
+ const portfolio = response.portfolio;
430
+ if (!isJsonObject(portfolio)) {
431
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
432
+ }
433
+ return portfolioHandleFromWire(portfolio, {
434
+ transport: this.transport,
435
+ });
436
+ }
437
+ /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
438
+ async deploy(portfolioId, options = {}) {
439
+ const body = {};
440
+ if (options.frequency !== undefined)
441
+ body.frequency = options.frequency;
442
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/deploy`, { body });
443
+ const result = response.deployment ?? response;
444
+ if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
445
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
446
+ }
447
+ return {
448
+ portfolioId: String(result.portfolioId),
449
+ chatPortfolioId: typeof result.chatPortfolioId === "string"
450
+ ? result.chatPortfolioId
451
+ : undefined,
452
+ name: typeof result.name === "string" ? result.name : "",
453
+ outcome: typeof result.outcome === "string" ? result.outcome : "",
454
+ deploymentType: typeof result.deploymentType === "string"
455
+ ? result.deploymentType
456
+ : undefined,
457
+ };
458
+ }
459
+ async undeploy(portfolioId) {
460
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/undeploy`, { body: {} });
461
+ const result = response.undeployment ?? response;
462
+ if (!isJsonObject(result)) {
463
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
464
+ }
465
+ return result;
466
+ }
370
467
  async createBacktests(backtests, options) {
371
468
  const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
372
469
  const response = await this.transport.request("POST", "backtests/batch", {
@@ -529,6 +626,11 @@ export class NexusTradeClient {
529
626
  function backtestInput(item) {
530
627
  const tool = item.tool;
531
628
  if (tool === undefined || tool === null) {
629
+ // Prefer portfolioId over an inline body when both are present.
630
+ if (typeof item.portfolioId === "string" && item.portfolioId) {
631
+ const { portfolio: _ignored, ...rest } = item;
632
+ return { ...rest, portfolioId: item.portfolioId };
633
+ }
532
634
  return { ...item };
533
635
  }
534
636
  if (tool !== "backtest_portfolio") {
@@ -555,6 +657,10 @@ function operationOf(response) {
555
657
  }
556
658
  return operation;
557
659
  }
660
+ /** @internal PortfolioHandle lazy-client attachment. */
661
+ export function clientTransport(client) {
662
+ return client.transport;
663
+ }
558
664
  /** Convenience wrapper for scripts that do not need a persistent client. */
559
665
  export async function createPortfolio(portfolio, options) {
560
666
  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;
@@ -527,7 +528,7 @@ export declare const portfolio: (name: string, strategies: Strategy[], options?:
527
528
  supportsFractionalShares?: boolean;
528
529
  supportsCrypto?: boolean;
529
530
  alertsEnabled?: boolean;
530
- }) => Portfolio;
531
+ }) => PortfolioHandle;
531
532
  /**
532
533
  * AbsoluteValue indicator.
533
534
  */
@@ -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 };
@@ -213,7 +211,7 @@ export const strategy = (name, condition, action, options = {}) => compact({ nam
213
211
  * Book-level only — CandidateCondition is rejected (same as strategy when).
214
212
  */
215
213
  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 });
214
+ export const portfolio = (name, strategies, options = {}) => new PortfolioHandle(compact({ name, initialValue: 10000, ...options, strategies }));
217
215
  // ---- generated indicator builders ----
218
216
  /**
219
217
  * 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.3.0",
4
4
  "description": "Typed TypeScript SDK for NexusTrade portfolio authoring, backtesting, and optimization",
5
5
  "license": "MIT",
6
6
  "author": "Starks Technology",