nexustrade 1.9.10 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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.RebalanceNetBenefit = exports.RebalanceExpectedBenefit = exports.RebalanceEstimatedCost = exports.RebalancePlannedTurnover = exports.RebalanceAllocationDrift = exports.volatilityTarget = exports.maximumDiversificationAllocation = exports.riskParityAllocation = exports.meanVarianceAllocation = 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.geneMaxSpreadPct = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneExposurePolicy = exports.geneAllocationPolicy = exports.geneStructureKind = exports.geneStopLossPct = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = exports.geneSubject = exports.optimization = exports.walkForward = exports.backtest = exports.SMA = exports.RSI = exports.PriceStdDev = exports.EMA = exports.BBand = void 0;
3
+ exports.currentLimit = exports.limitOrder = 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.RebalanceNetBenefit = exports.RebalanceExpectedBenefit = exports.RebalanceEstimatedCost = exports.RebalancePlannedTurnover = exports.RebalanceAllocationDrift = exports.volatilityTarget = exports.maximumDiversificationAllocation = exports.riskParityAllocation = exports.meanVarianceAllocation = exports.always = exports.andThen = 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.geneMaxSpreadPct = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneExposurePolicy = exports.geneAllocationPolicy = exports.geneStructureKind = exports.geneStopLossPct = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneConditionThreshold = exports.geneConditionWindowLength = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = 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.goodForMinutes = exports.goodForDay = exports.minimumNetCredit = exports.maximumNetDebit = exports.unitPriceLimit = void 0;
5
5
  exports.universe = universe;
6
6
  exports.AbsoluteValue = AbsoluteValue;
7
7
  exports.AverageTrueRange = AverageTrueRange;
@@ -39,6 +39,7 @@ exports.GapSize = GapSize;
39
39
  exports.HighOfDay = HighOfDay;
40
40
  exports.ImpliedVolatility = ImpliedVolatility;
41
41
  exports.Index = Index;
42
+ exports.IndicatorAtEntry = IndicatorAtEntry;
42
43
  exports.IndicatorAtMinutesAfterOpen = IndicatorAtMinutesAfterOpen;
43
44
  exports.IndicatorExponentialMovingAverage = IndicatorExponentialMovingAverage;
44
45
  exports.IndicatorMeanAbsoluteDeviation = IndicatorMeanAbsoluteDeviation;
@@ -255,6 +256,25 @@ exports.exactly = exactly;
255
256
  /** Multi with an explicit Comparator (same wire shape as YAML Multi). */
256
257
  const multi = (count, comparison, ...conditions) => ({ type: "Multi", comparison, value: count, conditions });
257
258
  exports.multi = multi;
259
+ /**
260
+ * Sequence. `andThen(30, "Minute", A, B)` is true at tick t when B is true at t
261
+ * and A was true at some STRICTLY EARLIER tick in the preceding 30 minutes.
262
+ *
263
+ * Simultaneous A and B does not fire — that is `and`. The window applies per
264
+ * transition, so with three or more steps each one must occur within the window
265
+ * of the step before it. Nesting is legal and means something different:
266
+ * `andThen(W, andThen(W, A, B), C)` is not `andThen(W, A, B, C)`.
267
+ *
268
+ * `interval` is REQUIRED and has no default. An omitted interval would fall
269
+ * back to Day and silently kill an intraday setup.
270
+ *
271
+ * Named `andThen` rather than `then`: a module namespace with a callable
272
+ * `then` export is assimilated as a thenable, so `await import("nexustrade")`
273
+ * would call it with resolve/reject and never settle. Emits wire type "Then",
274
+ * the same way atLeast/atMost/exactly emit "Multi".
275
+ */
276
+ const andThen = (length, interval, ...conditions) => ({ type: "Then", conditions, window: { length, interval } });
277
+ exports.andThen = andThen;
258
278
  /** Always-true gate for strategies whose cadence lives in the pipeline. */
259
279
  const always = () => compare(Value(1), Value(0), "greaterThan");
260
280
  exports.always = always;
@@ -404,8 +424,43 @@ const greeksTrigger = (bounds) => compact({ type: "greeks", ...bounds });
404
424
  exports.greeksTrigger = greeksTrigger;
405
425
  const closeOption = (config = {}) => compact({ type: "CloseOption", ...config });
406
426
  exports.closeOption = closeOption;
