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