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.
- package/AGENTS.md +66 -0
- package/README.md +86 -9
- package/dist/cjs/client.js +206 -33
- package/dist/cjs/generated/ntSdk.generated.js +99 -4
- package/dist/cjs/index.js +2 -1
- package/dist/esm/client.d.ts +75 -2
- package/dist/esm/client.js +204 -32
- package/dist/esm/generated/ntSdk.generated.d.ts +76 -0
- package/dist/esm/generated/ntSdk.generated.js +86 -2
- package/dist/esm/index.d.ts +2 -2
- package/dist/esm/index.js +1 -1
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -179,6 +179,72 @@ const book = nt.portfolio("Dip buyer", [
|
|
|
179
179
|
Combine with `nt.and`, `nt.or`, `nt.atLeast`, `nt.atMost`, `nt.exactly`.
|
|
180
180
|
</details>
|
|
181
181
|
|
|
182
|
+
<details>
|
|
183
|
+
<summary><b>Sequence two events, and freeze a level at entry</b></summary>
|
|
184
|
+
|
|
185
|
+
`nt.andThen(length, interval, ...conditions)` fires when the LAST condition is true
|
|
186
|
+
now and the one before it was true at a **strictly earlier** tick inside the
|
|
187
|
+
window. `nt.and(...)` is the simultaneous form. The interval is required and has
|
|
188
|
+
no default, because a silent `Day` fallback kills an intraday setup.
|
|
189
|
+
|
|
190
|
+
`nt.IndicatorAtEntry(operand, asset, side?)` freezes what `operand` read at the
|
|
191
|
+
most recent filled entry. A rolling window keeps moving, so a stop written
|
|
192
|
+
straight against `nt.MinimumPrice(spy, 5, "Minute")` is a **trailing** stop and
|
|
193
|
+
the R-multiple measured off it is measured against a moving risk.
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
const spy = nt.stockAsset("SPY");
|
|
197
|
+
const entry = nt.LastOrderPrice(spy, "Buy", "Filled");
|
|
198
|
+
const stopLevel = nt.IndicatorAtEntry(nt.MinimumPrice(spy, 5, "Minute"), spy, "Buy");
|
|
199
|
+
|
|
200
|
+
const book = nt.portfolio("Break and hold", [
|
|
201
|
+
nt.strategy(
|
|
202
|
+
"Red 15m candle, then a break of its high",
|
|
203
|
+
nt.and(
|
|
204
|
+
nt.eq(nt.PositionValue(spy), 0),
|
|
205
|
+
nt.andThen(
|
|
206
|
+
30,
|
|
207
|
+
"Minute",
|
|
208
|
+
nt.lt(nt.IndicatorWindowAgo(nt.PriceRateOfChange(spy, 15, "Minute"), 15, "Minute"), 0),
|
|
209
|
+
nt.gt(
|
|
210
|
+
nt.CrossAbove(
|
|
211
|
+
nt.Price(spy),
|
|
212
|
+
nt.IndicatorWindowAgo(nt.MaximumPrice(spy, 15, "Minute"), 15, "Minute"),
|
|
213
|
+
),
|
|
214
|
+
0,
|
|
215
|
+
),
|
|
216
|
+
),
|
|
217
|
+
),
|
|
218
|
+
nt.buy(spy, 100, "percent of buying power"),
|
|
219
|
+
),
|
|
220
|
+
nt.strategy(
|
|
221
|
+
"Stop under the low that was there at entry",
|
|
222
|
+
nt.and(nt.gt(nt.PositionValue(spy), 0), nt.lt(nt.Price(spy), stopLevel)),
|
|
223
|
+
nt.sell(spy, 100, "percent of current positions"),
|
|
224
|
+
),
|
|
225
|
+
nt.strategy(
|
|
226
|
+
"Take profit at 2.5R off the risk actually taken",
|
|
227
|
+
nt.and(
|
|
228
|
+
nt.gt(nt.PositionValue(spy), 0),
|
|
229
|
+
nt.gte(
|
|
230
|
+
nt.Price(spy),
|
|
231
|
+
nt.Plus(entry, nt.Multiply(nt.Value(2.5), nt.Minus(entry, stopLevel))),
|
|
232
|
+
),
|
|
233
|
+
),
|
|
234
|
+
nt.sell(spy, 100, "percent of current positions"),
|
|
235
|
+
),
|
|
236
|
+
]);
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
The stop and the target now reference the same frozen number, so the reward is
|
|
240
|
+
measured against the risk actually taken. Scalars are `nt.Value(2.5)` — the
|
|
241
|
+
arithmetic builders take indicators on both sides.
|
|
242
|
+
|
|
243
|
+
`IndicatorAtEntry` reads order state, so a strategy using it cannot be
|
|
244
|
+
materialised columnar. `nt.LastOrderPrice` already carries that cost, but it is
|
|
245
|
+
a real reason not to reach for either casually.
|
|
246
|
+
</details>
|
|
247
|
+
|
|
182
248
|
<details>
|
|
183
249
|
<summary><b>Rank and rotate a universe</b></summary>
|
|
184
250
|
|
package/README.md
CHANGED
|
@@ -101,10 +101,7 @@ import {
|
|
|
101
101
|
strategy,
|
|
102
102
|
} from "nexustrade";
|
|
103
103
|
|
|
104
|
-
const client = new NexusTradeClient(
|
|
105
|
-
apiKey: "sk-...",
|
|
106
|
-
baseUrl: "https://nexustrade.io/api/v1",
|
|
107
|
-
});
|
|
104
|
+
const client = new NexusTradeClient();
|
|
108
105
|
|
|
109
106
|
const book = portfolio("Example", [
|
|
110
107
|
strategy("Buy SPY", always(), buy(stockAsset("SPY"), 100)),
|
|
@@ -122,6 +119,28 @@ Backtest operations may include `warnings: string[]` immediately after
|
|
|
122
119
|
submission and again in the terminal `result`. Treat them as material caveats;
|
|
123
120
|
they do not change a successful operation into a failure.
|
|
124
121
|
|
|
122
|
+
### Collateral at risk
|
|
123
|
+
|
|
124
|
+
A terminal operation's `result.statistics` answers how much capital the run had
|
|
125
|
+
on the line, not only what it returned. Two fields carry it, typed as
|
|
126
|
+
`BacktestCollateralStatistics`:
|
|
127
|
+
|
|
128
|
+
| Field | Meaning |
|
|
129
|
+
| --------------------------- | ----------------------------------------------------------- |
|
|
130
|
+
| `peakReservedCollateral` | Largest collateral locked at any tick, in account currency |
|
|
131
|
+
| `medianReservedCollateral` | Median across the ticks that held at least one position |
|
|
132
|
+
|
|
133
|
+
Both are optional and may be `null`, and that absence is a real answer: a
|
|
134
|
+
backtest run before the engine reported collateral has no value, which is not
|
|
135
|
+
the same as a book that locked nothing. Display "not recorded" rather than `$0`
|
|
136
|
+
— a zero here reads as "this strategy risks nothing", the opposite of what an
|
|
137
|
+
unpopulated field means. Do not substitute the portfolio's value either: a book
|
|
138
|
+
risking a few thousand dollars would be reported as risking all of it.
|
|
139
|
+
|
|
140
|
+
Never reconstruct either number from `cash - buyingPower`. Buying power is
|
|
141
|
+
clamped at both ends and carries an open credit-spread premium term, so the
|
|
142
|
+
inversion breaks precisely on the heavily collateralised books this measures.
|
|
143
|
+
|
|
125
144
|
## Authoring strategies
|
|
126
145
|
|
|
127
146
|
Every builder is generated from the same indicator specification the NexusTrade
|
|
@@ -155,6 +174,30 @@ const book = nt.portfolio(
|
|
|
155
174
|
);
|
|
156
175
|
```
|
|
157
176
|
|
|
177
|
+
Order execution belongs to the strategy. Omit it for the backward-compatible
|
|
178
|
+
Market default, use a fixed unit price for Buy/Sell, or set an option strategy's
|
|
179
|
+
maximum net debit / minimum net credit:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
nt.strategy("Buy SPY at my price", nt.always(), nt.buy(nt.stockAsset("SPY"), 10), {
|
|
183
|
+
orderExecution: nt.limitOrder({
|
|
184
|
+
price: nt.unitPriceLimit(500),
|
|
185
|
+
workingTime: nt.goodForDay(),
|
|
186
|
+
}),
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
nt.strategy("Sell the spread for $1.50 or better", nt.always(), optionAction, {
|
|
190
|
+
orderExecution: nt.limitOrder({
|
|
191
|
+
price: nt.minimumNetCredit(1.5),
|
|
192
|
+
workingTime: nt.goodForMinutes(30),
|
|
193
|
+
}),
|
|
194
|
+
});
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`currentLimit()` creates a quote-relative Limit for dynamic rebalance strategies.
|
|
198
|
+
It keeps the no-worse-than-current-quote protection, but it is not a resting
|
|
199
|
+
price target. Live option strategies must choose an explicit Limit policy.
|
|
200
|
+
|
|
158
201
|
<details>
|
|
159
202
|
<summary><b>What you can build</b> — 170+ generated builders</summary>
|
|
160
203
|
|
|
@@ -168,7 +211,8 @@ const book = nt.portfolio(
|
|
|
168
211
|
| **Options** | `OptionDaysToExpiration` `OptionCollateral` `OptionUnrealizedPnL` `openOption` `closeOption` |
|
|
169
212
|
| **Actions** | `buy` `sell` `alert` `dynamicRebalance` `rebalanceOption` |
|
|
170
213
|
| **Selection** | `filter` `selectTop` `selectPercentile` `universe` |
|
|
171
|
-
| **Logic** | `always` `atLeast` `atMost` `exactly` `fewerThan` `multi` `and` `or`
|
|
214
|
+
| **Logic** | `always` `atLeast` `atMost` `exactly` `fewerThan` `multi` `and` `or` `sequence` |
|
|
215
|
+
| **Anchored levels** | `IndicatorAtEntry` `LastOrderPrice` `IndicatorAtMinutesAfterOpen` `IndicatorWindowAgo` |
|
|
172
216
|
|
|
173
217
|
Every builder is fully typed — your editor completes the whole surface.
|
|
174
218
|
|
|
@@ -588,6 +632,8 @@ is missing here, so this list cannot drift from the code.
|
|
|
588
632
|
| `createPortfolio(book, { idempotencyKey })` | Persist a portfolio definition |
|
|
589
633
|
| `listPortfolios(options)` | List portfolios, with filters and pagination |
|
|
590
634
|
| `getPortfolio(portfolioId)` | Read one portfolio |
|
|
635
|
+
| `updatePortfolio(id, operations, { idempotencyKey })` | Rename or edit strategies deterministically |
|
|
636
|
+
| `forkPublicPortfolio(sharedId, { idempotencyKey })` | Fork a public portfolio into the workspace |
|
|
591
637
|
| `deploy(portfolioId, { frequency })` | Start paper trading it |
|
|
592
638
|
| `undeploy(portfolioId)` | Stop it |
|
|
593
639
|
|
|
@@ -608,6 +654,9 @@ is missing here, so this list cannot drift from the code.
|
|
|
608
654
|
| `createOptimization(handle, { idempotencyKey })` | Submit an optimization |
|
|
609
655
|
| `getOptimization(optimizationId)` | Read the operation |
|
|
610
656
|
| `waitForOptimization(optimizationId, options)` | Block until terminal |
|
|
657
|
+
| `createSystematicSweep(handle, { idempotencyKey })` | Submit an explicit-gene sweep |
|
|
658
|
+
| `getSystematicSweep(optimizationId)` | Read the sweep operation |
|
|
659
|
+
| `waitForSystematicSweep(optimizationId, options)` | Block until terminal |
|
|
611
660
|
| `createWalkForward(handle, { idempotencyKey })` | Submit a walk-forward study |
|
|
612
661
|
| `getWalkForward(studyId)` | Read the operation |
|
|
613
662
|
| `waitForWalkForward(studyId, options)` | Block until terminal |
|
|
@@ -667,7 +716,10 @@ is missing here, so this list cannot drift from the code.
|
|
|
667
716
|
| Method | Purpose |
|
|
668
717
|
| ------------------------------------------- | ---------------------------------------- |
|
|
669
718
|
| `new NexusTradeClient({ apiKey, baseUrl })` | Explicit credentials |
|
|
719
|
+
| `new NexusTradeClient()` | Lazy anonymous workspace with strict limits |
|
|
670
720
|
| `NexusTradeClient.fromEnvironment()` | Read them from the environment or `.env` |
|
|
721
|
+
| `exportWorkspaceSession()` | Export an anonymous workspace for later use |
|
|
722
|
+
| `importWorkspaceSession(token)` | Resume an existing anonymous workspace |
|
|
671
723
|
|
|
672
724
|
**PortfolioHandle** — returned by the `portfolio(...)` builder and by
|
|
673
725
|
`getPortfolio` / `listPortfolios`.
|
|
@@ -681,8 +733,31 @@ is missing here, so this list cannot drift from the code.
|
|
|
681
733
|
|
|
682
734
|
## Authentication
|
|
683
735
|
|
|
684
|
-
|
|
685
|
-
|
|
736
|
+
An API key is optional. With no key, the first API operation lazily creates a
|
|
737
|
+
real unregistered NexusTrade workspace and applies stricter request, backtest,
|
|
738
|
+
and AI limits. Anonymous workspaces can create, edit, and fork portfolios,
|
|
739
|
+
launch backtests, and use the programmatic agent/chat surface. Every optimization
|
|
740
|
+
operation—including genetic and systematic sweep launches, result reads,
|
|
741
|
+
reruns, promotion, and out-of-sample workflows—requires a registered API key.
|
|
742
|
+
Export the workspace's opaque token if the work must survive a new process:
|
|
743
|
+
|
|
744
|
+
```ts
|
|
745
|
+
const guest = new NexusTradeClient();
|
|
746
|
+
await guest.listPortfolios();
|
|
747
|
+
const token = guest.exportWorkspaceSession();
|
|
748
|
+
|
|
749
|
+
const resumed = new NexusTradeClient({ workspaceSession: token });
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
An expired explicit workspace token raises
|
|
753
|
+
`NexusTradeWorkspaceSessionExpiredError`; the SDK never creates a replacement
|
|
754
|
+
workspace that would make saved work appear deleted.
|
|
755
|
+
|
|
756
|
+
Registered users can create a key at
|
|
757
|
+
**[nexustrade.io/developers](https://nexustrade.io/developers)** (Profile → API
|
|
758
|
+
Keys). Keys start with `sk-` and are shown once. When both credentials are
|
|
759
|
+
provided, registered `Authorization` takes precedence and the workspace header
|
|
760
|
+
is not sent.
|
|
686
761
|
|
|
687
762
|
```ts
|
|
688
763
|
const client = new NexusTradeClient({
|
|
@@ -709,8 +784,8 @@ written back to `process.env`. Opt out with `NEXUSTRADE_DISABLE_DOTENV=1`.
|
|
|
709
784
|
|
|
710
785
|
| Scope | Grants |
|
|
711
786
|
| ------- | --------------------------------------------------------------------------------- |
|
|
712
|
-
| `read` |
|
|
713
|
-
| `write` |
|
|
787
|
+
| `read` | Portfolio, backtest, genetic, sweep, and walk-forward reads |
|
|
788
|
+
| `write` | Portfolio create/edit/fork, backtests, genetic/sweep, and walk-forward launches |
|
|
714
789
|
| `lake` | Lake catalog, query lifecycle, manifests, result parts |
|
|
715
790
|
|
|
716
791
|
A key missing the scope gets `403 insufficient_scope`.
|
|
@@ -778,6 +853,8 @@ _job_ takes.
|
|
|
778
853
|
|
|
779
854
|
Portfolio drafting, backtesting, optimization, walk-forward studies, and
|
|
780
855
|
read-only SQL over the market-data lake, versioned under `/api/v1/nexustrade`.
|
|
856
|
+
The full surface requires a registered API key; anonymous workspaces are limited
|
|
857
|
+
to portfolio authoring/forking, backtests, and programmatic agent/chat calls.
|
|
781
858
|
The screener and creating a live deployment remain outside this surface.
|
|
782
859
|
Orders are reachable, but a live order is only ever staged for human approval —
|
|
783
860
|
never submitted. `deploy` and `undeploy` act on whatever an existing id already
|
package/dist/cjs/client.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.UPLOAD_PUT_JITTER_SECONDS = exports.UPLOAD_PUT_MAX_BACKOFF_SECONDS = exports.UPLOAD_PUT_INITIAL_BACKOFF_SECONDS = exports.MAX_UPLOAD_PUT_ATTEMPTS = exports.CONNECT_POLL_INTERVAL_SECONDS = exports.DEFAULT_CONNECT_TIMEOUT_SECONDS = 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;
|
|
9
|
+
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeWorkspaceSessionExpiredError = exports.NexusTradeApiError = exports.UPLOAD_PUT_JITTER_SECONDS = exports.UPLOAD_PUT_MAX_BACKOFF_SECONDS = exports.UPLOAD_PUT_INITIAL_BACKOFF_SECONDS = exports.MAX_UPLOAD_PUT_ATTEMPTS = exports.CONNECT_POLL_INTERVAL_SECONDS = exports.DEFAULT_CONNECT_TIMEOUT_SECONDS = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.WORKSPACE_SESSION_HEADER = exports.DEFAULT_API_BASE_URL = exports.NO_HTTP_STATUS = void 0;
|
|
10
10
|
exports.waitForOperation = waitForOperation;
|
|
11
11
|
exports.clientTransport = clientTransport;
|
|
12
12
|
exports.createCustomIndicator = createCustomIndicator;
|
|
@@ -43,6 +43,8 @@ const MAX_REDIRECTS = 5;
|
|
|
43
43
|
// API, or it returned 2xx with an envelope the client could not use. Reporting
|
|
44
44
|
// a literal 200 there would misattribute a 201 response.
|
|
45
45
|
exports.NO_HTTP_STATUS = 0;
|
|
46
|
+
exports.DEFAULT_API_BASE_URL = "https://nexustrade.io/api/v1";
|
|
47
|
+
exports.WORKSPACE_SESSION_HEADER = "X-NexusTrade-Session";
|
|
46
48
|
// Polling defaults. Every NexusTrade job — backtest, optimization,
|
|
47
49
|
// walk-forward, and any future operation kind — reports through the same
|
|
48
50
|
// envelope, so one poller serves all of them. Kept in lockstep with the Python
|
|
@@ -107,6 +109,19 @@ class NexusTradeApiError extends Error {
|
|
|
107
109
|
}
|
|
108
110
|
}
|
|
109
111
|
exports.NexusTradeApiError = NexusTradeApiError;
|
|
112
|
+
/**
|
|
113
|
+
* An explicitly supplied anonymous workspace can no longer be resumed.
|
|
114
|
+
*
|
|
115
|
+
* The client deliberately does not create a replacement workspace after this
|
|
116
|
+
* error: doing so would make the caller's saved portfolios appear to vanish.
|
|
117
|
+
*/
|
|
118
|
+
class NexusTradeWorkspaceSessionExpiredError extends NexusTradeApiError {
|
|
119
|
+
constructor(status, message) {
|
|
120
|
+
super(status, "workspace_session_expired", message);
|
|
121
|
+
this.name = "NexusTradeWorkspaceSessionExpiredError";
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
exports.NexusTradeWorkspaceSessionExpiredError = NexusTradeWorkspaceSessionExpiredError;
|
|
110
125
|
function isRetryableUploadHttpStatus(status) {
|
|
111
126
|
return status === 408 || status === 429 || status >= 500;
|
|
112
127
|
}
|
|
@@ -151,6 +166,14 @@ function assertValidApiKey(apiKey) {
|
|
|
151
166
|
throw new Error("NexusTrade apiKey must be a non-empty token.");
|
|
152
167
|
}
|
|
153
168
|
}
|
|
169
|
+
function assertValidWorkspaceSession(workspaceSession) {
|
|
170
|
+
const invalid = typeof workspaceSession !== "string" ||
|
|
171
|
+
workspaceSession.length === 0 ||
|
|
172
|
+
[...workspaceSession].some((character) => /\s/.test(character) || (character.codePointAt(0) ?? 0) < 32);
|
|
173
|
+
if (invalid) {
|
|
174
|
+
throw new Error("NexusTrade workspaceSession must be a non-empty opaque token.");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
154
177
|
function assertValidBaseUrl(baseUrl) {
|
|
155
178
|
let parsed;
|
|
156
179
|
try {
|
|
@@ -231,15 +254,58 @@ function decodeJsonObject(bytes, status) {
|
|
|
231
254
|
}
|
|
232
255
|
return decoded;
|
|
233
256
|
}
|
|
257
|
+
async function apiErrorFromResponse(response) {
|
|
258
|
+
const { bytes } = await readCapped(response, MAX_ERROR_BYTES);
|
|
259
|
+
let code = "api_error";
|
|
260
|
+
let message = response.statusText || `HTTP ${response.status}`;
|
|
261
|
+
try {
|
|
262
|
+
const decoded = decodeJsonObject(bytes, response.status);
|
|
263
|
+
const errorBody = decoded.error;
|
|
264
|
+
if (typeof errorBody === "object" &&
|
|
265
|
+
errorBody !== null &&
|
|
266
|
+
!Array.isArray(errorBody)) {
|
|
267
|
+
const body = errorBody;
|
|
268
|
+
if (body.code)
|
|
269
|
+
code = String(body.code);
|
|
270
|
+
if (body.message)
|
|
271
|
+
message = String(body.message);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
// Non-JSON error bodies keep the transport-level code/message.
|
|
276
|
+
}
|
|
277
|
+
if (code.toLowerCase() === "workspace_session_expired") {
|
|
278
|
+
return new NexusTradeWorkspaceSessionExpiredError(response.status, message);
|
|
279
|
+
}
|
|
280
|
+
return new NexusTradeApiError(response.status, code, message);
|
|
281
|
+
}
|
|
282
|
+
function workspaceSessionUrl(baseUrl) {
|
|
283
|
+
const parsed = new URL(baseUrl);
|
|
284
|
+
parsed.pathname = "/api/workspace/session";
|
|
285
|
+
parsed.search = "";
|
|
286
|
+
parsed.hash = "";
|
|
287
|
+
return parsed.toString();
|
|
288
|
+
}
|
|
289
|
+
function supportsWorkspaceSession(transport) {
|
|
290
|
+
const candidate = transport;
|
|
291
|
+
return (typeof candidate.exportWorkspaceSession === "function" &&
|
|
292
|
+
typeof candidate.importWorkspaceSession === "function");
|
|
293
|
+
}
|
|
234
294
|
class HttpTransport {
|
|
235
295
|
// `#` fields, not TS `private` — the credential must be unreachable at
|
|
236
296
|
// runtime too, matching the Python dataclass's `repr=False`.
|
|
237
297
|
#apiKey;
|
|
238
298
|
#baseUrl;
|
|
239
299
|
#timeoutSeconds;
|
|
300
|
+
#workspaceSession;
|
|
301
|
+
#bootstrapPromise;
|
|
240
302
|
constructor(options) {
|
|
241
303
|
const timeoutSeconds = options.timeoutSeconds ?? 30;
|
|
242
|
-
|
|
304
|
+
if (options.apiKey !== undefined)
|
|
305
|
+
assertValidApiKey(options.apiKey);
|
|
306
|
+
if (options.workspaceSession !== undefined) {
|
|
307
|
+
assertValidWorkspaceSession(options.workspaceSession);
|
|
308
|
+
}
|
|
243
309
|
assertValidBaseUrl(options.baseUrl);
|
|
244
310
|
if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
|
|
245
311
|
throw new Error("timeoutSeconds must be positive.");
|
|
@@ -247,10 +313,73 @@ class HttpTransport {
|
|
|
247
313
|
this.#apiKey = options.apiKey;
|
|
248
314
|
this.#baseUrl = options.baseUrl;
|
|
249
315
|
this.#timeoutSeconds = timeoutSeconds;
|
|
316
|
+
this.#workspaceSession = options.workspaceSession;
|
|
250
317
|
}
|
|
251
318
|
get baseUrl() {
|
|
252
319
|
return this.#baseUrl;
|
|
253
320
|
}
|
|
321
|
+
exportWorkspaceSession() {
|
|
322
|
+
return this.#workspaceSession;
|
|
323
|
+
}
|
|
324
|
+
importWorkspaceSession(workspaceSession) {
|
|
325
|
+
assertValidWorkspaceSession(workspaceSession);
|
|
326
|
+
this.#workspaceSession = workspaceSession;
|
|
327
|
+
}
|
|
328
|
+
async #credentialHeaders() {
|
|
329
|
+
if (this.#apiKey !== undefined) {
|
|
330
|
+
return { Authorization: `Bearer ${this.#apiKey}` };
|
|
331
|
+
}
|
|
332
|
+
return { [exports.WORKSPACE_SESSION_HEADER]: await this.#ensureWorkspaceSession() };
|
|
333
|
+
}
|
|
334
|
+
async #ensureWorkspaceSession() {
|
|
335
|
+
if (this.#workspaceSession !== undefined)
|
|
336
|
+
return this.#workspaceSession;
|
|
337
|
+
if (this.#bootstrapPromise !== undefined)
|
|
338
|
+
return this.#bootstrapPromise;
|
|
339
|
+
this.#bootstrapPromise = this.#bootstrapWorkspaceSession();
|
|
340
|
+
try {
|
|
341
|
+
const workspaceSession = await this.#bootstrapPromise;
|
|
342
|
+
this.#workspaceSession = workspaceSession;
|
|
343
|
+
return workspaceSession;
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
this.#bootstrapPromise = undefined;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
async #bootstrapWorkspaceSession() {
|
|
350
|
+
const controller = new AbortController();
|
|
351
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
|
|
352
|
+
try {
|
|
353
|
+
let response;
|
|
354
|
+
try {
|
|
355
|
+
response = await fetch(workspaceSessionUrl(this.#baseUrl), {
|
|
356
|
+
method: "POST",
|
|
357
|
+
headers: { Accept: "application/json" },
|
|
358
|
+
redirect: "manual",
|
|
359
|
+
signal: controller.signal,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
364
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "transport_error", reason);
|
|
365
|
+
}
|
|
366
|
+
if (!response.ok)
|
|
367
|
+
throw await apiErrorFromResponse(response);
|
|
368
|
+
const { bytes, truncated } = await readCapped(response, MAX_RESPONSE_BYTES);
|
|
369
|
+
if (truncated) {
|
|
370
|
+
throw new NexusTradeApiError(response.status, "response_too_large", "NexusTrade workspace response exceeded the SDK size limit.");
|
|
371
|
+
}
|
|
372
|
+
const decoded = decodeJsonObject(bytes, response.status);
|
|
373
|
+
if (typeof decoded.workspaceSession !== "string") {
|
|
374
|
+
throw new NexusTradeApiError(response.status, "invalid_response", "Workspace response is missing workspaceSession.");
|
|
375
|
+
}
|
|
376
|
+
assertValidWorkspaceSession(decoded.workspaceSession);
|
|
377
|
+
return decoded.workspaceSession;
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
clearTimeout(timer);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
254
383
|
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
255
384
|
async putBytes(url, data, options) {
|
|
256
385
|
let delaySeconds = exports.UPLOAD_PUT_INITIAL_BACKOFF_SECONDS;
|
|
@@ -309,7 +438,7 @@ class HttpTransport {
|
|
|
309
438
|
const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
|
|
310
439
|
const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
|
|
311
440
|
const headers = {
|
|
312
|
-
|
|
441
|
+
...(await this.#credentialHeaders()),
|
|
313
442
|
Accept: "application/json",
|
|
314
443
|
};
|
|
315
444
|
if (payload !== undefined)
|
|
@@ -358,26 +487,7 @@ class HttpTransport {
|
|
|
358
487
|
continue;
|
|
359
488
|
}
|
|
360
489
|
if (!response.ok) {
|
|
361
|
-
|
|
362
|
-
let code = "api_error";
|
|
363
|
-
let message = response.statusText || `HTTP ${response.status}`;
|
|
364
|
-
try {
|
|
365
|
-
const decoded = decodeJsonObject(bytes, response.status);
|
|
366
|
-
const errorBody = decoded.error;
|
|
367
|
-
if (typeof errorBody === "object" &&
|
|
368
|
-
errorBody !== null &&
|
|
369
|
-
!Array.isArray(errorBody)) {
|
|
370
|
-
const body = errorBody;
|
|
371
|
-
if (body.code)
|
|
372
|
-
code = String(body.code);
|
|
373
|
-
if (body.message)
|
|
374
|
-
message = String(body.message);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
catch {
|
|
378
|
-
// Non-JSON error bodies keep the transport-level code/message.
|
|
379
|
-
}
|
|
380
|
-
throw new NexusTradeApiError(response.status, code, message);
|
|
490
|
+
throw await apiErrorFromResponse(response);
|
|
381
491
|
}
|
|
382
492
|
const { bytes, truncated } = await readCapped(response, MAX_RESPONSE_BYTES);
|
|
383
493
|
if (truncated) {
|
|
@@ -640,20 +750,28 @@ class NexusTradeClient {
|
|
|
640
750
|
const dotenv = new env_ts_1.LazyDotenv();
|
|
641
751
|
const apiKey = options.apiKey ?? (0, env_ts_1.environmentValue)("NEXUSTRADE_API_KEY", dotenv);
|
|
642
752
|
const baseUrl = options.baseUrl ?? (0, env_ts_1.environmentValue)("NEXUSTRADE_API_BASE_URL", dotenv);
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
"Both are also read from a .env file at or above the current " +
|
|
649
|
-
"directory; the real environment takes precedence. " +
|
|
650
|
-
"OAuth tokens are not accepted by this API.");
|
|
651
|
-
}
|
|
652
|
-
this.transport = new HttpTransport({ apiKey, baseUrl });
|
|
753
|
+
this.transport = new HttpTransport({
|
|
754
|
+
apiKey,
|
|
755
|
+
baseUrl: baseUrl ?? exports.DEFAULT_API_BASE_URL,
|
|
756
|
+
workspaceSession: options.workspaceSession,
|
|
757
|
+
});
|
|
653
758
|
}
|
|
654
759
|
static fromEnvironment() {
|
|
655
760
|
return new NexusTradeClient();
|
|
656
761
|
}
|
|
762
|
+
/** Return the anonymous workspace token after the first API call bootstraps it. */
|
|
763
|
+
exportWorkspaceSession() {
|
|
764
|
+
return supportsWorkspaceSession(this.transport)
|
|
765
|
+
? this.transport.exportWorkspaceSession()
|
|
766
|
+
: undefined;
|
|
767
|
+
}
|
|
768
|
+
/** Resume an existing anonymous workspace without creating a replacement. */
|
|
769
|
+
importWorkspaceSession(workspaceSession) {
|
|
770
|
+
if (!supportsWorkspaceSession(this.transport)) {
|
|
771
|
+
throw new Error("The configured transport does not support workspace sessions.");
|
|
772
|
+
}
|
|
773
|
+
this.transport.importWorkspaceSession(workspaceSession);
|
|
774
|
+
}
|
|
657
775
|
async createPortfolio(portfolio, options) {
|
|
658
776
|
const response = await this.transport.request("POST", "portfolios", {
|
|
659
777
|
body: asJsonObject(portfolio),
|
|
@@ -715,6 +833,45 @@ class NexusTradeClient {
|
|
|
715
833
|
transport: this.transport,
|
|
716
834
|
});
|
|
717
835
|
}
|
|
836
|
+
/**
|
|
837
|
+
* Apply deterministic no-code portfolio edits without invoking Aurora.
|
|
838
|
+
* Guest workspaces may rename and add/remove/replace strategies; deployment,
|
|
839
|
+
* scheduling, policy, and trading operations remain account-only.
|
|
840
|
+
*/
|
|
841
|
+
async updatePortfolio(portfolioId, operations, options) {
|
|
842
|
+
if (operations.length === 0) {
|
|
843
|
+
throw new Error("updatePortfolio needs at least one operation.");
|
|
844
|
+
}
|
|
845
|
+
const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/operations`, {
|
|
846
|
+
body: { operations: operations.map((operation) => ({ ...operation })) },
|
|
847
|
+
idempotencyKey: options.idempotencyKey,
|
|
848
|
+
});
|
|
849
|
+
if (!isJsonObject(response.portfolio)) {
|
|
850
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio update response is missing portfolio.");
|
|
851
|
+
}
|
|
852
|
+
return (0, portfolio_ts_1.portfolioHandleFromWire)(response.portfolio, {
|
|
853
|
+
transport: this.transport,
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
/** Fork a public/shared portfolio into this workspace as an editable copy. */
|
|
857
|
+
async forkPublicPortfolio(sharedPortfolioId, options) {
|
|
858
|
+
const body = {
|
|
859
|
+
target: options.targetPortfolioId ? "existing" : "new",
|
|
860
|
+
mode: options.mode ?? "replace",
|
|
861
|
+
};
|
|
862
|
+
if (options.targetPortfolioId) {
|
|
863
|
+
body.targetPortfolioId = options.targetPortfolioId;
|
|
864
|
+
}
|
|
865
|
+
if (options.name)
|
|
866
|
+
body.name = options.name;
|
|
867
|
+
const response = await this.transport.request("POST", `shared-portfolios/${encodePathSegment(sharedPortfolioId)}/fork`, { body, idempotencyKey: options.idempotencyKey });
|
|
868
|
+
if (!isJsonObject(response.portfolio)) {
|
|
869
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio fork response is missing portfolio.");
|
|
870
|
+
}
|
|
871
|
+
return (0, portfolio_ts_1.portfolioHandleFromWire)(response.portfolio, {
|
|
872
|
+
transport: this.transport,
|
|
873
|
+
});
|
|
874
|
+
}
|
|
718
875
|
/** Mint/activate a paper portfolio from a chat draft (or re-activate). */
|
|
719
876
|
async deploy(portfolioId, options = {}) {
|
|
720
877
|
const body = {};
|
|
@@ -1147,13 +1304,25 @@ class NexusTradeClient {
|
|
|
1147
1304
|
const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
|
|
1148
1305
|
return operationOf(response);
|
|
1149
1306
|
}
|
|
1307
|
+
/** Requires a registered API key; anonymous workspaces cannot optimize. */
|
|
1150
1308
|
async createOptimization(handle, options) {
|
|
1151
1309
|
return this.createPortfolioJob("optimizations", handle, options.idempotencyKey);
|
|
1152
1310
|
}
|
|
1311
|
+
/** Requires a registered API key, including result reads. */
|
|
1153
1312
|
async getOptimization(optimizationId) {
|
|
1154
1313
|
const response = await this.transport.request("GET", `optimizations/${encodePathSegment(optimizationId)}`);
|
|
1155
1314
|
return operationOf(response);
|
|
1156
1315
|
}
|
|
1316
|
+
/** Submit a deterministic systematic sweep. Requires a registered API key. */
|
|
1317
|
+
async createSystematicSweep(handle, options) {
|
|
1318
|
+
return this.createPortfolioJob("sweeps", handle, options.idempotencyKey);
|
|
1319
|
+
}
|
|
1320
|
+
/** Requires a registered API key, including sweep result reads. */
|
|
1321
|
+
async getSystematicSweep(optimizationId) {
|
|
1322
|
+
const response = await this.transport.request("GET", `sweeps/${encodePathSegment(optimizationId)}`);
|
|
1323
|
+
return operationOf(response);
|
|
1324
|
+
}
|
|
1325
|
+
/** Requires a registered API key; anonymous workspaces cannot optimize. */
|
|
1157
1326
|
async createWalkForward(handle, options) {
|
|
1158
1327
|
return this.createPortfolioJob("walk-forward-studies", handle, options.idempotencyKey);
|
|
1159
1328
|
}
|
|
@@ -1257,6 +1426,10 @@ class NexusTradeClient {
|
|
|
1257
1426
|
async waitForOptimization(optimizationId, options = {}) {
|
|
1258
1427
|
return waitForOperation((id) => this.getOptimization(id), optimizationId, options);
|
|
1259
1428
|
}
|
|
1429
|
+
/** Resolve once a systematic sweep is terminal. */
|
|
1430
|
+
async waitForSystematicSweep(optimizationId, options = {}) {
|
|
1431
|
+
return waitForOperation((id) => this.getSystematicSweep(id), optimizationId, options);
|
|
1432
|
+
}
|
|
1260
1433
|
/** Resolve once a walk-forward study is terminal. See `waitForOperation`. */
|
|
1261
1434
|
async waitForWalkForward(studyId, options = {}) {
|
|
1262
1435
|
return waitForOperation((id) => this.getWalkForward(id), studyId, options);
|