nexustrade 1.9.10 → 1.10.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 +62 -9
- package/dist/cjs/client.js +206 -33
- package/dist/cjs/generated/ntSdk.generated.js +47 -3
- 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 +27 -0
- package/dist/esm/generated/ntSdk.generated.js +43 -1
- 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
|
|
@@ -168,7 +187,8 @@ const book = nt.portfolio(
|
|
|
168
187
|
| **Options** | `OptionDaysToExpiration` `OptionCollateral` `OptionUnrealizedPnL` `openOption` `closeOption` |
|
|
169
188
|
| **Actions** | `buy` `sell` `alert` `dynamicRebalance` `rebalanceOption` |
|
|
170
189
|
| **Selection** | `filter` `selectTop` `selectPercentile` `universe` |
|
|
171
|
-
| **Logic** | `always` `atLeast` `atMost` `exactly` `fewerThan` `multi` `and` `or`
|
|
190
|
+
| **Logic** | `always` `atLeast` `atMost` `exactly` `fewerThan` `multi` `and` `or` `sequence` |
|
|
191
|
+
| **Anchored levels** | `IndicatorAtEntry` `LastOrderPrice` `IndicatorAtMinutesAfterOpen` `IndicatorWindowAgo` |
|
|
172
192
|
|
|
173
193
|
Every builder is fully typed — your editor completes the whole surface.
|
|
174
194
|
|
|
@@ -588,6 +608,8 @@ is missing here, so this list cannot drift from the code.
|
|
|
588
608
|
| `createPortfolio(book, { idempotencyKey })` | Persist a portfolio definition |
|
|
589
609
|
| `listPortfolios(options)` | List portfolios, with filters and pagination |
|
|
590
610
|
| `getPortfolio(portfolioId)` | Read one portfolio |
|
|
611
|
+
| `updatePortfolio(id, operations, { idempotencyKey })` | Rename or edit strategies deterministically |
|
|
612
|
+
| `forkPublicPortfolio(sharedId, { idempotencyKey })` | Fork a public portfolio into the workspace |
|
|
591
613
|
| `deploy(portfolioId, { frequency })` | Start paper trading it |
|
|
592
614
|
| `undeploy(portfolioId)` | Stop it |
|
|
593
615
|
|
|
@@ -608,6 +630,9 @@ is missing here, so this list cannot drift from the code.
|
|
|
608
630
|
| `createOptimization(handle, { idempotencyKey })` | Submit an optimization |
|
|
609
631
|
| `getOptimization(optimizationId)` | Read the operation |
|
|
610
632
|
| `waitForOptimization(optimizationId, options)` | Block until terminal |
|
|
633
|
+
| `createSystematicSweep(handle, { idempotencyKey })` | Submit an explicit-gene sweep |
|
|
634
|
+
| `getSystematicSweep(optimizationId)` | Read the sweep operation |
|
|
635
|
+
| `waitForSystematicSweep(optimizationId, options)` | Block until terminal |
|
|
611
636
|
| `createWalkForward(handle, { idempotencyKey })` | Submit a walk-forward study |
|
|
612
637
|
| `getWalkForward(studyId)` | Read the operation |
|
|
613
638
|
| `waitForWalkForward(studyId, options)` | Block until terminal |
|
|
@@ -667,7 +692,10 @@ is missing here, so this list cannot drift from the code.
|
|
|
667
692
|
| Method | Purpose |
|
|
668
693
|
| ------------------------------------------- | ---------------------------------------- |
|
|
669
694
|
| `new NexusTradeClient({ apiKey, baseUrl })` | Explicit credentials |
|
|
695
|
+
| `new NexusTradeClient()` | Lazy anonymous workspace with strict limits |
|
|
670
696
|
| `NexusTradeClient.fromEnvironment()` | Read them from the environment or `.env` |
|
|
697
|
+
| `exportWorkspaceSession()` | Export an anonymous workspace for later use |
|
|
698
|
+
| `importWorkspaceSession(token)` | Resume an existing anonymous workspace |
|
|
671
699
|
|
|
672
700
|
**PortfolioHandle** — returned by the `portfolio(...)` builder and by
|
|
673
701
|
`getPortfolio` / `listPortfolios`.
|
|
@@ -681,8 +709,31 @@ is missing here, so this list cannot drift from the code.
|
|
|
681
709
|
|
|
682
710
|
## Authentication
|
|
683
711
|
|
|
684
|
-
|
|
685
|
-
|
|
712
|
+
An API key is optional. With no key, the first API operation lazily creates a
|
|
713
|
+
real unregistered NexusTrade workspace and applies stricter request, backtest,
|
|
714
|
+
and AI limits. Anonymous workspaces can create, edit, and fork portfolios,
|
|
715
|
+
launch backtests, and use the programmatic agent/chat surface. Every optimization
|
|
716
|
+
operation—including genetic and systematic sweep launches, result reads,
|
|
717
|
+
reruns, promotion, and out-of-sample workflows—requires a registered API key.
|
|
718
|
+
Export the workspace's opaque token if the work must survive a new process:
|
|
719
|
+
|
|
720
|
+
```ts
|
|
721
|
+
const guest = new NexusTradeClient();
|
|
722
|
+
await guest.listPortfolios();
|
|
723
|
+
const token = guest.exportWorkspaceSession();
|
|
724
|
+
|
|
725
|
+
const resumed = new NexusTradeClient({ workspaceSession: token });
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
An expired explicit workspace token raises
|
|
729
|
+
`NexusTradeWorkspaceSessionExpiredError`; the SDK never creates a replacement
|
|
730
|
+
workspace that would make saved work appear deleted.
|
|
731
|
+
|
|
732
|
+
Registered users can create a key at
|
|
733
|
+
**[nexustrade.io/developers](https://nexustrade.io/developers)** (Profile → API
|
|
734
|
+
Keys). Keys start with `sk-` and are shown once. When both credentials are
|
|
735
|
+
provided, registered `Authorization` takes precedence and the workspace header
|
|
736
|
+
is not sent.
|
|
686
737
|
|
|
687
738
|
```ts
|
|
688
739
|
const client = new NexusTradeClient({
|
|
@@ -709,8 +760,8 @@ written back to `process.env`. Opt out with `NEXUSTRADE_DISABLE_DOTENV=1`.
|
|
|
709
760
|
|
|
710
761
|
| Scope | Grants |
|
|
711
762
|
| ------- | --------------------------------------------------------------------------------- |
|
|
712
|
-
| `read` |
|
|
713
|
-
| `write` |
|
|
763
|
+
| `read` | Portfolio, backtest, genetic, sweep, and walk-forward reads |
|
|
764
|
+
| `write` | Portfolio create/edit/fork, backtests, genetic/sweep, and walk-forward launches |
|
|
714
765
|
| `lake` | Lake catalog, query lifecycle, manifests, result parts |
|
|
715
766
|
|
|
716
767
|
A key missing the scope gets `403 insufficient_scope`.
|
|
@@ -778,6 +829,8 @@ _job_ takes.
|
|
|
778
829
|
|
|
779
830
|
Portfolio drafting, backtesting, optimization, walk-forward studies, and
|
|
780
831
|
read-only SQL over the market-data lake, versioned under `/api/v1/nexustrade`.
|
|
832
|
+
The full surface requires a registered API key; anonymous workspaces are limited
|
|
833
|
+
to portfolio authoring/forking, backtests, and programmatic agent/chat calls.
|
|
781
834
|
The screener and creating a live deployment remain outside this surface.
|
|
782
835
|
Orders are reachable, but a live order is only ever staged for human approval —
|
|
783
836
|
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);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
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.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.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.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 = 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;
|
|
@@ -414,7 +434,17 @@ exports.strategy = strategy;
|
|
|
414
434
|
*/
|
|
415
435
|
const sessionFlatten = (condition, config = {}, name = "Session flatten") => (0, exports.strategy)(name, condition, (0, exports.closeOption)({ ...config }));
|
|
416
436
|
exports.sessionFlatten = sessionFlatten;
|
|
417
|
-
const portfolio = (name, strategies, options = {}) =>
|
|
437
|
+
const portfolio = (name, strategies, options = {}) => {
|
|
438
|
+
const initialValue = options.initialValue ?? 10000;
|
|
439
|
+
return new portfolio_ts_1.PortfolioHandle(compact({
|
|
440
|
+
name,
|
|
441
|
+
initialValue,
|
|
442
|
+
cash: initialValue,
|
|
443
|
+
buyingPower: initialValue,
|
|
444
|
+
...options,
|
|
445
|
+
strategies,
|
|
446
|
+
}));
|
|
447
|
+
};
|
|
418
448
|
exports.portfolio = portfolio;
|
|
419
449
|
// ---- generated indicator builders ----
|
|
420
450
|
/**
|
|
@@ -768,6 +798,20 @@ function Index(metric = "VIX") {
|
|
|
768
798
|
d["metric"] = metric;
|
|
769
799
|
return d;
|
|
770
800
|
}
|
|
801
|
+
/**
|
|
802
|
+
* IndicatorAtEntry indicator.
|
|
803
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
804
|
+
* @param side The side of the fill the value is anchored to
|
|
805
|
+
* @param orderStatus Matches order events with this status
|
|
806
|
+
*/
|
|
807
|
+
function IndicatorAtEntry(operand, asset, side, orderStatus = "Filled") {
|
|
808
|
+
const d = { type: "IndicatorAtEntry" };
|
|
809
|
+
setAsset(d, "targetAsset", asset);
|
|
810
|
+
d["side"] = side;
|
|
811
|
+
d["orderStatus"] = orderStatus;
|
|
812
|
+
d.indicators = [operand];
|
|
813
|
+
return d;
|
|
814
|
+
}
|
|
771
815
|
/**
|
|
772
816
|
* IndicatorAtMinutesAfterOpen indicator.
|
|
773
817
|
* @param minutesAfterOpen The number of minutes after market open to capture the indicator value
|
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; } });
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -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
|
|
104
|
+
apiKey?: string;
|
|
94
105
|
baseUrl: string;
|
|
106
|
+
workspaceSession?: string;
|
|
95
107
|
timeoutSeconds?: number;
|
|
96
108
|
}
|
|
97
|
-
export
|
|
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. */
|
package/dist/esm/client.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
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);
|
|
@@ -407,6 +407,8 @@ export interface Strategy {
|
|
|
407
407
|
export interface Portfolio {
|
|
408
408
|
name: string;
|
|
409
409
|
initialValue?: number;
|
|
410
|
+
cash?: number;
|
|
411
|
+
buyingPower?: number;
|
|
410
412
|
strategies: Strategy[];
|
|
411
413
|
main?: boolean;
|
|
412
414
|
supportsFractionalShares?: boolean;
|
|
@@ -462,6 +464,24 @@ export declare const fewerThan: (count: number, ...conditions: Condition[]) => C
|
|
|
462
464
|
export declare const exactly: (count: number, ...conditions: Condition[]) => Condition;
|
|
463
465
|
/** Multi with an explicit Comparator (same wire shape as YAML Multi). */
|
|
464
466
|
export declare const multi: (count: number, comparison: Comparator, ...conditions: Condition[]) => Condition;
|
|
467
|
+
/**
|
|
468
|
+
* Sequence. `andThen(30, "Minute", A, B)` is true at tick t when B is true at t
|
|
469
|
+
* and A was true at some STRICTLY EARLIER tick in the preceding 30 minutes.
|
|
470
|
+
*
|
|
471
|
+
* Simultaneous A and B does not fire — that is `and`. The window applies per
|
|
472
|
+
* transition, so with three or more steps each one must occur within the window
|
|
473
|
+
* of the step before it. Nesting is legal and means something different:
|
|
474
|
+
* `andThen(W, andThen(W, A, B), C)` is not `andThen(W, A, B, C)`.
|
|
475
|
+
*
|
|
476
|
+
* `interval` is REQUIRED and has no default. An omitted interval would fall
|
|
477
|
+
* back to Day and silently kill an intraday setup.
|
|
478
|
+
*
|
|
479
|
+
* Named `andThen` rather than `then`: a module namespace with a callable
|
|
480
|
+
* `then` export is assimilated as a thenable, so `await import("nexustrade")`
|
|
481
|
+
* would call it with resolve/reject and never settle. Emits wire type "Then",
|
|
482
|
+
* the same way atLeast/atMost/exactly emit "Multi".
|
|
483
|
+
*/
|
|
484
|
+
export declare const andThen: (length: number, interval: Interval, ...conditions: Condition[]) => Condition;
|
|
465
485
|
/** Always-true gate for strategies whose cadence lives in the pipeline. */
|
|
466
486
|
export declare const always: () => Condition;
|
|
467
487
|
export declare const meanVarianceAllocation: (config?: Partial<Omit<MeanVarianceAllocationPolicy, "type">>) => MeanVarianceAllocationPolicy;
|
|
@@ -799,6 +819,13 @@ export declare function ImpliedVolatility(asset: AssetArg, dte?: number): Indica
|
|
|
799
819
|
* @param metric Ticker key matching hydrated index price data (add more in BigQuery + rehydrate as needed)
|
|
800
820
|
*/
|
|
801
821
|
export declare function Index(metric?: "VIX" | "SPX" | "NDX" | "DJI" | "RUT" | "SKEW" | "VVIX" | "USDBROAD" | "TNX"): Indicator;
|
|
822
|
+
/**
|
|
823
|
+
* IndicatorAtEntry indicator.
|
|
824
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
825
|
+
* @param side The side of the fill the value is anchored to
|
|
826
|
+
* @param orderStatus Matches order events with this status
|
|
827
|
+
*/
|
|
828
|
+
export declare function IndicatorAtEntry(operand: Indicator, asset: AssetArg, side: Side, orderStatus?: OrderStatus): Indicator;
|
|
802
829
|
/**
|
|
803
830
|
* IndicatorAtMinutesAfterOpen indicator.
|
|
804
831
|
* @param minutesAfterOpen The number of minutes after market open to capture the indicator value
|
|
@@ -127,6 +127,24 @@ export const fewerThan = (count, ...conditions) => ({ type: "Multi", comparison:
|
|
|
127
127
|
export const exactly = (count, ...conditions) => ({ type: "Multi", comparison: "equal", value: count, conditions });
|
|
128
128
|
/** Multi with an explicit Comparator (same wire shape as YAML Multi). */
|
|
129
129
|
export const multi = (count, comparison, ...conditions) => ({ type: "Multi", comparison, value: count, conditions });
|
|
130
|
+
/**
|
|
131
|
+
* Sequence. `andThen(30, "Minute", A, B)` is true at tick t when B is true at t
|
|
132
|
+
* and A was true at some STRICTLY EARLIER tick in the preceding 30 minutes.
|
|
133
|
+
*
|
|
134
|
+
* Simultaneous A and B does not fire — that is `and`. The window applies per
|
|
135
|
+
* transition, so with three or more steps each one must occur within the window
|
|
136
|
+
* of the step before it. Nesting is legal and means something different:
|
|
137
|
+
* `andThen(W, andThen(W, A, B), C)` is not `andThen(W, A, B, C)`.
|
|
138
|
+
*
|
|
139
|
+
* `interval` is REQUIRED and has no default. An omitted interval would fall
|
|
140
|
+
* back to Day and silently kill an intraday setup.
|
|
141
|
+
*
|
|
142
|
+
* Named `andThen` rather than `then`: a module namespace with a callable
|
|
143
|
+
* `then` export is assimilated as a thenable, so `await import("nexustrade")`
|
|
144
|
+
* would call it with resolve/reject and never settle. Emits wire type "Then",
|
|
145
|
+
* the same way atLeast/atMost/exactly emit "Multi".
|
|
146
|
+
*/
|
|
147
|
+
export const andThen = (length, interval, ...conditions) => ({ type: "Then", conditions, window: { length, interval } });
|
|
130
148
|
/** Always-true gate for strategies whose cadence lives in the pipeline. */
|
|
131
149
|
export const always = () => compare(Value(1), Value(0), "greaterThan");
|
|
132
150
|
export const meanVarianceAllocation = (config = {}) => ({
|
|
@@ -254,7 +272,17 @@ export const strategy = (name, condition, action, options = {}) => compact({ nam
|
|
|
254
272
|
* Book-level only — CandidateCondition is rejected (same as strategy when).
|
|
255
273
|
*/
|
|
256
274
|
export const sessionFlatten = (condition, config = {}, name = "Session flatten") => strategy(name, condition, closeOption({ ...config }));
|
|
257
|
-
export const portfolio = (name, strategies, options = {}) =>
|
|
275
|
+
export const portfolio = (name, strategies, options = {}) => {
|
|
276
|
+
const initialValue = options.initialValue ?? 10000;
|
|
277
|
+
return new PortfolioHandle(compact({
|
|
278
|
+
name,
|
|
279
|
+
initialValue,
|
|
280
|
+
cash: initialValue,
|
|
281
|
+
buyingPower: initialValue,
|
|
282
|
+
...options,
|
|
283
|
+
strategies,
|
|
284
|
+
}));
|
|
285
|
+
};
|
|
258
286
|
// ---- generated indicator builders ----
|
|
259
287
|
/**
|
|
260
288
|
* AbsoluteValue indicator.
|
|
@@ -607,6 +635,20 @@ export function Index(metric = "VIX") {
|
|
|
607
635
|
d["metric"] = metric;
|
|
608
636
|
return d;
|
|
609
637
|
}
|
|
638
|
+
/**
|
|
639
|
+
* IndicatorAtEntry indicator.
|
|
640
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
641
|
+
* @param side The side of the fill the value is anchored to
|
|
642
|
+
* @param orderStatus Matches order events with this status
|
|
643
|
+
*/
|
|
644
|
+
export function IndicatorAtEntry(operand, asset, side, orderStatus = "Filled") {
|
|
645
|
+
const d = { type: "IndicatorAtEntry" };
|
|
646
|
+
setAsset(d, "targetAsset", asset);
|
|
647
|
+
d["side"] = side;
|
|
648
|
+
d["orderStatus"] = orderStatus;
|
|
649
|
+
d.indicators = [operand];
|
|
650
|
+
return d;
|
|
651
|
+
}
|
|
610
652
|
/**
|
|
611
653
|
* IndicatorAtMinutesAfterOpen indicator.
|
|
612
654
|
* @param minutesAfterOpen The number of minutes after market open to capture the indicator value
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { AgentRun } from "./agent.js";
|
|
2
2
|
export type { AgentEvent, AgentRunOptions } from "./agent.js";
|
|
3
|
-
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
4
|
-
export type { CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, UploadTransport, WaitOptions, } from "./client.js";
|
|
3
|
+
export { HttpTransport, NexusTradeApiError, NexusTradeClient, NexusTradeWorkspaceSessionExpiredError, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
4
|
+
export type { BacktestCollateralStatistics, CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, UploadTransport, WaitOptions, WorkspaceSessionTransport, } from "./client.js";
|
|
5
5
|
export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
|
|
6
6
|
export type { DeployOutcome, DeployResult, PortfolioHandleOptions, PortfolioListResult, PortfolioType, ReadonlyPortfolioPolicy, } from "./portfolio.js";
|
|
7
7
|
export * from "./generated/ntSdk.generated.js";
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { AgentRun } from "./agent.js";
|
|
2
|
-
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
2
|
+
export { HttpTransport, NexusTradeApiError, NexusTradeClient, NexusTradeWorkspaceSessionExpiredError, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
3
3
|
export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
|
|
4
4
|
export * from "./generated/ntSdk.generated.js";
|