nexustrade 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +27 -1
- package/dist/cjs/agent.js +223 -0
- package/dist/cjs/client.js +175 -23
- package/dist/cjs/env.js +28 -2
- package/dist/cjs/generated/ntSdk.generated.js +2 -4
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/portfolio.js +300 -0
- package/dist/esm/agent.d.ts +86 -0
- package/dist/esm/agent.js +219 -0
- package/dist/esm/client.d.ts +52 -0
- package/dist/esm/client.js +160 -9
- package/dist/esm/env.d.ts +16 -1
- package/dist/esm/env.js +26 -2
- package/dist/esm/generated/ntSdk.generated.d.ts +2 -1
- package/dist/esm/generated/ntSdk.generated.js +2 -4
- package/dist/esm/index.d.ts +5 -1
- package/dist/esm/index.js +2 -0
- package/dist/esm/portfolio.d.ts +89 -0
- package/dist/esm/portfolio.js +262 -0
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -217,6 +217,33 @@ Always parameterize with `?` rather than interpolating into the SQL string.
|
|
|
217
217
|
Stream parts with `downloadLakeQueryPart` instead of materializing large results.
|
|
218
218
|
</details>
|
|
219
219
|
|
|
220
|
+
<details>
|
|
221
|
+
<summary><b>Run an agent</b></summary>
|
|
222
|
+
|
|
223
|
+
Agents are the one job kind that is NOT fire-and-poll. Three states —
|
|
224
|
+
`pending_plan_approval`, `pending_action_approval`, `awaiting_user_input` — are
|
|
225
|
+
ones the run cannot leave on its own, so the caller is the approver.
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
const run = await nt.createAgent("Find momentum names in the S&P 500", {
|
|
229
|
+
idempotencyKey: "momentum-scan-v1",
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
for await (const event of run) {
|
|
233
|
+
console.log(event.text);
|
|
234
|
+
if (event.needsApproval) await run.approve(); // or run.reject()
|
|
235
|
+
else if (event.needsInput) await run.say("focus on semis");
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Iterating waits. If you never answer a blocked run, iteration throws
|
|
240
|
+
`agent_awaiting_input` rather than spinning silently — the run keeps going
|
|
241
|
+
server-side, so reattach with `nt.attachAgent(run.id)`.
|
|
242
|
+
|
|
243
|
+
Approving can place orders, so it needs the `trade` scope; everything else
|
|
244
|
+
needs `write`. Agent runs are unavailable to `run_compute` sandbox code.
|
|
245
|
+
</details>
|
|
246
|
+
|
|
220
247
|
## Errors
|
|
221
248
|
|
|
222
249
|
All failures throw `NexusTradeApiError` with a stable `.status`, `.code`, and
|
|
@@ -240,7 +267,6 @@ Not in this SDK. Do not attempt to reach them through it:
|
|
|
240
267
|
|
|
241
268
|
- **Screener** — MCP only.
|
|
242
269
|
- **Live trading and order placement** — deliberately excluded.
|
|
243
|
-
- **Agent runs** — the NexusTrade agent API is not exposed here yet.
|
|
244
270
|
|
|
245
271
|
## Verifying your work
|
|
246
272
|
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Agent runs as an async iterator.
|
|
4
|
+
*
|
|
5
|
+
* Every other NexusTrade job is fire-and-poll: submit, wait, read a terminal
|
|
6
|
+
* result. Agents are not, because three of their states —
|
|
7
|
+
* `pending_plan_approval`, `pending_action_approval` and `awaiting_user_input`
|
|
8
|
+
* — are ones the run cannot leave on its own. A caller that only polled would
|
|
9
|
+
* start a run that stalls forever waiting for an approval nobody is present to
|
|
10
|
+
* give, and bill for the wait.
|
|
11
|
+
*
|
|
12
|
+
* So the caller *is* the approver:
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* const run = await nt.createAgent("Find momentum names in the S&P 500", {
|
|
16
|
+
* idempotencyKey: "momentum-scan-v1",
|
|
17
|
+
* });
|
|
18
|
+
* for await (const event of run) {
|
|
19
|
+
* console.log(event.text);
|
|
20
|
+
* if (event.needsApproval) await run.approve();
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Mirrors `agent.py`. See designs/2026-07-26-sdk-agent-runs.md.
|
|
25
|
+
*/
|
|
26
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
|
+
exports.AgentRun = void 0;
|
|
28
|
+
const client_ts_1 = require("./client.js");
|
|
29
|
+
const DEFAULT_EVENT_LIMIT = 50;
|
|
30
|
+
function sleep(seconds) {
|
|
31
|
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
32
|
+
}
|
|
33
|
+
/** A live agent run. Iterate it; answer it when it asks. */
|
|
34
|
+
class AgentRun {
|
|
35
|
+
id;
|
|
36
|
+
status;
|
|
37
|
+
terminal = false;
|
|
38
|
+
/** Every event yielded so far, in order. */
|
|
39
|
+
events = [];
|
|
40
|
+
/**
|
|
41
|
+
* Pacing, public and mutable to mirror the Python dataclass fields. Tests
|
|
42
|
+
* collapse the backoff through these; callers can widen the timeout on a run
|
|
43
|
+
* they expect to sit blocked for a while.
|
|
44
|
+
*/
|
|
45
|
+
timeoutSeconds;
|
|
46
|
+
pollIntervalSeconds;
|
|
47
|
+
maxPollIntervalSeconds;
|
|
48
|
+
eventLimit;
|
|
49
|
+
#transport;
|
|
50
|
+
#cursor = null;
|
|
51
|
+
#seen = new Map();
|
|
52
|
+
constructor(id, transport, status = "initializing", options = {}) {
|
|
53
|
+
this.id = id;
|
|
54
|
+
this.status = status;
|
|
55
|
+
this.#transport = transport;
|
|
56
|
+
this.timeoutSeconds =
|
|
57
|
+
options.timeoutSeconds ?? client_ts_1.DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
58
|
+
this.pollIntervalSeconds =
|
|
59
|
+
options.pollIntervalSeconds ?? client_ts_1.DEFAULT_POLL_INTERVAL_SECONDS;
|
|
60
|
+
this.maxPollIntervalSeconds =
|
|
61
|
+
options.maxPollIntervalSeconds ?? client_ts_1.MAX_POLL_INTERVAL_SECONDS;
|
|
62
|
+
this.eventLimit = options.eventLimit ?? DEFAULT_EVENT_LIMIT;
|
|
63
|
+
}
|
|
64
|
+
/** Resume a run already in flight from a known cursor. */
|
|
65
|
+
setCursor(cursor) {
|
|
66
|
+
this.#cursor = cursor;
|
|
67
|
+
}
|
|
68
|
+
/** Re-read status without consuming events. */
|
|
69
|
+
async refresh() {
|
|
70
|
+
const response = await this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}`);
|
|
71
|
+
const agent = response.agent;
|
|
72
|
+
if (agent && typeof agent === "object" && !Array.isArray(agent)) {
|
|
73
|
+
const status = agent.status;
|
|
74
|
+
if (typeof status === "string")
|
|
75
|
+
this.status = status;
|
|
76
|
+
this.terminal = Boolean(agent.terminal);
|
|
77
|
+
}
|
|
78
|
+
return this.status;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Yield events until the run is terminal.
|
|
82
|
+
*
|
|
83
|
+
* Waits between polls on the same deterministic backoff the operation waiter
|
|
84
|
+
* uses. When the run reaches a state only the caller can clear, the blocking
|
|
85
|
+
* event is yielded and iteration then waits for the state to move — the
|
|
86
|
+
* caller is expected to answer from inside the loop body.
|
|
87
|
+
*/
|
|
88
|
+
async *[Symbol.asyncIterator]() {
|
|
89
|
+
let interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
|
|
90
|
+
let deadline = Date.now() + this.timeoutSeconds * 1000;
|
|
91
|
+
let blockedStatus = null;
|
|
92
|
+
for (;;) {
|
|
93
|
+
const page = await this.#fetch();
|
|
94
|
+
const fresh = this.#absorb(page);
|
|
95
|
+
for (const event of fresh)
|
|
96
|
+
yield event;
|
|
97
|
+
if (this.terminal)
|
|
98
|
+
return;
|
|
99
|
+
if (fresh.length > 0) {
|
|
100
|
+
// Progress resets both the backoff and the stall deadline: a run that is
|
|
101
|
+
// still talking is not stuck, however long it runs.
|
|
102
|
+
interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
|
|
103
|
+
deadline = Date.now() + this.timeoutSeconds * 1000;
|
|
104
|
+
}
|
|
105
|
+
const waitingOnCaller = Boolean(page.pendingApproval) || Boolean(page.needsInput);
|
|
106
|
+
if (waitingOnCaller) {
|
|
107
|
+
if (blockedStatus === null) {
|
|
108
|
+
blockedStatus = this.status;
|
|
109
|
+
}
|
|
110
|
+
else if (this.status !== blockedStatus) {
|
|
111
|
+
// The caller answered; resume at full speed.
|
|
112
|
+
blockedStatus = null;
|
|
113
|
+
interval = Math.min(this.pollIntervalSeconds, this.maxPollIntervalSeconds);
|
|
114
|
+
deadline = Date.now() + this.timeoutSeconds * 1000;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
blockedStatus = null;
|
|
119
|
+
}
|
|
120
|
+
const remaining = (deadline - Date.now()) / 1000;
|
|
121
|
+
if (remaining <= 0) {
|
|
122
|
+
throw new client_ts_1.NexusTradeApiError(client_ts_1.NO_HTTP_STATUS, waitingOnCaller ? "agent_awaiting_input" : "agent_timeout", `Agent ${this.id} was still '${this.status}' after ` +
|
|
123
|
+
`${this.timeoutSeconds}s. It is still running — answer ` +
|
|
124
|
+
"it, or attach again with the same id.");
|
|
125
|
+
}
|
|
126
|
+
if (interval > 0)
|
|
127
|
+
await sleep(Math.min(interval, remaining));
|
|
128
|
+
interval = Math.min(interval * client_ts_1.POLL_BACKOFF_FACTOR, this.maxPollIntervalSeconds);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
async #fetch() {
|
|
132
|
+
const query = new URLSearchParams({
|
|
133
|
+
limit: String(this.eventLimit),
|
|
134
|
+
});
|
|
135
|
+
if (this.#cursor)
|
|
136
|
+
query.set("cursor", this.#cursor);
|
|
137
|
+
return this.#transport.request("GET", `agents/${encodeURIComponent(this.id)}/events?${query.toString()}`);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Fold a page into run state, dropping anything already delivered.
|
|
141
|
+
*
|
|
142
|
+
* The server re-sends rather than risk skipping, so the same id can arrive
|
|
143
|
+
* twice. Deduping here is what turns that guarantee into an exactly-once
|
|
144
|
+
* stream for the caller.
|
|
145
|
+
*/
|
|
146
|
+
#absorb(page) {
|
|
147
|
+
if (typeof page.status === "string")
|
|
148
|
+
this.status = page.status;
|
|
149
|
+
this.terminal = Boolean(page.terminal);
|
|
150
|
+
if (typeof page.nextCursor === "string" && page.nextCursor) {
|
|
151
|
+
this.#cursor = page.nextCursor;
|
|
152
|
+
}
|
|
153
|
+
const approval = page.pendingApproval;
|
|
154
|
+
const approvalKind = approval && typeof approval === "object" && !Array.isArray(approval)
|
|
155
|
+
? String(approval.kind ?? "")
|
|
156
|
+
: null;
|
|
157
|
+
const needsInput = Boolean(page.needsInput);
|
|
158
|
+
const raw = page.events;
|
|
159
|
+
if (!Array.isArray(raw))
|
|
160
|
+
return [];
|
|
161
|
+
const fresh = [];
|
|
162
|
+
raw.forEach((item, index) => {
|
|
163
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
164
|
+
return;
|
|
165
|
+
const record = item;
|
|
166
|
+
const id = String(record.id ?? "");
|
|
167
|
+
const digest = String(record.digest ?? "");
|
|
168
|
+
if (!id)
|
|
169
|
+
return;
|
|
170
|
+
const previous = this.#seen.get(id);
|
|
171
|
+
if (previous === digest)
|
|
172
|
+
return; // already delivered, unchanged
|
|
173
|
+
this.#seen.set(id, digest);
|
|
174
|
+
const isLast = index === raw.length - 1;
|
|
175
|
+
const event = {
|
|
176
|
+
id,
|
|
177
|
+
digest,
|
|
178
|
+
role: String(record.role ?? "Assistant"),
|
|
179
|
+
text: String(record.text ?? ""),
|
|
180
|
+
data: record.data,
|
|
181
|
+
// Only the final event of a page can be the one the run is blocked on —
|
|
182
|
+
// the state applies to the tail, not the history.
|
|
183
|
+
needsApproval: Boolean(approvalKind) && isLast,
|
|
184
|
+
approvalKind: isLast && approvalKind ? approvalKind : null,
|
|
185
|
+
needsInput: needsInput && isLast,
|
|
186
|
+
supersedes: previous !== undefined,
|
|
187
|
+
};
|
|
188
|
+
fresh.push(event);
|
|
189
|
+
this.events.push(event);
|
|
190
|
+
});
|
|
191
|
+
return fresh;
|
|
192
|
+
}
|
|
193
|
+
/** Approve a pending plan or action. Needs the `trade` scope. */
|
|
194
|
+
approve() {
|
|
195
|
+
return this.#post("approve");
|
|
196
|
+
}
|
|
197
|
+
/** Reject a pending plan or action. */
|
|
198
|
+
reject() {
|
|
199
|
+
return this.#post("reject");
|
|
200
|
+
}
|
|
201
|
+
/** Stop the run. */
|
|
202
|
+
stop() {
|
|
203
|
+
return this.#post("stop");
|
|
204
|
+
}
|
|
205
|
+
/** Append a user message — a follow-up or a course correction. */
|
|
206
|
+
say(content) {
|
|
207
|
+
return this.#post("messages", { content });
|
|
208
|
+
}
|
|
209
|
+
async #post(action, body = {}) {
|
|
210
|
+
const response = await this.#transport.request("POST", `agents/${encodeURIComponent(this.id)}/${action}`, {
|
|
211
|
+
body,
|
|
212
|
+
idempotencyKey: `${this.id}:${action}:${this.events.length}`,
|
|
213
|
+
});
|
|
214
|
+
const agent = response.agent;
|
|
215
|
+
if (agent && typeof agent === "object" && !Array.isArray(agent)) {
|
|
216
|
+
const status = agent.status;
|
|
217
|
+
if (typeof status === "string")
|
|
218
|
+
this.status = status;
|
|
219
|
+
}
|
|
220
|
+
return this.status;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
exports.AgentRun = AgentRun;
|
package/dist/cjs/client.js
CHANGED
|
@@ -7,14 +7,33 @@
|
|
|
7
7
|
* or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
8
8
|
*/
|
|
9
9
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
-
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = void 0;
|
|
10
|
+
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
|
|
11
11
|
exports.waitForOperation = waitForOperation;
|
|
12
|
+
exports.clientTransport = clientTransport;
|
|
12
13
|
exports.createPortfolio = createPortfolio;
|
|
14
|
+
const agent_ts_1 = require("./agent.js");
|
|
13
15
|
const env_ts_1 = require("./env.js");
|
|
16
|
+
const portfolio_ts_1 = require("./portfolio.js");
|
|
14
17
|
/** Boundary adapter: builder output is JSON by construction. */
|
|
15
18
|
function asJsonObject(value) {
|
|
19
|
+
// PortfolioHandle.toJSON() omits `id`; a bare cast would leak it.
|
|
20
|
+
if (value && typeof value === "object" && "toJSON" in value) {
|
|
21
|
+
const candidate = value;
|
|
22
|
+
if (typeof candidate.toJSON === "function") {
|
|
23
|
+
return candidate.toJSON();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
16
26
|
return value;
|
|
17
27
|
}
|
|
28
|
+
function encodeQuery(params) {
|
|
29
|
+
const search = new URLSearchParams();
|
|
30
|
+
for (const [key, value] of Object.entries(params)) {
|
|
31
|
+
if (value !== undefined && value !== "")
|
|
32
|
+
search.set(key, value);
|
|
33
|
+
}
|
|
34
|
+
const encoded = search.toString();
|
|
35
|
+
return encoded ? `?${encoded}` : "";
|
|
36
|
+
}
|
|
18
37
|
const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
|
|
19
38
|
const MAX_ERROR_BYTES = 64 * 1024;
|
|
20
39
|
// Keep in lockstep with _MAX_REDIRECTS in sdk/python/nexustrade/client.py —
|
|
@@ -23,16 +42,16 @@ const MAX_REDIRECTS = 5;
|
|
|
23
42
|
// `status` for errors no HTTP status describes: the request never reached the
|
|
24
43
|
// API, or it returned 2xx with an envelope the client could not use. Reporting
|
|
25
44
|
// a literal 200 there would misattribute a 201 response.
|
|
26
|
-
|
|
45
|
+
exports.NO_HTTP_STATUS = 0;
|
|
27
46
|
// Polling defaults. Every NexusTrade job — backtest, optimization,
|
|
28
47
|
// walk-forward, and any future operation kind — reports through the same
|
|
29
48
|
// envelope, so one poller serves all of them. Kept in lockstep with the Python
|
|
30
49
|
// SDK by checkSdkClientParity.ts; the backoff is deterministic (no jitter) so
|
|
31
50
|
// both languages issue the identical request sequence.
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
51
|
+
exports.DEFAULT_POLL_TIMEOUT_SECONDS = 900;
|
|
52
|
+
exports.DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
53
|
+
exports.MAX_POLL_INTERVAL_SECONDS = 15;
|
|
54
|
+
exports.POLL_BACKOFF_FACTOR = 1.5;
|
|
36
55
|
const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
|
|
37
56
|
class NexusTradeApiError extends Error {
|
|
38
57
|
status;
|
|
@@ -197,7 +216,7 @@ class HttpTransport {
|
|
|
197
216
|
}
|
|
198
217
|
catch (error) {
|
|
199
218
|
const reason = error instanceof Error ? error.message : String(error);
|
|
200
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
|
|
219
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "transport_error", reason);
|
|
201
220
|
}
|
|
202
221
|
if (response.status >= 300 && response.status < 400) {
|
|
203
222
|
const location = response.headers.get("location");
|
|
@@ -286,7 +305,7 @@ function operationFailure(operation, operationId, status) {
|
|
|
286
305
|
if (error.message)
|
|
287
306
|
message = String(error.message);
|
|
288
307
|
}
|
|
289
|
-
return new NexusTradeApiError(NO_HTTP_STATUS, code, message);
|
|
308
|
+
return new NexusTradeApiError(exports.NO_HTTP_STATUS, code, message);
|
|
290
309
|
}
|
|
291
310
|
/**
|
|
292
311
|
* Poll `fetch(operationId)` until the operation reaches a terminal state.
|
|
@@ -301,9 +320,9 @@ function operationFailure(operation, operationId, status) {
|
|
|
301
320
|
* them would report an infrastructure outage as a still-running job.
|
|
302
321
|
*/
|
|
303
322
|
async function waitForOperation(fetch, operationId, options = {}) {
|
|
304
|
-
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
305
|
-
const pollIntervalSeconds = options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
|
|
306
|
-
const maxPollIntervalSeconds = options.maxPollIntervalSeconds ?? MAX_POLL_INTERVAL_SECONDS;
|
|
323
|
+
const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
324
|
+
const pollIntervalSeconds = options.pollIntervalSeconds ?? exports.DEFAULT_POLL_INTERVAL_SECONDS;
|
|
325
|
+
const maxPollIntervalSeconds = options.maxPollIntervalSeconds ?? exports.MAX_POLL_INTERVAL_SECONDS;
|
|
307
326
|
const raiseOnFailure = options.raiseOnFailure ?? true;
|
|
308
327
|
if (!(timeoutSeconds > 0)) {
|
|
309
328
|
throw new Error("timeoutSeconds must be positive.");
|
|
@@ -324,7 +343,7 @@ async function waitForOperation(fetch, operationId, options = {}) {
|
|
|
324
343
|
}
|
|
325
344
|
const remainingMs = deadline - Date.now();
|
|
326
345
|
if (remainingMs <= 0) {
|
|
327
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
|
|
346
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
|
|
328
347
|
`${timeoutSeconds}s. It is still running — poll again with the ` +
|
|
329
348
|
"same id rather than resubmitting.");
|
|
330
349
|
}
|
|
@@ -332,7 +351,7 @@ async function waitForOperation(fetch, operationId, options = {}) {
|
|
|
332
351
|
const delayMs = Math.min(interval * 1000, remainingMs);
|
|
333
352
|
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
334
353
|
}
|
|
335
|
-
interval = Math.min(interval * POLL_BACKOFF_FACTOR, maxPollIntervalSeconds);
|
|
354
|
+
interval = Math.min(interval * exports.POLL_BACKOFF_FACTOR, maxPollIntervalSeconds);
|
|
336
355
|
}
|
|
337
356
|
}
|
|
338
357
|
class NexusTradeClient {
|
|
@@ -342,9 +361,10 @@ class NexusTradeClient {
|
|
|
342
361
|
this.transport = options.transport;
|
|
343
362
|
return;
|
|
344
363
|
}
|
|
345
|
-
//
|
|
346
|
-
//
|
|
347
|
-
|
|
364
|
+
// Lazy and memoized: the tree is walked at most once, and not at all when
|
|
365
|
+
// the environment already answers — which is always true inside
|
|
366
|
+
// run_compute, where the platform injects both variables.
|
|
367
|
+
const dotenv = new env_ts_1.LazyDotenv();
|
|
348
368
|
const apiKey = options.apiKey ?? (0, env_ts_1.environmentValue)("NEXUSTRADE_API_KEY", dotenv);
|
|
349
369
|
const baseUrl = options.baseUrl ?? (0, env_ts_1.environmentValue)("NEXUSTRADE_API_BASE_URL", dotenv);
|
|
350
370
|
if (!apiKey || !baseUrl) {
|
|
@@ -368,7 +388,87 @@ class NexusTradeClient {
|
|
|
368
388
|
});
|
|
369
389
|
const result = response.portfolio;
|
|
370
390
|
if (!isJsonObject(result)) {
|
|
371
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
|
|
391
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
|
|
392
|
+
}
|
|
393
|
+
return result;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* List portfolios. Mirrors MCP `fetch_portfolios` (boolean includes, page/limit).
|
|
397
|
+
* `includePositions` defaults off when `search` is set.
|
|
398
|
+
*/
|
|
399
|
+
async listPortfolios(options = {}) {
|
|
400
|
+
const query = encodeQuery({
|
|
401
|
+
portfolioIds: options.portfolioIds?.join(","),
|
|
402
|
+
includeInactive: options.includeInactive === undefined
|
|
403
|
+
? undefined
|
|
404
|
+
: String(options.includeInactive),
|
|
405
|
+
includePaper: options.includePaper === undefined
|
|
406
|
+
? undefined
|
|
407
|
+
: String(options.includePaper),
|
|
408
|
+
includeLive: options.includeLive === undefined
|
|
409
|
+
? undefined
|
|
410
|
+
: String(options.includeLive),
|
|
411
|
+
includeChatPortfolios: options.includeChatPortfolios === undefined
|
|
412
|
+
? undefined
|
|
413
|
+
: String(options.includeChatPortfolios),
|
|
414
|
+
includePositions: options.includePositions === undefined
|
|
415
|
+
? undefined
|
|
416
|
+
: String(options.includePositions),
|
|
417
|
+
search: options.search,
|
|
418
|
+
limit: options.limit === undefined ? undefined : String(options.limit),
|
|
419
|
+
page: options.page === undefined ? undefined : String(options.page),
|
|
420
|
+
});
|
|
421
|
+
const response = await this.transport.request("GET", `portfolios${query}`);
|
|
422
|
+
const rows = response.portfolios;
|
|
423
|
+
if (!Array.isArray(rows)) {
|
|
424
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio list response is missing portfolios.");
|
|
425
|
+
}
|
|
426
|
+
return {
|
|
427
|
+
portfolios: rows.map((row) => (0, portfolio_ts_1.portfolioHandleFromWire)(row, { transport: this.transport })),
|
|
428
|
+
page: typeof response.page === "number" ? response.page : 1,
|
|
429
|
+
limit: typeof response.limit === "number" ? response.limit : 20,
|
|
430
|
+
total: typeof response.total === "number" ? response.total : rows.length,
|
|
431
|
+
totalPages: typeof response.totalPages === "number" ? response.totalPages : 1,
|
|
432
|
+
scopes: isJsonObject(response.scopes) ? response.scopes : undefined,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
async getPortfolio(portfolioId) {
|
|
436
|
+
const response = await this.transport.request("GET", `portfolios/${encodePathSegment(portfolioId)}`);
|
|
437
|
+
const portfolio = response.portfolio;
|
|
438
|
+
if (!isJsonObject(portfolio)) {
|
|
439
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
|
|
440
|
+
}
|
|
441
|
+
return (0, portfolio_ts_1.portfolioHandleFromWire)(portfolio, {
|
|
442
|
+
transport: this.transport,
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
/** Mint/activate a paper portfolio from a chat draft (or re-activate). */
|
|
446
|
+
async deploy(portfolioId, options = {}) {
|
|
447
|
+
const body = {};
|
|
448
|
+
if (options.frequency !== undefined)
|
|
449
|
+
body.frequency = options.frequency;
|
|
450
|
+
const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/deploy`, { body });
|
|
451
|
+
const result = response.deployment ?? response;
|
|
452
|
+
if (!isJsonObject(result) || typeof result.portfolioId !== "string") {
|
|
453
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Deploy response is missing portfolioId.");
|
|
454
|
+
}
|
|
455
|
+
return {
|
|
456
|
+
portfolioId: String(result.portfolioId),
|
|
457
|
+
chatPortfolioId: typeof result.chatPortfolioId === "string"
|
|
458
|
+
? result.chatPortfolioId
|
|
459
|
+
: undefined,
|
|
460
|
+
name: typeof result.name === "string" ? result.name : "",
|
|
461
|
+
outcome: typeof result.outcome === "string" ? result.outcome : "",
|
|
462
|
+
deploymentType: typeof result.deploymentType === "string"
|
|
463
|
+
? result.deploymentType
|
|
464
|
+
: undefined,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
async undeploy(portfolioId) {
|
|
468
|
+
const response = await this.transport.request("POST", `portfolios/${encodePathSegment(portfolioId)}/undeploy`, { body: {} });
|
|
469
|
+
const result = response.undeployment ?? response;
|
|
470
|
+
if (!isJsonObject(result)) {
|
|
471
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Undeploy response is missing body.");
|
|
372
472
|
}
|
|
373
473
|
return result;
|
|
374
474
|
}
|
|
@@ -381,7 +481,7 @@ class NexusTradeClient {
|
|
|
381
481
|
const operations = response.operations;
|
|
382
482
|
if (!Array.isArray(operations) ||
|
|
383
483
|
!operations.every((operation) => isJsonObject(operation))) {
|
|
384
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
|
|
484
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
|
|
385
485
|
}
|
|
386
486
|
return operations;
|
|
387
487
|
}
|
|
@@ -389,10 +489,53 @@ class NexusTradeClient {
|
|
|
389
489
|
async createBacktest(backtest, options) {
|
|
390
490
|
const operations = await this.createBacktests([backtest], options);
|
|
391
491
|
if (operations.length !== 1) {
|
|
392
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Single backtest response returned the wrong operation count.");
|
|
492
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Single backtest response returned the wrong operation count.");
|
|
393
493
|
}
|
|
394
494
|
return operations[0];
|
|
395
495
|
}
|
|
496
|
+
/**
|
|
497
|
+
* Start an agent run and return an iterable handle.
|
|
498
|
+
*
|
|
499
|
+
* Unlike the other job kinds this is not fire-and-poll: iterate the run to
|
|
500
|
+
* receive its events, and answer it when it asks. See `AgentRun`.
|
|
501
|
+
*/
|
|
502
|
+
async createAgent(prompt, options) {
|
|
503
|
+
const body = { prompt };
|
|
504
|
+
if (options.maxIterations !== undefined) {
|
|
505
|
+
body.maxIterations = options.maxIterations;
|
|
506
|
+
}
|
|
507
|
+
const response = await this.transport.request("POST", "agents", {
|
|
508
|
+
body,
|
|
509
|
+
idempotencyKey: options.idempotencyKey,
|
|
510
|
+
});
|
|
511
|
+
const agent = response.agent;
|
|
512
|
+
if (!isJsonObject(agent) || !agent.id) {
|
|
513
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Agent response is missing agent.");
|
|
514
|
+
}
|
|
515
|
+
return new agent_ts_1.AgentRun(String(agent.id), this.transport, typeof agent.status === "string" ? agent.status : "initializing");
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Reattach to a run already in flight.
|
|
519
|
+
*
|
|
520
|
+
* The run lives server-side and bills whether or not anyone is listening, so
|
|
521
|
+
* a dropped connection must not orphan it. Omit `cursor` to replay from the
|
|
522
|
+
* beginning; events are durable, so replay is exact.
|
|
523
|
+
*/
|
|
524
|
+
async attachAgent(agentId, options = {}) {
|
|
525
|
+
const agent = await this.getAgent(agentId);
|
|
526
|
+
const run = new agent_ts_1.AgentRun(typeof agent.id === "string" ? agent.id : agentId, this.transport, typeof agent.status === "string" ? agent.status : "initializing");
|
|
527
|
+
run.terminal = Boolean(agent.terminal);
|
|
528
|
+
run.setCursor(options.cursor ?? null);
|
|
529
|
+
return run;
|
|
530
|
+
}
|
|
531
|
+
async getAgent(agentId) {
|
|
532
|
+
const response = await this.transport.request("GET", `agents/${encodeURIComponent(agentId)}`);
|
|
533
|
+
const agent = response.agent;
|
|
534
|
+
if (!isJsonObject(agent)) {
|
|
535
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Agent response is missing agent.");
|
|
536
|
+
}
|
|
537
|
+
return agent;
|
|
538
|
+
}
|
|
396
539
|
async getBacktest(backtestId) {
|
|
397
540
|
const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
|
|
398
541
|
return operationOf(response);
|
|
@@ -431,7 +574,7 @@ class NexusTradeClient {
|
|
|
431
574
|
const response = await this.transport.request("GET", "lake/catalog");
|
|
432
575
|
const tables = response.tables;
|
|
433
576
|
if (!Array.isArray(tables) || !tables.every((t) => isJsonObject(t))) {
|
|
434
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Lake catalog response is missing tables.");
|
|
577
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Lake catalog response is missing tables.");
|
|
435
578
|
}
|
|
436
579
|
return tables;
|
|
437
580
|
}
|
|
@@ -440,14 +583,14 @@ class NexusTradeClient {
|
|
|
440
583
|
const response = await this.transport.request("GET", `lake/catalog/lake/${encodePathSegment(name)}`);
|
|
441
584
|
const described = response.table;
|
|
442
585
|
if (!isJsonObject(described)) {
|
|
443
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Lake describe response is missing table.");
|
|
586
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Lake describe response is missing table.");
|
|
444
587
|
}
|
|
445
588
|
return described;
|
|
446
589
|
}
|
|
447
590
|
/** Download one Parquet part, optionally a byte range of it. */
|
|
448
591
|
async downloadLakeQueryPart(queryId, part, options = {}) {
|
|
449
592
|
if (!supportsBinary(this.transport)) {
|
|
450
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Lake part download requires a transport implementing requestBytes.");
|
|
593
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "unsupported_transport", "Lake part download requires a transport implementing requestBytes.");
|
|
451
594
|
}
|
|
452
595
|
return this.transport.requestBytes("GET", `lake/queries/${encodePathSegment(queryId)}/parts/${Math.trunc(part)}`, options);
|
|
453
596
|
}
|
|
@@ -492,6 +635,11 @@ exports.NexusTradeClient = NexusTradeClient;
|
|
|
492
635
|
function backtestInput(item) {
|
|
493
636
|
const tool = item.tool;
|
|
494
637
|
if (tool === undefined || tool === null) {
|
|
638
|
+
// Prefer portfolioId over an inline body when both are present.
|
|
639
|
+
if (typeof item.portfolioId === "string" && item.portfolioId) {
|
|
640
|
+
const { portfolio: _ignored, ...rest } = item;
|
|
641
|
+
return { ...rest, portfolioId: item.portfolioId };
|
|
642
|
+
}
|
|
495
643
|
return { ...item };
|
|
496
644
|
}
|
|
497
645
|
if (tool !== "backtest_portfolio") {
|
|
@@ -514,10 +662,14 @@ function backtestInput(item) {
|
|
|
514
662
|
function operationOf(response) {
|
|
515
663
|
const operation = response.operation;
|
|
516
664
|
if (!isJsonObject(operation)) {
|
|
517
|
-
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Response is missing operation.");
|
|
665
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Response is missing operation.");
|
|
518
666
|
}
|
|
519
667
|
return operation;
|
|
520
668
|
}
|
|
669
|
+
/** @internal PortfolioHandle lazy-client attachment. */
|
|
670
|
+
function clientTransport(client) {
|
|
671
|
+
return client.transport;
|
|
672
|
+
}
|
|
521
673
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
522
674
|
async function createPortfolio(portfolio, options) {
|
|
523
675
|
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
package/dist/cjs/env.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* this package supports Node 18 — so the walk and parse live here.
|
|
25
25
|
*/
|
|
26
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
|
+
exports.LazyDotenv = void 0;
|
|
27
28
|
exports.dotenvDisabled = dotenvDisabled;
|
|
28
29
|
exports.parseDotenv = parseDotenv;
|
|
29
30
|
exports.findDotenv = findDotenv;
|
|
@@ -147,12 +148,37 @@ function loadDotenvValues(start) {
|
|
|
147
148
|
return {};
|
|
148
149
|
}
|
|
149
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Reads the `.env` at most once, and only if something actually needs it.
|
|
153
|
+
*
|
|
154
|
+
* The file walk is skipped entirely when the environment already answers —
|
|
155
|
+
* which is always the case inside `run_compute`, where the platform injects the
|
|
156
|
+
* variables. Constructing a client should not stat up to 32 directories to
|
|
157
|
+
* discover a file it was never going to consult.
|
|
158
|
+
*/
|
|
159
|
+
class LazyDotenv {
|
|
160
|
+
#values = null;
|
|
161
|
+
#start;
|
|
162
|
+
constructor(start) {
|
|
163
|
+
this.#start = start;
|
|
164
|
+
}
|
|
165
|
+
get(name) {
|
|
166
|
+
if (this.#values === null)
|
|
167
|
+
this.#values = loadDotenvValues(this.#start);
|
|
168
|
+
return this.#values[name];
|
|
169
|
+
}
|
|
170
|
+
/** True once the file has actually been read. Used by tests. */
|
|
171
|
+
get loaded() {
|
|
172
|
+
return this.#values !== null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
exports.LazyDotenv = LazyDotenv;
|
|
150
176
|
/** `process.env` first, then `.env`. Blank is treated as absent. */
|
|
151
177
|
function environmentValue(name, dotenv) {
|
|
152
178
|
const live = process.env[name];
|
|
153
179
|
if (live && live.trim())
|
|
154
180
|
return live;
|
|
155
|
-
const
|
|
156
|
-
const fallback =
|
|
181
|
+
const source = dotenv ?? new LazyDotenv();
|
|
182
|
+
const fallback = source instanceof LazyDotenv ? source.get(name) : source[name];
|
|
157
183
|
return fallback && fallback.trim() ? fallback : undefined;
|
|
158
184
|
}
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
/* eslint-disable */
|
|
3
|
-
// GENERATED by src/scripts/codegen/generateNtSdk.ts — do not edit by hand.
|
|
4
|
-
// Regenerate: cd server && npx ts-node src/scripts/codegen/generateNtSdk.ts
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
3
|
exports.walkForward = exports.backtest = exports.SMA = exports.RSI = exports.PriceStdDev = exports.EMA = exports.BBand = exports.portfolio = exports.sessionFlatten = exports.strategy = exports.closeOption = exports.greeksTrigger = exports.daysHeldTrigger = exports.dteTrigger = exports.pnlTrigger = exports.rebalanceOption = exports.sleeve = exports.structureTemplate = exports.openOption = exports.againstParent = exports.optionsBuilder = exports.leg = exports.dynamicRebalance = exports.launchAgent = exports.alert = exports.withdraw = exports.deposit = exports.sell = exports.buy = exports.selectPercentile = exports.selectTop = exports.filter = exports.always = exports.multi = exports.exactly = exports.fewerThan = exports.atMost = exports.atLeast = exports.or = exports.and = exports.neq = exports.eq = exports.lte = exports.gte = exports.lt = exports.gt = exports.cryptoAsset = exports.stockAsset = exports.PORTFOLIO_WIDE = exports.CANDIDATE = void 0;
|
|
7
4
|
exports.geneUniversePipelineFilter = exports.geneSelectTopLimit = exports.geneDteBracket = exports.geneStrikeDistance = exports.geneOptionDelta = exports.geneStructureKind = exports.geneTakeProfitPct = exports.geneRollTriggerDte = exports.geneDeploymentPct = exports.geneTotalBudgetPct = exports.geneAllocationPct = exports.geneBuyingPowerPct = exports.geneRankSignal = exports.geneEntryCooldownDays = exports.geneExitCondition = exports.geneEntryCondition = exports.geneSubject = exports.optimization = void 0;
|
|
@@ -109,6 +106,7 @@ exports.Value = Value;
|
|
|
109
106
|
exports.Volume = Volume;
|
|
110
107
|
exports.VWAP = VWAP;
|
|
111
108
|
exports.Year = Year;
|
|
109
|
+
const portfolio_ts_1 = require("../portfolio.js");
|
|
112
110
|
exports.CANDIDATE = { __candidate: true };
|
|
113
111
|
/** Portfolio-wide targetAssets: [] — rebalance cadence, not per-ticker DCA. */
|
|
114
112
|
exports.PORTFOLIO_WIDE = { __portfolioWide: true };
|
|
@@ -361,7 +359,7 @@ exports.strategy = strategy;
|
|
|
361
359
|
*/
|
|
362
360
|
const sessionFlatten = (condition, config = {}, name = "Session flatten") => (0, exports.strategy)(name, condition, (0, exports.closeOption)({ ...config }));
|
|
363
361
|
exports.sessionFlatten = sessionFlatten;
|
|
364
|
-
const portfolio = (name, strategies, options = {}) => compact({ name, initialValue: 10000, ...options, strategies });
|
|
362
|
+
const portfolio = (name, strategies, options = {}) => new portfolio_ts_1.PortfolioHandle(compact({ name, initialValue: 10000, ...options, strategies }));
|
|
365
363
|
exports.portfolio = portfolio;
|
|
366
364
|
// ---- generated indicator builders ----
|
|
367
365
|
/**
|