427
+ const limitOrder = (config) => compact({ type: "Limit", ...config });
428
+ exports.limitOrder = limitOrder;
429
+ const currentLimit = () => ({
430
+ type: "QuoteRelative",
431
+ reference: "Current",
432
+ });
433
+ exports.currentLimit = currentLimit;
434
+ const unitPriceLimit = (amount) => ({
435
+ type: "UnitPrice",
436
+ amount,
437
+ });
438
+ exports.unitPriceLimit = unitPriceLimit;
439
+ const maximumNetDebit = (amount) => ({
440
+ type: "MaximumNetDebit",
441
+ amount,
442
+ });
443
+ exports.maximumNetDebit = maximumNetDebit;
444
+ const minimumNetCredit = (amount) => ({
445
+ type: "MinimumNetCredit",
446
+ amount,
447
+ });
448
+ exports.minimumNetCredit = minimumNetCredit;
449
+ const goodForDay = () => ({ type: "Day" });
450
+ exports.goodForDay = goodForDay;
451
+ const goodForMinutes = (minutes) => ({
452
+ type: "Minutes",
453
+ minutes,
454
+ });
455
+ exports.goodForMinutes = goodForMinutes;
407
456
  // ---- assembly ----
408
- const strategy = (name, condition, action, options = {}) => compact({ name, condition, action, ...options });
457
+ const strategy = (name, condition, action, options = {}) => compact({
458
+ name,
459
+ condition,
460
+ action,
461
+ ...options,
462
+ orderExecution: options.orderExecution ?? { type: "Market" },
463
+ });
409
464
  exports.strategy = strategy;
410
465
  /**
411
466
  * Session / clock flatten — condition carries the gate (MinutesAfterOpen, Day, …).
@@ -414,7 +469,17 @@ exports.strategy = strategy;
414
469
  */
415
470
  const sessionFlatten = (condition, config = {}, name = "Session flatten") => (0, exports.strategy)(name, condition, (0, exports.closeOption)({ ...config }));
416
471
  exports.sessionFlatten = sessionFlatten;
417
- const portfolio = (name, strategies, options = {}) => new portfolio_ts_1.PortfolioHandle(compact({ name, initialValue: 10000, ...options, strategies }));
472
+ const portfolio = (name, strategies, options = {}) => {
473
+ const initialValue = options.initialValue ?? 10000;
474
+ return new portfolio_ts_1.PortfolioHandle(compact({
475
+ name,
476
+ initialValue,
477
+ cash: initialValue,
478
+ buyingPower: initialValue,
479
+ ...options,
480
+ strategies,
481
+ }));
482
+ };
418
483
  exports.portfolio = portfolio;
419
484
  // ---- generated indicator builders ----
420
485
  /**
@@ -768,6 +833,20 @@ function Index(metric = "VIX") {
768
833
  d["metric"] = metric;
769
834
  return d;
770
835
  }
836
+ /**
837
+ * IndicatorAtEntry indicator.
838
+ * @param asset Ticker name (ex. SPY, BTC)
839
+ * @param side The side of the fill the value is anchored to
840
+ * @param orderStatus Matches order events with this status
841
+ */
842
+ function IndicatorAtEntry(operand, asset, side, orderStatus = "Filled") {
843
+ const d = { type: "IndicatorAtEntry" };
844
+ setAsset(d, "targetAsset", asset);
845
+ d["side"] = side;
846
+ d["orderStatus"] = orderStatus;
847
+ d.indicators = [operand];
848
+ return d;
849
+ }
771
850
  /**
772
851
  * IndicatorAtMinutesAfterOpen indicator.
773
852
  * @param minutesAfterOpen The number of minutes after market open to capture the indicator value
@@ -1658,6 +1737,22 @@ const geneEntryCooldownDays = (strategyIndex, values) => ({
1658
1737
  values: values,
1659
1738
  });
1660
1739
  exports.geneEntryCooldownDays = geneEntryCooldownDays;
1740
+ /** Sweep ConditionWindowLength (Strategy scope) over a value set. */
1741
+ const geneConditionWindowLength = (strategyIndex, path, slot, values) => ({
1742
+ field: "ConditionWindowLength",
1743
+ scope: "Strategy",
1744
+ target: { scope: "Strategy", field: "ConditionWindowLength", strategyIndex, path, slot },
1745
+ values: values,
1746
+ });
1747
+ exports.geneConditionWindowLength = geneConditionWindowLength;
1748
+ /** Sweep ConditionThreshold (Strategy scope) over a value set. */
1749
+ const geneConditionThreshold = (strategyIndex, path, slot, values) => ({
1750
+ field: "ConditionThreshold",
1751
+ scope: "Strategy",
1752
+ target: { scope: "Strategy", field: "ConditionThreshold", strategyIndex, path, slot },
1753
+ values: values,
1754
+ });
1755
+ exports.geneConditionThreshold = geneConditionThreshold;
1661
1756
  /** Sweep RankSignal (Action scope) over a value set. */
