nexustrade 1.0.0 → 1.2.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 +49 -3
- package/README.md +361 -63
- package/dist/cjs/client.js +382 -9
- package/dist/cjs/generated/ntSdk.generated.js +51 -0
- package/dist/esm/client.d.ts +98 -0
- package/dist/esm/client.js +381 -8
- package/dist/esm/generated/ntSdk.generated.d.ts +51 -4
- package/dist/esm/generated/ntSdk.generated.js +47 -0
- package/package.json +1 -1
package/dist/cjs/client.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* pass an API key/base URL, or set NEXUSTRADE_API_KEY / NEXUSTRADE_API_BASE_URL.
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
|
|
9
|
+
exports.NexusTradeClient = exports.HttpTransport = exports.NexusTradeApiError = exports.UPLOAD_PUT_JITTER_SECONDS = exports.UPLOAD_PUT_MAX_BACKOFF_SECONDS = exports.UPLOAD_PUT_INITIAL_BACKOFF_SECONDS = exports.MAX_UPLOAD_PUT_ATTEMPTS = exports.CONNECT_POLL_INTERVAL_SECONDS = exports.DEFAULT_CONNECT_TIMEOUT_SECONDS = exports.POLL_BACKOFF_FACTOR = exports.MAX_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_INTERVAL_SECONDS = exports.DEFAULT_POLL_TIMEOUT_SECONDS = exports.NO_HTTP_STATUS = void 0;
|
|
10
10
|
exports.waitForOperation = waitForOperation;
|
|
11
11
|
exports.clientTransport = clientTransport;
|
|
12
12
|
exports.createCustomIndicator = createCustomIndicator;
|
|
@@ -53,9 +53,33 @@ exports.DEFAULT_POLL_INTERVAL_SECONDS = 2;
|
|
|
53
53
|
exports.MAX_POLL_INTERVAL_SECONDS = 15;
|
|
54
54
|
exports.POLL_BACKOFF_FACTOR = 1.5;
|
|
55
55
|
const TERMINAL_STATUSES = ["cancelled", "completed", "failed"];
|
|
56
|
+
// Connecting a brokerage is a human opening a browser. Long enough for that,
|
|
57
|
+
// short enough that a forgotten terminal does not hang all afternoon.
|
|
58
|
+
exports.DEFAULT_CONNECT_TIMEOUT_SECONDS = 300;
|
|
59
|
+
exports.CONNECT_POLL_INTERVAL_SECONDS = 3;
|
|
60
|
+
function sleep(ms) {
|
|
61
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
62
|
+
}
|
|
63
|
+
/** Whether a human is plausibly watching. Never throws on odd streams. */
|
|
64
|
+
function stdoutIsInteractive() {
|
|
65
|
+
try {
|
|
66
|
+
return process.stdout.isTTY === true;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
56
72
|
// Point batches larger than this are uploaded rather than sent inline.
|
|
57
73
|
const MAX_INLINE_POINT_BYTES = 512 * 1024;
|
|
58
74
|
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
|
75
|
+
// A presigned PUT crosses the open internet with no API-side retry behind it, so
|
|
76
|
+
// the client owns transient recovery. Jittered (unlike the poll backoff) because
|
|
77
|
+
// every client retrying a storage blip on the same schedule is the blip.
|
|
78
|
+
// checkSdkClientParity.ts asserts these match the Python SDK.
|
|
79
|
+
exports.MAX_UPLOAD_PUT_ATTEMPTS = 5;
|
|
80
|
+
exports.UPLOAD_PUT_INITIAL_BACKOFF_SECONDS = 0.5;
|
|
81
|
+
exports.UPLOAD_PUT_MAX_BACKOFF_SECONDS = 8.0;
|
|
82
|
+
exports.UPLOAD_PUT_JITTER_SECONDS = 0.25;
|
|
59
83
|
const POINT_FIELDS = {
|
|
60
84
|
timestamp: "timestamp",
|
|
61
85
|
value: "value",
|
|
@@ -83,6 +107,22 @@ class NexusTradeApiError extends Error {
|
|
|
83
107
|
}
|
|
84
108
|
}
|
|
85
109
|
exports.NexusTradeApiError = NexusTradeApiError;
|
|
110
|
+
function isRetryableUploadHttpStatus(status) {
|
|
111
|
+
return status === 408 || status === 429 || status >= 500;
|
|
112
|
+
}
|
|
113
|
+
/** Only a transport fault or a storage-side transient earns another PUT. */
|
|
114
|
+
function isRetryableUploadError(error) {
|
|
115
|
+
if (!(error instanceof NexusTradeApiError)) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
if (error.code === "transport_error") {
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
if (error.code === "upload_failed" && error.status !== exports.NO_HTTP_STATUS) {
|
|
122
|
+
return isRetryableUploadHttpStatus(error.status);
|
|
123
|
+
}
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
86
126
|
function origin(url) {
|
|
87
127
|
const parsed = new URL(url);
|
|
88
128
|
const scheme = parsed.protocol.replace(":", "").toLowerCase();
|
|
@@ -98,7 +138,7 @@ function sameOrigin(left, right) {
|
|
|
98
138
|
return a.scheme === b.scheme && a.host === b.host && a.port === b.port;
|
|
99
139
|
}
|
|
100
140
|
function supportsBinary(transport) {
|
|
101
|
-
return
|
|
141
|
+
return typeof transport.requestBytes === "function";
|
|
102
142
|
}
|
|
103
143
|
function supportsUpload(transport) {
|
|
104
144
|
return typeof transport.putBytes === "function";
|
|
@@ -184,7 +224,9 @@ function decodeJsonObject(bytes, status) {
|
|
|
184
224
|
catch {
|
|
185
225
|
throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned invalid JSON.");
|
|
186
226
|
}
|
|
187
|
-
if (typeof decoded !== "object" ||
|
|
227
|
+
if (typeof decoded !== "object" ||
|
|
228
|
+
decoded === null ||
|
|
229
|
+
Array.isArray(decoded)) {
|
|
188
230
|
throw new NexusTradeApiError(status, "invalid_response", "NexusTrade returned a non-object JSON response.");
|
|
189
231
|
}
|
|
190
232
|
return decoded;
|
|
@@ -211,6 +253,23 @@ class HttpTransport {
|
|
|
211
253
|
}
|
|
212
254
|
/** PUT a payload to a presigned storage URL. Sends no credential. */
|
|
213
255
|
async putBytes(url, data, options) {
|
|
256
|
+
let delaySeconds = exports.UPLOAD_PUT_INITIAL_BACKOFF_SECONDS;
|
|
257
|
+
for (let attempt = 0; attempt < exports.MAX_UPLOAD_PUT_ATTEMPTS; attempt++) {
|
|
258
|
+
try {
|
|
259
|
+
await this.#putBytesOnce(url, data, options);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
catch (error) {
|
|
263
|
+
if (attempt >= exports.MAX_UPLOAD_PUT_ATTEMPTS - 1 ||
|
|
264
|
+
!isRetryableUploadError(error)) {
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
delaySeconds = Math.min(delaySeconds * 2, exports.UPLOAD_PUT_MAX_BACKOFF_SECONDS);
|
|
269
|
+
await sleep((delaySeconds + Math.random() * exports.UPLOAD_PUT_JITTER_SECONDS) * 1000);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async #putBytesOnce(url, data, options) {
|
|
214
273
|
let parsed;
|
|
215
274
|
try {
|
|
216
275
|
parsed = new URL(url);
|
|
@@ -404,6 +463,129 @@ function customIndicatorPoints(points) {
|
|
|
404
463
|
}
|
|
405
464
|
return points.map(customIndicatorPoint);
|
|
406
465
|
}
|
|
466
|
+
function dateOnly(value) {
|
|
467
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
|
468
|
+
return undefined;
|
|
469
|
+
}
|
|
470
|
+
const parsed = new Date(`${value}T00:00:00.000Z`);
|
|
471
|
+
return Number.isNaN(parsed.getTime()) ||
|
|
472
|
+
parsed.toISOString().slice(0, 10) !== value
|
|
473
|
+
? undefined
|
|
474
|
+
: parsed;
|
|
475
|
+
}
|
|
476
|
+
function utcMidnight(day) {
|
|
477
|
+
return `${day.toISOString().slice(0, 10)}T00:00:00.000Z`;
|
|
478
|
+
}
|
|
479
|
+
function utcDateTime(value) {
|
|
480
|
+
const day = dateOnly(value);
|
|
481
|
+
if (day)
|
|
482
|
+
return day;
|
|
483
|
+
if (typeof value !== "string")
|
|
484
|
+
return undefined;
|
|
485
|
+
const hasExplicitZone = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/i.test(value);
|
|
486
|
+
if (!hasExplicitZone)
|
|
487
|
+
return undefined;
|
|
488
|
+
const parsed = new Date(value);
|
|
489
|
+
return Number.isNaN(parsed.getTime()) ? undefined : parsed;
|
|
490
|
+
}
|
|
491
|
+
function addUtcDays(day, days) {
|
|
492
|
+
return new Date(Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate() + days));
|
|
493
|
+
}
|
|
494
|
+
function pointKindPoints(points, pointKind, aggregatePeriod) {
|
|
495
|
+
if (!pointKind) {
|
|
496
|
+
if (aggregatePeriod) {
|
|
497
|
+
throw new Error("aggregatePeriod requires pointKind period_aggregate.");
|
|
498
|
+
}
|
|
499
|
+
return points;
|
|
500
|
+
}
|
|
501
|
+
if (pointKind !== "period_aggregate" && aggregatePeriod) {
|
|
502
|
+
throw new Error("aggregatePeriod is only valid for period_aggregate.");
|
|
503
|
+
}
|
|
504
|
+
if (pointKind === "period_aggregate" && !aggregatePeriod) {
|
|
505
|
+
throw new Error("period_aggregate requires aggregatePeriod.");
|
|
506
|
+
}
|
|
507
|
+
return points.map((point, index) => {
|
|
508
|
+
const row = { ...point };
|
|
509
|
+
const eventDay = dateOnly(row.timestamp);
|
|
510
|
+
const availableDay = dateOnly(row.availableAt);
|
|
511
|
+
const eventTime = utcDateTime(row.timestamp);
|
|
512
|
+
const availableTime = utcDateTime(row.availableAt);
|
|
513
|
+
if (pointKind === "observation") {
|
|
514
|
+
if (row.availableAt === undefined) {
|
|
515
|
+
row.availableAt = eventDay ? utcMidnight(eventDay) : row.timestamp;
|
|
516
|
+
}
|
|
517
|
+
else if (eventDay && availableDay?.getTime() === eventDay.getTime()) {
|
|
518
|
+
row.availableAt = utcMidnight(eventDay);
|
|
519
|
+
}
|
|
520
|
+
else if (availableDay) {
|
|
521
|
+
row.availableAt = utcMidnight(addUtcDays(availableDay, 1));
|
|
522
|
+
}
|
|
523
|
+
if (eventTime &&
|
|
524
|
+
availableTime &&
|
|
525
|
+
availableTime.toISOString().slice(0, 10) >
|
|
526
|
+
eventTime.toISOString().slice(0, 10)) {
|
|
527
|
+
throw new Error(`Point ${index + 1}: observation availableAt is after the event date.`);
|
|
528
|
+
}
|
|
529
|
+
return row;
|
|
530
|
+
}
|
|
531
|
+
if (pointKind === "disclosed") {
|
|
532
|
+
if (row.availableAt === undefined) {
|
|
533
|
+
throw new Error(`Point ${index + 1}: disclosed pointKind requires availableAt.`);
|
|
534
|
+
}
|
|
535
|
+
if (availableDay) {
|
|
536
|
+
row.availableAt = utcMidnight(addUtcDays(availableDay, 1));
|
|
537
|
+
}
|
|
538
|
+
return row;
|
|
539
|
+
}
|
|
540
|
+
if (!eventTime) {
|
|
541
|
+
throw new Error(`Point ${index + 1}: aggregate timestamp must be date-only or include an explicit UTC offset.`);
|
|
542
|
+
}
|
|
543
|
+
if (eventTime.getUTCHours() !== 0 ||
|
|
544
|
+
eventTime.getUTCMinutes() !== 0 ||
|
|
545
|
+
eventTime.getUTCSeconds() !== 0 ||
|
|
546
|
+
eventTime.getUTCMilliseconds() !== 0) {
|
|
547
|
+
throw new Error(`Point ${index + 1}: aggregate timestamp must be UTC midnight.`);
|
|
548
|
+
}
|
|
549
|
+
let periodEnd;
|
|
550
|
+
if (aggregatePeriod === "1d") {
|
|
551
|
+
periodEnd = addUtcDays(eventTime, 1);
|
|
552
|
+
}
|
|
553
|
+
else if (aggregatePeriod === "1w") {
|
|
554
|
+
if (eventTime.getUTCDay() !== 1) {
|
|
555
|
+
throw new Error(`Point ${index + 1}: 1w timestamp must be a Monday.`);
|
|
556
|
+
}
|
|
557
|
+
periodEnd = addUtcDays(eventTime, 7);
|
|
558
|
+
}
|
|
559
|
+
else if (aggregatePeriod === "1mo") {
|
|
560
|
+
if (eventTime.getUTCDate() !== 1) {
|
|
561
|
+
throw new Error(`Point ${index + 1}: 1mo timestamp must be month start.`);
|
|
562
|
+
}
|
|
563
|
+
periodEnd = new Date(Date.UTC(eventTime.getUTCFullYear(), eventTime.getUTCMonth() + 1, 1));
|
|
564
|
+
}
|
|
565
|
+
else {
|
|
566
|
+
if (eventTime.getUTCDate() !== 1 ||
|
|
567
|
+
![0, 3, 6, 9].includes(eventTime.getUTCMonth())) {
|
|
568
|
+
throw new Error(`Point ${index + 1}: 1q timestamp must be quarter start.`);
|
|
569
|
+
}
|
|
570
|
+
periodEnd = new Date(Date.UTC(eventTime.getUTCFullYear(), eventTime.getUTCMonth() + 3, 1));
|
|
571
|
+
}
|
|
572
|
+
const derived = utcMidnight(periodEnd);
|
|
573
|
+
if (row.availableAt === undefined) {
|
|
574
|
+
row.availableAt = derived;
|
|
575
|
+
}
|
|
576
|
+
else if (availableDay) {
|
|
577
|
+
const explicit = utcMidnight(addUtcDays(availableDay, 1));
|
|
578
|
+
if (explicit < derived) {
|
|
579
|
+
throw new Error(`Point ${index + 1}: availableAt precedes the aggregate close.`);
|
|
580
|
+
}
|
|
581
|
+
row.availableAt = explicit;
|
|
582
|
+
}
|
|
583
|
+
else if (availableTime && availableTime.getTime() < periodEnd.getTime()) {
|
|
584
|
+
throw new Error(`Point ${index + 1}: availableAt precedes the aggregate close.`);
|
|
585
|
+
}
|
|
586
|
+
return row;
|
|
587
|
+
});
|
|
588
|
+
}
|
|
407
589
|
function pointsJsonl(points) {
|
|
408
590
|
return new TextEncoder().encode(points.map((point) => `${JSON.stringify(point)}\n`).join(""));
|
|
409
591
|
}
|
|
@@ -590,21 +772,25 @@ class NexusTradeClient {
|
|
|
590
772
|
* than creating a second one.
|
|
591
773
|
*/
|
|
592
774
|
async createCustomIndicator(indicator, options) {
|
|
593
|
-
const { name, description, scope, points, ...rest } = indicator;
|
|
775
|
+
const { name, description, scope, pointKind, aggregatePeriod, points, ...rest } = indicator;
|
|
594
776
|
if (typeof name !== "string" || !name.trim()) {
|
|
595
777
|
throw new Error("createCustomIndicator requires a name.");
|
|
596
778
|
}
|
|
597
779
|
const unknown = Object.keys(rest);
|
|
598
780
|
if (unknown.length > 0) {
|
|
599
781
|
throw new Error(`Unknown custom indicator field(s): ${unknown.sort().join(", ")}. ` +
|
|
600
|
-
"Expected name, description, scope, and points.");
|
|
782
|
+
"Expected name, description, scope, pointKind, aggregatePeriod, and points.");
|
|
601
783
|
}
|
|
602
|
-
const normalized = points ? customIndicatorPoints(points) : [];
|
|
784
|
+
const normalized = pointKindPoints(points ? customIndicatorPoints(points) : [], pointKind, aggregatePeriod);
|
|
603
785
|
const body = { name: name.trim() };
|
|
604
786
|
if (description !== undefined)
|
|
605
787
|
body.description = description;
|
|
606
788
|
if (scope !== undefined)
|
|
607
789
|
body.scope = scope;
|
|
790
|
+
if (pointKind !== undefined)
|
|
791
|
+
body.pointKind = pointKind;
|
|
792
|
+
if (aggregatePeriod !== undefined)
|
|
793
|
+
body.aggregatePeriod = aggregatePeriod;
|
|
608
794
|
const inline = normalized.length > 0 &&
|
|
609
795
|
inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES;
|
|
610
796
|
if (inline)
|
|
@@ -655,12 +841,21 @@ class NexusTradeClient {
|
|
|
655
841
|
* uploaded depending on how large it is.
|
|
656
842
|
*/
|
|
657
843
|
async appendCustomIndicatorPoints(customIndicatorId, points, options) {
|
|
658
|
-
const normalized = customIndicatorPoints(points);
|
|
844
|
+
const normalized = pointKindPoints(customIndicatorPoints(points), options.pointKind, options.aggregatePeriod);
|
|
659
845
|
if (normalized.length === 0) {
|
|
660
846
|
throw new Error("appendCustomIndicatorPoints needs at least one point.");
|
|
661
847
|
}
|
|
662
848
|
if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
|
|
663
|
-
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, {
|
|
849
|
+
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, {
|
|
850
|
+
body: {
|
|
851
|
+
points: normalized,
|
|
852
|
+
...(options.pointKind ? { pointKind: options.pointKind } : {}),
|
|
853
|
+
...(options.aggregatePeriod
|
|
854
|
+
? { aggregatePeriod: options.aggregatePeriod }
|
|
855
|
+
: {}),
|
|
856
|
+
},
|
|
857
|
+
idempotencyKey: options.idempotencyKey,
|
|
858
|
+
});
|
|
664
859
|
const indicator = response.indicator;
|
|
665
860
|
if (!isJsonObject(indicator)) {
|
|
666
861
|
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator response is missing indicator.");
|
|
@@ -673,6 +868,43 @@ class NexusTradeClient {
|
|
|
673
868
|
upload,
|
|
674
869
|
};
|
|
675
870
|
}
|
|
871
|
+
/** Replace the complete series while retaining the same CustomIndicator id. */
|
|
872
|
+
async replaceCustomIndicatorPoints(customIndicatorId, points, options) {
|
|
873
|
+
const normalized = pointKindPoints(customIndicatorPoints(points), options.pointKind, options.aggregatePeriod);
|
|
874
|
+
if (normalized.length === 0) {
|
|
875
|
+
throw new Error("replaceCustomIndicatorPoints needs at least one point.");
|
|
876
|
+
}
|
|
877
|
+
if (inlinePointBytes(normalized) <= MAX_INLINE_POINT_BYTES) {
|
|
878
|
+
return customIndicatorOf(await this.transport.request("PUT", `custom-indicators/${encodePathSegment(customIndicatorId)}/points`, {
|
|
879
|
+
body: {
|
|
880
|
+
points: normalized,
|
|
881
|
+
allowShrink: options.allowShrink === true,
|
|
882
|
+
...(options.pointKind ? { pointKind: options.pointKind } : {}),
|
|
883
|
+
...(options.aggregatePeriod
|
|
884
|
+
? { aggregatePeriod: options.aggregatePeriod }
|
|
885
|
+
: {}),
|
|
886
|
+
},
|
|
887
|
+
idempotencyKey: options.idempotencyKey,
|
|
888
|
+
}));
|
|
889
|
+
}
|
|
890
|
+
const upload = await this.uploadCustomIndicatorPoints(customIndicatorId, normalized, options.idempotencyKey, { mode: "replace", allowShrink: options.allowShrink === true });
|
|
891
|
+
return {
|
|
892
|
+
...(await this.getCustomIndicator(customIndicatorId)),
|
|
893
|
+
upload,
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
/** Soft-archive a CustomIndicator. Pass confirm when active portfolios use it. */
|
|
897
|
+
async archiveCustomIndicator(customIndicatorId, options = {}) {
|
|
898
|
+
const response = await this.transport.request("DELETE", `custom-indicators/${encodePathSegment(customIndicatorId)}`, { body: { confirm: options.confirm === true } });
|
|
899
|
+
if (!isJsonObject(response.archive)) {
|
|
900
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Custom indicator archive response is missing archive details.");
|
|
901
|
+
}
|
|
902
|
+
return response.archive;
|
|
903
|
+
}
|
|
904
|
+
/** Restore a soft-archived CustomIndicator. */
|
|
905
|
+
async restoreCustomIndicator(customIndicatorId) {
|
|
906
|
+
return customIndicatorOf(await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/restore`, { body: {} }));
|
|
907
|
+
}
|
|
676
908
|
/**
|
|
677
909
|
* Open an upload slot and return a presigned `uploadUrl` to PUT to.
|
|
678
910
|
*
|
|
@@ -695,6 +927,10 @@ class NexusTradeClient {
|
|
|
695
927
|
body.contentType = options.contentType;
|
|
696
928
|
if (options.sizeBytes !== undefined)
|
|
697
929
|
body.sizeBytes = options.sizeBytes;
|
|
930
|
+
if (options.mode !== undefined)
|
|
931
|
+
body.mode = options.mode;
|
|
932
|
+
if (options.allowShrink !== undefined)
|
|
933
|
+
body.allowShrink = options.allowShrink;
|
|
698
934
|
const response = await this.transport.request("POST", `custom-indicators/${encodePathSegment(customIndicatorId)}/uploads`, { body, idempotencyKey: options.idempotencyKey });
|
|
699
935
|
const ticket = response.ticket;
|
|
700
936
|
if (!isJsonObject(ticket) || !ticket.jobId) {
|
|
@@ -716,7 +952,7 @@ class NexusTradeClient {
|
|
|
716
952
|
async waitForCustomIndicatorUpload(customIndicatorId, jobId, options = {}) {
|
|
717
953
|
return waitForOperation((pendingId) => this.getCustomIndicatorUpload(customIndicatorId, pendingId), jobId, options);
|
|
718
954
|
}
|
|
719
|
-
async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey) {
|
|
955
|
+
async uploadCustomIndicatorPoints(customIndicatorId, points, idempotencyKey, options = {}) {
|
|
720
956
|
const payload = pointsJsonl(points);
|
|
721
957
|
if (payload.length > MAX_UPLOAD_BYTES) {
|
|
722
958
|
throw new Error(`${points.length} points serialize to ` +
|
|
@@ -731,6 +967,8 @@ class NexusTradeClient {
|
|
|
731
967
|
format: "jsonl",
|
|
732
968
|
sizeBytes: payload.length,
|
|
733
969
|
idempotencyKey,
|
|
970
|
+
mode: options.mode,
|
|
971
|
+
allowShrink: options.allowShrink,
|
|
734
972
|
});
|
|
735
973
|
const jobId = String(ticket.jobId);
|
|
736
974
|
// No upload URL means this batch already reached the server on an earlier
|
|
@@ -747,6 +985,97 @@ class NexusTradeClient {
|
|
|
747
985
|
}
|
|
748
986
|
return this.waitForCustomIndicatorUpload(customIndicatorId, jobId);
|
|
749
987
|
}
|
|
988
|
+
/**
|
|
989
|
+
* Every connectable brokerage and whether this account has linked it.
|
|
990
|
+
*
|
|
991
|
+
* Reports all of them, connected or not, each with a `connectUrl` — an empty
|
|
992
|
+
* result would say nothing about what to do next.
|
|
993
|
+
*/
|
|
994
|
+
async listBrokerages() {
|
|
995
|
+
const response = await this.transport.request("GET", "brokerages");
|
|
996
|
+
const brokerages = response.brokerages;
|
|
997
|
+
if (!Array.isArray(brokerages)) {
|
|
998
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerages.");
|
|
999
|
+
}
|
|
1000
|
+
return brokerages.filter((row) => isJsonObject(row));
|
|
1001
|
+
}
|
|
1002
|
+
/** Whether one named brokerage is connected. */
|
|
1003
|
+
async getBrokerage(brokerage) {
|
|
1004
|
+
const response = await this.transport.request("GET", `brokerages/${encodePathSegment(brokerage)}`);
|
|
1005
|
+
const result = response.brokerage;
|
|
1006
|
+
if (!isJsonObject(result)) {
|
|
1007
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "invalid_response", "Brokerage response is missing brokerage.");
|
|
1008
|
+
}
|
|
1009
|
+
return result;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* Resolve once the brokerage is connected, logging where to connect it.
|
|
1013
|
+
*
|
|
1014
|
+
* Linking a brokerage is an OAuth redirect, so an API key cannot complete it
|
|
1015
|
+
* — a human has to open the URL. What this does is make that unmissable and
|
|
1016
|
+
* then wait for it.
|
|
1017
|
+
*
|
|
1018
|
+
* `wait` defaults to whether stdout is a TTY. Interactively it logs the URL
|
|
1019
|
+
* and polls until the link appears. Non-interactively — CI, cron, a piped
|
|
1020
|
+
* script — it rejects with `brokerage_not_connected` at once rather than
|
|
1021
|
+
* stalling for the timeout in front of nobody. Pass `wait` to override.
|
|
1022
|
+
*/
|
|
1023
|
+
async connectBrokerage(brokerage, options = {}) {
|
|
1024
|
+
let current = await this.getBrokerage(brokerage);
|
|
1025
|
+
if (current.connected === true)
|
|
1026
|
+
return current;
|
|
1027
|
+
const connectUrl = String(current.connectUrl ?? "");
|
|
1028
|
+
const message = `${brokerage} is not connected. Connect it at ${connectUrl} — ` +
|
|
1029
|
+
"linking a brokerage is a browser flow an API key cannot complete.";
|
|
1030
|
+
const shouldWait = options.wait ?? stdoutIsInteractive();
|
|
1031
|
+
if (!shouldWait) {
|
|
1032
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "brokerage_not_connected", message);
|
|
1033
|
+
}
|
|
1034
|
+
const timeoutSeconds = options.timeoutSeconds ?? exports.DEFAULT_CONNECT_TIMEOUT_SECONDS;
|
|
1035
|
+
const pollSeconds = options.pollIntervalSeconds ?? exports.CONNECT_POLL_INTERVAL_SECONDS;
|
|
1036
|
+
console.log(message);
|
|
1037
|
+
console.log(`Waiting for ${brokerage} to be connected…`);
|
|
1038
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
1039
|
+
for (;;) {
|
|
1040
|
+
const remaining = deadline - Date.now();
|
|
1041
|
+
if (remaining <= 0) {
|
|
1042
|
+
throw new NexusTradeApiError(exports.NO_HTTP_STATUS, "brokerage_not_connected", `${brokerage} was still not connected after ${timeoutSeconds}s. ${message}`);
|
|
1043
|
+
}
|
|
1044
|
+
await sleep(Math.min(pollSeconds * 1000, remaining));
|
|
1045
|
+
current = await this.getBrokerage(brokerage);
|
|
1046
|
+
if (current.connected === true) {
|
|
1047
|
+
console.log(`${brokerage} connected.`);
|
|
1048
|
+
return current;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Stage orders against a portfolio.
|
|
1054
|
+
*
|
|
1055
|
+
* **Paper orders are accepted immediately. Live orders are staged for
|
|
1056
|
+
* approval and are never sent to a broker by this call.** A live response
|
|
1057
|
+
* carries `requiresApproval: true` and an `approvalUrl`; nothing has traded
|
|
1058
|
+
* until a human approves it there. No argument changes that.
|
|
1059
|
+
*
|
|
1060
|
+
* ```ts
|
|
1061
|
+
* const result = await client.createOrders(
|
|
1062
|
+
* portfolioId,
|
|
1063
|
+
* [{ asset: { name: "SPY", type: "STOCK", symbol: "SPY" },
|
|
1064
|
+
* side: "BUY", quantity: 10, orderType: "MARKET" }],
|
|
1065
|
+
* { idempotencyKey: "rebalance-2024-04-01" },
|
|
1066
|
+
* );
|
|
1067
|
+
* if (result.requiresApproval) console.log("approve at", result.approvalUrl);
|
|
1068
|
+
* ```
|
|
1069
|
+
*/
|
|
1070
|
+
async createOrders(portfolioId, orders, options) {
|
|
1071
|
+
if (!Array.isArray(orders) || orders.length === 0) {
|
|
1072
|
+
throw new Error("createOrders needs at least one order.");
|
|
1073
|
+
}
|
|
1074
|
+
return this.transport.request("POST", "orders", {
|
|
1075
|
+
body: { portfolioId, orders: orders.map((order) => ({ ...order })) },
|
|
1076
|
+
idempotencyKey: options.idempotencyKey,
|
|
1077
|
+
});
|
|
1078
|
+
}
|
|
750
1079
|
async createBacktests(backtests, options) {
|
|
751
1080
|
const inputs = backtests.map((item) => backtestInput(asJsonObject(item)));
|
|
752
1081
|
const response = await this.transport.request("POST", "backtests/batch", {
|
|
@@ -842,6 +1171,50 @@ class NexusTradeClient {
|
|
|
842
1171
|
async cancelLakeQuery(queryId) {
|
|
843
1172
|
return operationOf(await this.transport.request("POST", `lake/queries/${encodePathSegment(queryId)}/cancel`));
|
|
844
1173
|
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Submit a natural-language stock screen. Returns immediately; poll it.
|
|
1176
|
+
*
|
|
1177
|
+
* `returnQuery` keeps the generated SQL, engine and catalog version on the
|
|
1178
|
+
* result. It defaults on: the SQL is the audit trail, and without it the rows
|
|
1179
|
+
* are a number nobody can re-derive. It is returned on failure regardless,
|
|
1180
|
+
* because a rejected query is the most useful thing to read.
|
|
1181
|
+
*/
|
|
1182
|
+
async createNlScreen(question, options = {}) {
|
|
1183
|
+
return operationOf(await this.transport.request("POST", "nl/screens", {
|
|
1184
|
+
body: {
|
|
1185
|
+
question,
|
|
1186
|
+
returnQuery: options.returnQuery ?? true,
|
|
1187
|
+
},
|
|
1188
|
+
}));
|
|
1189
|
+
}
|
|
1190
|
+
async getNlScreen(screenId) {
|
|
1191
|
+
return operationOf(await this.transport.request("GET", `nl/screens/${encodePathSegment(screenId)}`));
|
|
1192
|
+
}
|
|
1193
|
+
async cancelNlScreen(screenId) {
|
|
1194
|
+
return operationOf(await this.transport.request("POST", `nl/screens/${encodePathSegment(screenId)}/cancel`));
|
|
1195
|
+
}
|
|
1196
|
+
/** Block until a screen is terminal. See `waitForOperation`. */
|
|
1197
|
+
async waitForNlScreen(screenId, options = {}) {
|
|
1198
|
+
return waitForOperation((id) => this.getNlScreen(id), screenId, options);
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* Submit a natural-language lake ask. Returns immediately; poll it.
|
|
1202
|
+
*/
|
|
1203
|
+
async createLakeAsk(question) {
|
|
1204
|
+
return operationOf(await this.transport.request("POST", "lake/ask", {
|
|
1205
|
+
body: { question },
|
|
1206
|
+
}));
|
|
1207
|
+
}
|
|
1208
|
+
async getLakeAsk(askId) {
|
|
1209
|
+
return operationOf(await this.transport.request("GET", `lake/ask/${encodePathSegment(askId)}`));
|
|
1210
|
+
}
|
|
1211
|
+
async cancelLakeAsk(askId) {
|
|
1212
|
+
return operationOf(await this.transport.request("POST", `lake/ask/${encodePathSegment(askId)}/cancel`));
|
|
1213
|
+
}
|
|
1214
|
+
/** Block until a lake ask is terminal. See `waitForOperation`. */
|
|
1215
|
+
async waitForLakeAsk(askId, options = {}) {
|
|
1216
|
+
return waitForOperation((id) => this.getLakeAsk(id), askId, options);
|
|
1217
|
+
}
|
|
845
1218
|
async getLakeQueryManifest(queryId) {
|
|
846
1219
|
return operationOf(await this.transport.request("GET", `lake/queries/${encodePathSegment(queryId)}/manifest`));
|
|
847
1220
|
}
|
|
@@ -37,6 +37,7 @@ exports.Fundamental = Fundamental;
|
|
|
37
37
|
exports.GapPercentage = GapPercentage;
|
|
38
38
|
exports.GapSize = GapSize;
|
|
39
39
|
exports.HighOfDay = HighOfDay;
|
|
40
|
+
exports.ImpliedVolatility = ImpliedVolatility;
|
|
40
41
|
exports.Index = Index;
|
|
41
42
|
exports.IndicatorAtMinutesAfterOpen = IndicatorAtMinutesAfterOpen;
|
|
42
43
|
exports.IndicatorExponentialMovingAverage = IndicatorExponentialMovingAverage;
|
|
@@ -51,6 +52,9 @@ exports.IsAssetType = IsAssetType;
|
|
|
51
52
|
exports.IsIndexMember = IsIndexMember;
|
|
52
53
|
exports.IsIndustry = IsIndustry;
|
|
53
54
|
exports.IsNotAsset = IsNotAsset;
|
|
55
|
+
exports.IVHVRatio = IVHVRatio;
|
|
56
|
+
exports.IVPercentile = IVPercentile;
|
|
57
|
+
exports.IVRank = IVRank;
|
|
54
58
|
exports.LastOrderPrice = LastOrderPrice;
|
|
55
59
|
exports.Log = Log;
|
|
56
60
|
exports.LowOfDay = LowOfDay;
|
|
@@ -316,6 +320,7 @@ const leg = (config) => {
|
|
|
316
320
|
expirationRange: config.expirationRange,
|
|
317
321
|
ratio: config.ratio,
|
|
318
322
|
greekFilter: config.greekFilter,
|
|
323
|
+
liquidityFilter: config.liquidityFilter,
|
|
319
324
|
});
|
|
320
325
|
};
|
|
321
326
|
exports.leg = leg;
|
|
@@ -689,6 +694,17 @@ function HighOfDay(asset) {
|
|
|
689
694
|
setAsset(d, "targetAsset", asset);
|
|
690
695
|
return d;
|
|
691
696
|
}
|
|
697
|
+
/**
|
|
698
|
+
* ImpliedVolatility indicator.
|
|
699
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
700
|
+
* @param dte Target constant-maturity tenor in calendar days (e.g. 30)
|
|
701
|
+
*/
|
|
702
|
+
function ImpliedVolatility(asset, dte = 30) {
|
|
703
|
+
const d = { type: "ImpliedVolatility" };
|
|
704
|
+
setAsset(d, "targetAsset", asset);
|
|
705
|
+
d["dte"] = dte;
|
|
706
|
+
return d;
|
|
707
|
+
}
|
|
692
708
|
/**
|
|
693
709
|
* Index indicator.
|
|
694
710
|
* @param metric Ticker key matching hydrated index price data (add more in BigQuery + rehydrate as needed)
|
|
@@ -836,6 +852,41 @@ function IsNotAsset(matchAsset, asset) {
|
|
|
836
852
|
setAsset(d, "targetAsset", asset);
|
|
837
853
|
return d;
|
|
838
854
|
}
|
|
855
|
+
/**
|
|
856
|
+
* IVHVRatio indicator.
|
|
857
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
858
|
+
* @param hvWindow Trading days of log-return history for realized volatility
|
|
859
|
+
*/
|
|
860
|
+
function IVHVRatio(asset, hvWindow = 20) {
|
|
861
|
+
const d = { type: "IVHVRatio" };
|
|
862
|
+
setAsset(d, "targetAsset", asset);
|
|
863
|
+
d["hvWindow"] = hvWindow;
|
|
864
|
+
return d;
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* IVPercentile indicator.
|
|
868
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
869
|
+
* @param length Length of time
|
|
870
|
+
* @param interval Unit of time
|
|
871
|
+
*/
|
|
872
|
+
function IVPercentile(asset, length = 252, interval = "Day") {
|
|
873
|
+
const d = { type: "IVPercentile" };
|
|
874
|
+
setAsset(d, "targetAsset", asset);
|
|
875
|
+
d.window = { length: length, interval: interval };
|
|
876
|
+
return d;
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* IVRank indicator.
|
|
880
|
+
* @param asset Ticker name (ex. SPY, BTC)
|
|
881
|
+
* @param length Length of time
|
|
882
|
+
* @param interval Unit of time
|
|
883
|
+
*/
|
|
884
|
+
function IVRank(asset, length = 252, interval = "Day") {
|
|
885
|
+
const d = { type: "IVRank" };
|
|
886
|
+
setAsset(d, "targetAsset", asset);
|
|
887
|
+
d.window = { length: length, interval: interval };
|
|
888
|
+
return d;
|
|
889
|
+
}
|
|
839
890
|
/**
|
|
840
891
|
* LastOrderPrice indicator.
|
|
841
892
|
* @param asset Ticker name (ex. SPY, BTC)
|