nexustrade 0.3.0 → 1.0.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 +35 -12
- package/README.md +161 -14
- package/dist/cjs/agent.js +12 -6
- package/dist/cjs/client.js +305 -16
- package/dist/cjs/generated/ntSdk.generated.js +2 -6
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/portfolio.js +1 -3
- package/dist/esm/agent.d.ts +2 -5
- package/dist/esm/agent.js +12 -6
- package/dist/esm/client.d.ts +120 -6
- package/dist/esm/client.js +304 -16
- package/dist/esm/generated/ntSdk.generated.d.ts +0 -2
- package/dist/esm/generated/ntSdk.generated.js +0 -2
- package/dist/esm/index.d.ts +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/portfolio.d.ts +1 -3
- package/dist/esm/portfolio.js +1 -3
- package/package.json +1 -1
package/dist/esm/client.d.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Typed NexusTrade JSON API client.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
4
|
+
* Method names and behavior match the Python SDK. Transport-generic: callers
|
|
5
|
+
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
7
6
|
*/
|
|
8
7
|
import { AgentRun } from "./agent.ts";
|
|
9
8
|
import type { JobRequest, Portfolio } from "./generated/ntSdk.generated.js";
|
|
@@ -45,7 +44,13 @@ export declare const POLL_BACKOFF_FACTOR = 1.5;
|
|
|
45
44
|
export declare class NexusTradeApiError extends Error {
|
|
46
45
|
readonly status: number;
|
|
47
46
|
readonly code: string;
|
|
48
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Set for operation errors (timeout / failure). A timed-out job is still
|
|
49
|
+
* running, so the caller needs the id to resume waiting without resubmitting
|
|
50
|
+
* — reading it out of the message is not an interface.
|
|
51
|
+
*/
|
|
52
|
+
readonly operationId?: string;
|
|
53
|
+
constructor(status: number, code: string, message: string, operationId?: string);
|
|
49
54
|
}
|
|
50
55
|
export interface RequestOptions {
|
|
51
56
|
body?: JsonObject;
|
|
@@ -68,15 +73,29 @@ export interface BinaryTransport extends Transport {
|
|
|
68
73
|
maxBytes?: number;
|
|
69
74
|
}): Promise<Uint8Array>;
|
|
70
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Transports that can PUT bytes to a presigned storage URL.
|
|
78
|
+
*
|
|
79
|
+
* The URL is absolute and the call carries no credential.
|
|
80
|
+
*/
|
|
81
|
+
export interface UploadTransport extends Transport {
|
|
82
|
+
putBytes(url: string, data: Uint8Array<ArrayBuffer>, options: {
|
|
83
|
+
contentType: string;
|
|
84
|
+
}): Promise<void>;
|
|
85
|
+
}
|
|
71
86
|
export interface HttpTransportOptions {
|
|
72
87
|
apiKey: string;
|
|
73
88
|
baseUrl: string;
|
|
74
89
|
timeoutSeconds?: number;
|
|
75
90
|
}
|
|
76
|
-
export declare class HttpTransport implements Transport {
|
|
91
|
+
export declare class HttpTransport implements Transport, UploadTransport {
|
|
77
92
|
#private;
|
|
78
93
|
constructor(options: HttpTransportOptions);
|
|
79
94
|
get baseUrl(): string;
|
|
95
|
+
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
96
|
+
putBytes(url: string, data: Uint8Array<ArrayBuffer>, options: {
|
|
97
|
+
contentType: string;
|
|
98
|
+
}): Promise<void>;
|
|
80
99
|
request(method: string, path: string, options?: RequestOptions): Promise<JsonObject>;
|
|
81
100
|
}
|
|
82
101
|
export interface NexusTradeClientOptions {
|
|
@@ -102,6 +121,20 @@ export interface WaitOptions {
|
|
|
102
121
|
* false. Transport errors from `fetch` propagate — a poller that swallowed
|
|
103
122
|
* them would report an infrastructure outage as a still-running job.
|
|
104
123
|
*/
|
|
124
|
+
export interface CustomIndicatorPointInput {
|
|
125
|
+
timestamp: string | Date;
|
|
126
|
+
value: number;
|
|
127
|
+
ticker?: string;
|
|
128
|
+
assetType?: string;
|
|
129
|
+
availableAt?: string | Date;
|
|
130
|
+
[field: string]: unknown;
|
|
131
|
+
}
|
|
132
|
+
export interface CustomIndicatorInput {
|
|
133
|
+
name: string;
|
|
134
|
+
description?: string;
|
|
135
|
+
scope?: "global" | "asset";
|
|
136
|
+
points?: ReadonlyArray<CustomIndicatorPointInput>;
|
|
137
|
+
}
|
|
105
138
|
export declare function waitForOperation(fetch: (operationId: string) => Promise<JsonObject>, operationId: string, options?: WaitOptions): Promise<JsonObject>;
|
|
106
139
|
export declare class NexusTradeClient {
|
|
107
140
|
private readonly transport;
|
|
@@ -111,7 +144,7 @@ export declare class NexusTradeClient {
|
|
|
111
144
|
idempotencyKey: string;
|
|
112
145
|
}): Promise<JsonObject>;
|
|
113
146
|
/**
|
|
114
|
-
* List portfolios
|
|
147
|
+
* List portfolios with optional filters and pagination.
|
|
115
148
|
* `includePositions` defaults off when `search` is set.
|
|
116
149
|
*/
|
|
117
150
|
listPortfolios(options?: ListPortfoliosOptions): Promise<PortfolioListResult>;
|
|
@@ -121,6 +154,82 @@ export declare class NexusTradeClient {
|
|
|
121
154
|
frequency?: string;
|
|
122
155
|
}): Promise<DeployResult>;
|
|
123
156
|
undeploy(portfolioId: string): Promise<JsonObject>;
|
|
157
|
+
/**
|
|
158
|
+
* Create a custom data source and return it, including its id.
|
|
159
|
+
*
|
|
160
|
+
* `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
|
|
161
|
+
* every point needs a `ticker`); it defaults to `"global"` and cannot be
|
|
162
|
+
* changed later. `points` is optional and unlimited in size — small batches
|
|
163
|
+
* are sent with the request, larger ones are uploaded, and the returned
|
|
164
|
+
* indicator reflects what landed either way.
|
|
165
|
+
*
|
|
166
|
+
* The id it returns is what a `CustomIndicator` node binds to:
|
|
167
|
+
*
|
|
168
|
+
* ```ts
|
|
169
|
+
* const series = await client.createCustomIndicator(
|
|
170
|
+
* {
|
|
171
|
+
* name: "WSB NVDA Mentions",
|
|
172
|
+
* scope: "asset",
|
|
173
|
+
* points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
|
|
174
|
+
* },
|
|
175
|
+
* { idempotencyKey: "wsb-mentions-v1" },
|
|
176
|
+
* );
|
|
177
|
+
* CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
|
|
178
|
+
* ```
|
|
179
|
+
*
|
|
180
|
+
* Retrying with the same `idempotencyKey` returns the original series rather
|
|
181
|
+
* than creating a second one.
|
|
182
|
+
*/
|
|
183
|
+
createCustomIndicator(indicator: CustomIndicatorInput, options: {
|
|
184
|
+
idempotencyKey: string;
|
|
185
|
+
}): Promise<JsonObject>;
|
|
186
|
+
/** List the custom data sources this account owns. */
|
|
187
|
+
listCustomIndicators(options?: {
|
|
188
|
+
includeArchived?: boolean;
|
|
189
|
+
}): Promise<JsonObject[]>;
|
|
190
|
+
/** Read one custom data source, including its current point count. */
|
|
191
|
+
getCustomIndicator(customIndicatorId: string): Promise<JsonObject>;
|
|
192
|
+
/**
|
|
193
|
+
* Add points to an existing series and return the updated indicator.
|
|
194
|
+
*
|
|
195
|
+
* Recurring collection must append to the same `customIndicatorId` every
|
|
196
|
+
* run; creating a fresh series per run splits the history into fragments a
|
|
197
|
+
* strategy cannot read. Re-sending an identical batch is safe — the
|
|
198
|
+
* duplicate is not written twice.
|
|
199
|
+
*
|
|
200
|
+
* The batch is unlimited in size and, as with creation, is sent inline or
|
|
201
|
+
* uploaded depending on how large it is.
|
|
202
|
+
*/
|
|
203
|
+
appendCustomIndicatorPoints(customIndicatorId: string, points: ReadonlyArray<CustomIndicatorPointInput>, options: {
|
|
204
|
+
idempotencyKey: string;
|
|
205
|
+
}): Promise<JsonObject>;
|
|
206
|
+
/**
|
|
207
|
+
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
208
|
+
*
|
|
209
|
+
* Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
|
|
210
|
+
* returned URL, then call `completeCustomIndicatorUpload`. Most callers can
|
|
211
|
+
* pass `points` to `createCustomIndicator` or
|
|
212
|
+
* `appendCustomIndicatorPoints` instead and skip all three steps.
|
|
213
|
+
*
|
|
214
|
+
* Retrying with the same `idempotencyKey` re-signs the same job, since the
|
|
215
|
+
* first URL expires in 15 minutes. Once its bytes have arrived the reply
|
|
216
|
+
* carries no `uploadUrl` — there is nothing left to send, so skip the PUT
|
|
217
|
+
* and wait on `jobId`.
|
|
218
|
+
*/
|
|
219
|
+
createCustomIndicatorUpload(customIndicatorId: string, options: {
|
|
220
|
+
fileName: string;
|
|
221
|
+
idempotencyKey: string;
|
|
222
|
+
format?: "csv" | "json" | "jsonl";
|
|
223
|
+
contentType?: string;
|
|
224
|
+
sizeBytes?: number;
|
|
225
|
+
}): Promise<JsonObject>;
|
|
226
|
+
/** Start validation of uploaded bytes and return the operation. */
|
|
227
|
+
completeCustomIndicatorUpload(customIndicatorId: string, jobId: string): Promise<JsonObject>;
|
|
228
|
+
/** Read an upload operation. `phase` distinguishes the live states. */
|
|
229
|
+
getCustomIndicatorUpload(customIndicatorId: string, jobId: string): Promise<JsonObject>;
|
|
230
|
+
/** Block until an upload is validated. See `waitForOperation`. */
|
|
231
|
+
waitForCustomIndicatorUpload(customIndicatorId: string, jobId: string, options?: WaitOptions): Promise<JsonObject>;
|
|
232
|
+
private uploadCustomIndicatorPoints;
|
|
124
233
|
createBacktests(backtests: ReadonlyArray<JobInput>, options: {
|
|
125
234
|
idempotencyKey: string;
|
|
126
235
|
}): Promise<JsonObject[]>;
|
|
@@ -186,6 +295,11 @@ export declare class NexusTradeClient {
|
|
|
186
295
|
/** @internal PortfolioHandle lazy-client attachment. */
|
|
187
296
|
export declare function clientTransport(client: NexusTradeClient): Transport;
|
|
188
297
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
298
|
+
export declare function createCustomIndicator(indicator: CustomIndicatorInput, options: {
|
|
299
|
+
idempotencyKey: string;
|
|
300
|
+
client?: NexusTradeClient;
|
|
301
|
+
}): Promise<JsonObject>;
|
|
302
|
+
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
189
303
|
export declare function createPortfolio(portfolio: JsonObject, options: {
|
|
190
304
|
idempotencyKey: string;
|
|
191
305
|
client?: NexusTradeClient;
|
package/dist/esm/client.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Typed NexusTrade JSON API client.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
4
|
+
* Method names and behavior match the Python SDK. Transport-generic: callers
|
|
5
|
+
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
7
6
|
*/
|
|
8
7
|
import { AgentRun } from "./agent.js";
|
|
9
8
|
import { LazyDotenv, environmentValue } from "./env.js";
|
|
@@ -47,14 +46,33 @@ export const DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
|
47
46
|
export const MAX_POLL_INTERVAL_SECONDS = 15;
|
|
48
47
|
export const POLL_BACKOFF_FACTOR = 1.5;
|
|
49
48
|
const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
|
|
49
|
+
// Point batches larger than this are uploaded rather than sent inline.
|
|
50
|
+
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
51
|
+
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
52
|
+
const POINT_FIELDS = {
|
|
53
|
+
timestamp: "timestamp",
|
|
54
|
+
value: "value",
|
|
55
|
+
ticker: "ticker",
|
|
56
|
+
assetType: "assetType",
|
|
57
|
+
asset_type: "assetType",
|
|
58
|
+
availableAt: "availableAt",
|
|
59
|
+
available_at: "availableAt",
|
|
60
|
+
};
|
|
50
61
|
export class NexusTradeApiError extends Error {
|
|
51
62
|
status;
|
|
52
63
|
code;
|
|
53
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Set for operation errors (timeout / failure). A timed-out job is still
|
|
66
|
+
* running, so the caller needs the id to resume waiting without resubmitting
|
|
67
|
+
* — reading it out of the message is not an interface.
|
|
68
|
+
*/
|
|
69
|
+
operationId;
|
|
70
|
+
constructor(status, code, message, operationId) {
|
|
54
71
|
super(`${code}: ${message}`);
|
|
55
72
|
this.name = "NexusTradeApiError";
|
|
56
73
|
this.status = status;
|
|
57
74
|
this.code = code;
|
|
75
|
+
this.operationId = operationId;
|
|
58
76
|
}
|
|
59
77
|
}
|
|
60
78
|
function origin(url) {
|
|
@@ -74,6 +92,9 @@ function sameOrigin(left, right) {
|
|
|
74
92
|
function supportsBinary(transport) {
|
|
75
93
|
return (typeof transport.requestBytes === "function");
|
|
76
94
|
}
|
|
95
|
+
function supportsUpload(transport) {
|
|
96
|
+
return typeof transport.putBytes === "function";
|
|
97
|
+
}
|
|
77
98
|
function assertValidApiKey(apiKey) {
|
|
78
99
|
const invalid = typeof apiKey !== "string" ||
|
|
79
100
|
apiKey.length === 0 ||
|
|
@@ -180,6 +201,43 @@ export class HttpTransport {
|
|
|
180
201
|
get baseUrl() {
|
|
181
202
|
return this.#baseUrl;
|
|
182
203
|
}
|
|
204
|
+
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
205
|
+
async putBytes(url, data, options) {
|
|
206
|
+
let parsed;
|
|
207
|
+
try {
|
|
208
|
+
parsed = new URL(url);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a malformed upload URL.");
|
|
212
|
+
}
|
|
213
|
+
if (parsed.protocol.toLowerCase() !== "https:") {
|
|
214
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsafe_upload_url", "NexusTrade refused a non-HTTPS upload URL.");
|
|
215
|
+
}
|
|
216
|
+
const controller = new AbortController();
|
|
217
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutSeconds * 1000);
|
|
218
|
+
try {
|
|
219
|
+
let response;
|
|
220
|
+
try {
|
|
221
|
+
response = await fetch(url, {
|
|
222
|
+
method: "PUT",
|
|
223
|
+
headers: { "Content-Type": options.contentType },
|
|
224
|
+
body: new Blob([data], { type: options.contentType }),
|
|
225
|
+
redirect: "manual",
|
|
226
|
+
signal: controller.signal,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
231
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "transport_error", reason);
|
|
232
|
+
}
|
|
233
|
+
if (!response.ok) {
|
|
234
|
+
throw new NexusTradeApiError(response.status, "upload_failed", `Storage rejected the upload: ${response.statusText || `HTTP ${response.status}`}.`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
finally {
|
|
238
|
+
clearTimeout(timer);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
183
241
|
async request(method, path, options = {}) {
|
|
184
242
|
const url = `${this.#baseUrl.replace(/\/+$/, "")}/nexustrade/${path.replace(/^\/+/, "")}`;
|
|
185
243
|
const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
|
|
@@ -297,20 +355,52 @@ function operationFailure(operation, operationId, status) {
|
|
|
297
355
|
if (error.message)
|
|
298
356
|
message = String(error.message);
|
|
299
357
|
}
|
|
300
|
-
return new NexusTradeApiError(NO_HTTP_STATUS, code, message);
|
|
358
|
+
return new NexusTradeApiError(NO_HTTP_STATUS, code, message, operationId);
|
|
359
|
+
}
|
|
360
|
+
function pointTimestamp(value) {
|
|
361
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
301
362
|
}
|
|
302
363
|
/**
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
* Works for any operation kind because every NexusTrade job reports the same
|
|
306
|
-
* `{id, kind, status, result?, error?}` envelope. Pass any getter with that
|
|
307
|
-
* shape — `client.getBacktest`, `getOptimization`, `getWalkForward`.
|
|
364
|
+
* Normalize one point to its wire shape.
|
|
308
365
|
*
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
* false. Transport errors from `fetch` propagate — a poller that swallowed
|
|
312
|
-
* them would report an infrastructure outage as a still-running job.
|
|
366
|
+
* Accepts snake_case or camelCase field names and Date objects. Throws on an
|
|
367
|
+
* unrecognized field rather than dropping it silently.
|
|
313
368
|
*/
|
|
369
|
+
function customIndicatorPoint(point) {
|
|
370
|
+
const normalized = {};
|
|
371
|
+
for (const [key, value] of Object.entries(point)) {
|
|
372
|
+
const target = POINT_FIELDS[key];
|
|
373
|
+
if (target === undefined) {
|
|
374
|
+
throw new Error(`Unknown custom indicator point field "${key}". Points accept ` +
|
|
375
|
+
"timestamp, value, ticker, assetType, and availableAt.");
|
|
376
|
+
}
|
|
377
|
+
if (value === undefined || value === null)
|
|
378
|
+
continue;
|
|
379
|
+
normalized[target] =
|
|
380
|
+
target === "timestamp" || target === "availableAt"
|
|
381
|
+
? pointTimestamp(value)
|
|
382
|
+
: value;
|
|
383
|
+
}
|
|
384
|
+
if (normalized.timestamp === undefined) {
|
|
385
|
+
throw new Error("Every custom indicator point needs a timestamp.");
|
|
386
|
+
}
|
|
387
|
+
if (normalized.value === undefined) {
|
|
388
|
+
throw new Error("Every custom indicator point needs a value.");
|
|
389
|
+
}
|
|
390
|
+
return normalized;
|
|
391
|
+
}
|
|
392
|
+
function customIndicatorPoints(points) {
|
|
393
|
+
if (!Array.isArray(points)) {
|
|
394
|
+
throw new Error("points must be an array of point objects.");
|
|
395
|
+
}
|
|
396
|
+
return points.map(customIndicatorPoint);
|
|
397
|
+
}
|
|
398
|
+
function pointsJsonl(points) {
|
|
399
|
+
return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
|
|
400
|
+
}
|
|
401
|
+
function inlinePointBytes(points) {
|
|
402
|
+
return new TextEncoder().encode(JSON.stringify(points)).length;
|
|
403
|
+
}
|
|
314
404
|
export async function waitForOperation(fetch, operationId, options = {}) {
|
|
315
405
|
const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_POLL_TIMEOUT_SECONDS;
|
|
316
406
|
const pollIntervalSeconds = options.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS;
|
|
@@ -337,7 +427,7 @@ export async function waitForOperation(fetch, operationId, options = {}) {
|
|
|
337
427
|
if (remainingMs <= 0) {
|
|
338
428
|
throw new NexusTradeApiError(NO_HTTP_STATUS, "operation_timeout", `Operation ${operationId} was still '${status || "unknown"}' after ` +
|
|
339
429
|
`${timeoutSeconds}s. It is still running — poll again with the ` +
|
|
340
|
-
"same id rather than resubmitting.");
|
|
430
|
+
"same id (error.operationId) rather than resubmitting.", operationId);
|
|
341
431
|
}
|
|
342
432
|
if (interval > 0) {
|
|
343
433
|
const delayMs = Math.min(interval * 1000, remainingMs);
|
|
@@ -385,7 +475,7 @@ export class NexusTradeClient {
|
|
|
385
475
|
return result;
|
|
386
476
|
}
|
|
387
477
|
/**
|
|
388
|
-
* List portfolios
|
|
478
|
+
* List portfolios with optional filters and pagination.
|
|
389
479
|
* `includePositions` defaults off when `search` is set.
|
|
390
480
|
*/
|
|
391
481
|
async listPortfolios(options = {}) {
|
|
@@ -464,6 +554,190 @@ export class NexusTradeClient {
|
|
|
464
554
|
}
|
|
465
555
|
return result;
|
|
466
556
|
}
|
|
557
|
+
/**
|
|
558
|
+
* Create a custom data source and return it, including its id.
|
|
559
|
+
*
|
|
560
|
+
* `scope` is `"global"` (one series) or `"asset"` (one series per ticker, so
|
|
561
|
+
* every point needs a `ticker`); it defaults to `"global"` and cannot be
|
|
562
|
+
* changed later. `points` is optional and unlimited in size — small batches
|
|
563
|
+
* are sent with the request, larger ones are uploaded, and the returned
|
|
564
|
+
* indicator reflects what landed either way.
|
|
565
|
+
*
|
|
566
|
+
* The id it returns is what a `CustomIndicator` node binds to:
|
|
567
|
+
*
|
|
568
|
+
* ```ts
|
|
569
|
+
* const series = await client.createCustomIndicator(
|
|
570
|
+
* {
|
|
571
|
+
* name: "WSB NVDA Mentions",
|
|
572
|
+
* scope: "asset",
|
|
573
|
+
* points: [{ timestamp: "2024-04-01", value: 152, ticker: "NVDA" }],
|
|
574
|
+
* },
|
|
575
|
+
* { idempotencyKey: "wsb-mentions-v1" },
|
|
576
|
+
* );
|
|
577
|
+
* CustomIndicator(stockAsset("NVDA"), String(series.customIndicatorId));
|
|
578
|
+
* ```
|
|
579
|
+
*
|
|
580
|
+
* Retrying with the same `idempotencyKey` returns the original series rather
|
|
581
|
+
* than creating a second one.
|
|
582
|
+
*/
|
|
583
|
+
async createCustomIndicator(indicator, options) {
|
|
584
|
+
const { name, description, scope, points, ...rest } = indicator;
|
|
585
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
586
|
+
throw new Error("createCustomIndicator requires a name.");
|
|
587
|
+
}
|
|
588
|
+
const unknown = Object.keys(rest);
|
|
589
|
+
if (unknown.length > 0) {
|
|
590
|
+
throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
|
|
591
|
+
"Expected name, description, scope, and points.");
|
|
592
|
+
}
|
|
593
|
+
const normalized = points ? customIndicatorPoints(points) : [];
|
|
594
|
+
const body = { name: name.trim() };
|
|
595
|
+
if (description !== undefined)
|
|
596
|
+
body.description = description;
|
|
597
|
+
if (scope !== undefined)
|
|
598
|
+
body.scope = scope;
|
|
599
|
+
const inline = normalized.length > 0 &&
|
|
600
|
+
inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
|
|
601
|
+
if (inline)
|
|
602
|
+
body.points = normalized;
|
|
603
|
+
const created = customIndicatorOf(await this.transport.request("POST", "custom-indicators", {
|
|
604
|
+
body,
|
|
605
|
+
idempotencyKey: options.idempotencyKey,
|
|
606
|
+
}));
|
|
607
|
+
if (inline || normalized.length === 0)
|
|
608
|
+
return created;
|
|
609
|
+
const customIndicatorId = String(created.customIndicatorId);
|
|
610
|
+
// The same key is safe here: the server namespaces an idempotency claim
|
|
611
|
+
// by operation, and deriving a suffixed key could overrun its
|
|
612
|
+
// 160-character limit.
|
|
613
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
614
|
+
return {
|
|
615
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
616
|
+
upload,
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
/** List the custom data sources this account owns. */
|
|
620
|
+
async listCustomIndicators(options = {}) {
|
|
621
|
+
const query = encodeQuery({
|
|
622
|
+
includeArchived: options.includeArchived === undefined
|
|
623
|
+
? undefined
|
|
624
|
+
: String(options.includeArchived),
|
|
625
|
+
});
|
|
626
|
+
const response = await this.transport.request("GET", `custom-indicators${query}`);
|
|
627
|
+
const indicators = response.indicators;
|
|
628
|
+
if (!Array.isArray(indicators)) {
|
|
629
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator list response is missing indicators.");
|
|
630
|
+
}
|
|
631
|
+
return indicators.filter((row) => isJsonObject(row));
|
|
632
|
+
}
|
|
633
|
+
/** Read one custom data source, including its current point count. */
|
|
634
|
+
async getCustomIndicator(customIndicatorId) {
|
|
635
|
+
return customIndicatorOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}`));
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Add points to an existing series and return the updated indicator.
|
|
639
|
+
*
|
|
640
|
+
* Recurring collection must append to the same `customIndicatorId` every
|
|
641
|
+
* run; creating a fresh series per run splits the history into fragments a
|
|
642
|
+
* strategy cannot read. Re-sending an identical batch is safe — the
|
|
643
|
+
* duplicate is not written twice.
|
|
644
|
+
*
|
|
645
|
+
* The batch is unlimited in size and, as with creation, is sent inline or
|
|
646
|
+
* uploaded depending on how large it is.
|
|
647
|
+
*/
|
|
648
|
+
async appendCustomIndicatorPoints(customIndicatorId, points, options) {
|
|
649
|
+
const normalized = customIndicatorPoints(points);
|
|
650
|
+
if (normalized.length === 0) {
|
|
651
|
+
throw new Error("appendCustomIndicatorPoints needs at least one point.");
|
|
652
|
+
}
|
|
653
|
+
if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
|
|
654
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, { body: { points: normalized }, idempotencyKey: options.idempotencyKey });
|
|
655
|
+
const indicator = response.indicator;
|
|
656
|
+
if (!isJsonObject(indicator)) {
|
|
657
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
658
|
+
}
|
|
659
|
+
return indicator;
|
|
660
|
+
}
|
|
661
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey);
|
|
662
|
+
return {
|
|
663
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
664
|
+
upload,
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
669
|
+
*
|
|
670
|
+
* Accepts `csv`, `json`, or `jsonl` up to 100 MB. PUT the bytes to the
|
|
671
|
+
* returned URL, then call `completeCustomIndicatorUpload`. Most callers can
|
|
672
|
+
* pass `points` to `createCustomIndicator` or
|
|
673
|
+
* `appendCustomIndicatorPoints` instead and skip all three steps.
|
|
674
|
+
*
|
|
675
|
+
* Retrying with the same `idempotencyKey` re-signs the same job, since the
|
|
676
|
+
* first URL expires in 15 minutes. Once its bytes have arrived the reply
|
|
677
|
+
* carries no `uploadUrl` — there is nothing left to send, so skip the PUT
|
|
678
|
+
* and wait on `jobId`.
|
|
679
|
+
*/
|
|
680
|
+
async createCustomIndicatorUpload(customIndicatorId, options) {
|
|
681
|
+
const body = {
|
|
682
|
+
fileName: options.fileName,
|
|
683
|
+
format: options.format ?? "jsonl",
|
|
684
|
+
};
|
|
685
|
+
if (options.contentType !== undefined)
|
|
686
|
+
body.contentType = options.contentType;
|
|
687
|
+
if (options.sizeBytes !== undefined)
|
|
688
|
+
body.sizeBytes = options.sizeBytes;
|
|
689
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
|
|
690
|
+
const ticket = response.ticket;
|
|
691
|
+
if (!isJsonObject(ticket) || !ticket.jobId) {
|
|
692
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Upload response is missing ticket.");
|
|
693
|
+
}
|
|
694
|
+
return ticket;
|
|
695
|
+
}
|
|
696
|
+
/** Start validation of uploaded bytes and return the operation. */
|
|
697
|
+
async completeCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
698
|
+
return operationOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
699
|
+
`/uploads/${encodePathSegment(jobId)}/complete`, { body: {} }));
|
|
700
|
+
}
|
|
701
|
+
/** Read an upload operation. `phase` distinguishes the live states. */
|
|
702
|
+
async getCustomIndicatorUpload(customIndicatorId, jobId) {
|
|
703
|
+
return operationOf(await this.transport.request("GET", `custom-indicators/${encodePathSegment(customIndicatorId)}` +
|
|
704
|
+
`/uploads/${encodePathSegment(jobId)}`));
|
|
705
|
+
}
|
|
706
|
+
/** Block until an upload is validated. See `waitForOperation`. */
|
|
707
|
+
async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
|
|
708
|
+
return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
|
|
709
|
+
}
|
|
710
|
+
async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
|
|
711
|
+
const payload = pointsJsonl(points);
|
|
712
|
+
if (payload.length > MAX_UPLOAD_BYTES) {
|
|
713
|
+
throw new Error(`${points.length} points serialize to ` +
|
|
714
|
+
`${Math.floor(payload.length / (1024 * 1024))} MB, over the 100 MB ` +
|
|
715
|
+
"upload limit. Send them in several batches.");
|
|
716
|
+
}
|
|
717
|
+
if (!supportsUpload(this.transport)) {
|
|
718
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "unsupported_transport", "Uploading a large point batch requires HttpTransport.putBytes.");
|
|
719
|
+
}
|
|
720
|
+
const ticket = await this.createCustomIndicatorUpload(customIndicatorId, {
|
|
721
|
+
fileName: `${customIndicatorId}-points.jsonl`,
|
|
722
|
+
format: "jsonl",
|
|
723
|
+
sizeBytes: payload.length,
|
|
724
|
+
idempotencyKey,
|
|
725
|
+
});
|
|
726
|
+
const jobId = String(ticket.jobId);
|
|
727
|
+
// No upload URL means this batch already reached the server on an earlier
|
|
728
|
+
// attempt, so resume at polling instead of re-sending it.
|
|
729
|
+
if (ticket.uploadUrl) {
|
|
730
|
+
const headers = ticket.headers;
|
|
731
|
+
const contentType = isJsonObject(headers) && typeof headers["Content-Type"] === "string"
|
|
732
|
+
? headers["Content-Type"]
|
|
733
|
+
: "application/x-ndjson";
|
|
734
|
+
await this.transport.putBytes(String(ticket.uploadUrl), payload, {
|
|
735
|
+
contentType,
|
|
736
|
+
});
|
|
737
|
+
await this.completeCustomIndicatorUpload(customIndicatorId, jobId);
|
|
738
|
+
}
|
|
739
|
+
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
740
|
+
}
|
|
467
741
|
async createBacktests(backtests, options) {
|
|
468
742
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
469
743
|
const response = await this.transport.request("POST", "backtests/batch", {
|
|
@@ -650,6 +924,13 @@ function backtestInput(item) {
|
|
|
650
924
|
}
|
|
651
925
|
return normalized;
|
|
652
926
|
}
|
|
927
|
+
function customIndicatorOf(response) {
|
|
928
|
+
const indicator = response.indicator;
|
|
929
|
+
if (!isJsonObject(indicator) || !indicator.customIndicatorId) {
|
|
930
|
+
throw new NexusTradeApiError(NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
931
|
+
}
|
|
932
|
+
return indicator;
|
|
933
|
+
}
|
|
653
934
|
function operationOf(response) {
|
|
654
935
|
const operation = response.operation;
|
|
655
936
|
if (!isJsonObject(operation)) {
|
|
@@ -662,6 +943,13 @@ export function clientTransport(client) {
|
|
|
662
943
|
return client.transport;
|
|
663
944
|
}
|
|
664
945
|
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
946
|
+
export async function createCustomIndicator(indicator, options) {
|
|
947
|
+
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
948
|
+
return client.createCustomIndicator(indicator, {
|
|
949
|
+
idempotencyKey: options.idempotencyKey,
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
/** Convenience wrapper for scripts that do not need a persistent client. */
|
|
665
953
|
export async function createPortfolio(portfolio, options) {
|
|
666
954
|
const client = options.client ?? NexusTradeClient.fromEnvironment();
|
|
667
955
|
return client.createPortfolio(portfolio, {
|
|
@@ -407,8 +407,6 @@ export declare function universe(source: "ALL_US_STOCKS" | "SP500" | "NASDAQ100"
|
|
|
407
407
|
export declare function universe(source: "SPECIFIC_ASSETS", assets: AssetArg[]): Universe;
|
|
408
408
|
export declare const buy: (target: AssetArg, amount: number, type?: AllocationType) => BuyOrSellAction;
|
|
409
409
|
export declare const sell: (target: AssetArg, amount: number, type?: AllocationType) => BuyOrSellAction;
|
|
410
|
-
export declare const deposit: (amount: number, type?: DepositWithdrawAllocationType) => DepositOrWithdrawAction;
|
|
411
|
-
export declare const withdraw: (amount: number, type?: DepositWithdrawAllocationType) => DepositOrWithdrawAction;
|
|
412
410
|
export declare const alert: (message: string) => AlertAction;
|
|
413
411
|
export declare const launchAgent: (config: {
|
|
414
412
|
planningModel: string;
|
|
@@ -141,8 +141,6 @@ export function universe(source, assets) {
|
|
|
141
141
|
// ---- equity + cash actions ----
|
|
142
142
|
export const buy = (target, amount, type = "percent of portfolio") => ({ type: "Buy", targetAsset: toAsset(target), amount: { type, amount } });
|
|
143
143
|
export const sell = (target, amount, type = "percent of portfolio") => ({ type: "Sell", targetAsset: toAsset(target), amount: { type, amount } });
|
|
144
|
-
export const deposit = (amount, type = "dollars") => ({ type: "Deposit", amount: { type, amount } });
|
|
145
|
-
export const withdraw = (amount, type = "dollars") => ({ type: "Withdraw", amount: { type, amount } });
|
|
146
144
|
export const alert = (message) => ({ type: "Alert", message });
|
|
147
145
|
export const launchAgent = (config) => compact({ type: "LaunchAgent", ...config });
|
|
148
146
|
export const dynamicRebalance = (config) => compact({ type: "DynamicRebalance", ...config });
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { AgentRun } from "./agent.js";
|
|
2
2
|
export type { AgentEvent, AgentRunOptions } from "./agent.js";
|
|
3
|
-
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
|
|
4
|
-
export type { HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, WaitOptions, } from "./client.js";
|
|
3
|
+
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
4
|
+
export type { CustomIndicatorInput, CustomIndicatorPointInput, HttpTransportOptions, JsonObject, JsonValue, ListPortfoliosOptions, NexusTradeClientOptions, RequestOptions, Transport, UploadTransport, WaitOptions, } from "./client.js";
|
|
5
5
|
export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
|
|
6
6
|
export type { DeployOutcome, DeployResult, PortfolioHandleOptions, PortfolioListResult, PortfolioType, } from "./portfolio.js";
|
|
7
7
|
export * from "./generated/ntSdk.generated.js";
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { AgentRun } from "./agent.js";
|
|
2
|
-
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createPortfolio, waitForOperation, } from "./client.js";
|
|
2
|
+
export { HttpTransport, NexusTradeApiError, NexusTradeClient, createCustomIndicator, createPortfolio, waitForOperation, } from "./client.js";
|
|
3
3
|
export { PortfolioHandle, portfolioHandleFromWire, } from "./portfolio.js";
|
|
4
4
|
export * from "./generated/ntSdk.generated.js";
|
package/dist/esm/portfolio.d.ts
CHANGED
|
@@ -3,12 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Keeps the generated `Portfolio` interface as the shape; this class adds
|
|
5
5
|
* lifecycle methods. `toJSON()` omits `id` so request bodies never leak
|
|
6
|
-
* `"id": null`.
|
|
6
|
+
* `"id": null`.
|
|
7
7
|
*
|
|
8
8
|
* Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
|
|
9
9
|
* import this module without a cycle through `client.ts`.
|
|
10
|
-
*
|
|
11
|
-
* See designs/2026-07-26-sdk-portfolio-objects.md.
|
|
12
10
|
*/
|
|
13
11
|
import { type JsonObject, type Transport } from "./client.ts";
|
|
14
12
|
import type { Portfolio, Strategy } from "./generated/ntSdk.generated.js";
|
package/dist/esm/portfolio.js
CHANGED
|
@@ -3,12 +3,10 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Keeps the generated `Portfolio` interface as the shape; this class adds
|
|
5
5
|
* lifecycle methods. `toJSON()` omits `id` so request bodies never leak
|
|
6
|
-
* `"id": null`.
|
|
6
|
+
* `"id": null`.
|
|
7
7
|
*
|
|
8
8
|
* Holds a `Transport` (same pattern as `AgentRun`) so the generated builder can
|
|
9
9
|
* import this module without a cycle through `client.ts`.
|
|
10
|
-
*
|
|
11
|
-
* See designs/2026-07-26-sdk-portfolio-objects.md.
|
|
12
10
|
*/
|
|
13
11
|
import { NexusTradeApiError, NO_HTTP_STATUS, } from "./client.js";
|
|
14
12
|
function isJsonObject(value) {
|