1662
1757
  const geneRankSignal = (strategyIndex, values) => ({
1663
1758
  field: "RankSignal",
package/dist/cjs/index.js CHANGED
@@ -14,13 +14,14 @@ 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.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = exports.createCustomIndicator = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = exports.AgentRun = void 0;
17
+ exports.portfolioHandleFromWire = exports.PortfolioHandle = exports.waitForOperation = exports.createPortfolio = exports.createCustomIndicator = exports.NexusTradeWorkspaceSessionExpiredError = 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");
21
21
  Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return client_js_1.HttpTransport; } });
22
22
  Object.defineProperty(exports, "NexusTradeApiError", { enumerable: true, get: function () { return client_js_1.NexusTradeApiError; } });
23
23
  Object.defineProperty(exports, "NexusTradeClient", { enumerable: true, get: function () { return client_js_1.NexusTradeClient; } });
24
+ Object.defineProperty(exports, "NexusTradeWorkspaceSessionExpiredError", { enumerable: true, get: function () { return client_js_1.NexusTradeWorkspaceSessionExpiredError; } });
24
25
  Object.defineProperty(exports, "createCustomIndicator", { enumerable: true, get: function () { return client_js_1.createCustomIndicator; } });
25
26
  Object.defineProperty(exports, "createPortfolio", { enumerable: true, get: function () { return client_js_1.createPortfolio; } });
26
27
  Object.defineProperty(exports, "waitForOperation", { enumerable: true, get: function () { return client_js_1.waitForOperation; } });
@@ -37,6 +37,8 @@ export interface ListPortfoliosOptions {
37
37
  page?: number;
38
38
  }
39
39
  export declare const NO_HTTP_STATUS = 0;
40
+ export declare const DEFAULT_API_BASE_URL = "https://nexustrade.io/api/v1";
41
+ export declare const WORKSPACE_SESSION_HEADER = "X-NexusTrade-Session";
40
42
  export declare const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
41
43
  export declare const DEFAULT_POLL_INTERVAL_SECONDS = 2;
42
44
  export declare const MAX_POLL_INTERVAL_SECONDS = 15;
@@ -58,6 +60,15 @@ export declare class NexusTradeApiError extends Error {
58
60
  readonly operationId?: string;
59
61
  constructor(status: number, code: string, message: string, operationId?: string);
60
62
  }
63
+ /**
64
+ * An explicitly supplied anonymous workspace can no longer be resumed.
65
+ *
66
+ * The client deliberately does not create a replacement workspace after this
67
+ * error: doing so would make the caller's saved portfolios appear to vanish.
68
+ */
69
+ export declare class NexusTradeWorkspaceSessionExpiredError extends NexusTradeApiError {
70
+ constructor(status: number, message: string);
71
+ }
61
72
  export interface RequestOptions {
62
73
  body?: JsonObject;
63
74
  idempotencyKey?: string;
@@ -90,14 +101,21 @@ export interface UploadTransport extends Transport {
90
101
  }): Promise<void>;
91
102
  }
92
103
  export interface HttpTransportOptions {
93
- apiKey: string;
104
+ apiKey?: string;
94
105
  baseUrl: string;
106
+ workspaceSession?: string;
95
107
  timeoutSeconds?: number;
96
108
  }
