nexustrade 0.1.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.
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.waitForOperation = exports.createPortfolio = exports.NexusTradeClient = exports.NexusTradeApiError = exports.HttpTransport = void 0;
18
+ var client_js_1 = require("./client.js");
19
+ Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return client_js_1.HttpTransport; } });
20
+ Object.defineProperty(exports, "NexusTradeApiError", { enumerable: true, get: function () { return client_js_1.NexusTradeApiError; } });
21
+ Object.defineProperty(exports, "NexusTradeClient", { enumerable: true, get: function () { return client_js_1.NexusTradeClient; } });
22
+ Object.defineProperty(exports, "createPortfolio", { enumerable: true, get: function () { return client_js_1.createPortfolio; } });
23
+ Object.defineProperty(exports, "waitForOperation", { enumerable: true, get: function () { return client_js_1.waitForOperation; } });
24
+ __exportStar(require("./generated/ntSdk.generated.js"), exports);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Typed NexusTrade JSON API client.
3
+ *
4
+ * Mirrors the Python client method-for-method; `verifyNtSdk.ts` asserts the two
5
+ * surfaces stay identical. Transport-generic: callers pass an API key/base URL,
6
+ * or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
7
+ */
8
+ import type { JobRequest, Portfolio } from "./generated/ntSdk.generated.js";
9
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
10
+ [key: string]: JsonValue;
11
+ };
12
+ export type JsonObject = {
13
+ [key: string]: JsonValue;
14
+ };
15
+ /**
16
+ * What a request body may be: the output of a generated builder, or a
17
+ * hand-written JSON literal.
18
+ *
19
+ * The builder types are `interface`s, and TypeScript does not give an interface
20
+ * the implicit index signature `JsonObject` requires — so a parameter typed
21
+ * `JsonObject` rejects `portfolio(...)` and `backtest(...)`, which is every
22
+ * documented entry point into this SDK. Naming both sides here keeps the
23
+ * signature self-describing instead of widening to bare `object`.
24
+ */
25
+ export type PortfolioInput = Portfolio | JsonObject;
26
+ export type JobInput = JobRequest | JsonObject;
27
+ export declare class NexusTradeApiError extends Error {
28
+ readonly status: number;
29
+ readonly code: string;
30
+ constructor(status: number, code: string, message: string);
31
+ }
32
+ export interface RequestOptions {
33
+ body?: JsonObject;
34
+ idempotencyKey?: string;
35
+ }
36
+ export interface Transport {
37
+ request(method: string, path: string, options?: RequestOptions): Promise<JsonObject>;
38
+ }
39
+ /**
40
+ * Transports that can also return raw bytes.
41
+ *
42
+ * Lake result parts are Parquet, so they do not fit `Transport`, which is a
43
+ * JSON contract. Declaring the capability keeps custom and test transports able
44
+ * to implement downloads through a typed interface instead of a duck-typed
45
+ * check.
46
+ */
47
+ export interface BinaryTransport extends Transport {
48
+ requestBytes(method: string, path: string, options?: {
49
+ byteRange?: [number, number];
50
+ maxBytes?: number;
51
+ }): Promise<Uint8Array>;
52
+ }
53
+ export interface HttpTransportOptions {
54
+ apiKey: string;
55
+ baseUrl: string;
56
+ timeoutSeconds?: number;
57
+ }
58
+ export declare class HttpTransport implements Transport {
59
+ #private;
60
+ constructor(options: HttpTransportOptions);
61
+ get baseUrl(): string;
62
+ request(method: string, path: string, options?: RequestOptions): Promise<JsonObject>;
63
+ }
64
+ export interface NexusTradeClientOptions {
65
+ apiKey?: string;
66
+ baseUrl?: string;
67
+ transport?: Transport;
68
+ }
69
+ export interface WaitOptions {
70
+ timeoutSeconds?: number;
71
+ pollIntervalSeconds?: number;
72
+ maxPollIntervalSeconds?: number;
73
+ raiseOnFailure?: boolean;
74
+ }
75
+ /**
76
+ * Poll `fetch(operationId)` until the operation reaches a terminal state.
77
+ *
78
+ * Works for any operation kind because every NexusTrade job reports the same
79
+ * `{id, kind, status, result?, error?}` envelope. Pass any getter with that
80
+ * shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
81
+ *
82
+ * Resolves with the terminal operation. Rejects with `NexusTradeApiError` on
83
+ * timeout, and on a failed/cancelled operation unless `raiseOnFailure` is
84
+ * false. Transport errors from `fetch` propagate — a poller that swallowed
85
+ * them would report an infrastructure outage as a still-running job.
86
+ */
87
+ export declare function waitForOperation(fetch: (operationId: string) => Promise<JsonObject>, operationId: string, options?: WaitOptions): Promise<JsonObject>;
88
+ export declare class NexusTradeClient {
89
+ private readonly transport;
90
+ constructor(options?: NexusTradeClientOptions);
91
+ static fromEnvironment(): NexusTradeClient;
92
+ createPortfolio(portfolio: PortfolioInput, options: {
93
+ idempotencyKey: string;
94
+ }): Promise<JsonObject>;
95
+ createBacktests(backtests: ReadonlyArray<JobInput>, options: {
96
+ idempotencyKey: string;
97
+ }): Promise<JsonObject[]>;
98
+ /** Submit one generated `backtest(...)` handle or raw API input. */
99
+ createBacktest(backtest: JobInput, options: {
100
+ idempotencyKey: string;
101
+ }): Promise<JsonObject>;
102
+ getBacktest(backtestId: string): Promise<JsonObject>;
103
+ createOptimization(handle: JobInput, options: {
104
+ idempotencyKey: string;
105
+ }): Promise<JsonObject>;
106
+ getOptimization(optimizationId: string): Promise<JsonObject>;
107
+ createWalkForward(handle: JobInput, options: {
108
+ idempotencyKey: string;
109
+ }): Promise<JsonObject>;
110
+ getWalkForward(studyId: string): Promise<JsonObject>;
111
+ createLakeQuery(request: JsonObject, options: {
112
+ idempotencyKey: string;
113
+ }): Promise<JsonObject>;
114
+ getLakeQuery(queryId: string): Promise<JsonObject>;
115
+ cancelLakeQuery(queryId: string): Promise<JsonObject>;
116
+ getLakeQueryManifest(queryId: string): Promise<JsonObject>;
117
+ getLakeCatalog(): Promise<JsonObject[]>;
118
+ describeLakeTable(table: string): Promise<JsonObject>;
119
+ /** Download one Parquet part, optionally a byte range of it. */
120
+ downloadLakeQueryPart(queryId: string, part: number, options?: {
121
+ byteRange?: [number, number];
122
+ maxBytes?: number;
123
+ }): Promise<Uint8Array>;
124
+ /** Resolve once a lake query is terminal. See `waitForOperation`. */
125
+ waitForLakeQuery(queryId: string, options?: WaitOptions): Promise<JsonObject>;
126
+ /** Resolve once a backtest is terminal. See `waitForOperation`. */
127
+ waitForBacktest(backtestId: string, options?: WaitOptions): Promise<JsonObject>;
128
+ /** Resolve once an optimization is terminal. See `waitForOperation`. */
129
+ waitForOptimization(optimizationId: string, options?: WaitOptions): Promise<JsonObject>;
130
+ /** Resolve once a walk-forward study is terminal. See `waitForOperation`. */
131
+ waitForWalkForward(studyId: string, options?: WaitOptions): Promise<JsonObject>;
132
+ /** Wait on a whole `createBacktests` batch, in submission order. */
133
+ waitForBacktests(operations: ReadonlyArray<JsonObject>, options?: WaitOptions): Promise<JsonObject[]>;
134
+ private createPortfolioJob;
135
+ }
136
+ /** Convenience wrapper for scripts that do not need a persistent client. */
137
+ export declare function createPortfolio(portfolio: JsonObject, options: {
138
+ idempotencyKey: string;
139
+ client?: NexusTradeClient;
140
+ }): Promise<JsonObject>;
@@ -0,0 +1,519 @@
1
+ /**
2
+ * Typed NexusTrade JSON API client.
3
+ *
4
+ * Mirrors the Python client method-for-method; `verifyNtSdk.ts` asserts the two
5
+ * surfaces stay identical. Transport-generic: callers pass an API key/base URL,
6
+ * or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
7
+ */
8
+ import { environmentValue, loadDotenvValues } from "./env.js";
9
+ /** Boundary adapter: builder output is JSON by construction. */
10
+ function asJsonObject(value) {
11
+ return value;
12
+ }
13
+ const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
14
+ const MAX_ERROR_BYTES = 64 * 1024;
15
+ // Keep in lockstep with _MAX_REDIRECTS in sdk/python/nexustrade/client.py —
16
+ // checkSdkClientParity.ts asserts the two numbers match.
17
+ const MAX_REDIRECTS = 5;
18
+ // `status` for errors no HTTP status describes: the request never reached the
19
+ // API, or it returned 2xx with an envelope the client could not use. Reporting
20
+ // a literal 200 there would misattribute a 201 response.
21
+ const NO_HTTP_STATUS = 0;
22
+ // Polling defaults. Every NexusTrade job — backtest, optimization,
23
+ // walk-forward, and any future operation kind — reports through the same
24
+ // envelope, so one poller serves all of them. Kept in lockstep with the Python
25
+ // SDK by checkSdkClientParity.ts; the backoff is deterministic (no jitter) so
26
+ // both languages issue the identical request sequence.
27
+ const DEFAULT_POLL_TIMEOUT_SECONDS = 900;
28
+ const DEFAULT_POLL_INTERVAL_SECONDS = 2;
29
+ const MAX_POLL_INTERVAL_SECONDS = 15;
30
+ const POLL_BACKOFF_FACTOR = 1.5;
31
+ const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
32
+ export class NexusTradeApiError extends Error {
33
+ status;
34
+ code;
35
+ constructor(status, code, message) {
36
+ super(`${code}: ${message}`);
37
+ this.name = "NexusTradeApiError";
38
+ this.status = status;
39
+ this.code = code;
40
+ }
41
+ }
42
+ function origin(url) {
43
+ const parsed = new URL(url);
44
+ const scheme = parsed.protocol.replace(":", "").toLowerCase();
45
+ return {
46
+ scheme,
47
+ host: parsed.hostname.toLowerCase(),
48
+ port: parsed.port || (scheme === "https" ? "443" : "80"),
49
+ };
50
+ }
51
+ function sameOrigin(left, right) {
52
+ const a = origin(left);
53
+ const b = origin(right);
54
+ return a.scheme === b.scheme && a.host === b.host && a.port === b.port;
55
+ }
56
+ function supportsBinary(transport) {
57
+ return (typeof transport.requestBytes === "function");
58
+ }
59
+ function assertValidApiKey(apiKey) {
60
+ const invalid = typeof apiKey !== "string" ||
61
+ apiKey.length === 0 ||
62
+ [...apiKey].some((character) => /\s/.test(character) || (character.codePointAt(0) ?? 0) < 32);
63
+ if (invalid) {
64
+ throw new Error("NexusTrade apiKey must be a non-empty token.");
65
+ }
66
+ }
67
+ function assertValidBaseUrl(baseUrl) {
68
+ let parsed;
69
+ try {
70
+ parsed = new URL(baseUrl);
71
+ }
72
+ catch {
73
+ throw new Error("NexusTrade baseUrl must be an absolute URL.");
74
+ }
75
+ if (!parsed.protocol || !parsed.hostname) {
76
+ throw new Error("NexusTrade baseUrl must be an absolute URL.");
77
+ }
78
+ const scheme = parsed.protocol.replace(":", "").toLowerCase();
79
+ const isLoopback = ["localhost", "127.0.0.1", "[::1]", "::1"].includes(parsed.hostname.toLowerCase());
80
+ if (scheme !== "https" && !(scheme === "http" && isLoopback)) {
81
+ throw new Error("NexusTrade baseUrl must use HTTPS (HTTP is allowed only for loopback development).");
82
+ }
83
+ if (parsed.username || parsed.password) {
84
+ throw new Error("NexusTrade baseUrl must not contain credentials.");
85
+ }
86
+ if (parsed.search || parsed.hash) {
87
+ throw new Error("NexusTrade baseUrl must not contain a query or fragment.");
88
+ }
89
+ }
90
+ /** Reads at most `limit` bytes, so an oversized body is never fully buffered. */
91
+ async function readCapped(response, limit) {
92
+ if (!response.body) {
93
+ return { bytes: new Uint8Array(0), truncated: false };
94
+ }
95
+ const reader = response.body.getReader();
96
+ const chunks = [];
97
+ let total = 0;
98
+ try {
99
+ for (;;) {
100
+ const { done, value } = await reader.read();
101
+ if (done)
102
+ break;
103
+ if (!value)
104
+ continue;
105
+ chunks.push(value);
106
+ total += value.byteLength;
107
+ if (total > limit) {
108
+ return { bytes: new Uint8Array(0), truncated: true };
109
+ }
110
+ }
111
+ }
112
+ finally {
113
+ reader.releaseLock();
114
+ }
115
+ const bytes = new Uint8Array(total);
116
+ let offset = 0;
117
+ for (const chunk of chunks) {
118
+ bytes.set(chunk, offset);
119
+ offset += chunk.byteLength;
120
+ }
121
+ return { bytes, truncated: false };
122
+ }
123
+ function decodeJsonObject(bytes, status) {
124
+ if (bytes.byteLength === 0)
125
+ return {};
126
+ let text;
127
+ try {
128
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
129
+ }
130
+ catch {
131
+ throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned invalid JSON.");
132
+ }
133
+ let decoded;
134
+ try {
135
+ decoded = JSON.parse(text);
136
+ }
137
+ catch {
138
+ throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned invalid JSON.");
139
+ }
140
+ if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
141
+ throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned a non-object JSON response.");
142
+ }
143
+ return decoded;
144
+ }
145
+ export class HttpTransport {
146
+ // `#` fields, not TS `private` — the credential must be unreachable at
147
+ // runtime too, matching the Python dataclass's `repr=False`.
148
+ #apiKey;
149
+ #baseUrl;
150
+ #timeoutSeconds;
151
+ constructor(options) {
152
+ const timeoutSeconds = options.timeoutSeconds ?? 30;
153
+ assertValidApiKey(options.apiKey);
154
+ assertValidBaseUrl(options.baseUrl);
155
+ if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
156
+ throw new Error("timeoutSeconds must be positive.");
157
+ }
158
+ this.#apiKey = options.apiKey;
159
+ this.#baseUrl = options.baseUrl;
160
+ this.#timeoutSeconds = timeoutSeconds;
161
+ }
162
+ get baseUrl() {
163
+ return this.#baseUrl;
164
+ }
165
+ async request(method, path, options = {}) {
166
+ const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
167
+ const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
168
+ const headers = {
169
+ Authorization: `Bearer ${this.#apiKey}`,
170
+ Accept: "application/json",
171
+ };
172
+ if (payload !== undefined)
173
+ headers["Content-Type"] = "application/json";
174
+ if (options.idempotencyKey !== undefined) {
175
+ headers["Idempotency-Key"] = options.idempotencyKey;
176
+ }
177
+ const controller = new AbortController();
178
+ const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
179
+ try {
180
+ let currentUrl = url;
181
+ for (let hop = 0;; hop += 1) {
182
+ let response;
183
+ try {
184
+ response = await fetch(currentUrl, {
185
+ method,
186
+ headers,
187
+ body: payload,
188
+ redirect: "manual",
189
+ signal: controller.signal,
190
+ });
191
+ }
192
+ catch (error) {
193
+ const reason = error instanceof Error ? error.message : String(error);
194
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
195
+ }
196
+ if (response.status >= 300 && response.status < 400) {
197
+ const location = response.headers.get("location");
198
+ if (!location) {
199
+ throw new NexusTradeApiError(response.status, "invalid_response", "NexusTrade returned a redirect without a location.");
200
+ }
201
+ const next = new URL(location, currentUrl).toString();
202
+ if (!sameOrigin(currentUrl, next)) {
203
+ throw new NexusTradeApiError(response.status, "unsafe_redirect", "NexusTrade refused a cross-origin API redirect.");
204
+ }
205
+ // Never replay a mutation. Re-sending the body would double-submit a
206
+ // paid job; dropping it (what urllib does) would send a meaningless
207
+ // bodyless GET to a POST route. Both SDKs refuse instead.
208
+ if (method.toUpperCase() !== "GET") {
209
+ throw new NexusTradeApiError(response.status, "unsafe_redirect", `NexusTrade refused to follow a redirect on a ${method} request.`);
210
+ }
211
+ if (hop >= MAX_REDIRECTS) {
212
+ throw new NexusTradeApiError(response.status, "transport_error", "NexusTrade exceeded the SDK redirect limit.");
213
+ }
214
+ currentUrl = next;
215
+ continue;
216
+ }
217
+ if (!response.ok) {
218
+ const { bytes } = await readCapped(response, MAX_ERROR_BYTES);
219
+ let code = "api_error";
220
+ let message = response.statusText || `HTTP ${response.status}`;
221
+ try {
222
+ const decoded = decodeJsonObject(bytes, response.status);
223
+ const errorBody = decoded.error;
224
+ if (typeof errorBody === "object" &&
225
+ errorBody !== null &&
226
+ !Array.isArray(errorBody)) {
227
+ const body = errorBody;
228
+ if (body.code)
229
+ code = String(body.code);
230
+ if (body.message)
231
+ message = String(body.message);
232
+ }
233
+ }
234
+ catch {
235
+ // Non-JSON error bodies keep the transport-level code/message.
236
+ }
237
+ throw new NexusTradeApiError(response.status, code, message);
238
+ }
239
+ const { bytes, truncated } = await readCapped(response, MAX_RESPONSE_BYTES);
240
+ if (truncated) {
241
+ throw new NexusTradeApiError(response.status, "response_too_large", "NexusTrade response exceeded the SDK size limit.");
242
+ }
243
+ return decodeJsonObject(bytes, response.status);
244
+ }
245
+ }
246
+ finally {
247
+ clearTimeout(timer);
248
+ }
249
+ }
250
+ }
251
+ const BACKTEST_ARG_NAMES = [
252
+ ["start_date", "startDate"],
253
+ ["end_date", "endDate"],
254
+ ["baseline_symbol", "baseline"],
255
+ ["interval", "interval"],
256
+ ["initial_value", "initialValue"],
257
+ ["generate_events", "generateEvents"],
258
+ ["fee_config", "feeConfig"],
259
+ ];
260
+ function isJsonObject(value) {
261
+ return typeof value === "object" && value !== null && !Array.isArray(value);
262
+ }
263
+ /**
264
+ * Match Python's `urllib.parse.quote(value, safe="")`, which escapes `!'()*`
265
+ * where `encodeURIComponent` leaves them literal. Both decode identically, but
266
+ * the two SDKs must put the same bytes on the wire — see the shared
267
+ * conformance fixture.
268
+ */
269
+ function encodePathSegment(value) {
270
+ return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
271
+ }
272
+ function operationFailure(operation, operationId, status) {
273
+ let code = status === "cancelled" ? "operation_cancelled" : "operation_failed";
274
+ let message = `Operation ${operationId} ${status}.`;
275
+ const error = operation.error;
276
+ if (isJsonObject(error)) {
277
+ if (error.code)
278
+ code = String(error.code);
279
+ if (error.message)
280
+ message = String(error.message);
281
+ }
282
+ return new NexusTradeApiError(NO_HTTP_STATUS, code, message);
283
+ }
284
+ /**
285
+ * Poll `fetch(operationId)` until the operation reaches a terminal state.
286
+ *
287
+ * Works for any operation kind because every NexusTrade job reports the same
288
+ * `{id, kind, status, result?, error?}` envelope. Pass any getter with that
289
+ * shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
290
+ *
291
+ * Resolves with the terminal operation. Rejects with `NexusTradeApiError` on
292
+ * timeout, and on a failed/cancelled operation unless `raiseOnFailure` is
293
+ * false. Transport errors from `fetch` propagate — a poller that swallowed
294
+ * them would report an infrastructure outage as a still-running job.
295
+ */
296
+ export async function waitForOperation(fetch, operationId, options = {}) {
297
+ const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
298
+ const pollIntervalSeconds = options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
299
+ const maxPollIntervalSeconds = options.maxPollIntervalSeconds ?? MAX_POLL_INTERVAL_SECONDS;
300
+ const raiseOnFailure = options.raiseOnFailure ?? true;
301
+ if (!(timeoutSeconds > 0)) {
302
+ throw new Error("timeoutSeconds must be positive.");
303
+ }
304
+ if (pollIntervalSeconds < 0 || maxPollIntervalSeconds < 0) {
305
+ throw new Error("poll intervals must not be negative.");
306
+ }
307
+ const deadline = Date.now() + timeoutSeconds * 1000;
308
+ let interval = Math.min(pollIntervalSeconds, maxPollIntervalSeconds);
309
+ for (;;) {
310
+ const operation = await fetch(operationId);
311
+ const status = String(operation.status ?? "");
312
+ if (TERMINAL_STATUSES.includes(status)) {
313
+ if (raiseOnFailure && status !== "completed") {
314
+ throw operationFailure(operation, operationId, status);
315
+ }
316
+ return operation;
317
+ }
318
+ const remainingMs = deadline - Date.now();
319
+ if (remainingMs <= 0) {
320
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
321
+ `${timeoutSeconds}s. It is still running — poll again with the ` +
322
+ "same id rather than resubmitting.");
323
+ }
324
+ if (interval > 0) {
325
+ const delayMs = Math.min(interval * 1000, remainingMs);
326
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
327
+ }
328
+ interval = Math.min(interval * POLL_BACKOFF_FACTOR, maxPollIntervalSeconds);
329
+ }
330
+ }
331
+ export class NexusTradeClient {
332
+ transport;
333
+ constructor(options = {}) {
334
+ if (options.transport) {
335
+ this.transport = options.transport;
336
+ return;
337
+ }
338
+ // Read the file once, so a two-variable lookup does not walk the tree
339
+ // twice and cannot see two different files mid-resolution.
340
+ const dotenv = loadDotenvValues();
341
+ const apiKey = options.apiKey ?? environmentValue("NEXUSTRADE_API_KEY", dotenv);
342
+ const baseUrl = options.baseUrl ?? environmentValue("NEXUSTRADE_API_BASE_URL", dotenv);
343
+ if (!apiKey || !baseUrl) {
344
+ throw new Error("NexusTradeClient requires an API key. Create one at " +
345
+ "https://nexustrade.io/developers, then either pass apiKey/baseUrl " +
346
+ "or set NEXUSTRADE_API_KEY and NEXUSTRADE_API_BASE_URL " +
347
+ "(base URL is https://nexustrade.io/api/v1). " +
348
+ "Both are also read from a .env file at or above the current " +
349
+ "directory; the real environment takes precedence. " +
350
+ "OAuth tokens are not accepted by this API.");
351
+ }
352
+ this.transport = new HttpTransport({ apiKey, baseUrl });
353
+ }
354
+ static fromEnvironment() {
355
+ return new NexusTradeClient();
356
+ }
357
+ async createPortfolio(portfolio, options) {
358
+ const response = await this.transport.request("POST", "portfolios", {
359
+ body: asJsonObject(portfolio),
360
+ idempotencyKey: options.idempotencyKey,
361
+ });
362
+ const result = response.portfolio;
363
+ if (!isJsonObject(result)) {
364
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Portfolio response is missing portfolio.");
365
+ }
366
+ return result;
367
+ }
368
+ async createBacktests(backtests, options) {
369
+ const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
370
+ const response = await this.transport.request("POST", "backtests/batch", {
371
+ body: { backtests: inputs },
372
+ idempotencyKey: options.idempotencyKey,
373
+ });
374
+ const operations = response.operations;
375
+ if (!Array.isArray(operations) ||
376
+ !operations.every((operation) => isJsonObject(operation))) {
377
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Backtest response is missing operations.");
378
+ }
379
+ return operations;
380
+ }
381
+ /** Submit one generated `backtest(...)` handle or raw API input. */
382
+ async createBacktest(backtest, options) {
383
+ const operations = await this.createBacktests([backtest], options);
384
+ if (operations.length !== 1) {
385
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Single backtest response returned the wrong operation count.");
386
+ }
387
+ return operations[0];
388
+ }
389
+ async getBacktest(backtestId) {
390
+ const response = await this.transport.request("GET", `backtests/${encodePathSegment(backtestId)}`);
391
+ return operationOf(response);
392
+ }
393
+ async createOptimization(handle, options) {
394
+ return this.createPortfolioJob("optimizations", handle, options.idempotencyKey);
395
+ }
396
+ async getOptimization(optimizationId) {
397
+ const response = await this.transport.request("GET", `optimizations/${encodePathSegment(optimizationId)}`);
398
+ return operationOf(response);
399
+ }
400
+ async createWalkForward(handle, options) {
401
+ return this.createPortfolioJob("walk-forward-studies", handle, options.idempotencyKey);
402
+ }
403
+ async getWalkForward(studyId) {
404
+ const response = await this.transport.request("GET", `walk-forward-studies/${encodePathSegment(studyId)}`);
405
+ return operationOf(response);
406
+ }
407
+ async createLakeQuery(request, options) {
408
+ const response = await this.transport.request("POST", "lake/queries", {
409
+ body: request,
410
+ idempotencyKey: options.idempotencyKey,
411
+ });
412
+ return operationOf(response);
413
+ }
414
+ async getLakeQuery(queryId) {
415
+ return operationOf(await this.transport.request("GET", `lake/queries/${encodePathSegment(queryId)}`));
416
+ }
417
+ async cancelLakeQuery(queryId) {
418
+ return operationOf(await this.transport.request("POST", `lake/queries/${encodePathSegment(queryId)}/cancel`));
419
+ }
420
+ async getLakeQueryManifest(queryId) {
421
+ return operationOf(await this.transport.request("GET", `lake/queries/${encodePathSegment(queryId)}/manifest`));
422
+ }
423
+ async getLakeCatalog() {
424
+ const response = await this.transport.request("GET", "lake/catalog");
425
+ const tables = response.tables;
426
+ if (!Array.isArray(tables) || !tables.every((t) => isJsonObject(t))) {
427
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Lake catalog response is missing tables.");
428
+ }
429
+ return tables;
430
+ }
431
+ async describeLakeTable(table) {
432
+ const name = table.startsWith("lake.") ? table.slice(5) : table;
433
+ const response = await this.transport.request("GET", `lake/catalog/lake/${encodePathSegment(name)}`);
434
+ const described = response.table;
435
+ if (!isJsonObject(described)) {
436
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Lake describe response is missing table.");
437
+ }
438
+ return described;
439
+ }
440
+ /** Download one Parquet part, optionally a byte range of it. */
441
+ async downloadLakeQueryPart(queryId, part, options = {}) {
442
+ if (!supportsBinary(this.transport)) {
443
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Lake part download requires a transport implementing requestBytes.");
444
+ }
445
+ return this.transport.requestBytes("GET", `lake/queries/${encodePathSegment(queryId)}/parts/${Math.trunc(part)}`, options);
446
+ }
447
+ /** Resolve once a lake query is terminal. See `waitForOperation`. */
448
+ async waitForLakeQuery(queryId, options = {}) {
449
+ return waitForOperation((id) => this.getLakeQuery(id), queryId, options);
450
+ }
451
+ /** Resolve once a backtest is terminal. See `waitForOperation`. */
452
+ async waitForBacktest(backtestId, options = {}) {
453
+ return waitForOperation((id) => this.getBacktest(id), backtestId, options);
454
+ }
455
+ /** Resolve once an optimization is terminal. See `waitForOperation`. */
456
+ async waitForOptimization(optimizationId, options = {}) {
457
+ return waitForOperation((id) => this.getOptimization(id), optimizationId, options);
458
+ }
459
+ /** Resolve once a walk-forward study is terminal. See `waitForOperation`. */
460
+ async waitForWalkForward(studyId, options = {}) {
461
+ return waitForOperation((id) => this.getWalkForward(id), studyId, options);
462
+ }
463
+ /** Wait on a whole `createBacktests` batch, in submission order. */
464
+ async waitForBacktests(operations, options = {}) {
465
+ const finished = [];
466
+ for (const operation of operations) {
467
+ finished.push(await this.waitForBacktest(String(operation.id), options));
468
+ }
469
+ return finished;
470
+ }
471
+ async createPortfolioJob(path, input, idempotencyKey) {
472
+ const handle = asJsonObject(input);
473
+ const args = handle.args;
474
+ const response = await this.transport.request("POST", path, {
475
+ body: {
476
+ portfolio: handle.portfolio ?? null,
477
+ args: isJsonObject(args) ? args : {},
478
+ },
479
+ idempotencyKey,
480
+ });
481
+ return operationOf(response);
482
+ }
483
+ }
484
+ function backtestInput(item) {
485
+ const tool = item.tool;
486
+ if (tool === undefined || tool === null) {
487
+ return { ...item };
488
+ }
489
+ if (tool !== "backtest_portfolio") {
490
+ throw new Error("createBacktests accepts backtest(...) handles or raw API inputs.");
491
+ }
492
+ const portfolio = item.portfolio;
493
+ const args = item.args;
494
+ if (!isJsonObject(portfolio) || !isJsonObject(args)) {
495
+ throw new Error("backtest(...) handle is missing portfolio or args.");
496
+ }
497
+ const normalized = { portfolio: { ...portfolio } };
498
+ for (const [source, target] of BACKTEST_ARG_NAMES) {
499
+ const value = args[source];
500
+ if (value !== undefined && value !== null) {
501
+ normalized[target] = value;
502
+ }
503
+ }
504
+ return normalized;
505
+ }
506
+ function operationOf(response) {
507
+ const operation = response.operation;
508
+ if (!isJsonObject(operation)) {
509
+ throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Response is missing operation.");
510
+ }
511
+ return operation;
512
+ }
513
+ /** Convenience wrapper for scripts that do not need a persistent client. */
514
+ export async function createPortfolio(portfolio, options) {
515
+ const client = options.client ?? NexusTradeClient.fromEnvironment();
516
+ return client.createPortfolio(portfolio, {
517
+ idempotencyKey: options.idempotencyKey,
518
+ });
519
+ }