97
- export declare class HttpTransport implements Transport, UploadTransport {
109
+ export interface WorkspaceSessionTransport extends Transport {
110
+ exportWorkspaceSession(): string | undefined;
111
+ importWorkspaceSession(workspaceSession: string): void;
112
+ }
113
+ export declare class HttpTransport implements Transport, UploadTransport, WorkspaceSessionTransport {
98
114
  #private;
99
115
  constructor(options: HttpTransportOptions);
100
116
  get baseUrl(): string;
117
+ exportWorkspaceSession(): string | undefined;
118
+ importWorkspaceSession(workspaceSession: string): void;
101
119
  /** PUT a payload to a presigned storage URL. Sends no credential. */
102
120
  putBytes(url: string, data: Uint8Array<ArrayBuffer>, options: {
103
121
  contentType: string;
@@ -107,6 +125,7 @@ export declare class HttpTransport implements Transport, UploadTransport {
107
125
  export interface NexusTradeClientOptions {
108
126
  apiKey?: string;
109
127
  baseUrl?: string;
128
+ workspaceSession?: string;
110
129
  transport?: Transport;
111
130
  }
112
131
  export interface WaitOptions {
@@ -115,6 +134,30 @@ export interface WaitOptions {
115
134
  maxPollIntervalSeconds?: number;
116
135
  raiseOnFailure?: boolean;
117
136
  }
137
+ /**
138
+ * How much capital a backtest actually had on the line, reported alongside the
139
+ * return it earned. Read it off a terminal operation's `result.statistics`.
140
+ *
141
+ * Both fields are optional and nullable, and absence is meaningful: a backtest
142
+ * run before the engine reported collateral carries no value at all. That is
143
+ * NOT zero — these books lock a few thousand dollars against a portfolio worth
144
+ * orders of magnitude more, so substituting 0, or the portfolio's value, turns
145
+ * an unanswered question into a wrong answer. Show "not recorded" instead.
146
+ *
147
+ * Never reconstruct either number from `cash - buyingPower`: buying power is
148
+ * clamped at both ends and carries an open credit-spread premium term, so the
149
+ * inversion breaks precisely on the heavily collateralised books this measures.
150
+ */
151
+ export interface BacktestCollateralStatistics {
152
+ /** Largest collateral locked at any tick of the run, in account currency. */
153
+ peakReservedCollateral?: number | null;
154
+ /**
155
+ * Median collateral across the ticks that HELD at least one position.
156
+ * Flat ticks are excluded on purpose — a 0DTE book is empty overnight and at
157
+ * weekends, and counting those ticks would drive the median to zero.
158
+ */
159
+ medianReservedCollateral?: number | null;
160
+ }
118
161
  /**
119
162
  * Poll `fetch(operationId)` until the operation reaches a terminal state.
120
163
  *
@@ -150,6 +193,10 @@ export declare class NexusTradeClient {
150
193
  private readonly transport;
151
194
  constructor(options?: NexusTradeClientOptions);
152
195
  static fromEnvironment(): NexusTradeClient;
196
+ /** Return the anonymous workspace token after the first API call bootstraps it. */
197
+ exportWorkspaceSession(): string | undefined;
198
+ /** Resume an existing anonymous workspace without creating a replacement. */
199
+ importWorkspaceSession(workspaceSession: string): void;
153
200
  createPortfolio(portfolio: PortfolioInput, options: {
154
201
  idempotencyKey: string;
155
202
  }): Promise<JsonObject>;
@@ -159,6 +206,21 @@ export declare class NexusTradeClient {
159
206
  */
160
207
  listPortfolios(options?: ListPortfoliosOptions): Promise<PortfolioListResult>;
161
208
  getPortfolio(portfolioId: string): Promise<PortfolioHandle>;
209
+ /**
210
+ * Apply deterministic no-code portfolio edits without invoking Aurora.
211
+ * Guest workspaces may rename and add/remove/replace strategies; deployment,
212
+ * scheduling, policy, and trading operations remain account-only.
213
+ */
214
+ updatePortfolio(portfolioId: string, operations: ReadonlyArray<JsonObject>, options: {
215
+ idempotencyKey: string;
216
+ }): Promise<PortfolioHandle>;
217
+ /** Fork a public/shared portfolio into this workspace as an editable copy. */
218
+ forkPublicPortfolio(sharedPortfolioId: string, options: {
219
+ idempotencyKey: string;
220
+ targetPortfolioId?: string;
221
+ name?: string;
222
+ mode?: "replace" | "append";
223
+ }): Promise<PortfolioHandle>;
162
224
  /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
163
225
  deploy(portfolioId: string, options?: {
164
226
  frequency?: string;
@@ -334,10 +396,19 @@ export declare class NexusTradeClient {
334
396
  }): Promise<AgentRun>;
335
397
  getAgent(agentId: string): Promise<JsonObject>;
336
398
  getBacktest(backtestId: string): Promise<JsonObject>;
399
+ /** Requires a registered API key; anonymous workspaces cannot optimize. */
337
400
  createOptimization(handle: JobInput, options: {
338
401
  idempotencyKey: string;
339
402
  }): Promise<JsonObject>;
403
+ /** Requires a registered API key, including result reads. */
340
404
  getOptimization(optimizationId: string): Promise<JsonObject>;
405
+ /** Submit a deterministic systematic sweep. Requires a registered API key. */
406
+ createSystematicSweep(handle: JobInput, options: {
407
+ idempotencyKey: string;
408
+ }): Promise<JsonObject>;
409
+ /** Requires a registered API key, including sweep result reads. */
410
+ getSystematicSweep(optimizationId: string): Promise<JsonObject>;
411
+ /** Requires a registered API key; anonymous workspaces cannot optimize. */
341
412
  createWalkForward(handle: JobInput, options: {
342
413
  idempotencyKey: string;
343
414
  }): Promise<JsonObject>;
@@ -384,6 +455,8 @@ export declare class NexusTradeClient {
384
455
  waitForBacktest(backtestId: string, options?: WaitOptions): Promise<JsonObject>;
385
456
  /** Resolve once an optimization is terminal. See `waitForOperation`. */
386
457
  waitForOptimization(optimizationId: string, options?: WaitOptions): Promise<JsonObject>;
458
+ /** Resolve once a systematic sweep is terminal. */
459
+ waitForSystematicSweep(optimizationId: string, options?: WaitOptions): Promise<JsonObject>;
387
460
  /** Resolve once a walk-forward study is terminal. See `waitForOperation`. */
388
461
  waitForWalkForward(studyId: string, options?: WaitOptions): Promise<JsonObject>;
389
462
  /** Wait on a whole `createBacktests` batch, in submission order. */
@@ -36,6 +36,8 @@ const MAX_REDIRECTS = 5;
36
36
  // API, or it returned 2xx with an envelope the client could not use. Reporting
37
37
  // a literal 200 there would misattribute a 201 response.
38
38
  export const NO_HTTP_STATUS = 0;
39
+ export const DEFAULT_API_BASE_URL = "https://nexustrade.io/api/v1";
40
+ export const WORKSPACE_SESSION_HEADER = "X-NexusTrade-Session";
39
41
  // Polling defaults. Every NexusTrade job — backtest, optimization,
40
42
  // walk-forward, and any future operation kind — reports through the same
41
43
  // envelope, so one poller serves all of them. Kept in lockstep with the Python
@@ -99,6 +101,18 @@ export class NexusTradeApiError extends Error {
99
101
  this.operationId = operationId;
100
102
  }
101
103
  }
104
+ /**
105
+ * An explicitly supplied anonymous workspace can no longer be resumed.
106
+ *
107
+ * The client deliberately does not create a replacement workspace after this
108
+ * error: doing so would make the caller's saved portfolios appear to vanish.
109
+ */
110
+ export class NexusTradeWorkspaceSessionExpiredError extends NexusTradeApiError {
111
+ constructor(status, message) {
112
+ super(status, "workspace_session_expired", message);
113
+ this.name = "NexusTradeWorkspaceSessionExpiredError";
114
+ }
115
+ }
102
116
  function isRetryableUploadHttpStatus(status) {
103
117
  return status === 408 || status === 429 || status >= 500;
104
118
  }
@@ -143,6 +157,14 @@ function assertValidApiKey(apiKey) {
143
157
  throw new Error("NexusTrade apiKey must be a non-empty token.");
144
158
  }
145
159
  }
160
+ function assertValidWorkspaceSession(workspaceSession) {
161
+ const invalid = typeof workspaceSession !== "string" ||
162
+ workspaceSession.length === 0 ||
163
+ [...workspaceSession].some((character) => /\s/.test(character) || (character.codePointAt(0) ?? 0) < 32);
164
+ if (invalid) {
165
+ throw new Error("NexusTrade workspaceSession must be a non-empty opaque token.");
166
+ }
167
+ }
146
168
  function assertValidBaseUrl(baseUrl) {
147
169
  let parsed;
148
170
  try {
@@ -223,15 +245,58 @@ function decodeJsonObject(bytes, status) {
223
245
  }
224
246
  return decoded;
225
247
  }
248
+ async function apiErrorFromResponse(response) {
249
+ const { bytes } = await readCapped(response, MAX_ERROR_BYTES);
250
+ let code = "api_error";
251
+ let message = response.statusText || `HTTP ${response.status}`;
252
+ try {
253
+ const decoded = decodeJsonObject(bytes, response.status);
254
+ const errorBody = decoded.error;
255
+ if (typeof errorBody === "object" &&
256
+ errorBody !== null &&
257
+ !Array.isArray(errorBody)) {
258
+ const body = errorBody;
259
+ if (body.code)
260
+ code = String(body.code);
261
+ if (body.message)
262
+ message = String(body.message);
263
+ }
264
+ }
265
+ catch {
266
+ // Non-JSON error bodies keep the transport-level code/message.
267
+ }
268
+ if (code.toLowerCase() === "workspace_session_expired") {
269
+ return new NexusTradeWorkspaceSessionExpiredError(response.status, message);
270
+ }
271
+ return new NexusTradeApiError(response.status, code, message);
272
+ }
273
+ function workspaceSessionUrl(baseUrl) {
274
+ const parsed = new URL(baseUrl);
275
+ parsed.pathname = "/api/workspace/session";
276
+ parsed.search = "";
277
+ parsed.hash = "";
278
+ return parsed.toString();
279
+ }
280
+ function supportsWorkspaceSession(transport) {
281
+ const candidate = transport;
282
+ return (typeof candidate.exportWorkspaceSession === "function" &&
283
+ typeof candidate.importWorkspaceSession === "function");
284
+ }
226
285
  export class HttpTransport {
227
286
  // `#` fields, not TS `private` — the credential must be unreachable at
228
287
  // runtime too, matching the Python dataclass's `repr=False`.
229
288
  #apiKey;
230
289
  #baseUrl;
231
290
  #timeoutSeconds;
291
+ #workspaceSession;
292
+ #bootstrapPromise;
232
293
  constructor(options) {
233
294
  const timeoutSeconds = options.timeoutSeconds ?? 30;
234
- assertValidApiKey(options.apiKey);
295
+ if (options.apiKey !== undefined)
296
+ assertValidApiKey(options.apiKey);
297
+ if (options.workspaceSession !== undefined) {
298
+ assertValidWorkspaceSession(options.workspaceSession);
299
+ }
235
300
  assertValidBaseUrl(options.baseUrl);
236
301
  if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
237
302
  throw new Error("timeoutSeconds must be positive.");
@@ -239,10 +304,73 @@ export class HttpTransport {
239
304
  this.#apiKey = options.apiKey;
240
305
  this.#baseUrl = options.baseUrl;
241
306
  this.#timeoutSeconds = timeoutSeconds;
307
+ this.#workspaceSession = options.workspaceSession;
242
308
  }
243
309
  get baseUrl() {
244
310
  return this.#baseUrl;
245
311
  }
312
+ exportWorkspaceSession() {
313
+ return this.#workspaceSession;
314
+ }
315
+ importWorkspaceSession(workspaceSession) {
316
+ assertValidWorkspaceSession(workspaceSession);
317
+ this.#workspaceSession = workspaceSession;
318
+ }
319
+ async #credentialHeaders() {
320
+ if (this.#apiKey !== undefined) {
321
+ return { Authorization: `Bearer ${this.#apiKey}` };
322
+ }
323
+ return { [WORKSPACE_SESSION_HEADER]: await this.#ensureWorkspaceSession() };
324
+ }
325
+ async #ensureWorkspaceSession() {
326
+ if (this.#workspaceSession !== undefined)
327
+ return this.#workspaceSession;
328
+ if (this.#bootstrapPromise !== undefined)
329
+ return this.#bootstrapPromise;
330
+ this.#bootstrapPromise = this.#bootstrapWorkspaceSession();
331
+ try {
332
+ const workspaceSession = await this.#bootstrapPromise;
333
+ this.#workspaceSession = workspaceSession;
334
+ return workspaceSession;
335
+ }
336
+ finally {
337
+ this.#bootstrapPromise = undefined;
338
+ }
339
+ }
340
+ async #bootstrapWorkspaceSession() {
341
+ const controller = new AbortController();
342
+ const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
343
+ try {
344
+ let response;
345
+ try {
346
+ response = await fetch(workspaceSessionUrl(this.#baseUrl), {
347
+ method: "POST",
348
+ headers: { Accept: "application/json" },
349
+ redirect: "manual",
350
+ signal: controller.signal,
351
+ });
352
+ }
353
+ catch (error) {
354
+ const reason = error instanceof Error ? error.message : String(error);
355
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
356
+ }
357
+ if (!response.ok)
358
+ throw await apiErrorFromResponse(response);
359
+ const { bytes, truncated } = await readCapped(response, MAX_RESPONSE_BYTES);
360
+ if (truncated) {
361
+ throw new NexusTradeApiError(response.status, "response_too_large", "NexusTrade workspace response exceeded the SDK size limit.");
362
+ }
363
+ const decoded = decodeJsonObject(bytes, response.status);
364
+ if (typeof decoded.workspaceSession !== "string") {
365
+ throw new NexusTradeApiError(response.status, "invalid_response", "Workspace response is missing workspaceSession.");
366
+ }
367
+ assertValidWorkspaceSession(decoded.workspaceSession);
368
+ return decoded.workspaceSession;
369
+ }
370
+ finally {
371
+ clearTimeout(timer);
372
+ }
373
+ }
246
374
  /** PUT a payload to a presigned storage URL. Sends no credential. */
247
375
  async putBytes(url, data, options) {
248
376
  let delaySeconds = UPLOAD_PUT_INITIAL_BACKOFF_SECONDS;
@@ -301,7 +429,7 @@ export class HttpTransport {
301
429
  const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
302
430
  const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
303
431
  const headers = {
304
- Authorization: `Bearer ${this.#apiKey}`,
432
+ ...(await this.#credentialHeaders()),
305
433
  Accept: "application/json",
306
434
  };
307
435
  if (payload !== undefined)
@@ -350,26 +478,7 @@ export class HttpTransport {
350
478
  continue;
351
479
  }
352
480
  if (!response.ok) {
353
- const { bytes } = await readCapped(response, MAX_ERROR_BYTES);
354
- let code = "api_error";
355
- let message = response.statusText || `HTTP ${response.status}`;
356
- try {
357
- const decoded = decodeJsonObject(bytes, response.status);
358
- const errorBody = decoded.error;
359
- if (typeof errorBody === "object" &&
360
- errorBody !== null &&
361
- !Array.isArray(errorBody)) {
362
- const body = errorBody;
363
- if (body.code)
364
- code = String(body.code);
365
- if (body.message)
366
- message = String(body.message);
367
- }
368
- }
369
- catch {
370
- // Non-JSON error bodies keep the transport-level code/message.
371
- }
372
- throw new NexusTradeApiError(response.status, code, message);
481
+ throw await apiErrorFromResponse(response);
373
482
  }
374
483
  const { bytes, truncated } = await readCapped(response, MAX_RESPONSE_BYTES);
375
484
  if (truncated) {
@@ -631,20 +740,28 @@ export class NexusTradeClient {
631
740
  const dotenv = new LazyDotenv();
632
741
  const apiKey = options.apiKey ?? environmentValue("NEXUSTRADE_API_KEY", dotenv);
633
742
  const baseUrl = options.baseUrl ?? environmentValue("NEXUSTRADE_API_BASE_URL", dotenv);
634
- if (!apiKey || !baseUrl) {
635
- throw new Error("NexusTradeClient requires an API key. Create one at " +
636
- "https://nexustrade.io/developers, then either pass apiKey/baseUrl " +
637
- "or set NEXUSTRADE_API_KEY and NEXUSTRADE_API_BASE_URL " +
638
- "(base URL is https://nexustrade.io/api/v1). " +
639
- "Both are also read from a .env file at or above the current " +
640
- "directory; the real environment takes precedence. " +
641
- "OAuth tokens are not accepted by this API.");
642
- }
643
- this.transport = new HttpTransport({ apiKey, baseUrl });
743
+ this.transport = new HttpTransport({
744
+ apiKey,
745
+ baseUrl: baseUrl ?? DEFAULT_API_BASE_URL,
746
+ workspaceSession: options.workspaceSession,
747
+ });
644
748
  }
645
749
  static fromEnvironment() {
646
750
  return new NexusTradeClient();
647
751
  }
752
+ /** Return the anonymous workspace token after the first API call bootstraps it. */
753
+ exportWorkspaceSession() {
754
+ return supportsWorkspaceSession(this.transport)
755
+ ? this.transport.exportWorkspaceSession()
756
+ : undefined;
757
+ }
758
+ /** Resume an existing anonymous workspace without creating a replacement. */
759
+ importWorkspaceSession(workspaceSession) {
760
+ if (!supportsWorkspaceSession(this.transport)) {
761
+ throw new Error("The configured transport does not support workspace sessions.");
762
+ }
763
+ this.transport.importWorkspaceSession(workspaceSession);
764
+ }
648
765
  async createPortfolio(portfolio, options) {
649
766
  const response = await this.transport.request("POST", "portfolios", {
650
767
  body: asJsonObject(portfolio),
@@ -706,6 +823,45 @@ export class NexusTradeClient {
706
823
  transport: this.transport,
707
824
  });
708
825
  }
826
+ /**
827
+ * Apply deterministic no-code portfolio edits without invoking Aurora.
828
+ * Guest workspaces may rename and add/remove/replace strategies; deployment,
829
+ * scheduling, policy, and trading operations remain account-only.
830
+ */
831
+ async updatePortfolio(portfolioId, operations, options) {
832
+ if (operations.length === 0) {
833
+ throw new Error("updatePortfolio needs at least one operation.");
834
+ }
835
+ const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/operations`, {
836
+ body: { operations: operations.map((operation) => ({ ...operation })) },
837
+ idempotencyKey: options.idempotencyKey,
838
+ });
839
+ if (!isJsonObject(response.portfolio)) {
840
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio update response is missing portfolio.");
841
+ }
842
+ return portfolioHandleFromWire(response.portfolio, {
843
+ transport: this.transport,
844
+ });
845
+ }
846
+ /** Fork a public/shared portfolio into this workspace as an editable copy. */
847
+ async forkPublicPortfolio(sharedPortfolioId, options) {
848
+ const body = {
849
+ target: options.targetPortfolioId ? "existing" : "new",
850
+ mode: options.mode ?? "replace",
851
+ };
852
+ if (options.targetPortfolioId) {
853
+ body.targetPortfolioId = options.targetPortfolioId;
854
+ }
855
+ if (options.name)
856
+ body.name = options.name;
857
+ const response = await this.transport.request("POST", `shared-portfolios/${encodePathSegment(sharedPortfolioId)}/fork`, { body, idempotencyKey: options.idempotencyKey });
858
+ if (!isJsonObject(response.portfolio)) {
859
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio fork response is missing portfolio.");
860
+ }
861
+ return portfolioHandleFromWire(response.portfolio, {
862
+ transport: this.transport,
863
+ });
864
+ }
709
865
  /** Mint/activate a paper portfolio from a chat draft (or re-activate). */
710
866
  async deploy(portfolioId, options = {}) {
711
867
  const body = {};
@@ -1138,13 +1294,25 @@ export class NexusTradeClient {
1138
1294
  const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
1139
1295
  return operationOf(response);
1140
1296
  }
1297
+ /** Requires a registered API key; anonymous workspaces cannot optimize. */
1141
1298
  async createOptimization(handle, options) {
1142
1299
  return this.createPortfolioJob("optimizations", handle, options.idempotencyKey);
1143
1300
  }
1301
+ /** Requires a registered API key, including result reads. */
1144
1302
  async getOptimization(optimizationId) {
1145
1303
  const response = await this.transport.request("GET", `optimizations/${encodePathSegment(optimizationId)}`);
1146
1304
  return operationOf(response);
1147
1305
  }
1306
+ /** Submit a deterministic systematic sweep. Requires a registered API key. */
1307
+ async createSystematicSweep(handle, options) {
1308
+ return this.createPortfolioJob("sweeps", handle, options.idempotencyKey);
1309
+ }
1310
+ /** Requires a registered API key, including sweep result reads. */
1311
+ async getSystematicSweep(optimizationId) {
1312
+ const response = await this.transport.request("GET", `sweeps/${encodePathSegment(optimizationId)}`);
1313
+ return operationOf(response);
1314
+ }
1315
+ /** Requires a registered API key; anonymous workspaces cannot optimize. */
1148
1316
  async createWalkForward(handle, options) {
1149
1317
  return this.createPortfolioJob("walk-forward-studies", handle, options.idempotencyKey);
1150
1318
  }
@@ -1248,6 +1416,10 @@ export class NexusTradeClient {
1248
1416
  async waitForOptimization(optimizationId, options = {}) {
1249
1417
  return waitForOperation((id) => this.getOptimization(id), optimizationId, options);
1250
1418
  }
1419
+ /** Resolve once a systematic sweep is terminal. */
1420
+ async waitForSystematicSweep(optimizationId, options = {}) {
1421
+ return waitForOperation((id) => this.getSystematicSweep(id), optimizationId, options);
1422
+ }
1251
1423
  /** Resolve once a walk-forward study is terminal. See `waitForOperation`. */
1252
1424
  async waitForWalkForward(studyId, options = {}) {
1253
1425
  return waitForOperation((id) => this.getWalkForward(id), studyId, options);