@stxapp/stx-typescript 0.6.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/CHANGELOG.md +16 -0
- package/LICENSE +21 -0
- package/README.md +79 -0
- package/dist/chunk-R664LTIB.cjs +2774 -0
- package/dist/chunk-R664LTIB.cjs.map +1 -0
- package/dist/chunk-U3KT3I43.js +2774 -0
- package/dist/chunk-U3KT3I43.js.map +1 -0
- package/dist/client-5n7RRquU.d.cts +3355 -0
- package/dist/client-5n7RRquU.d.ts +3355 -0
- package/dist/index.cjs +121 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +55 -0
- package/dist/index.d.ts +55 -0
- package/dist/index.js +121 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth.cjs +967 -0
- package/dist/oauth.cjs.map +1 -0
- package/dist/oauth.d.cts +644 -0
- package/dist/oauth.d.ts +644 -0
- package/dist/oauth.js +967 -0
- package/dist/oauth.js.map +1 -0
- package/package.json +93 -0
|
@@ -0,0 +1,2774 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5;// src/enums.ts
|
|
2
|
+
var Region = {
|
|
3
|
+
US: "us",
|
|
4
|
+
ONTARIO: "ontario"
|
|
5
|
+
};
|
|
6
|
+
var Environment = {
|
|
7
|
+
PRODUCTION: "production",
|
|
8
|
+
DEMO: "demo"
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// src/geo.ts
|
|
12
|
+
var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
|
|
13
|
+
function geoRejection(message) {
|
|
14
|
+
const ip = IP_NOT_ALLOWED.exec(message);
|
|
15
|
+
if (ip) return { reason: "ip_not_allowed", ipAddress: ip[1] };
|
|
16
|
+
if (/geo location check was not done by this user|unknown user in geocomply/i.test(message)) {
|
|
17
|
+
return { reason: "packet_other_user" };
|
|
18
|
+
}
|
|
19
|
+
if (/IP address doesn't match geo location/i.test(message)) {
|
|
20
|
+
return { reason: "packet_ip_mismatch" };
|
|
21
|
+
}
|
|
22
|
+
if (/geo ?location package is invalid|geocomply location response|unable to find expected tag/i.test(message)) {
|
|
23
|
+
return { reason: "packet_invalid" };
|
|
24
|
+
}
|
|
25
|
+
if (/invalid geo ?location|geo[- ]?(location|fenc)/i.test(message)) {
|
|
26
|
+
return { reason: "location_not_allowed" };
|
|
27
|
+
}
|
|
28
|
+
return void 0;
|
|
29
|
+
}
|
|
30
|
+
async function resolveGeoLocation(provider) {
|
|
31
|
+
if (provider === void 0 || provider === null) return void 0;
|
|
32
|
+
const value = typeof provider === "function" ? await provider() : provider;
|
|
33
|
+
return value === null || value === void 0 || value === "" ? void 0 : value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/exceptions.ts
|
|
37
|
+
var STXException = class extends Error {
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
constructor(message, opts = {}) {
|
|
43
|
+
super(message, opts.cause === void 0 ? void 0 : { cause: opts.cause });
|
|
44
|
+
this.name = new.target.name;
|
|
45
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
46
|
+
this.statusCode = opts.statusCode;
|
|
47
|
+
this.body = opts.body;
|
|
48
|
+
this.method = opts.method;
|
|
49
|
+
this.path = opts.path;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var STXConfigException = class extends STXException {
|
|
53
|
+
};
|
|
54
|
+
var STXAPIException = class extends STXException {
|
|
55
|
+
};
|
|
56
|
+
var STXValidationException = class extends STXAPIException {
|
|
57
|
+
};
|
|
58
|
+
var STXAuthenticationException = class extends STXAPIException {
|
|
59
|
+
};
|
|
60
|
+
var STXForbiddenException = class extends STXAPIException {
|
|
61
|
+
|
|
62
|
+
constructor(message, opts = {}) {
|
|
63
|
+
super(message, opts);
|
|
64
|
+
this.requiredScopes = _nullishCoalesce(opts.requiredScopes, () => ( []));
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var STXInvalidTokenException = class extends STXAuthenticationException {
|
|
68
|
+
};
|
|
69
|
+
var STXInsufficientScopeException = class extends STXForbiddenException {
|
|
70
|
+
};
|
|
71
|
+
var STXNotFoundException = class extends STXAPIException {
|
|
72
|
+
};
|
|
73
|
+
var STXRejectedException = class extends STXAPIException {
|
|
74
|
+
};
|
|
75
|
+
var STXGeoLocationException = class extends STXRejectedException {
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
constructor(message, rejection, opts = {}) {
|
|
79
|
+
super(message, opts);
|
|
80
|
+
this.reason = rejection.reason;
|
|
81
|
+
this.ipAddress = rejection.ipAddress;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
var STXRateLimitException = class extends STXAPIException {
|
|
85
|
+
|
|
86
|
+
constructor(message, opts = {}) {
|
|
87
|
+
super(message, opts);
|
|
88
|
+
this.retryAfter = opts.retryAfter;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
var STXServerException = class extends STXAPIException {
|
|
92
|
+
};
|
|
93
|
+
var STXTransportException = class extends STXException {
|
|
94
|
+
};
|
|
95
|
+
var STXChannelException = class extends STXException {
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
constructor(message, opts = {}) {
|
|
99
|
+
super(message);
|
|
100
|
+
this.topic = _nullishCoalesce(opts.topic, () => ( ""));
|
|
101
|
+
this.reply = opts.reply;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The server's refusal reason, e.g. `unauthorized` (the topic is not yours)
|
|
105
|
+
* or `insufficient_scope` (an OAuth token lacks the scope the topic needs).
|
|
106
|
+
*/
|
|
107
|
+
get reason() {
|
|
108
|
+
const r = this.reply;
|
|
109
|
+
if (r && typeof r === "object" && typeof r.reason === "string") {
|
|
110
|
+
return r.reason;
|
|
111
|
+
}
|
|
112
|
+
return void 0;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
var STXTimeoutException = class extends STXChannelException {
|
|
116
|
+
};
|
|
117
|
+
function errorForStatus(statusCode, body, opts) {
|
|
118
|
+
let message;
|
|
119
|
+
if (body && typeof body === "object" && typeof body.error === "string") {
|
|
120
|
+
message = body.error;
|
|
121
|
+
} else if (typeof body === "string" && body.trim()) {
|
|
122
|
+
message = body.trim().slice(0, 500);
|
|
123
|
+
} else {
|
|
124
|
+
message = `HTTP ${statusCode}`;
|
|
125
|
+
}
|
|
126
|
+
const base = { statusCode, body, method: opts.method, path: opts.path };
|
|
127
|
+
switch (statusCode) {
|
|
128
|
+
case 400:
|
|
129
|
+
return new STXValidationException(message, base);
|
|
130
|
+
case 401:
|
|
131
|
+
return bearerError(opts.wwwAuthenticate) === "invalid_token" ? new STXInvalidTokenException(message, base) : new STXAuthenticationException(message, base);
|
|
132
|
+
case 403: {
|
|
133
|
+
if (bearerError(opts.wwwAuthenticate) === "insufficient_scope" || /insufficient scope/i.test(message)) {
|
|
134
|
+
return new STXInsufficientScopeException(message, {
|
|
135
|
+
...base,
|
|
136
|
+
requiredScopes: insufficientScopes(opts.wwwAuthenticate, body)
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return new STXForbiddenException(message, base);
|
|
140
|
+
}
|
|
141
|
+
case 404:
|
|
142
|
+
return new STXNotFoundException(message, base);
|
|
143
|
+
case 422: {
|
|
144
|
+
const geo = geoRejection(message);
|
|
145
|
+
return geo ? new STXGeoLocationException(message, geo, base) : new STXRejectedException(message, base);
|
|
146
|
+
}
|
|
147
|
+
case 429:
|
|
148
|
+
return new STXRateLimitException(message, { ...base, retryAfter: parseRetryAfter(opts.retryAfter) });
|
|
149
|
+
default:
|
|
150
|
+
return statusCode >= 500 ? new STXServerException(message, base) : new STXAPIException(message, base);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function parseRetryAfter(value) {
|
|
154
|
+
if (value === null || value === void 0 || value.trim() === "") return void 0;
|
|
155
|
+
const n = Number(value);
|
|
156
|
+
return Number.isFinite(n) ? Math.max(0, n) : void 0;
|
|
157
|
+
}
|
|
158
|
+
function bearerError(header) {
|
|
159
|
+
if (!header || !/^\s*Bearer\b/i.test(header)) return void 0;
|
|
160
|
+
return _optionalChain([/error\s*=\s*"([^"]*)"/, 'access', _ => _.exec, 'call', _2 => _2(header), 'optionalAccess', _3 => _3[1]]);
|
|
161
|
+
}
|
|
162
|
+
function insufficientScopes(header, body) {
|
|
163
|
+
const m = header ? /scope\s*=\s*"([^"]*)"/.exec(header) : null;
|
|
164
|
+
let raw = _optionalChain([m, 'optionalAccess', _4 => _4[1]]);
|
|
165
|
+
if (!raw && body && typeof body === "object" && typeof body.scope === "string") {
|
|
166
|
+
raw = body.scope;
|
|
167
|
+
}
|
|
168
|
+
return raw ? raw.split(/\s+/).filter(Boolean) : [];
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/config.ts
|
|
172
|
+
var Environments = {
|
|
173
|
+
/** United States demo. Shared by every integrator. No real money. */
|
|
174
|
+
USDemo: { name: "us-demo", region: Region.US, env: Environment.DEMO, host: "demo.stxapp.io", realMoney: false },
|
|
175
|
+
/** Ontario demo. Shared, no real money. */
|
|
176
|
+
OntarioDemo: {
|
|
177
|
+
name: "ontario-demo",
|
|
178
|
+
region: Region.ONTARIO,
|
|
179
|
+
env: Environment.DEMO,
|
|
180
|
+
host: "demo.stxapp.ca",
|
|
181
|
+
realMoney: false
|
|
182
|
+
},
|
|
183
|
+
/** **Ontario production. Real money.** Exercise your integration against `OntarioDemo` first. */
|
|
184
|
+
OntarioProduction: {
|
|
185
|
+
name: "ontario-production",
|
|
186
|
+
region: Region.ONTARIO,
|
|
187
|
+
env: Environment.PRODUCTION,
|
|
188
|
+
host: "stxapp.ca",
|
|
189
|
+
realMoney: true
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
var ALL_ENVIRONMENTS = Object.values(Environments);
|
|
193
|
+
var HOSTS = Object.fromEntries(
|
|
194
|
+
ALL_ENVIRONMENTS.map((e) => [`${e.region}/${e.env}`, e.host])
|
|
195
|
+
);
|
|
196
|
+
function environmentNamed(name) {
|
|
197
|
+
const found = ALL_ENVIRONMENTS.find((e) => e.name === name.trim().toLowerCase());
|
|
198
|
+
if (!found) {
|
|
199
|
+
throw new STXConfigException(
|
|
200
|
+
`Unknown environment: ${JSON.stringify(name)}. Known: ${ALL_ENVIRONMENTS.map((e) => e.name).join(", ")}. Any other host is reachable through host.`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
return found;
|
|
204
|
+
}
|
|
205
|
+
var ENV_ALIASES = {
|
|
206
|
+
prod: Environment.PRODUCTION,
|
|
207
|
+
live: Environment.PRODUCTION
|
|
208
|
+
};
|
|
209
|
+
var SOCKET_PATH = "/socket/websocket";
|
|
210
|
+
function coerceRegion(value) {
|
|
211
|
+
if (value === null || value === void 0) return void 0;
|
|
212
|
+
const lowered = value.toLowerCase();
|
|
213
|
+
const known = Object.values(Region);
|
|
214
|
+
if (!known.includes(lowered)) {
|
|
215
|
+
throw new STXConfigException(`Unknown region: ${JSON.stringify(value)}. Known: ${known.join(", ")}.`);
|
|
216
|
+
}
|
|
217
|
+
return lowered;
|
|
218
|
+
}
|
|
219
|
+
function coerceEnv(value) {
|
|
220
|
+
if (value === null || value === void 0) return void 0;
|
|
221
|
+
const lowered = value.toLowerCase();
|
|
222
|
+
if (ENV_ALIASES[lowered]) return ENV_ALIASES[lowered];
|
|
223
|
+
const known = Object.values(Environment);
|
|
224
|
+
if (!known.includes(lowered)) {
|
|
225
|
+
throw new STXConfigException(
|
|
226
|
+
`Unknown env: ${JSON.stringify(value)}. Known: ${known.join(", ")}. Any other host is reachable through host.`
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
return lowered;
|
|
230
|
+
}
|
|
231
|
+
function resolveHost(region, env) {
|
|
232
|
+
const r = coerceRegion(region);
|
|
233
|
+
const e = coerceEnv(env);
|
|
234
|
+
if (r === void 0 || e === void 0) {
|
|
235
|
+
throw new STXConfigException(
|
|
236
|
+
"No host configured. Pass region and env (for example region: 'ontario', env: 'production'), or environment, or host, or set them in a profile in ~/.stx/credentials."
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
const host = HOSTS[`${r}/${e}`];
|
|
240
|
+
if (!host) {
|
|
241
|
+
throw new STXConfigException(`No host configured for region=${r}, env=${e}. Pass host explicitly.`);
|
|
242
|
+
}
|
|
243
|
+
return host;
|
|
244
|
+
}
|
|
245
|
+
function baseUrlFor(region, env, host) {
|
|
246
|
+
if (host) {
|
|
247
|
+
const h = host.trim();
|
|
248
|
+
if (/^https?:\/\//i.test(h)) {
|
|
249
|
+
let parsed;
|
|
250
|
+
try {
|
|
251
|
+
parsed = new URL(h);
|
|
252
|
+
} catch (e2) {
|
|
253
|
+
throw new STXConfigException(`Cannot parse host ${JSON.stringify(h)}.`);
|
|
254
|
+
}
|
|
255
|
+
return `${parsed.protocol}//${parsed.host}`;
|
|
256
|
+
}
|
|
257
|
+
return `https://${h.replace(/\/+$/, "")}`;
|
|
258
|
+
}
|
|
259
|
+
return `https://${resolveHost(region, env)}`;
|
|
260
|
+
}
|
|
261
|
+
function socketUrlFor(baseUrl) {
|
|
262
|
+
const parsed = new URL(baseUrl);
|
|
263
|
+
const scheme = parsed.protocol === "http:" ? "ws" : "wss";
|
|
264
|
+
return `${scheme}://${parsed.host}${SOCKET_PATH}?vsn=2.0.0`;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/operations.ts
|
|
268
|
+
var OPERATIONS = {
|
|
269
|
+
account_balance_get: {
|
|
270
|
+
method: "GET",
|
|
271
|
+
path: "/api/v1/account/balance",
|
|
272
|
+
query: [],
|
|
273
|
+
pathParams: [],
|
|
274
|
+
hasBody: false,
|
|
275
|
+
responseKey: "balance",
|
|
276
|
+
model: "Balance",
|
|
277
|
+
isList: false,
|
|
278
|
+
paginated: false
|
|
279
|
+
},
|
|
280
|
+
account_market_stats_get: {
|
|
281
|
+
method: "GET",
|
|
282
|
+
path: "/api/v1/account/market_stats",
|
|
283
|
+
query: ["market_ids", "event_ids", "exclude_zero_settlements", "from_time", "to_time", "sports", "competitions", "limit", "cursor"],
|
|
284
|
+
pathParams: [],
|
|
285
|
+
hasBody: false,
|
|
286
|
+
responseKey: "market_stats",
|
|
287
|
+
model: "MarketStat",
|
|
288
|
+
isList: true,
|
|
289
|
+
paginated: true
|
|
290
|
+
},
|
|
291
|
+
events_get: {
|
|
292
|
+
method: "GET",
|
|
293
|
+
path: "/api/v1/events",
|
|
294
|
+
query: ["event_ids", "sports", "competitions", "event_types", "title", "status", "promoted", "sort_by[name]", "sort_by[direction]", "limit", "cursor"],
|
|
295
|
+
pathParams: [],
|
|
296
|
+
hasBody: false,
|
|
297
|
+
responseKey: "events",
|
|
298
|
+
model: "Event",
|
|
299
|
+
isList: true,
|
|
300
|
+
paginated: true
|
|
301
|
+
},
|
|
302
|
+
fills_get: {
|
|
303
|
+
method: "GET",
|
|
304
|
+
path: "/api/v1/fills",
|
|
305
|
+
query: ["market_ids", "order_ids", "status", "limit", "cursor"],
|
|
306
|
+
pathParams: [],
|
|
307
|
+
hasBody: false,
|
|
308
|
+
responseKey: "fills",
|
|
309
|
+
model: "Fill",
|
|
310
|
+
isList: true,
|
|
311
|
+
paginated: true
|
|
312
|
+
},
|
|
313
|
+
markets_get: {
|
|
314
|
+
method: "GET",
|
|
315
|
+
path: "/api/v1/markets",
|
|
316
|
+
query: ["market_ids", "event_ids", "status", "trading", "sports", "competitions", "sort_by[name]", "sort_by[direction]", "limit", "cursor"],
|
|
317
|
+
pathParams: [],
|
|
318
|
+
hasBody: false,
|
|
319
|
+
responseKey: "markets",
|
|
320
|
+
model: "Market",
|
|
321
|
+
isList: true,
|
|
322
|
+
paginated: true
|
|
323
|
+
},
|
|
324
|
+
me_get: {
|
|
325
|
+
method: "GET",
|
|
326
|
+
path: "/api/v1/me",
|
|
327
|
+
query: [],
|
|
328
|
+
pathParams: [],
|
|
329
|
+
hasBody: false,
|
|
330
|
+
responseKey: "me",
|
|
331
|
+
model: "Me",
|
|
332
|
+
isList: false,
|
|
333
|
+
paginated: false
|
|
334
|
+
},
|
|
335
|
+
orders_get: {
|
|
336
|
+
method: "GET",
|
|
337
|
+
path: "/api/v1/orders",
|
|
338
|
+
query: ["order_ids", "client_order_ids", "market_ids", "status", "limit", "cursor"],
|
|
339
|
+
pathParams: [],
|
|
340
|
+
hasBody: false,
|
|
341
|
+
responseKey: "orders",
|
|
342
|
+
model: "Order",
|
|
343
|
+
isList: true,
|
|
344
|
+
paginated: true
|
|
345
|
+
},
|
|
346
|
+
orders_post: {
|
|
347
|
+
method: "POST",
|
|
348
|
+
path: "/api/v1/orders",
|
|
349
|
+
query: [],
|
|
350
|
+
pathParams: [],
|
|
351
|
+
hasBody: true,
|
|
352
|
+
responseKey: "order",
|
|
353
|
+
model: "Order",
|
|
354
|
+
isList: false,
|
|
355
|
+
paginated: false
|
|
356
|
+
},
|
|
357
|
+
orders_all_delete: {
|
|
358
|
+
method: "DELETE",
|
|
359
|
+
path: "/api/v1/orders/all",
|
|
360
|
+
query: [],
|
|
361
|
+
pathParams: [],
|
|
362
|
+
hasBody: false,
|
|
363
|
+
responseKey: "cancellations",
|
|
364
|
+
model: "Cancellation",
|
|
365
|
+
isList: true,
|
|
366
|
+
paginated: false
|
|
367
|
+
},
|
|
368
|
+
orders_batched_delete: {
|
|
369
|
+
method: "DELETE",
|
|
370
|
+
path: "/api/v1/orders/batched",
|
|
371
|
+
query: [],
|
|
372
|
+
pathParams: [],
|
|
373
|
+
hasBody: true,
|
|
374
|
+
responseKey: "cancellations",
|
|
375
|
+
model: "Cancellation",
|
|
376
|
+
isList: true,
|
|
377
|
+
paginated: false
|
|
378
|
+
},
|
|
379
|
+
orders_batched_post: {
|
|
380
|
+
method: "POST",
|
|
381
|
+
path: "/api/v1/orders/batched",
|
|
382
|
+
query: [],
|
|
383
|
+
pathParams: [],
|
|
384
|
+
hasBody: true,
|
|
385
|
+
responseKey: "results",
|
|
386
|
+
model: "",
|
|
387
|
+
isList: true,
|
|
388
|
+
paginated: false
|
|
389
|
+
},
|
|
390
|
+
orders__order_id_delete: {
|
|
391
|
+
method: "DELETE",
|
|
392
|
+
path: "/api/v1/orders/{order_id}",
|
|
393
|
+
query: [],
|
|
394
|
+
pathParams: ["order_id"],
|
|
395
|
+
hasBody: false,
|
|
396
|
+
responseKey: "",
|
|
397
|
+
model: "",
|
|
398
|
+
isList: false,
|
|
399
|
+
paginated: false
|
|
400
|
+
},
|
|
401
|
+
orders__id_get: {
|
|
402
|
+
method: "GET",
|
|
403
|
+
path: "/api/v1/orders/{order_id}",
|
|
404
|
+
query: [],
|
|
405
|
+
pathParams: ["order_id"],
|
|
406
|
+
hasBody: false,
|
|
407
|
+
responseKey: "order",
|
|
408
|
+
model: "Order",
|
|
409
|
+
isList: false,
|
|
410
|
+
paginated: false
|
|
411
|
+
},
|
|
412
|
+
portfolio_adjustments_get: {
|
|
413
|
+
method: "GET",
|
|
414
|
+
path: "/api/v1/portfolio/adjustments",
|
|
415
|
+
query: ["limit", "cursor"],
|
|
416
|
+
pathParams: [],
|
|
417
|
+
hasBody: false,
|
|
418
|
+
responseKey: "adjustments",
|
|
419
|
+
model: "PaymentTransaction",
|
|
420
|
+
isList: true,
|
|
421
|
+
paginated: true
|
|
422
|
+
},
|
|
423
|
+
portfolio_deposits_get: {
|
|
424
|
+
method: "GET",
|
|
425
|
+
path: "/api/v1/portfolio/deposits",
|
|
426
|
+
query: ["limit", "cursor"],
|
|
427
|
+
pathParams: [],
|
|
428
|
+
hasBody: false,
|
|
429
|
+
responseKey: "deposits",
|
|
430
|
+
model: "PaymentTransaction",
|
|
431
|
+
isList: true,
|
|
432
|
+
paginated: true
|
|
433
|
+
},
|
|
434
|
+
portfolio_fees_get: {
|
|
435
|
+
method: "GET",
|
|
436
|
+
path: "/api/v1/portfolio/fees",
|
|
437
|
+
query: ["limit", "cursor"],
|
|
438
|
+
pathParams: [],
|
|
439
|
+
hasBody: false,
|
|
440
|
+
responseKey: "fees",
|
|
441
|
+
model: "FeeTransaction",
|
|
442
|
+
isList: true,
|
|
443
|
+
paginated: true
|
|
444
|
+
},
|
|
445
|
+
portfolio_loyalty_get: {
|
|
446
|
+
method: "GET",
|
|
447
|
+
path: "/api/v1/portfolio/loyalty",
|
|
448
|
+
query: ["limit", "cursor"],
|
|
449
|
+
pathParams: [],
|
|
450
|
+
hasBody: false,
|
|
451
|
+
responseKey: "loyalty",
|
|
452
|
+
model: "Transaction",
|
|
453
|
+
isList: true,
|
|
454
|
+
paginated: true
|
|
455
|
+
},
|
|
456
|
+
portfolio_settlements_get: {
|
|
457
|
+
method: "GET",
|
|
458
|
+
path: "/api/v1/portfolio/settlements",
|
|
459
|
+
query: ["market_ids", "type", "limit", "cursor"],
|
|
460
|
+
pathParams: [],
|
|
461
|
+
hasBody: false,
|
|
462
|
+
responseKey: "settlements",
|
|
463
|
+
model: "Settlement",
|
|
464
|
+
isList: true,
|
|
465
|
+
paginated: true
|
|
466
|
+
},
|
|
467
|
+
portfolio_withdrawals_get: {
|
|
468
|
+
method: "GET",
|
|
469
|
+
path: "/api/v1/portfolio/withdrawals",
|
|
470
|
+
query: ["limit", "cursor"],
|
|
471
|
+
pathParams: [],
|
|
472
|
+
hasBody: false,
|
|
473
|
+
responseKey: "withdrawals",
|
|
474
|
+
model: "PaymentTransaction",
|
|
475
|
+
isList: true,
|
|
476
|
+
paginated: true
|
|
477
|
+
},
|
|
478
|
+
positions_get: {
|
|
479
|
+
method: "GET",
|
|
480
|
+
path: "/api/v1/positions",
|
|
481
|
+
query: ["market_ids"],
|
|
482
|
+
pathParams: [],
|
|
483
|
+
hasBody: false,
|
|
484
|
+
responseKey: "positions",
|
|
485
|
+
model: "Position",
|
|
486
|
+
isList: true,
|
|
487
|
+
paginated: false
|
|
488
|
+
},
|
|
489
|
+
tnc_accept_post: {
|
|
490
|
+
method: "POST",
|
|
491
|
+
path: "/api/v1/tnc/accept",
|
|
492
|
+
query: [],
|
|
493
|
+
pathParams: [],
|
|
494
|
+
hasBody: true,
|
|
495
|
+
responseKey: "message",
|
|
496
|
+
model: "",
|
|
497
|
+
isList: false,
|
|
498
|
+
paginated: false
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// src/paging.ts
|
|
503
|
+
var Page = class {
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
constructor(items, cursor) {
|
|
507
|
+
this.items = items;
|
|
508
|
+
this.cursor = cursor;
|
|
509
|
+
}
|
|
510
|
+
/** True when another page exists. */
|
|
511
|
+
get hasMore() {
|
|
512
|
+
return Boolean(this.cursor);
|
|
513
|
+
}
|
|
514
|
+
get length() {
|
|
515
|
+
return this.items.length;
|
|
516
|
+
}
|
|
517
|
+
/** The item at `index`; negative counts from the end. */
|
|
518
|
+
at(index) {
|
|
519
|
+
return this.items.at(index);
|
|
520
|
+
}
|
|
521
|
+
[Symbol.iterator]() {
|
|
522
|
+
return this.items[Symbol.iterator]();
|
|
523
|
+
}
|
|
524
|
+
toString() {
|
|
525
|
+
return `Page(${this.items.length} items${this.hasMore ? ", more" : ""})`;
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
// src/retry.ts
|
|
530
|
+
var RetryPolicy = class {
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
constructor(opts = {}) {
|
|
537
|
+
this.maxAttempts = _nullishCoalesce(opts.maxAttempts, () => ( 3));
|
|
538
|
+
this.initialBackoffMs = _nullishCoalesce(opts.initialBackoffMs, () => ( 500));
|
|
539
|
+
this.maxBackoffMs = _nullishCoalesce(opts.maxBackoffMs, () => ( 3e4));
|
|
540
|
+
this.jitter = _nullishCoalesce(opts.jitter, () => ( true));
|
|
541
|
+
this.retryableExceptions = _nullishCoalesce(opts.retryableExceptions, () => ( [
|
|
542
|
+
STXServerException,
|
|
543
|
+
STXTransportException,
|
|
544
|
+
STXRateLimitException
|
|
545
|
+
]));
|
|
546
|
+
}
|
|
547
|
+
/** Whether to try again after `exc` ended attempt number `attempt`. */
|
|
548
|
+
shouldRetry(exc, attempt, idempotent) {
|
|
549
|
+
if (attempt >= this.maxAttempts) return false;
|
|
550
|
+
if (!this.retryableExceptions.some((cls) => exc instanceof cls)) return false;
|
|
551
|
+
return idempotent || exc instanceof STXRateLimitException;
|
|
552
|
+
}
|
|
553
|
+
/** Milliseconds to wait after attempt `attempt` (1-based) failed. */
|
|
554
|
+
computeBackoffMs(attempt, exc) {
|
|
555
|
+
if (exc instanceof STXRateLimitException && exc.retryAfter !== void 0) {
|
|
556
|
+
return Math.min(exc.retryAfter * 1e3, this.maxBackoffMs);
|
|
557
|
+
}
|
|
558
|
+
const capped = Math.min(this.initialBackoffMs * 2 ** (attempt - 1), this.maxBackoffMs);
|
|
559
|
+
return this.jitter ? capped * (0.5 + Math.random() * 0.5) : capped;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
var NO_RETRY = new RetryPolicy({ maxAttempts: 1 });
|
|
563
|
+
|
|
564
|
+
// src/settings.ts
|
|
565
|
+
var _fs = require('fs');
|
|
566
|
+
var _os = require('os');
|
|
567
|
+
var _path = require('path');
|
|
568
|
+
var DEFAULT_PROFILE_NAME = "default";
|
|
569
|
+
var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
570
|
+
var FALSY = /* @__PURE__ */ new Set(["0", "false", "no", "off"]);
|
|
571
|
+
function parseBool(value, key) {
|
|
572
|
+
if (value === void 0 || value === null) return void 0;
|
|
573
|
+
const lower = value.trim().toLowerCase();
|
|
574
|
+
if (!lower) return void 0;
|
|
575
|
+
if (TRUTHY.has(lower)) return true;
|
|
576
|
+
if (FALSY.has(lower)) return false;
|
|
577
|
+
throw new STXConfigException(
|
|
578
|
+
`Invalid boolean for ${key}: ${JSON.stringify(value)}. Use one of ${[...FALSY, ...TRUTHY].sort().join(", ")}.`
|
|
579
|
+
);
|
|
580
|
+
}
|
|
581
|
+
function expandHome(path) {
|
|
582
|
+
const home = process.env.HOME || _os.homedir.call(void 0, );
|
|
583
|
+
return path === "~" || path.startsWith("~/") ? _path.join.call(void 0, home, path.slice(1)) : path;
|
|
584
|
+
}
|
|
585
|
+
function defaultProfileFile(environ) {
|
|
586
|
+
const override = environ.STX_CREDENTIALS;
|
|
587
|
+
return override ? expandHome(override) : _path.join.call(void 0, process.env.HOME || _os.homedir.call(void 0, ), ".stx", "credentials");
|
|
588
|
+
}
|
|
589
|
+
function parseIni(text) {
|
|
590
|
+
const sections = /* @__PURE__ */ new Map();
|
|
591
|
+
let current;
|
|
592
|
+
let lineNo = 0;
|
|
593
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
594
|
+
lineNo += 1;
|
|
595
|
+
const line = raw.trim();
|
|
596
|
+
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
|
|
597
|
+
const header = /^\[([^\]]+)\]$/.exec(line);
|
|
598
|
+
if (header) {
|
|
599
|
+
const name = header[1].trim();
|
|
600
|
+
if (sections.has(name)) {
|
|
601
|
+
throw new Error(`section ${JSON.stringify(name)} already exists (line ${lineNo})`);
|
|
602
|
+
}
|
|
603
|
+
current = {};
|
|
604
|
+
sections.set(name, current);
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
const sep = line.search(/[=:]/);
|
|
608
|
+
if (sep <= 0 || current === void 0) {
|
|
609
|
+
throw new Error(`cannot parse line ${lineNo}: ${JSON.stringify(raw)}`);
|
|
610
|
+
}
|
|
611
|
+
current[line.slice(0, sep).trim().toLowerCase()] = line.slice(sep + 1).trim();
|
|
612
|
+
}
|
|
613
|
+
return sections;
|
|
614
|
+
}
|
|
615
|
+
function readProfile(profileName, path) {
|
|
616
|
+
try {
|
|
617
|
+
if (!_fs.statSync.call(void 0, path).isFile()) return [{}, false];
|
|
618
|
+
} catch (e3) {
|
|
619
|
+
return [{}, false];
|
|
620
|
+
}
|
|
621
|
+
let sections;
|
|
622
|
+
try {
|
|
623
|
+
sections = parseIni(_fs.readFileSync.call(void 0, path, "utf8"));
|
|
624
|
+
} catch (err) {
|
|
625
|
+
throw new STXConfigException(`Failed to parse credentials file ${path}: ${err.message}`);
|
|
626
|
+
}
|
|
627
|
+
const section = sections.get(profileName);
|
|
628
|
+
if (!section) {
|
|
629
|
+
if (profileName === DEFAULT_PROFILE_NAME) return [{}, true];
|
|
630
|
+
throw new STXConfigException(
|
|
631
|
+
`Profile ${JSON.stringify(profileName)} not found in ${path}. Available profiles: ${JSON.stringify([...sections.keys()])}`
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
return [{ ...section }, true];
|
|
635
|
+
}
|
|
636
|
+
function processEnv() {
|
|
637
|
+
const p = globalThis.process;
|
|
638
|
+
return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _5 => _5.env]), () => ( {}));
|
|
639
|
+
}
|
|
640
|
+
function resolveSettings(input = {}) {
|
|
641
|
+
const environ = _nullishCoalesce(input.environ, () => ( processEnv()));
|
|
642
|
+
const profileName = input.profile === void 0 ? environ.STX_PROFILE || DEFAULT_PROFILE_NAME : input.profile || DEFAULT_PROFILE_NAME;
|
|
643
|
+
const [profileValues, fileExisted] = readProfile(profileName, _nullishCoalesce(input.profileFile, () => ( defaultProfileFile(environ))));
|
|
644
|
+
const profileUsed = input.profile !== void 0 && input.profile !== null || "STX_PROFILE" in environ || fileExisted && Object.keys(profileValues).length > 0;
|
|
645
|
+
const pick = (option, envKeys, ...profileKeys) => {
|
|
646
|
+
if (option !== void 0) return _nullishCoalesce(option, () => ( void 0));
|
|
647
|
+
for (const key of envKeys) {
|
|
648
|
+
if (environ[key]) return environ[key];
|
|
649
|
+
}
|
|
650
|
+
for (const key of profileKeys) {
|
|
651
|
+
if (key in profileValues) return profileValues[key];
|
|
652
|
+
}
|
|
653
|
+
return void 0;
|
|
654
|
+
};
|
|
655
|
+
let verifyTls;
|
|
656
|
+
if (input.verifyTls !== void 0) {
|
|
657
|
+
verifyTls = _nullishCoalesce(input.verifyTls, () => ( true));
|
|
658
|
+
} else {
|
|
659
|
+
const fromEnv = parseBool(environ.STX_VERIFY_TLS, "STX_VERIFY_TLS");
|
|
660
|
+
if (fromEnv !== void 0) verifyTls = fromEnv;
|
|
661
|
+
else if ("verify_tls" in profileValues) verifyTls = _nullishCoalesce(parseBool(profileValues.verify_tls, "verify_tls"), () => ( true));
|
|
662
|
+
else verifyTls = true;
|
|
663
|
+
}
|
|
664
|
+
return {
|
|
665
|
+
host: pick(input.host, ["STX_HOST", "STX_BASE_URL"], "host", "base_url"),
|
|
666
|
+
region: pick(input.region, ["STX_REGION"], "region"),
|
|
667
|
+
env: pick(input.env, ["STX_ENV"], "env"),
|
|
668
|
+
verifyTls,
|
|
669
|
+
profileName,
|
|
670
|
+
profileUsed,
|
|
671
|
+
keyId: pick(input.keyId, ["STX_KEY_ID"], "key_id"),
|
|
672
|
+
privateKey: pick(input.privateKey, ["STX_PRIVATE_KEY"], "private_key", "key_file")
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// src/signing.ts
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
var _crypto = require('crypto');
|
|
681
|
+
var KEY_HEADER = "X-STX-ACCESS-KEY";
|
|
682
|
+
var TIMESTAMP_HEADER = "X-STX-ACCESS-TIMESTAMP";
|
|
683
|
+
var SIGNATURE_HEADER = "X-STX-ACCESS-SIGNATURE";
|
|
684
|
+
var WEBSOCKET_PATH = "/socket/websocket";
|
|
685
|
+
function buildMessage(timestampMs, method, path) {
|
|
686
|
+
if (!method) throw new Error("HTTP method is required.");
|
|
687
|
+
if (!path) throw new Error("Request path is required.");
|
|
688
|
+
return `${timestampMs}${method.toUpperCase()}${path}`;
|
|
689
|
+
}
|
|
690
|
+
function requestPath(url) {
|
|
691
|
+
const parsed = new URL(url);
|
|
692
|
+
const path = parsed.pathname || "/";
|
|
693
|
+
return parsed.search ? `${path}${parsed.search}` : path;
|
|
694
|
+
}
|
|
695
|
+
function handshakePath(url) {
|
|
696
|
+
return new URL(url).pathname || "/";
|
|
697
|
+
}
|
|
698
|
+
function expandHome2(path) {
|
|
699
|
+
const home = process.env.HOME || _os.homedir.call(void 0, );
|
|
700
|
+
return path === "~" || path.startsWith("~/") ? _path.join.call(void 0, home, path.slice(1)) : path;
|
|
701
|
+
}
|
|
702
|
+
function loadPrivateKey(value) {
|
|
703
|
+
let pem;
|
|
704
|
+
if (typeof value === "string") {
|
|
705
|
+
if (value.includes("-----BEGIN")) {
|
|
706
|
+
pem = value;
|
|
707
|
+
} else {
|
|
708
|
+
const path = expandHome2(value);
|
|
709
|
+
let isFile = false;
|
|
710
|
+
try {
|
|
711
|
+
isFile = _fs.statSync.call(void 0, path).isFile();
|
|
712
|
+
} catch (e4) {
|
|
713
|
+
isFile = false;
|
|
714
|
+
}
|
|
715
|
+
if (!isFile) {
|
|
716
|
+
throw new STXConfigException(
|
|
717
|
+
`Private key not found at ${path}. Pass either the path to a PEM file or the PEM text itself.`
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
pem = _fs.readFileSync.call(void 0, path);
|
|
721
|
+
}
|
|
722
|
+
} else if (value instanceof Uint8Array) {
|
|
723
|
+
pem = value;
|
|
724
|
+
} else {
|
|
725
|
+
return checkEd25519(value);
|
|
726
|
+
}
|
|
727
|
+
let key;
|
|
728
|
+
try {
|
|
729
|
+
key = _crypto.createPrivateKey.call(void 0, { key: Buffer.from(pem), format: "pem" });
|
|
730
|
+
} catch (e5) {
|
|
731
|
+
throw new STXConfigException(
|
|
732
|
+
"Private key is not valid PEM. Expected a PKCS#8 block beginning '-----BEGIN PRIVATE KEY-----'."
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
return checkEd25519(key);
|
|
736
|
+
}
|
|
737
|
+
function checkEd25519(key) {
|
|
738
|
+
if (key.type !== "private" || key.asymmetricKeyType !== "ed25519") {
|
|
739
|
+
throw new STXConfigException("Private key is not an Ed25519 key. STX API keys use Ed25519.");
|
|
740
|
+
}
|
|
741
|
+
return key;
|
|
742
|
+
}
|
|
743
|
+
function signerFromPrivateKey(value) {
|
|
744
|
+
const key = loadPrivateKey(value);
|
|
745
|
+
return (message) => new Uint8Array(_crypto.sign.call(void 0, null, message, key));
|
|
746
|
+
}
|
|
747
|
+
var ApiKeyCredentials = (_class = class {
|
|
748
|
+
__init() {this.kind = "api_key"}
|
|
749
|
+
|
|
750
|
+
#sign;
|
|
751
|
+
constructor(keyId, privateKey, opts = {}) {;_class.prototype.__init.call(this);
|
|
752
|
+
if (!keyId || !String(keyId).trim()) throw new STXConfigException("API key id is required.");
|
|
753
|
+
const signer = opts.signer;
|
|
754
|
+
if (!signer && (privateKey === void 0 || privateKey === null)) {
|
|
755
|
+
throw new STXConfigException("Either `privateKey` (PEM text or path) or `signer` is required.");
|
|
756
|
+
}
|
|
757
|
+
if (signer && privateKey !== void 0 && privateKey !== null) {
|
|
758
|
+
throw new STXConfigException("Pass `privateKey` or `signer`, not both.");
|
|
759
|
+
}
|
|
760
|
+
this.keyId = String(keyId).trim();
|
|
761
|
+
this.#sign = _nullishCoalesce(signer, () => ( signerFromPrivateKey(privateKey)));
|
|
762
|
+
}
|
|
763
|
+
/** Raw Ed25519 signature over `message`. */
|
|
764
|
+
async sign(message) {
|
|
765
|
+
return this.#sign(message);
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* The three signed headers for one request. A fresh timestamp per call
|
|
769
|
+
* unless `timestampMs` is given (tests): the server rejects anything more
|
|
770
|
+
* than 30 seconds from its clock, so never cache a signature.
|
|
771
|
+
*/
|
|
772
|
+
async headers(method, path, timestampMs) {
|
|
773
|
+
const ts = timestampMs === void 0 ? Date.now() : Math.trunc(timestampMs);
|
|
774
|
+
const message = new TextEncoder().encode(buildMessage(ts, method, path));
|
|
775
|
+
const signature = Buffer.from(await this.sign(message)).toString("base64");
|
|
776
|
+
return {
|
|
777
|
+
[KEY_HEADER]: this.keyId,
|
|
778
|
+
[TIMESTAMP_HEADER]: String(ts),
|
|
779
|
+
[SIGNATURE_HEADER]: signature
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
authHeaders(request) {
|
|
783
|
+
return this.headers(request.method, request.path);
|
|
784
|
+
}
|
|
785
|
+
async websocketHeaders() {
|
|
786
|
+
return this.headers("GET", WEBSOCKET_PATH);
|
|
787
|
+
}
|
|
788
|
+
toString() {
|
|
789
|
+
return `ApiKeyCredentials(keyId=${JSON.stringify(this.keyId)})`;
|
|
790
|
+
}
|
|
791
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
792
|
+
return this.toString();
|
|
793
|
+
}
|
|
794
|
+
}, _class);
|
|
795
|
+
function credentialsFromSettings(keyId, privateKey, signer) {
|
|
796
|
+
const hasMaterial = privateKey !== void 0 && privateKey !== null || signer !== void 0;
|
|
797
|
+
if (!keyId && !hasMaterial) return void 0;
|
|
798
|
+
if (keyId && !hasMaterial) {
|
|
799
|
+
throw new STXConfigException(
|
|
800
|
+
"keyId is set but no private key was given. Pass `privateKey` (PEM text or path), set STX_PRIVATE_KEY, or add `private_key` to the profile in ~/.stx/credentials."
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
if (hasMaterial && !keyId) {
|
|
804
|
+
throw new STXConfigException(
|
|
805
|
+
"A private key was given but no keyId. Pass `keyId`, set STX_KEY_ID, or add `key_id` to the profile in ~/.stx/credentials."
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
return new ApiKeyCredentials(keyId, privateKey, { signer });
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
// src/version.ts
|
|
812
|
+
var VERSION = "0.6.0";
|
|
813
|
+
var USER_AGENT = `stx-typescript/${VERSION}`;
|
|
814
|
+
var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
|
|
815
|
+
|
|
816
|
+
// src/account-view.ts
|
|
817
|
+
var TERMINAL_ORDER_STATUSES = /* @__PURE__ */ new Set([
|
|
818
|
+
"filled",
|
|
819
|
+
"cancelled",
|
|
820
|
+
"partially_cancelled",
|
|
821
|
+
"rejected"
|
|
822
|
+
]);
|
|
823
|
+
var CHANNELS = ["balances", "orders", "fills", "positions"];
|
|
824
|
+
var isZero = (q) => q !== null && q !== void 0 && Number(q) === 0;
|
|
825
|
+
var newestFirst = (a, b) => stamp(b) - stamp(a);
|
|
826
|
+
function stamp(item) {
|
|
827
|
+
if (typeof item.inserted_at === "number") return item.inserted_at;
|
|
828
|
+
const t = Date.parse(String(_nullishCoalesce(_nullishCoalesce(item.time, () => ( item.inserted_at)), () => ( ""))));
|
|
829
|
+
return Number.isNaN(t) ? 0 : t * 1e3;
|
|
830
|
+
}
|
|
831
|
+
var AccountView = (_class2 = class {
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
/** The joined channels, by name. */
|
|
835
|
+
__init2() {this.channels = {}}
|
|
836
|
+
/** Join snapshots applied so far, per channel: 1 after the first seed, more after reconnects. */
|
|
837
|
+
__init3() {this.seeds = { balances: 0, orders: 0, fills: 0, positions: 0 }}
|
|
838
|
+
#balance = null;
|
|
839
|
+
#orders = /* @__PURE__ */ new Map();
|
|
840
|
+
#fills = /* @__PURE__ */ new Map();
|
|
841
|
+
#positions = /* @__PURE__ */ new Map();
|
|
842
|
+
#keepFlat;
|
|
843
|
+
#maxFills;
|
|
844
|
+
#closed = false;
|
|
845
|
+
/** @internal Use `ws.accountView()`. */
|
|
846
|
+
constructor(ws, opts = {}) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);
|
|
847
|
+
this.ws = ws;
|
|
848
|
+
this.onChange = opts.onChange;
|
|
849
|
+
this.#keepFlat = _nullishCoalesce(opts.keepFlatPositions, () => ( false));
|
|
850
|
+
this.#maxFills = _nullishCoalesce(opts.maxFills, () => ( 1e3));
|
|
851
|
+
}
|
|
852
|
+
/** @internal Join the four channels and wait for their snapshots. */
|
|
853
|
+
async _open(opts) {
|
|
854
|
+
const handler = (msg) => {
|
|
855
|
+
this.apply(msg);
|
|
856
|
+
};
|
|
857
|
+
const marketIds = opts.marketIds;
|
|
858
|
+
try {
|
|
859
|
+
this.channels.balances = await this.ws.balances({ accountId: opts.accountId, onMessage: handler });
|
|
860
|
+
this.channels.orders = await this.ws.orders({ marketIds, onMessage: handler });
|
|
861
|
+
this.channels.fills = await this.ws.fills({ marketIds, onMessage: handler });
|
|
862
|
+
this.channels.positions = await this.ws.positions({ marketIds, onMessage: handler });
|
|
863
|
+
const timeout = opts.snapshotTimeoutMs === void 0 ? 15e3 : opts.snapshotTimeoutMs;
|
|
864
|
+
await Promise.all(CHANNELS.map((name) => this.channels[name].waitSnapshot(timeout)));
|
|
865
|
+
} catch (err) {
|
|
866
|
+
await this.close();
|
|
867
|
+
throw err;
|
|
868
|
+
}
|
|
869
|
+
return this;
|
|
870
|
+
}
|
|
871
|
+
/** The latest balance summary, or `null` before the first snapshot. */
|
|
872
|
+
get balance() {
|
|
873
|
+
return this.#balance;
|
|
874
|
+
}
|
|
875
|
+
/** Open orders, newest first. */
|
|
876
|
+
get openOrders() {
|
|
877
|
+
return [...this.#orders.values()].sort(newestFirst);
|
|
878
|
+
}
|
|
879
|
+
/** Fills, newest first. */
|
|
880
|
+
get fills() {
|
|
881
|
+
return [...this.#fills.values()].sort(newestFirst);
|
|
882
|
+
}
|
|
883
|
+
/** Positions, one per market. */
|
|
884
|
+
get positions() {
|
|
885
|
+
return [...this.#positions.values()];
|
|
886
|
+
}
|
|
887
|
+
/** True once every channel has delivered its join snapshot. */
|
|
888
|
+
get ready() {
|
|
889
|
+
return CHANNELS.every((name) => (_nullishCoalesce(this.seeds[name], () => ( 0))) > 0);
|
|
890
|
+
}
|
|
891
|
+
get closed() {
|
|
892
|
+
return this.#closed;
|
|
893
|
+
}
|
|
894
|
+
/** The whole view as plain data. */
|
|
895
|
+
state() {
|
|
896
|
+
return {
|
|
897
|
+
balance: this.#balance,
|
|
898
|
+
openOrders: this.openOrders,
|
|
899
|
+
fills: this.fills,
|
|
900
|
+
positions: this.positions
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
toJSON() {
|
|
904
|
+
return this.state();
|
|
905
|
+
}
|
|
906
|
+
/**
|
|
907
|
+
* Apply one channel message. The view calls this for the channels it
|
|
908
|
+
* joined; call it yourself to feed messages from an `account:` channel or a
|
|
909
|
+
* channel you joined elsewhere. Unknown events are ignored.
|
|
910
|
+
*/
|
|
911
|
+
apply(msg) {
|
|
912
|
+
const change = this.#apply(msg.event, msg.payload);
|
|
913
|
+
if (!change) return void 0;
|
|
914
|
+
if (this.onChange) {
|
|
915
|
+
try {
|
|
916
|
+
this.onChange(change);
|
|
917
|
+
} catch (err) {
|
|
918
|
+
this.ws.logger.error("accountView onChange threw", err);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return change;
|
|
922
|
+
}
|
|
923
|
+
#apply(event, payload) {
|
|
924
|
+
const change = (kind, snapshot) => ({
|
|
925
|
+
kind,
|
|
926
|
+
event,
|
|
927
|
+
snapshot,
|
|
928
|
+
payload,
|
|
929
|
+
view: this
|
|
930
|
+
});
|
|
931
|
+
switch (event) {
|
|
932
|
+
case "balances":
|
|
933
|
+
this.seeds.balances = (_nullishCoalesce(this.seeds.balances, () => ( 0))) + 1;
|
|
934
|
+
this.#balance = _nullishCoalesce(payload, () => ( null));
|
|
935
|
+
return change("balance", true);
|
|
936
|
+
case "update":
|
|
937
|
+
this.#balance = _nullishCoalesce(payload, () => ( this.#balance));
|
|
938
|
+
return change("balance", false);
|
|
939
|
+
case "payment_update":
|
|
940
|
+
return change("payment", false);
|
|
941
|
+
case "all_orders":
|
|
942
|
+
this.seeds.orders = (_nullishCoalesce(this.seeds.orders, () => ( 0))) + 1;
|
|
943
|
+
this.#orders.clear();
|
|
944
|
+
for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _6 => _6.orders]), () => ( []))) this.#upsertOrder(o);
|
|
945
|
+
return change("orders", true);
|
|
946
|
+
case "new_open_order":
|
|
947
|
+
this.#upsertOrder(payload);
|
|
948
|
+
return change("orders", false);
|
|
949
|
+
case "all_trades":
|
|
950
|
+
this.seeds.fills = (_nullishCoalesce(this.seeds.fills, () => ( 0))) + 1;
|
|
951
|
+
this.#fills.clear();
|
|
952
|
+
for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _7 => _7.trades]), () => ( []))) this.#upsertFill(t);
|
|
953
|
+
return change("fills", true);
|
|
954
|
+
case "trade":
|
|
955
|
+
this.#upsertFill(payload);
|
|
956
|
+
return change("fills", false);
|
|
957
|
+
case "all_positions":
|
|
958
|
+
this.seeds.positions = (_nullishCoalesce(this.seeds.positions, () => ( 0))) + 1;
|
|
959
|
+
this.#positions.clear();
|
|
960
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _8 => _8.positions]), () => ( []))) this.#upsertPosition(p);
|
|
961
|
+
return change("positions", true);
|
|
962
|
+
case "updated_positions":
|
|
963
|
+
for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.positions]), () => ( []))) this.#upsertPosition(p);
|
|
964
|
+
return change("positions", false);
|
|
965
|
+
default:
|
|
966
|
+
return void 0;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
#upsertOrder(order) {
|
|
970
|
+
if (!_optionalChain([order, 'optionalAccess', _10 => _10.id])) return;
|
|
971
|
+
if (TERMINAL_ORDER_STATUSES.has(String(order.status))) this.#orders.delete(order.id);
|
|
972
|
+
else this.#orders.set(order.id, order);
|
|
973
|
+
}
|
|
974
|
+
#upsertFill(fill) {
|
|
975
|
+
if (!_optionalChain([fill, 'optionalAccess', _11 => _11.id])) return;
|
|
976
|
+
this.#fills.delete(fill.id);
|
|
977
|
+
this.#fills.set(fill.id, fill);
|
|
978
|
+
if (this.#fills.size > this.#maxFills) {
|
|
979
|
+
const oldest = [...this.#fills.values()].sort(newestFirst).slice(this.#maxFills);
|
|
980
|
+
for (const f of oldest) this.#fills.delete(f.id);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
#upsertPosition(position) {
|
|
984
|
+
const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _12 => _12.market_id]), () => ( _optionalChain([position, 'optionalAccess', _13 => _13.id])));
|
|
985
|
+
if (!key) return;
|
|
986
|
+
if (!this.#keepFlat && isZero(position.position)) this.#positions.delete(key);
|
|
987
|
+
else this.#positions.set(key, position);
|
|
988
|
+
}
|
|
989
|
+
/** Leave the four channels. The socket stays open. */
|
|
990
|
+
async close() {
|
|
991
|
+
if (this.#closed) return;
|
|
992
|
+
this.#closed = true;
|
|
993
|
+
await Promise.all(
|
|
994
|
+
CHANNELS.map((name) => this.channels[name]).filter((c) => c !== void 0 && !c.closed).map((c) => c.leave())
|
|
995
|
+
);
|
|
996
|
+
}
|
|
997
|
+
}, _class2);
|
|
998
|
+
|
|
999
|
+
// src/money.ts
|
|
1000
|
+
var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
|
|
1001
|
+
var QUANTITY_FIELDS = ["total_volume", "volume_24h", "open_interest"];
|
|
1002
|
+
var LEVEL_LISTS = ["bids", "offers", "recent_trades"];
|
|
1003
|
+
var PRICE_RULE_FIELDS = /* @__PURE__ */ new Set(["from", "to", "inc"]);
|
|
1004
|
+
function toDecimal(value) {
|
|
1005
|
+
if (!Number.isFinite(value)) return void 0;
|
|
1006
|
+
const m = /^(-?)(\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/i.exec(String(value));
|
|
1007
|
+
if (!m) return void 0;
|
|
1008
|
+
const frac = _nullishCoalesce(m[3], () => ( ""));
|
|
1009
|
+
let digits = (m[2] + frac).replace(/^0+(?=\d)/, "");
|
|
1010
|
+
let scale = frac.length - Number(_nullishCoalesce(m[4], () => ( 0)));
|
|
1011
|
+
if (scale < 0) {
|
|
1012
|
+
digits += "0".repeat(-scale);
|
|
1013
|
+
scale = 0;
|
|
1014
|
+
}
|
|
1015
|
+
return { negative: m[1] === "-", digits, scale };
|
|
1016
|
+
}
|
|
1017
|
+
function format(dec, minPlaces) {
|
|
1018
|
+
let { digits, scale } = dec;
|
|
1019
|
+
while (scale > 0 && digits.endsWith("0") && digits.length > 1) {
|
|
1020
|
+
digits = digits.slice(0, -1);
|
|
1021
|
+
scale -= 1;
|
|
1022
|
+
}
|
|
1023
|
+
const places = Math.max(minPlaces, scale);
|
|
1024
|
+
digits += "0".repeat(places - scale);
|
|
1025
|
+
digits = digits.padStart(places + 1, "0");
|
|
1026
|
+
const intPart = digits.slice(0, digits.length - places);
|
|
1027
|
+
const fracPart = digits.slice(digits.length - places);
|
|
1028
|
+
const isZero2 = /^0*$/.test(intPart + fracPart);
|
|
1029
|
+
return `${dec.negative && !isZero2 ? "-" : ""}${intPart}${places ? "." + fracPart : ""}`;
|
|
1030
|
+
}
|
|
1031
|
+
function centsToDollars(value) {
|
|
1032
|
+
if (typeof value !== "number") return value;
|
|
1033
|
+
const dec = toDecimal(value);
|
|
1034
|
+
if (!dec) return value;
|
|
1035
|
+
return format({ ...dec, scale: dec.scale + 2 }, 4);
|
|
1036
|
+
}
|
|
1037
|
+
function toDollarString(value) {
|
|
1038
|
+
if (typeof value !== "number") return value;
|
|
1039
|
+
const dec = toDecimal(value);
|
|
1040
|
+
return dec ? format(dec, 4) : value;
|
|
1041
|
+
}
|
|
1042
|
+
function toQuantity(value) {
|
|
1043
|
+
if (typeof value !== "number") return value;
|
|
1044
|
+
const dec = toDecimal(value);
|
|
1045
|
+
return dec ? format(dec, 2) : value;
|
|
1046
|
+
}
|
|
1047
|
+
function convertMarketPayload(payload) {
|
|
1048
|
+
const out = { ...payload };
|
|
1049
|
+
for (const key of PRICE_FIELDS) if (key in out) out[key] = centsToDollars(out[key]);
|
|
1050
|
+
for (const key of QUANTITY_FIELDS) if (key in out) out[key] = toQuantity(out[key]);
|
|
1051
|
+
for (const key of LEVEL_LISTS) {
|
|
1052
|
+
const levels = out[key];
|
|
1053
|
+
if (Array.isArray(levels)) {
|
|
1054
|
+
out[key] = levels.map((level) => {
|
|
1055
|
+
if (!level || typeof level !== "object") return level;
|
|
1056
|
+
const l = { ...level };
|
|
1057
|
+
if ("price" in l) l.price = centsToDollars(l.price);
|
|
1058
|
+
if ("quantity" in l) l.quantity = toQuantity(l.quantity);
|
|
1059
|
+
return l;
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
const rules = out.order_price_rules;
|
|
1064
|
+
if (Array.isArray(rules)) {
|
|
1065
|
+
out.order_price_rules = rules.map(
|
|
1066
|
+
(rule) => rule && typeof rule === "object" ? Object.fromEntries(
|
|
1067
|
+
Object.entries(rule).map(([k, v]) => [k, PRICE_RULE_FIELDS.has(k) ? centsToDollars(v) : v])
|
|
1068
|
+
) : rule
|
|
1069
|
+
);
|
|
1070
|
+
}
|
|
1071
|
+
return out;
|
|
1072
|
+
}
|
|
1073
|
+
function convertMarketsFrame(payload) {
|
|
1074
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
|
|
1075
|
+
return Object.fromEntries(
|
|
1076
|
+
Object.entries(payload).map(([id, market]) => [
|
|
1077
|
+
id,
|
|
1078
|
+
market && typeof market === "object" && !Array.isArray(market) ? convertMarketPayload(market) : market
|
|
1079
|
+
])
|
|
1080
|
+
);
|
|
1081
|
+
}
|
|
1082
|
+
var BOOK_DOLLAR_FIELDS = ["p", "l", "tl"];
|
|
1083
|
+
var BOOK_QUANTITY_FIELDS = ["q", "tc"];
|
|
1084
|
+
function convertBook(ob) {
|
|
1085
|
+
if (!ob || typeof ob !== "object" || Array.isArray(ob)) return ob;
|
|
1086
|
+
const out = { ...ob };
|
|
1087
|
+
for (const side of ["b", "o"]) {
|
|
1088
|
+
const levels = out[side];
|
|
1089
|
+
if (!Array.isArray(levels)) continue;
|
|
1090
|
+
out[side] = levels.map((level) => {
|
|
1091
|
+
if (!level || typeof level !== "object") return level;
|
|
1092
|
+
const l = { ...level };
|
|
1093
|
+
for (const key of BOOK_DOLLAR_FIELDS) if (key in l) l[key] = toDollarString(l[key]);
|
|
1094
|
+
for (const key of BOOK_QUANTITY_FIELDS) if (key in l) l[key] = toQuantity(l[key]);
|
|
1095
|
+
return l;
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
return out;
|
|
1099
|
+
}
|
|
1100
|
+
function convertMarketChannelPayload(payload) {
|
|
1101
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return payload;
|
|
1102
|
+
const out = convertMarketPayload(payload);
|
|
1103
|
+
if ("ob" in out) out.ob = convertBook(out.ob);
|
|
1104
|
+
return out;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// src/ws.ts
|
|
1108
|
+
var _ws = require('ws'); var _ws2 = _interopRequireDefault(_ws);
|
|
1109
|
+
|
|
1110
|
+
// src/http.ts
|
|
1111
|
+
function quote(value, safe = "") {
|
|
1112
|
+
let out = encodeURIComponent(value).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
|
|
1113
|
+
if (safe.includes(",")) out = out.replace(/%2C/g, ",");
|
|
1114
|
+
return out;
|
|
1115
|
+
}
|
|
1116
|
+
function encodeValue(value) {
|
|
1117
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
1118
|
+
if (Array.isArray(value)) return value.map((v) => encodeValue(v)).join(",");
|
|
1119
|
+
return String(value);
|
|
1120
|
+
}
|
|
1121
|
+
function encodeQuery(params) {
|
|
1122
|
+
const parts = [];
|
|
1123
|
+
for (const [key, value] of Object.entries(params)) {
|
|
1124
|
+
if (value === null || value === void 0) continue;
|
|
1125
|
+
if (Array.isArray(value) && value.length === 0) continue;
|
|
1126
|
+
parts.push(`${quote(key)}=${quote(encodeValue(value), ",")}`);
|
|
1127
|
+
}
|
|
1128
|
+
return parts.join("&");
|
|
1129
|
+
}
|
|
1130
|
+
function buildRequest(operationId, args = {}) {
|
|
1131
|
+
const op = OPERATIONS[operationId];
|
|
1132
|
+
let path = op.path;
|
|
1133
|
+
for (const name of op.pathParams) {
|
|
1134
|
+
const value = _optionalChain([args, 'access', _14 => _14.pathParams, 'optionalAccess', _15 => _15[name]]);
|
|
1135
|
+
if (!value) throw new TypeError(`${name} is required`);
|
|
1136
|
+
path = path.replace(`{${name}}`, quote(String(value)));
|
|
1137
|
+
}
|
|
1138
|
+
const query = _nullishCoalesce(args.query, () => ( {}));
|
|
1139
|
+
const unknown = Object.keys(query).filter((k) => !op.query.includes(k));
|
|
1140
|
+
if (unknown.length) throw new TypeError(`${operationId} does not take ${unknown.sort().join(", ")}`);
|
|
1141
|
+
const qs = encodeQuery(query);
|
|
1142
|
+
if (qs) path = `${path}?${qs}`;
|
|
1143
|
+
const body = op.hasBody || args.body !== void 0 ? JSON.stringify(_nullishCoalesce(args.body, () => ( {}))) : void 0;
|
|
1144
|
+
return {
|
|
1145
|
+
operationId,
|
|
1146
|
+
method: op.method,
|
|
1147
|
+
path,
|
|
1148
|
+
body,
|
|
1149
|
+
idempotent: op.method === "GET" || op.method === "DELETE"
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
function decodeResponse(request, status, text, headers = {}) {
|
|
1153
|
+
let body;
|
|
1154
|
+
try {
|
|
1155
|
+
body = text ? JSON.parse(text) : null;
|
|
1156
|
+
} catch (e6) {
|
|
1157
|
+
body = text;
|
|
1158
|
+
}
|
|
1159
|
+
if (status >= 200 && status < 300) {
|
|
1160
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1161
|
+
throw new STXException(
|
|
1162
|
+
`Expected a JSON object from ${request.method} ${request.path}, got ${String(text).slice(0, 200)}`,
|
|
1163
|
+
{ statusCode: status, body, method: request.method, path: request.path }
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
return body;
|
|
1167
|
+
}
|
|
1168
|
+
throw errorForStatus(status, body, {
|
|
1169
|
+
method: request.method,
|
|
1170
|
+
path: request.path,
|
|
1171
|
+
retryAfter: headers.retryAfter,
|
|
1172
|
+
wwwAuthenticate: headers.wwwAuthenticate
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
function splitPage(operationId, body) {
|
|
1176
|
+
const op = OPERATIONS[operationId];
|
|
1177
|
+
const items = body[op.responseKey];
|
|
1178
|
+
const cursor = body.cursor;
|
|
1179
|
+
return [Array.isArray(items) ? items : [], typeof cursor === "string" && cursor ? cursor : null];
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// src/results.ts
|
|
1183
|
+
function toBatchOrderResult(raw) {
|
|
1184
|
+
const obj = raw && typeof raw === "object" ? raw : {};
|
|
1185
|
+
const order = _nullishCoalesce(obj.order, () => ( null));
|
|
1186
|
+
const errors = Array.isArray(obj.errors) ? obj.errors : null;
|
|
1187
|
+
return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _16 => _16.length]) };
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// src/client.ts
|
|
1191
|
+
var NEW_ORDER_FIELDS = {
|
|
1192
|
+
marketId: "market_id",
|
|
1193
|
+
action: "action",
|
|
1194
|
+
orderType: "order_type",
|
|
1195
|
+
price: "price",
|
|
1196
|
+
quantity: "quantity",
|
|
1197
|
+
clientOrderId: "client_order_id",
|
|
1198
|
+
expiration: "expiration",
|
|
1199
|
+
expirationTime: "expiration_time",
|
|
1200
|
+
cancelOnDisconnect: "cancel_on_disconnect",
|
|
1201
|
+
deviceId: "device_id"
|
|
1202
|
+
};
|
|
1203
|
+
function amount(name, value, required) {
|
|
1204
|
+
if (value === void 0 || value === null) {
|
|
1205
|
+
if (required) throw new TypeError(`${name} is required`);
|
|
1206
|
+
return void 0;
|
|
1207
|
+
}
|
|
1208
|
+
if (typeof value !== "string") {
|
|
1209
|
+
throw new TypeError(
|
|
1210
|
+
`${name} must be a decimal string such as ${name === "price" ? '"0.56"' : '"2"'}, got ${typeof value}`
|
|
1211
|
+
);
|
|
1212
|
+
}
|
|
1213
|
+
return value;
|
|
1214
|
+
}
|
|
1215
|
+
function orderBody(marketId, action, orderType, opts) {
|
|
1216
|
+
const body = {
|
|
1217
|
+
market_id: marketId,
|
|
1218
|
+
action,
|
|
1219
|
+
order_type: orderType,
|
|
1220
|
+
quantity: amount("quantity", opts.quantity, true)
|
|
1221
|
+
};
|
|
1222
|
+
const optional = {
|
|
1223
|
+
price: amount("price", opts.price, false),
|
|
1224
|
+
client_order_id: opts.clientOrderId,
|
|
1225
|
+
expiration: opts.expiration,
|
|
1226
|
+
expiration_time: opts.expirationTime,
|
|
1227
|
+
cancel_on_disconnect: opts.cancelOnDisconnect,
|
|
1228
|
+
device_id: opts.deviceId
|
|
1229
|
+
};
|
|
1230
|
+
for (const [k, v] of Object.entries(optional)) if (v !== void 0 && v !== null) body[k] = v;
|
|
1231
|
+
return body;
|
|
1232
|
+
}
|
|
1233
|
+
function normalizeOrder(order) {
|
|
1234
|
+
const unknown = Object.keys(order).filter((k) => !(k in NEW_ORDER_FIELDS));
|
|
1235
|
+
if (unknown.length) {
|
|
1236
|
+
throw new TypeError(
|
|
1237
|
+
`Unknown order fields ${JSON.stringify(unknown.sort())}; expected ${JSON.stringify(Object.keys(NEW_ORDER_FIELDS).sort())}`
|
|
1238
|
+
);
|
|
1239
|
+
}
|
|
1240
|
+
for (const key of ["marketId", "action", "orderType"]) {
|
|
1241
|
+
if (!order[key]) throw new TypeError(`${key} is required on every order`);
|
|
1242
|
+
}
|
|
1243
|
+
const { marketId, action, orderType, ...rest } = order;
|
|
1244
|
+
return orderBody(marketId, action, orderType, rest);
|
|
1245
|
+
}
|
|
1246
|
+
function ids(value) {
|
|
1247
|
+
if (value === void 0 || value === null) return void 0;
|
|
1248
|
+
return typeof value === "string" ? [value] : [...value];
|
|
1249
|
+
}
|
|
1250
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1251
|
+
var STX = (_class3 = class _STX {
|
|
1252
|
+
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
/** The API key, when one is configured. */
|
|
1256
|
+
|
|
1257
|
+
/** What authenticates requests: the API key, or the `auth` option. */
|
|
1258
|
+
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
#fetch;
|
|
1265
|
+
#me;
|
|
1266
|
+
/** Test hook: how retries wait. */
|
|
1267
|
+
__init4() {this._sleep = sleep}
|
|
1268
|
+
constructor(opts = {}) {;_class3.prototype.__init4.call(this);
|
|
1269
|
+
if (opts.auth && (opts.keyId || opts.privateKey || opts.signer)) {
|
|
1270
|
+
throw new STXConfigException("Pass `auth` or an API key (keyId with privateKey or signer), not both.");
|
|
1271
|
+
}
|
|
1272
|
+
const binaryKey = opts.privateKey !== void 0 && opts.privateKey !== null && typeof opts.privateKey !== "string" ? opts.privateKey : void 0;
|
|
1273
|
+
let region = opts.region;
|
|
1274
|
+
let env = opts.env;
|
|
1275
|
+
if (opts.environment !== void 0) {
|
|
1276
|
+
if (region !== void 0 || env !== void 0) {
|
|
1277
|
+
throw new STXConfigException("Pass `environment` or `region` + `env`, not both.");
|
|
1278
|
+
}
|
|
1279
|
+
const chosen = typeof opts.environment === "string" ? environmentNamed(opts.environment) : opts.environment;
|
|
1280
|
+
region = chosen.region;
|
|
1281
|
+
env = chosen.env;
|
|
1282
|
+
}
|
|
1283
|
+
const settings = resolveSettings({
|
|
1284
|
+
region,
|
|
1285
|
+
env,
|
|
1286
|
+
host: opts.host,
|
|
1287
|
+
// `auth` replaces the API key, so one from the environment is ignored.
|
|
1288
|
+
keyId: opts.auth ? null : opts.keyId,
|
|
1289
|
+
privateKey: opts.auth || binaryKey ? null : opts.privateKey,
|
|
1290
|
+
verifyTls: opts.verifyTls,
|
|
1291
|
+
profile: opts.profile
|
|
1292
|
+
});
|
|
1293
|
+
this.baseUrl = baseUrlFor(settings.region, settings.env, settings.host);
|
|
1294
|
+
this.socketUrl = socketUrlFor(this.baseUrl);
|
|
1295
|
+
this.profile = settings.profileName;
|
|
1296
|
+
let keyMaterial = _nullishCoalesce(binaryKey, () => ( settings.privateKey));
|
|
1297
|
+
if (opts.signer && opts.privateKey === void 0) keyMaterial = void 0;
|
|
1298
|
+
this.credentials = opts.auth ? void 0 : credentialsFromSettings(settings.keyId, keyMaterial, opts.signer);
|
|
1299
|
+
this.auth = _nullishCoalesce(opts.auth, () => ( this.credentials));
|
|
1300
|
+
this.verifyTls = settings.verifyTls;
|
|
1301
|
+
this.retry = _nullishCoalesce(opts.retry, () => ( new RetryPolicy()));
|
|
1302
|
+
this.timeoutMs = _nullishCoalesce(opts.timeoutMs, () => ( 3e4));
|
|
1303
|
+
this.geoLocation = opts.geoLocation;
|
|
1304
|
+
this.onResponse = opts.onResponse;
|
|
1305
|
+
const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
|
|
1306
|
+
if (typeof fetchImpl !== "function") {
|
|
1307
|
+
throw new STXConfigException("No fetch implementation available. Use Node 18+, or pass { fetch }.");
|
|
1308
|
+
}
|
|
1309
|
+
if (!this.verifyTls && !opts.fetch && this.baseUrl.startsWith("https://")) {
|
|
1310
|
+
throw new STXConfigException(
|
|
1311
|
+
"verifyTls: false needs a custom `fetch` for REST calls (Node's global fetch cannot skip certificate checks per call). Pass fetch, or use http:// for a local server."
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
this.#fetch = fetchImpl;
|
|
1315
|
+
}
|
|
1316
|
+
toString() {
|
|
1317
|
+
return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _17 => _17.credentials, 'optionalAccess', _18 => _18.keyId]), () => ( null)))})`;
|
|
1318
|
+
}
|
|
1319
|
+
/** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
|
|
1320
|
+
async close() {
|
|
1321
|
+
}
|
|
1322
|
+
async [ASYNC_DISPOSE]() {
|
|
1323
|
+
await this.close();
|
|
1324
|
+
}
|
|
1325
|
+
// ------------------------------------------------------------------
|
|
1326
|
+
// Transport
|
|
1327
|
+
// ------------------------------------------------------------------
|
|
1328
|
+
async #headers(request) {
|
|
1329
|
+
if (!this.auth) {
|
|
1330
|
+
throw new STXConfigException(
|
|
1331
|
+
"No API key configured. Pass keyId and privateKey (or set STX_KEY_ID and STX_PRIVATE_KEY, or use a profile in ~/.stx/credentials). Every REST route is signed."
|
|
1332
|
+
);
|
|
1333
|
+
}
|
|
1334
|
+
const headers = {
|
|
1335
|
+
"User-Agent": USER_AGENT,
|
|
1336
|
+
Accept: "application/json",
|
|
1337
|
+
...await this.auth.authHeaders({ method: request.method, path: request.path })
|
|
1338
|
+
};
|
|
1339
|
+
if (request.body !== void 0) headers["Content-Type"] = "application/json";
|
|
1340
|
+
return headers;
|
|
1341
|
+
}
|
|
1342
|
+
#report(request, status, attempt, started, responseBody) {
|
|
1343
|
+
if (!this.onResponse) return;
|
|
1344
|
+
try {
|
|
1345
|
+
this.onResponse({
|
|
1346
|
+
operationId: request.operationId,
|
|
1347
|
+
method: request.method,
|
|
1348
|
+
path: request.path,
|
|
1349
|
+
status,
|
|
1350
|
+
attempt,
|
|
1351
|
+
durationMs: Date.now() - started,
|
|
1352
|
+
authKind: _optionalChain([this, 'access', _19 => _19.auth, 'optionalAccess', _20 => _20.kind]),
|
|
1353
|
+
requestBody: request.body,
|
|
1354
|
+
responseBody
|
|
1355
|
+
});
|
|
1356
|
+
} catch (e7) {
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
async #sendOnce(request, attempt = 1) {
|
|
1360
|
+
const headers = await this.#headers(request);
|
|
1361
|
+
const controller = new AbortController();
|
|
1362
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
1363
|
+
const started = Date.now();
|
|
1364
|
+
let response;
|
|
1365
|
+
let text;
|
|
1366
|
+
try {
|
|
1367
|
+
response = await this.#fetch(this.baseUrl + request.path, {
|
|
1368
|
+
method: request.method,
|
|
1369
|
+
headers,
|
|
1370
|
+
body: request.body,
|
|
1371
|
+
signal: controller.signal
|
|
1372
|
+
});
|
|
1373
|
+
text = await response.text();
|
|
1374
|
+
} catch (err) {
|
|
1375
|
+
this.#report(request, null, attempt, started, null);
|
|
1376
|
+
if (controller.signal.aborted) {
|
|
1377
|
+
throw new STXTransportException(`${request.method} ${request.path} timed out after ${this.timeoutMs / 1e3}s`, {
|
|
1378
|
+
method: request.method,
|
|
1379
|
+
path: request.path,
|
|
1380
|
+
cause: err
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
1383
|
+
throw new STXTransportException(
|
|
1384
|
+
`${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _21 => _21.message]), () => ( String(err)))}`,
|
|
1385
|
+
{ method: request.method, path: request.path, cause: err }
|
|
1386
|
+
);
|
|
1387
|
+
} finally {
|
|
1388
|
+
clearTimeout(timer);
|
|
1389
|
+
}
|
|
1390
|
+
this.#report(request, response.status, attempt, started, text);
|
|
1391
|
+
return decodeResponse(request, response.status, text, {
|
|
1392
|
+
retryAfter: response.headers.get("Retry-After"),
|
|
1393
|
+
wwwAuthenticate: response.headers.get("WWW-Authenticate")
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
async #send(request) {
|
|
1397
|
+
let attempt = 1;
|
|
1398
|
+
let sent = 0;
|
|
1399
|
+
let reauthenticated = false;
|
|
1400
|
+
for (; ; ) {
|
|
1401
|
+
try {
|
|
1402
|
+
sent += 1;
|
|
1403
|
+
return await this.#sendOnce(request, sent);
|
|
1404
|
+
} catch (err) {
|
|
1405
|
+
if (!(err instanceof STXException)) throw err;
|
|
1406
|
+
if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _22 => _22.auth, 'optionalAccess', _23 => _23.onUnauthorized])) {
|
|
1407
|
+
reauthenticated = true;
|
|
1408
|
+
if (await this.auth.onUnauthorized()) continue;
|
|
1409
|
+
}
|
|
1410
|
+
if (!this.retry.shouldRetry(err, attempt, request.idempotent)) throw err;
|
|
1411
|
+
await this._sleep(this.retry.computeBackoffMs(attempt, err));
|
|
1412
|
+
attempt += 1;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
async #call(operationId, args = {}) {
|
|
1417
|
+
return this.#send(buildRequest(operationId, args));
|
|
1418
|
+
}
|
|
1419
|
+
async #one(operationId, args = {}) {
|
|
1420
|
+
const body = await this.#call(operationId, args);
|
|
1421
|
+
const key = OPERATIONS[operationId].responseKey;
|
|
1422
|
+
return key ? body[key] : body;
|
|
1423
|
+
}
|
|
1424
|
+
async #list(operationId, args = {}) {
|
|
1425
|
+
const [items] = splitPage(operationId, await this.#call(operationId, args));
|
|
1426
|
+
return items;
|
|
1427
|
+
}
|
|
1428
|
+
async #page(operationId, query) {
|
|
1429
|
+
const [items, cursor] = splitPage(operationId, await this.#call(operationId, { query }));
|
|
1430
|
+
return new Page(items, cursor);
|
|
1431
|
+
}
|
|
1432
|
+
async *#iterate(operationId, query) {
|
|
1433
|
+
const q = { ...query };
|
|
1434
|
+
for (; ; ) {
|
|
1435
|
+
const page = await this.#page(operationId, q);
|
|
1436
|
+
yield* page.items;
|
|
1437
|
+
if (!page.cursor) return;
|
|
1438
|
+
q.cursor = page.cursor;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
async #geoBody(body, opts) {
|
|
1442
|
+
const packet = _optionalChain([opts, 'optionalAccess', _24 => _24.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
|
|
1443
|
+
return packet === void 0 ? body : { ...body, geo_location: packet };
|
|
1444
|
+
}
|
|
1445
|
+
// ------------------------------------------------------------------
|
|
1446
|
+
// Identity
|
|
1447
|
+
// ------------------------------------------------------------------
|
|
1448
|
+
/**
|
|
1449
|
+
* `GET /api/v1/me`: who this key belongs to. Returns the `user_id` the
|
|
1450
|
+
* account channels are keyed by, the `account_id`, and the key's `scope`
|
|
1451
|
+
* (`read_only` or `read_write`).
|
|
1452
|
+
*/
|
|
1453
|
+
async me() {
|
|
1454
|
+
this.#me = await this.#one("me_get");
|
|
1455
|
+
return this.#me;
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* The user id from `me()`, fetched once and cached. An OAuth token granted
|
|
1459
|
+
* without `profile.read` cannot call `me()`; the id then comes from
|
|
1460
|
+
* `balance()` (`balance.read`), which carries the same `user_id`.
|
|
1461
|
+
*/
|
|
1462
|
+
async userId() {
|
|
1463
|
+
if (_optionalChain([this, 'access', _25 => _25.#me, 'optionalAccess', _26 => _26.user_id])) return this.#me.user_id;
|
|
1464
|
+
try {
|
|
1465
|
+
await this.me();
|
|
1466
|
+
} catch (err) {
|
|
1467
|
+
if (!(err instanceof STXForbiddenException)) throw err;
|
|
1468
|
+
const balance = await this.balance().catch(() => {
|
|
1469
|
+
throw err;
|
|
1470
|
+
});
|
|
1471
|
+
if (!balance.user_id) throw err;
|
|
1472
|
+
this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
|
|
1473
|
+
}
|
|
1474
|
+
if (!_optionalChain([this, 'access', _27 => _27.#me, 'optionalAccess', _28 => _28.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
|
|
1475
|
+
return this.#me.user_id;
|
|
1476
|
+
}
|
|
1477
|
+
// ------------------------------------------------------------------
|
|
1478
|
+
// Markets and events
|
|
1479
|
+
// ------------------------------------------------------------------
|
|
1480
|
+
static #marketsQuery(q) {
|
|
1481
|
+
return {
|
|
1482
|
+
market_ids: ids(q.marketIds),
|
|
1483
|
+
event_ids: ids(q.eventIds),
|
|
1484
|
+
status: ids(q.status),
|
|
1485
|
+
trading: q.trading,
|
|
1486
|
+
sports: ids(q.sports),
|
|
1487
|
+
competitions: ids(q.competitions),
|
|
1488
|
+
"sort_by[name]": q.sortBy,
|
|
1489
|
+
"sort_by[direction]": q.sortDirection,
|
|
1490
|
+
limit: q.limit,
|
|
1491
|
+
cursor: q.cursor
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* `GET /api/v1/markets`: one page of markets. Filters combine with AND;
|
|
1496
|
+
* list filters match any value.
|
|
1497
|
+
*/
|
|
1498
|
+
markets(query = {}) {
|
|
1499
|
+
return this.#page("markets_get", _STX.#marketsQuery(query));
|
|
1500
|
+
}
|
|
1501
|
+
/** Every market matching the filters, following the cursor. */
|
|
1502
|
+
iterMarkets(query = {}) {
|
|
1503
|
+
return this.#iterate("markets_get", _STX.#marketsQuery({ ...query, cursor: void 0 }));
|
|
1504
|
+
}
|
|
1505
|
+
/** One market by id. Throws `STXNotFoundException` if there is none. */
|
|
1506
|
+
async market(marketId) {
|
|
1507
|
+
const page = await this.markets({ marketIds: [marketId], limit: 1 });
|
|
1508
|
+
const first = page.items[0];
|
|
1509
|
+
if (!first) throw new STXNotFoundException(`Market ${marketId} not found`, { statusCode: 404 });
|
|
1510
|
+
return first;
|
|
1511
|
+
}
|
|
1512
|
+
static #eventsQuery(q) {
|
|
1513
|
+
return {
|
|
1514
|
+
event_ids: ids(q.eventIds),
|
|
1515
|
+
sports: ids(q.sports),
|
|
1516
|
+
competitions: ids(q.competitions),
|
|
1517
|
+
event_types: ids(q.eventTypes),
|
|
1518
|
+
title: q.title,
|
|
1519
|
+
status: q.status,
|
|
1520
|
+
promoted: q.promoted,
|
|
1521
|
+
"sort_by[name]": q.sortBy,
|
|
1522
|
+
"sort_by[direction]": q.sortDirection,
|
|
1523
|
+
limit: q.limit,
|
|
1524
|
+
cursor: q.cursor
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
/** `GET /api/v1/events`: one page of events. */
|
|
1528
|
+
events(query = {}) {
|
|
1529
|
+
return this.#page("events_get", _STX.#eventsQuery(query));
|
|
1530
|
+
}
|
|
1531
|
+
/** Every event matching the filters, following the cursor. */
|
|
1532
|
+
iterEvents(query = {}) {
|
|
1533
|
+
return this.#iterate("events_get", _STX.#eventsQuery({ ...query, cursor: void 0 }));
|
|
1534
|
+
}
|
|
1535
|
+
// ------------------------------------------------------------------
|
|
1536
|
+
// Orders
|
|
1537
|
+
// ------------------------------------------------------------------
|
|
1538
|
+
static #ordersQuery(q) {
|
|
1539
|
+
return {
|
|
1540
|
+
order_ids: ids(q.orderIds),
|
|
1541
|
+
client_order_ids: ids(q.clientOrderIds),
|
|
1542
|
+
market_ids: ids(q.marketIds),
|
|
1543
|
+
status: ids(q.status),
|
|
1544
|
+
limit: q.limit,
|
|
1545
|
+
cursor: q.cursor
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
/** `GET /api/v1/orders`: one page of your orders, newest first. */
|
|
1549
|
+
orders(query = {}) {
|
|
1550
|
+
return this.#page("orders_get", _STX.#ordersQuery(query));
|
|
1551
|
+
}
|
|
1552
|
+
/** Every order matching the filters, following the cursor. */
|
|
1553
|
+
iterOrders(query = {}) {
|
|
1554
|
+
return this.#iterate("orders_get", _STX.#ordersQuery({ ...query, cursor: void 0 }));
|
|
1555
|
+
}
|
|
1556
|
+
/** `GET /api/v1/orders/{order_id}`: one of your orders. */
|
|
1557
|
+
order(orderId) {
|
|
1558
|
+
return this.#one("orders__id_get", { pathParams: { order_id: orderId } });
|
|
1559
|
+
}
|
|
1560
|
+
/**
|
|
1561
|
+
* `POST /api/v1/orders`: place one order.
|
|
1562
|
+
*
|
|
1563
|
+
* `action` is `"buy"` or `"sell"`; `orderType` is `"limit"` or `"market"`.
|
|
1564
|
+
* `price` (dollars, required for a limit order) and `quantity` (contracts)
|
|
1565
|
+
* are decimal strings, e.g. `{ price: "0.56", quantity: "2" }`. Numbers are
|
|
1566
|
+
* refused client-side.
|
|
1567
|
+
*
|
|
1568
|
+
* The exchange validates the order: a bad price step or a fractional
|
|
1569
|
+
* quantity throws `STXValidationException` (400) or `STXRejectedException`
|
|
1570
|
+
* (422) with the API's message; a geo-fencing refusal throws
|
|
1571
|
+
* `STXGeoLocationException`.
|
|
1572
|
+
*
|
|
1573
|
+
* A POST is never retried after a 5xx or a dropped connection; pass
|
|
1574
|
+
* `clientOrderId` so you can look the order up if that happens.
|
|
1575
|
+
*/
|
|
1576
|
+
async placeOrder(marketId, action, orderType, opts) {
|
|
1577
|
+
const { geoLocation, ...fields } = _nullishCoalesce(opts, () => ( {}));
|
|
1578
|
+
const body = orderBody(marketId, action, orderType, fields);
|
|
1579
|
+
return this.#one("orders_post", { body: await this.#geoBody(body, { geoLocation }) });
|
|
1580
|
+
}
|
|
1581
|
+
/**
|
|
1582
|
+
* `POST /api/v1/orders/batched`: place several orders in one call. One geo
|
|
1583
|
+
* check covers the batch. Returns one result per order, in order; a
|
|
1584
|
+
* rejected order has `errors` instead of `order` and does not stop the
|
|
1585
|
+
* others.
|
|
1586
|
+
*/
|
|
1587
|
+
async placeOrders(orders, opts) {
|
|
1588
|
+
const body = { orders: orders.map(normalizeOrder) };
|
|
1589
|
+
const raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
|
|
1590
|
+
return raw.map(toBatchOrderResult);
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* `DELETE /api/v1/orders/{order_id}`: request a cancel. A cancel is a
|
|
1594
|
+
* request: a fill already in flight can still land.
|
|
1595
|
+
*/
|
|
1596
|
+
async cancelOrder(orderId, opts) {
|
|
1597
|
+
const geo = await this.#geoBody({}, opts);
|
|
1598
|
+
return this.#one("orders__order_id_delete", {
|
|
1599
|
+
pathParams: { order_id: orderId },
|
|
1600
|
+
body: "geo_location" in geo ? geo : void 0
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
/** `DELETE /api/v1/orders/batched`: cancel the named orders. */
|
|
1604
|
+
async cancelOrders(orderIds, opts) {
|
|
1605
|
+
const body = { orders: orderIds.map((id) => ({ order_id: id })) };
|
|
1606
|
+
return this.#list("orders_batched_delete", { body: await this.#geoBody(body, opts) });
|
|
1607
|
+
}
|
|
1608
|
+
/** `DELETE /api/v1/orders/all`: cancel everything resting on the account. */
|
|
1609
|
+
async cancelAllOrders(opts) {
|
|
1610
|
+
const geo = await this.#geoBody({}, opts);
|
|
1611
|
+
return this.#list("orders_all_delete", { body: "geo_location" in geo ? geo : void 0 });
|
|
1612
|
+
}
|
|
1613
|
+
// ------------------------------------------------------------------
|
|
1614
|
+
// Geo-fencing
|
|
1615
|
+
// ------------------------------------------------------------------
|
|
1616
|
+
/**
|
|
1617
|
+
* Ask the exchange whether this machine may trade right now, without
|
|
1618
|
+
* placing or cancelling anything.
|
|
1619
|
+
*
|
|
1620
|
+
* Sends `DELETE /api/v1/orders/00000000-0000-0000-0000-000000000000` (an
|
|
1621
|
+
* order id that cannot exist) with the geolocation packet, if one is
|
|
1622
|
+
* configured. The exchange runs its geo check before it looks the order
|
|
1623
|
+
* up, so a 404 means the check passed, and a geo 422 means it did not. On
|
|
1624
|
+
* an exchange without geo-fencing it always passes.
|
|
1625
|
+
*
|
|
1626
|
+
* Needs a `read_write` key (the probe is a write route). The exchange
|
|
1627
|
+
* records a failed check in its geolocation log exactly as it would a real
|
|
1628
|
+
* order from the same place, and may raise a compliance alert, so call it
|
|
1629
|
+
* once at start-up, not in a loop.
|
|
1630
|
+
*/
|
|
1631
|
+
async geoCheck(opts) {
|
|
1632
|
+
const geo = await this.#geoBody({}, opts);
|
|
1633
|
+
const sentPacket = "geo_location" in geo;
|
|
1634
|
+
try {
|
|
1635
|
+
await this.#one("orders__order_id_delete", {
|
|
1636
|
+
pathParams: { order_id: "00000000-0000-0000-0000-000000000000" },
|
|
1637
|
+
body: sentPacket ? geo : void 0
|
|
1638
|
+
});
|
|
1639
|
+
return { allowed: true, sentPacket };
|
|
1640
|
+
} catch (err) {
|
|
1641
|
+
if (err instanceof STXNotFoundException) return { allowed: true, sentPacket };
|
|
1642
|
+
if (err instanceof STXGeoLocationException) {
|
|
1643
|
+
return { allowed: false, reason: err.reason, message: err.message, ipAddress: err.ipAddress, sentPacket };
|
|
1644
|
+
}
|
|
1645
|
+
throw err;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
// ------------------------------------------------------------------
|
|
1649
|
+
// Fills, positions, balance
|
|
1650
|
+
// ------------------------------------------------------------------
|
|
1651
|
+
static #fillsQuery(q) {
|
|
1652
|
+
return {
|
|
1653
|
+
market_ids: ids(q.marketIds),
|
|
1654
|
+
order_ids: ids(q.orderIds),
|
|
1655
|
+
status: q.status,
|
|
1656
|
+
limit: q.limit,
|
|
1657
|
+
cursor: q.cursor
|
|
1658
|
+
};
|
|
1659
|
+
}
|
|
1660
|
+
/** `GET /api/v1/fills`: one page of your executions. */
|
|
1661
|
+
fills(query = {}) {
|
|
1662
|
+
return this.#page("fills_get", _STX.#fillsQuery(query));
|
|
1663
|
+
}
|
|
1664
|
+
/** Every fill matching the filters, following the cursor. */
|
|
1665
|
+
iterFills(query = {}) {
|
|
1666
|
+
return this.#iterate("fills_get", _STX.#fillsQuery({ ...query, cursor: void 0 }));
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* `GET /api/v1/positions`: your open positions, the same objects the
|
|
1670
|
+
* `positions` channel sends on join. `position` is positive when long,
|
|
1671
|
+
* negative when short.
|
|
1672
|
+
*/
|
|
1673
|
+
positions(query = {}) {
|
|
1674
|
+
return this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* `GET /api/v1/account/balance`: balance, liabilities and fee schedule.
|
|
1678
|
+
* The same object the `balances` channel pushes.
|
|
1679
|
+
*/
|
|
1680
|
+
balance() {
|
|
1681
|
+
return this.#one("account_balance_get");
|
|
1682
|
+
}
|
|
1683
|
+
static #marketStatsQuery(q) {
|
|
1684
|
+
return {
|
|
1685
|
+
market_ids: ids(q.marketIds),
|
|
1686
|
+
event_ids: ids(q.eventIds),
|
|
1687
|
+
exclude_zero_settlements: q.excludeZeroSettlements,
|
|
1688
|
+
from_time: q.fromTime,
|
|
1689
|
+
to_time: q.toTime,
|
|
1690
|
+
sports: ids(q.sports),
|
|
1691
|
+
competitions: ids(q.competitions),
|
|
1692
|
+
limit: q.limit,
|
|
1693
|
+
cursor: q.cursor
|
|
1694
|
+
};
|
|
1695
|
+
}
|
|
1696
|
+
/**
|
|
1697
|
+
* `GET /api/v1/account/market_stats`: your exposure and P&L per market.
|
|
1698
|
+
* Not the public `market_stats` channel, which carries prices.
|
|
1699
|
+
*/
|
|
1700
|
+
accountMarketStats(query = {}) {
|
|
1701
|
+
return this.#page("account_market_stats_get", _STX.#marketStatsQuery(query));
|
|
1702
|
+
}
|
|
1703
|
+
/** Every per-market stat row, following the cursor. */
|
|
1704
|
+
iterAccountMarketStats(query = {}) {
|
|
1705
|
+
return this.#iterate("account_market_stats_get", _STX.#marketStatsQuery({ ...query, cursor: void 0 }));
|
|
1706
|
+
}
|
|
1707
|
+
// ------------------------------------------------------------------
|
|
1708
|
+
// Portfolio history
|
|
1709
|
+
// ------------------------------------------------------------------
|
|
1710
|
+
/** `GET /api/v1/portfolio/settlements`: settlements on your account. */
|
|
1711
|
+
settlements(query = {}) {
|
|
1712
|
+
const { marketIds, type, limit, cursor } = query;
|
|
1713
|
+
return this.#page("portfolio_settlements_get", { market_ids: ids(marketIds), type, limit, cursor });
|
|
1714
|
+
}
|
|
1715
|
+
/** Every settlement, following the cursor. */
|
|
1716
|
+
iterSettlements(query = {}) {
|
|
1717
|
+
const { marketIds, type, limit } = query;
|
|
1718
|
+
return this.#iterate("portfolio_settlements_get", { market_ids: ids(marketIds), type, limit });
|
|
1719
|
+
}
|
|
1720
|
+
/** `GET /api/v1/portfolio/deposits`. */
|
|
1721
|
+
deposits(query = {}) {
|
|
1722
|
+
return this.#page("portfolio_deposits_get", { limit: query.limit, cursor: query.cursor });
|
|
1723
|
+
}
|
|
1724
|
+
/** Every deposit, following the cursor. */
|
|
1725
|
+
iterDeposits(query = {}) {
|
|
1726
|
+
return this.#iterate("portfolio_deposits_get", { limit: query.limit });
|
|
1727
|
+
}
|
|
1728
|
+
/** `GET /api/v1/portfolio/withdrawals`. */
|
|
1729
|
+
withdrawals(query = {}) {
|
|
1730
|
+
return this.#page("portfolio_withdrawals_get", { limit: query.limit, cursor: query.cursor });
|
|
1731
|
+
}
|
|
1732
|
+
/** Every withdrawal, following the cursor. */
|
|
1733
|
+
iterWithdrawals(query = {}) {
|
|
1734
|
+
return this.#iterate("portfolio_withdrawals_get", { limit: query.limit });
|
|
1735
|
+
}
|
|
1736
|
+
/** `GET /api/v1/portfolio/adjustments`: manual balance adjustments. */
|
|
1737
|
+
adjustments(query = {}) {
|
|
1738
|
+
return this.#page("portfolio_adjustments_get", { limit: query.limit, cursor: query.cursor });
|
|
1739
|
+
}
|
|
1740
|
+
/** Every adjustment, following the cursor. */
|
|
1741
|
+
iterAdjustments(query = {}) {
|
|
1742
|
+
return this.#iterate("portfolio_adjustments_get", { limit: query.limit });
|
|
1743
|
+
}
|
|
1744
|
+
/** `GET /api/v1/portfolio/fees`: fee and fee-refund entries. */
|
|
1745
|
+
fees(query = {}) {
|
|
1746
|
+
return this.#page("portfolio_fees_get", { limit: query.limit, cursor: query.cursor });
|
|
1747
|
+
}
|
|
1748
|
+
/** Every fee entry, following the cursor. */
|
|
1749
|
+
iterFees(query = {}) {
|
|
1750
|
+
return this.#iterate("portfolio_fees_get", { limit: query.limit });
|
|
1751
|
+
}
|
|
1752
|
+
/** `GET /api/v1/portfolio/loyalty`: loyalty entries. */
|
|
1753
|
+
loyalty(query = {}) {
|
|
1754
|
+
return this.#page("portfolio_loyalty_get", { limit: query.limit, cursor: query.cursor });
|
|
1755
|
+
}
|
|
1756
|
+
/** Every loyalty entry, following the cursor. */
|
|
1757
|
+
iterLoyalty(query = {}) {
|
|
1758
|
+
return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
|
|
1759
|
+
}
|
|
1760
|
+
// ------------------------------------------------------------------
|
|
1761
|
+
// Terms
|
|
1762
|
+
// ------------------------------------------------------------------
|
|
1763
|
+
/** `POST /api/v1/tnc/accept`: accept the current terms. Resolves to the server's message. */
|
|
1764
|
+
async acceptTerms(deviceId, opts = {}) {
|
|
1765
|
+
const body = {
|
|
1766
|
+
device_id: deviceId,
|
|
1767
|
+
accept_terms: _nullishCoalesce(opts.acceptTerms, () => ( true)),
|
|
1768
|
+
accept_privacy: _nullishCoalesce(opts.acceptPrivacy, () => ( true))
|
|
1769
|
+
};
|
|
1770
|
+
if (opts.acceptHouseRules !== void 0) body.accept_house_rules = opts.acceptHouseRules;
|
|
1771
|
+
const result = await this.#call("tnc_accept_post", { body });
|
|
1772
|
+
return String(_nullishCoalesce(result.message, () => ( "")));
|
|
1773
|
+
}
|
|
1774
|
+
// ------------------------------------------------------------------
|
|
1775
|
+
// WebSocket
|
|
1776
|
+
// ------------------------------------------------------------------
|
|
1777
|
+
/**
|
|
1778
|
+
* An `STXWebSocket` using this client's host and key. Account channels
|
|
1779
|
+
* need your user id; the socket fetches it through `me()` on first use.
|
|
1780
|
+
*/
|
|
1781
|
+
websocket(opts = {}) {
|
|
1782
|
+
return new STXWebSocket({ ...opts, rest: this });
|
|
1783
|
+
}
|
|
1784
|
+
}, _class3);
|
|
1785
|
+
|
|
1786
|
+
// src/ws.ts
|
|
1787
|
+
var PHOENIX_TOPIC = "phoenix";
|
|
1788
|
+
var SNAPSHOT_EVENTS = {
|
|
1789
|
+
orders: ["all_orders"],
|
|
1790
|
+
fills: ["all_trades"],
|
|
1791
|
+
positions: ["all_positions"],
|
|
1792
|
+
balances: ["balances"],
|
|
1793
|
+
account: ["all_orders", "all_trades", "all_positions", "balances"],
|
|
1794
|
+
user_info: ["user_updated"]
|
|
1795
|
+
};
|
|
1796
|
+
var REPLY_SNAPSHOT_CHANNELS = /* @__PURE__ */ new Set(["market_stats", "market"]);
|
|
1797
|
+
var ChannelMessage = class {
|
|
1798
|
+
constructor(topic, event, payload, ref = null, joinRef = null) {
|
|
1799
|
+
this.topic = topic;
|
|
1800
|
+
this.event = event;
|
|
1801
|
+
this.payload = payload;
|
|
1802
|
+
this.ref = ref;
|
|
1803
|
+
this.joinRef = joinRef;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
|
|
1807
|
+
|
|
1808
|
+
|
|
1809
|
+
|
|
1810
|
+
/** The topic without the user id: `"orders"` for `orders:<user_id>`. */
|
|
1811
|
+
get channel() {
|
|
1812
|
+
return this.topic.split(":", 1)[0];
|
|
1813
|
+
}
|
|
1814
|
+
/** True for the state-on-join events (`all_orders`, `balances`, ...). */
|
|
1815
|
+
get isSnapshot() {
|
|
1816
|
+
return (_nullishCoalesce(SNAPSHOT_EVENTS[this.channel], () => ( []))).includes(this.event);
|
|
1817
|
+
}
|
|
1818
|
+
};
|
|
1819
|
+
var ReconnectPolicy = class {
|
|
1820
|
+
|
|
1821
|
+
|
|
1822
|
+
|
|
1823
|
+
|
|
1824
|
+
constructor(opts = {}) {
|
|
1825
|
+
this.initialBackoffMs = _nullishCoalesce(opts.initialBackoffMs, () => ( 500));
|
|
1826
|
+
this.maxBackoffMs = _nullishCoalesce(opts.maxBackoffMs, () => ( 3e4));
|
|
1827
|
+
this.maxAttempts = _nullishCoalesce(opts.maxAttempts, () => ( null));
|
|
1828
|
+
this.jitter = _nullishCoalesce(opts.jitter, () => ( true));
|
|
1829
|
+
}
|
|
1830
|
+
delayMs(attempt) {
|
|
1831
|
+
const base = Math.min(this.initialBackoffMs * 2 ** (attempt - 1), this.maxBackoffMs);
|
|
1832
|
+
return this.jitter ? base * (0.5 + Math.random() * 0.5) : base;
|
|
1833
|
+
}
|
|
1834
|
+
};
|
|
1835
|
+
var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1836
|
+
var TimeoutError = class extends Error {
|
|
1837
|
+
};
|
|
1838
|
+
var MessageQueue = class {
|
|
1839
|
+
constructor(max) {
|
|
1840
|
+
this.max = max;
|
|
1841
|
+
}
|
|
1842
|
+
|
|
1843
|
+
#items = [];
|
|
1844
|
+
#waiters = [];
|
|
1845
|
+
put(msg) {
|
|
1846
|
+
const waiter = this.#waiters.shift();
|
|
1847
|
+
if (waiter) {
|
|
1848
|
+
waiter(msg);
|
|
1849
|
+
return false;
|
|
1850
|
+
}
|
|
1851
|
+
let dropped = false;
|
|
1852
|
+
if (this.#items.length >= this.max) {
|
|
1853
|
+
this.#items.shift();
|
|
1854
|
+
dropped = true;
|
|
1855
|
+
}
|
|
1856
|
+
this.#items.push(msg);
|
|
1857
|
+
return dropped;
|
|
1858
|
+
}
|
|
1859
|
+
get(timeoutMs) {
|
|
1860
|
+
if (this.#items.length) return Promise.resolve(this.#items.shift());
|
|
1861
|
+
return new Promise((resolve, reject) => {
|
|
1862
|
+
let timer;
|
|
1863
|
+
const waiter = (msg) => {
|
|
1864
|
+
if (timer) clearTimeout(timer);
|
|
1865
|
+
resolve(msg);
|
|
1866
|
+
};
|
|
1867
|
+
this.#waiters.push(waiter);
|
|
1868
|
+
if (timeoutMs !== void 0 && timeoutMs !== null) {
|
|
1869
|
+
timer = setTimeout(() => {
|
|
1870
|
+
this.#waiters = this.#waiters.filter((w) => w !== waiter);
|
|
1871
|
+
reject(new TimeoutError(`no message within ${timeoutMs} ms`));
|
|
1872
|
+
}, timeoutMs);
|
|
1873
|
+
}
|
|
1874
|
+
});
|
|
1875
|
+
}
|
|
1876
|
+
};
|
|
1877
|
+
var Channel = (_class4 = class {
|
|
1878
|
+
/** The wire topic, e.g. `orders:<user_id>`. */
|
|
1879
|
+
|
|
1880
|
+
/** The topic without the user id, e.g. `orders`. */
|
|
1881
|
+
|
|
1882
|
+
/** What the next (re)join sends; updated by the `select*` and `watch` helpers so a reconnect keeps them. */
|
|
1883
|
+
|
|
1884
|
+
|
|
1885
|
+
|
|
1886
|
+
/** The `response` object from the latest join reply, e.g. `{selected_market_ids: null}`. */
|
|
1887
|
+
__init5() {this.reply = {}}
|
|
1888
|
+
/** The latest snapshot payload per snapshot event name. */
|
|
1889
|
+
__init6() {this.snapshots = {}}
|
|
1890
|
+
/** Market ids watched on `market_updates`; re-sent after a reconnect. */
|
|
1891
|
+
__init7() {this.watches = []}
|
|
1892
|
+
__init8() {this.joinRef = null}
|
|
1893
|
+
__init9() {this.joined = false}
|
|
1894
|
+
__init10() {this.closed = false}
|
|
1895
|
+
#ws;
|
|
1896
|
+
#queue;
|
|
1897
|
+
#snapshotWaiters = [];
|
|
1898
|
+
#pingTimer;
|
|
1899
|
+
constructor(ws, topic, joinPayload, onMessage, opts) {;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);_class4.prototype.__init7.call(this);_class4.prototype.__init8.call(this);_class4.prototype.__init9.call(this);_class4.prototype.__init10.call(this);
|
|
1900
|
+
this.#ws = ws;
|
|
1901
|
+
this.topic = topic;
|
|
1902
|
+
this.name = topic.split(":", 1)[0];
|
|
1903
|
+
this.joinPayload = { ...joinPayload };
|
|
1904
|
+
this.onMessage = onMessage;
|
|
1905
|
+
this.pingIntervalMs = opts.pingIntervalMs;
|
|
1906
|
+
this.#queue = new MessageQueue(opts.queueSize);
|
|
1907
|
+
}
|
|
1908
|
+
toString() {
|
|
1909
|
+
return `Channel(${this.topic}, ${this.joined ? "joined" : this.closed ? "closed" : "joining"})`;
|
|
1910
|
+
}
|
|
1911
|
+
// -- receiving --------------------------------------------------------
|
|
1912
|
+
async *[Symbol.asyncIterator]() {
|
|
1913
|
+
for (; ; ) {
|
|
1914
|
+
const msg = await this.#queue.get();
|
|
1915
|
+
if (msg === null) return;
|
|
1916
|
+
yield msg;
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
/**
|
|
1920
|
+
* The next message on this channel. Rejects with `STXChannelException` if
|
|
1921
|
+
* none arrives within `timeoutMs` or the channel closes.
|
|
1922
|
+
*/
|
|
1923
|
+
async next(timeoutMs) {
|
|
1924
|
+
let msg;
|
|
1925
|
+
try {
|
|
1926
|
+
msg = await this.#queue.get(timeoutMs);
|
|
1927
|
+
} catch (err) {
|
|
1928
|
+
if (err instanceof TimeoutError) {
|
|
1929
|
+
throw new STXTimeoutException(`No message on ${this.topic} within ${timeoutMs} ms`, { topic: this.topic });
|
|
1930
|
+
}
|
|
1931
|
+
throw err;
|
|
1932
|
+
}
|
|
1933
|
+
if (msg === null) throw new STXChannelException(`${this.topic} is closed`, { topic: this.topic });
|
|
1934
|
+
return msg;
|
|
1935
|
+
}
|
|
1936
|
+
/**
|
|
1937
|
+
* Wait for the state-on-join and return it as `{event: payload}`. `orders`
|
|
1938
|
+
* gives `{all_orders: {...}}`; `account` waits for all four of its
|
|
1939
|
+
* snapshots. `market_stats` and `market:<id>` return the join reply, which
|
|
1940
|
+
* carries the series or the whole market. Channels with no snapshot (`settlements`, `ticker`, `trades`,
|
|
1941
|
+
* `orderbook`, `markets`, `market_updates`) throw.
|
|
1942
|
+
*/
|
|
1943
|
+
async waitSnapshot(timeoutMs = 1e4) {
|
|
1944
|
+
if (REPLY_SNAPSHOT_CHANNELS.has(this.name)) return { reply: this.reply };
|
|
1945
|
+
const expected = SNAPSHOT_EVENTS[this.name];
|
|
1946
|
+
if (!expected) throw new TypeError(`${this.name} sends no snapshot on join`);
|
|
1947
|
+
if (!expected.every((e) => e in this.snapshots)) {
|
|
1948
|
+
await new Promise((resolve, reject) => {
|
|
1949
|
+
let timer;
|
|
1950
|
+
const waiter = () => {
|
|
1951
|
+
if (timer) clearTimeout(timer);
|
|
1952
|
+
resolve();
|
|
1953
|
+
};
|
|
1954
|
+
this.#snapshotWaiters.push(waiter);
|
|
1955
|
+
if (timeoutMs !== null) {
|
|
1956
|
+
timer = setTimeout(() => {
|
|
1957
|
+
this.#snapshotWaiters = this.#snapshotWaiters.filter((w) => w !== waiter);
|
|
1958
|
+
reject(
|
|
1959
|
+
new STXTimeoutException(`No snapshot on ${this.topic} within ${timeoutMs} ms`, { topic: this.topic })
|
|
1960
|
+
);
|
|
1961
|
+
}, timeoutMs);
|
|
1962
|
+
}
|
|
1963
|
+
});
|
|
1964
|
+
}
|
|
1965
|
+
return { ...this.snapshots };
|
|
1966
|
+
}
|
|
1967
|
+
/** @internal */
|
|
1968
|
+
async _deliver(msg) {
|
|
1969
|
+
const expected = _nullishCoalesce(SNAPSHOT_EVENTS[this.name], () => ( []));
|
|
1970
|
+
if (expected.includes(msg.event)) {
|
|
1971
|
+
this.snapshots[msg.event] = msg.payload;
|
|
1972
|
+
if (expected.every((e) => e in this.snapshots)) {
|
|
1973
|
+
const waiters = this.#snapshotWaiters;
|
|
1974
|
+
this.#snapshotWaiters = [];
|
|
1975
|
+
for (const w of waiters) w();
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
if (this.onMessage) {
|
|
1979
|
+
try {
|
|
1980
|
+
await this.onMessage(msg);
|
|
1981
|
+
} catch (err) {
|
|
1982
|
+
this.#ws.logger.error(`onMessage for ${this.topic} threw`, err);
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
if (this.#queue.put(msg)) this.#ws.logger.warn(`${this.topic} queue full; dropped the oldest message`);
|
|
1986
|
+
}
|
|
1987
|
+
// -- sending ----------------------------------------------------------
|
|
1988
|
+
/** Send `event` on this channel and resolve to the reply's `response`. Rejects when the reply status is `error`. */
|
|
1989
|
+
push(event, payload = {}, timeoutMs) {
|
|
1990
|
+
if (!this.joined || this.joinRef === null) {
|
|
1991
|
+
return Promise.reject(new STXChannelException(`${this.topic} is not joined`, { topic: this.topic }));
|
|
1992
|
+
}
|
|
1993
|
+
return this.#ws._request(this.topic, event, _nullishCoalesce(payload, () => ( {})), this.joinRef, timeoutMs);
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Channel `ping`. On `orders` with cancel-on-disconnect armed this resets
|
|
1997
|
+
* the cancel deadline; on `account` and `orders` it keeps the session alive.
|
|
1998
|
+
*/
|
|
1999
|
+
ping() {
|
|
2000
|
+
return this.push("ping", {});
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Change the `market_ids` filter without rejoining. On `orders`, `fills`,
|
|
2004
|
+
* `positions`, `settlements` and `account`, `null` clears the filter;
|
|
2005
|
+
* `orderbook` and `market_stats` require at least one id.
|
|
2006
|
+
*/
|
|
2007
|
+
async selectMarketIds(marketIds) {
|
|
2008
|
+
const value = marketIds === null ? null : [...marketIds];
|
|
2009
|
+
const reply = await this.push("select_market_ids", { market_ids: value });
|
|
2010
|
+
this.joinPayload.market_ids = value;
|
|
2011
|
+
return reply;
|
|
2012
|
+
}
|
|
2013
|
+
/** `ticker` (`sports`, `competitions`) and `trades` (`market_ids`, `event_ids`): change filters without rejoining. */
|
|
2014
|
+
async selectFilters(filters) {
|
|
2015
|
+
const payload = Object.fromEntries(Object.entries(filters).map(([k, v]) => [k, v === null ? null : [...v]]));
|
|
2016
|
+
const reply = await this.push("select_filters", payload);
|
|
2017
|
+
Object.assign(this.joinPayload, payload);
|
|
2018
|
+
return reply;
|
|
2019
|
+
}
|
|
2020
|
+
/** `markets`: change the `rules` filter; `null` disables it. */
|
|
2021
|
+
async selectRuleFilters(ruleFilters) {
|
|
2022
|
+
const value = ruleFilters === null ? null : [...ruleFilters];
|
|
2023
|
+
const reply = await this.push("select_rule_filters", { rule_filters: value });
|
|
2024
|
+
this.joinPayload.rule_filters = value;
|
|
2025
|
+
return reply;
|
|
2026
|
+
}
|
|
2027
|
+
/** `markets`: receive `market_created`, `market_updated` or both. */
|
|
2028
|
+
async selectMessageTypes(messageTypes) {
|
|
2029
|
+
const value = messageTypes === null ? null : [...messageTypes];
|
|
2030
|
+
const reply = await this.push("select_message_types", { message_types: value });
|
|
2031
|
+
this.joinPayload.message_types = value;
|
|
2032
|
+
return reply;
|
|
2033
|
+
}
|
|
2034
|
+
/**
|
|
2035
|
+
* `market_updates`: start receiving `created`/`updated` for these markets.
|
|
2036
|
+
* Re-sent automatically after a reconnect.
|
|
2037
|
+
*/
|
|
2038
|
+
async watch(marketIds) {
|
|
2039
|
+
const list = [...marketIds];
|
|
2040
|
+
const reply = await this.push("watch", list);
|
|
2041
|
+
for (const id of list) if (!this.watches.includes(id)) this.watches.push(id);
|
|
2042
|
+
return reply;
|
|
2043
|
+
}
|
|
2044
|
+
/**
|
|
2045
|
+
* `market:<id>`: push the market's current `market_update` and
|
|
2046
|
+
* `order_book_update` again now (after a gap, or to re-read a field).
|
|
2047
|
+
*/
|
|
2048
|
+
requestSnapshot() {
|
|
2049
|
+
return this.push("request_snapshot", {});
|
|
2050
|
+
}
|
|
2051
|
+
/** `market_stats`: fetch history at `range` (`day`, `week`, `month`, `all`) without changing the subscription. */
|
|
2052
|
+
requestSeries(marketIds, range = "all") {
|
|
2053
|
+
return this.push("request_series", { market_ids: [...marketIds], range });
|
|
2054
|
+
}
|
|
2055
|
+
/** Leave the topic. The channel stops receiving and its iterator ends. */
|
|
2056
|
+
leave() {
|
|
2057
|
+
return this.#ws._leave(this);
|
|
2058
|
+
}
|
|
2059
|
+
// -- internals --------------------------------------------------------
|
|
2060
|
+
/** @internal */
|
|
2061
|
+
_startPinger() {
|
|
2062
|
+
this._stopPinger();
|
|
2063
|
+
let interval = this.pingIntervalMs;
|
|
2064
|
+
const granted = _optionalChain([this, 'access', _29 => _29.reply, 'optionalAccess', _30 => _30.ping_timeout]);
|
|
2065
|
+
if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
|
|
2066
|
+
const cod = granted * 0.6;
|
|
2067
|
+
interval = interval === null ? cod : Math.min(interval, cod);
|
|
2068
|
+
}
|
|
2069
|
+
if (interval) {
|
|
2070
|
+
const every = interval;
|
|
2071
|
+
this.#pingTimer = setInterval(() => {
|
|
2072
|
+
if (!this.joined || this.closed) return;
|
|
2073
|
+
this.push("ping", {}, Math.max(every, 5e3)).catch(
|
|
2074
|
+
(err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
|
|
2075
|
+
);
|
|
2076
|
+
}, every);
|
|
2077
|
+
_optionalChain([this, 'access', _31 => _31.#pingTimer, 'access', _32 => _32.unref, 'optionalCall', _33 => _33()]);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
/** @internal */
|
|
2081
|
+
_stopPinger() {
|
|
2082
|
+
if (this.#pingTimer) clearInterval(this.#pingTimer);
|
|
2083
|
+
this.#pingTimer = void 0;
|
|
2084
|
+
}
|
|
2085
|
+
/** @internal */
|
|
2086
|
+
_resetForRejoin() {
|
|
2087
|
+
this.joined = false;
|
|
2088
|
+
this.snapshots = {};
|
|
2089
|
+
this._stopPinger();
|
|
2090
|
+
}
|
|
2091
|
+
/** @internal */
|
|
2092
|
+
_close() {
|
|
2093
|
+
this.closed = true;
|
|
2094
|
+
this.joined = false;
|
|
2095
|
+
this._stopPinger();
|
|
2096
|
+
this.#queue.put(null);
|
|
2097
|
+
}
|
|
2098
|
+
}, _class4);
|
|
2099
|
+
var DEFAULT_LOGGER = {
|
|
2100
|
+
debug: () => {
|
|
2101
|
+
},
|
|
2102
|
+
info: () => {
|
|
2103
|
+
},
|
|
2104
|
+
warn: (...a) => console.warn("[stx.ws]", ...a),
|
|
2105
|
+
error: (...a) => console.error("[stx.ws]", ...a)
|
|
2106
|
+
};
|
|
2107
|
+
var STXWebSocket = (_class5 = class {
|
|
2108
|
+
|
|
2109
|
+
|
|
2110
|
+
|
|
2111
|
+
|
|
2112
|
+
|
|
2113
|
+
|
|
2114
|
+
|
|
2115
|
+
|
|
2116
|
+
/** Why the socket closed itself, when it did: a terminal auth failure. */
|
|
2117
|
+
|
|
2118
|
+
|
|
2119
|
+
|
|
2120
|
+
|
|
2121
|
+
__init11() {this.channels = /* @__PURE__ */ new Map()}
|
|
2122
|
+
/** Successful reconnects so far. */
|
|
2123
|
+
__init12() {this.reconnects = 0}
|
|
2124
|
+
#userId;
|
|
2125
|
+
#conn;
|
|
2126
|
+
#ref = 0;
|
|
2127
|
+
#pending = /* @__PURE__ */ new Map();
|
|
2128
|
+
#heartbeat;
|
|
2129
|
+
#pendingHeartbeat = null;
|
|
2130
|
+
#closed = false;
|
|
2131
|
+
#connecting;
|
|
2132
|
+
#reconnecting = false;
|
|
2133
|
+
#closedWaiters = [];
|
|
2134
|
+
// Frames are handled one at a time, in arrival order: each waits for the
|
|
2135
|
+
// previous one's handler to finish.
|
|
2136
|
+
#inbox = Promise.resolve();
|
|
2137
|
+
constructor(opts = {}) {;_class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this);
|
|
2138
|
+
if (opts.rest) {
|
|
2139
|
+
this.rest = opts.rest;
|
|
2140
|
+
} else {
|
|
2141
|
+
this.rest = new STX({
|
|
2142
|
+
environment: opts.environment,
|
|
2143
|
+
region: opts.region,
|
|
2144
|
+
env: opts.env,
|
|
2145
|
+
host: opts.host,
|
|
2146
|
+
keyId: opts.keyId,
|
|
2147
|
+
privateKey: opts.privateKey,
|
|
2148
|
+
signer: opts.signer,
|
|
2149
|
+
auth: opts.auth,
|
|
2150
|
+
profile: opts.profile,
|
|
2151
|
+
verifyTls: opts.verifyTls
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
this.url = this.rest.socketUrl;
|
|
2155
|
+
this.#userId = opts.userId;
|
|
2156
|
+
this.heartbeatIntervalMs = _nullishCoalesce(opts.heartbeatIntervalMs, () => ( 25e3));
|
|
2157
|
+
this.channelPingIntervalMs = opts.channelPingIntervalMs === void 0 ? 3e4 : opts.channelPingIntervalMs;
|
|
2158
|
+
this.reconnect = _nullishCoalesce(opts.reconnect, () => ( true));
|
|
2159
|
+
this.reconnectPolicy = _nullishCoalesce(opts.reconnectPolicy, () => ( new ReconnectPolicy()));
|
|
2160
|
+
this.onReconnect = opts.onReconnect;
|
|
2161
|
+
this.onAuthError = opts.onAuthError;
|
|
2162
|
+
this.joinTimeoutMs = _nullishCoalesce(opts.joinTimeoutMs, () => ( 1e4));
|
|
2163
|
+
this.queueSize = _nullishCoalesce(opts.queueSize, () => ( 1e4));
|
|
2164
|
+
this.logger = _nullishCoalesce(opts.logger, () => ( DEFAULT_LOGGER));
|
|
2165
|
+
}
|
|
2166
|
+
toString() {
|
|
2167
|
+
return `STXWebSocket(${this.url}, channels=${JSON.stringify([...this.channels.keys()])})`;
|
|
2168
|
+
}
|
|
2169
|
+
// ------------------------------------------------------------------
|
|
2170
|
+
// Lifecycle
|
|
2171
|
+
// ------------------------------------------------------------------
|
|
2172
|
+
get connected() {
|
|
2173
|
+
return this.#conn !== void 0 && this.#conn.readyState === _ws2.default.OPEN;
|
|
2174
|
+
}
|
|
2175
|
+
get closed() {
|
|
2176
|
+
return this.#closed;
|
|
2177
|
+
}
|
|
2178
|
+
/** Open the socket. Idempotent; resolves to this socket. */
|
|
2179
|
+
async connect() {
|
|
2180
|
+
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
2181
|
+
if (this.connected) return this;
|
|
2182
|
+
if (!this.#connecting) {
|
|
2183
|
+
this.#connecting = this.#openAuthenticated().finally(() => {
|
|
2184
|
+
this.#connecting = void 0;
|
|
2185
|
+
});
|
|
2186
|
+
}
|
|
2187
|
+
await this.#connecting;
|
|
2188
|
+
return this;
|
|
2189
|
+
}
|
|
2190
|
+
/** Leave every channel and close the socket. Safe to call twice. */
|
|
2191
|
+
async close() {
|
|
2192
|
+
if (this.#closed) return;
|
|
2193
|
+
this.#closed = true;
|
|
2194
|
+
const leaves = [];
|
|
2195
|
+
for (const channel of this.channels.values()) {
|
|
2196
|
+
channel.closed = true;
|
|
2197
|
+
if (channel.joined && this.connected) {
|
|
2198
|
+
leaves.push(this._request(channel.topic, "phx_leave", {}, channel.joinRef, 2e3).catch(() => {
|
|
2199
|
+
}));
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
await Promise.all(leaves);
|
|
2203
|
+
for (const channel of this.channels.values()) channel._close();
|
|
2204
|
+
this.channels.clear();
|
|
2205
|
+
this.#stopHeartbeat();
|
|
2206
|
+
this.#closeConn();
|
|
2207
|
+
this.#failPending(new STXTransportException("socket closed"));
|
|
2208
|
+
this.#notifyClosed();
|
|
2209
|
+
}
|
|
2210
|
+
async [ASYNC_DISPOSE]() {
|
|
2211
|
+
await this.close();
|
|
2212
|
+
}
|
|
2213
|
+
/** Resolve once `close()` is called (or reconnects are exhausted). */
|
|
2214
|
+
runForever() {
|
|
2215
|
+
if (this.#closed) return Promise.resolve();
|
|
2216
|
+
return new Promise((resolve) => this.#closedWaiters.push(resolve));
|
|
2217
|
+
}
|
|
2218
|
+
/** Your user id, from `userId` or `GET /api/v1/me`. */
|
|
2219
|
+
async userId() {
|
|
2220
|
+
if (this.#userId === void 0) this.#userId = await this.rest.userId();
|
|
2221
|
+
return this.#userId;
|
|
2222
|
+
}
|
|
2223
|
+
// ------------------------------------------------------------------
|
|
2224
|
+
// Public market channels
|
|
2225
|
+
// ------------------------------------------------------------------
|
|
2226
|
+
/**
|
|
2227
|
+
* `orderbook`: the aggregated book, one `book` push per market. Each push
|
|
2228
|
+
* is a full snapshot of that market's book; replace what you hold rather
|
|
2229
|
+
* than merging. `marketIds` is required.
|
|
2230
|
+
*/
|
|
2231
|
+
orderbook(marketIds, opts = {}) {
|
|
2232
|
+
if (!marketIds.length) return Promise.reject(new TypeError("orderbook needs at least one market id"));
|
|
2233
|
+
return this.join("orderbook", { market_ids: [...marketIds] }, opts.onMessage);
|
|
2234
|
+
}
|
|
2235
|
+
/** `ticker`: a `ticker` push whenever a market's price, top of book, volume or open interest moves. */
|
|
2236
|
+
ticker(opts = {}) {
|
|
2237
|
+
return this.join("ticker", dropUndefined({ sports: opts.sports, competitions: opts.competitions }), opts.onMessage);
|
|
2238
|
+
}
|
|
2239
|
+
/** `trades`: every execution on the exchange, anonymised. `action` is the taker's side. Not your fills: see `fills`. */
|
|
2240
|
+
trades(opts = {}) {
|
|
2241
|
+
return this.join("trades", dropUndefined({ market_ids: opts.marketIds, event_ids: opts.eventIds }), opts.onMessage);
|
|
2242
|
+
}
|
|
2243
|
+
/**
|
|
2244
|
+
* `markets`: `market_created` and `market_updated` for every market. Each
|
|
2245
|
+
* payload maps market id to a market object; `market_updated` carries only
|
|
2246
|
+
* the changed fields. Prices arrive in cents on the wire and are converted
|
|
2247
|
+
* to dollar strings here.
|
|
2248
|
+
*/
|
|
2249
|
+
markets(opts = {}) {
|
|
2250
|
+
return this.join(
|
|
2251
|
+
"markets",
|
|
2252
|
+
dropUndefined({ rule_filters: opts.ruleFilters, message_types: opts.messageTypes }),
|
|
2253
|
+
opts.onMessage
|
|
2254
|
+
);
|
|
2255
|
+
}
|
|
2256
|
+
/**
|
|
2257
|
+
* `market_stats`: a price series per market. The history is in the join
|
|
2258
|
+
* reply (`channel.reply.markets`); `market_stats` pushes changed buckets
|
|
2259
|
+
* (upsert by `timestamp_us`) and `market_stats_snapshot` replaces a series.
|
|
2260
|
+
*/
|
|
2261
|
+
marketStats(marketIds, opts = {}) {
|
|
2262
|
+
if (!marketIds.length) return Promise.reject(new TypeError("market_stats needs at least one market id"));
|
|
2263
|
+
return this.join("market_stats", dropUndefined({ market_ids: [...marketIds], range: opts.range }), opts.onMessage);
|
|
2264
|
+
}
|
|
2265
|
+
/**
|
|
2266
|
+
* `market_updates`: `created` and `updated` for the markets you watch.
|
|
2267
|
+
* Nothing arrives until you watch something; pass `watch` or call
|
|
2268
|
+
* `channel.watch([...])`. Prices are converted from cents to dollar strings.
|
|
2269
|
+
*/
|
|
2270
|
+
async marketUpdates(opts = {}) {
|
|
2271
|
+
const channel = await this.join("market_updates", {}, opts.onMessage);
|
|
2272
|
+
if (_optionalChain([opts, 'access', _34 => _34.watch, 'optionalAccess', _35 => _35.length])) await channel.watch(opts.watch);
|
|
2273
|
+
return channel;
|
|
2274
|
+
}
|
|
2275
|
+
/**
|
|
2276
|
+
* `market:<id>`: one market in full. The join reply (`channel.reply`) is the
|
|
2277
|
+
* market's current state, every market field plus `ob`, its aggregated book
|
|
2278
|
+
* (`{b, o}`, each level `{p, q, l, tc, tl}`). Then `market_update` carries the
|
|
2279
|
+
* fields that changed and `order_book_update` a fresh `{ob}` about every
|
|
2280
|
+
* 200 ms. The event's live status text rides along: `event_brief` and
|
|
2281
|
+
* `detailed_event_brief` (the score and clock while in play, e.g.
|
|
2282
|
+
* `"CHC 3 - 4 BOS : Bottom 8th 1 Outs"`, the start time before), with
|
|
2283
|
+
* `event_status`. `marketId` is the market id or symbol. Prices are
|
|
2284
|
+
* converted from cents to dollar strings; book levels are written as strings.
|
|
2285
|
+
* A resulted or voided market sends one last `market_update` and the server
|
|
2286
|
+
* closes the topic.
|
|
2287
|
+
*/
|
|
2288
|
+
market(marketId, opts = {}) {
|
|
2289
|
+
if (!marketId) return Promise.reject(new TypeError("market needs a market id or symbol"));
|
|
2290
|
+
return this.join(`market:${marketId}`, {}, opts.onMessage);
|
|
2291
|
+
}
|
|
2292
|
+
// ------------------------------------------------------------------
|
|
2293
|
+
// Account channels
|
|
2294
|
+
// ------------------------------------------------------------------
|
|
2295
|
+
/**
|
|
2296
|
+
* `orders:{user_id}`: `all_orders` on join, then `new_open_order`.
|
|
2297
|
+
*
|
|
2298
|
+
* `cancelOnDisconnect: true` arms cancel-on-disconnect for orders placed
|
|
2299
|
+
* with `cancelOnDisconnect: true`. `pingTimeout` is in milliseconds,
|
|
2300
|
+
* clamped by the server to 5000 to 20000; the granted value is in
|
|
2301
|
+
* `channel.reply.ping_timeout` and the SDK pings at 60% of it for as long
|
|
2302
|
+
* as the channel is joined.
|
|
2303
|
+
*/
|
|
2304
|
+
orders(opts = {}) {
|
|
2305
|
+
const payload = dropUndefined({ market_ids: opts.marketIds });
|
|
2306
|
+
if (opts.cancelOnDisconnect) {
|
|
2307
|
+
payload.cancel_on_disconnect = true;
|
|
2308
|
+
payload.ping_timeout = Math.trunc(_nullishCoalesce(opts.pingTimeout, () => ( 5e3)));
|
|
2309
|
+
}
|
|
2310
|
+
return this.#joinAccount("orders", payload, opts.onMessage);
|
|
2311
|
+
}
|
|
2312
|
+
/** `fills:{user_id}`: `all_trades` on join, then one `trade` per execution or status change. */
|
|
2313
|
+
fills(opts = {}) {
|
|
2314
|
+
return this.#joinAccount("fills", dropUndefined({ market_ids: opts.marketIds }), opts.onMessage);
|
|
2315
|
+
}
|
|
2316
|
+
/** `positions:{user_id}`: `all_positions` on join, then `updated_positions` deltas with only the changed positions. */
|
|
2317
|
+
positions(opts = {}) {
|
|
2318
|
+
return this.#joinAccount("positions", dropUndefined({ market_ids: opts.marketIds }), opts.onMessage);
|
|
2319
|
+
}
|
|
2320
|
+
/** `settlements:{user_id}`: `new_settlements` as they are recorded. No snapshot; history is `STX.settlements()`. */
|
|
2321
|
+
settlements(opts = {}) {
|
|
2322
|
+
return this.#joinAccount("settlements", dropUndefined({ market_ids: opts.marketIds }), opts.onMessage);
|
|
2323
|
+
}
|
|
2324
|
+
/** `balances:{user_id}`: `balances` on join, then `update` and `payment_update`. `accountId` picks one of your accounts. */
|
|
2325
|
+
balances(opts = {}) {
|
|
2326
|
+
return this.#joinAccount("balances", dropUndefined({ account_id: opts.accountId }), opts.onMessage);
|
|
2327
|
+
}
|
|
2328
|
+
/**
|
|
2329
|
+
* `account:{user_id}`: everything the five channels above carry, on one
|
|
2330
|
+
* join. Do not also join a per-type channel (you would get every message
|
|
2331
|
+
* twice), and use `orders` if you need cancel-on-disconnect.
|
|
2332
|
+
*/
|
|
2333
|
+
account(opts = {}) {
|
|
2334
|
+
return this.#joinAccount("account", dropUndefined({ market_ids: opts.marketIds }), opts.onMessage);
|
|
2335
|
+
}
|
|
2336
|
+
/**
|
|
2337
|
+
* A live view of your account: joins `balances`, `orders`, `fills` and
|
|
2338
|
+
* `positions`, seeds each from its join snapshot and applies every pushed
|
|
2339
|
+
* update, re-seeding from the new snapshots after a reconnect. Resolves once
|
|
2340
|
+
* all four snapshots have arrived. See `AccountView`.
|
|
2341
|
+
*/
|
|
2342
|
+
async accountView(opts = {}) {
|
|
2343
|
+
return new AccountView(this, opts)._open(opts);
|
|
2344
|
+
}
|
|
2345
|
+
/** `user_info:{user_id}`: `user_updated` right after joining, then on every profile change. */
|
|
2346
|
+
userInfo(opts = {}) {
|
|
2347
|
+
return this.#joinAccount("user_info", {}, opts.onMessage);
|
|
2348
|
+
}
|
|
2349
|
+
// ------------------------------------------------------------------
|
|
2350
|
+
// Generic join
|
|
2351
|
+
// ------------------------------------------------------------------
|
|
2352
|
+
/**
|
|
2353
|
+
* Join `topic` with `payload` and wait for the reply. Rejects with
|
|
2354
|
+
* `STXChannelException` carrying the server's reason (for example
|
|
2355
|
+
* `market_ids_required` or `unauthorized`) if the join is refused.
|
|
2356
|
+
*/
|
|
2357
|
+
async join(topic, payload = {}, onMessage, opts = {}) {
|
|
2358
|
+
const existing = this.channels.get(topic);
|
|
2359
|
+
if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
|
|
2360
|
+
await this.connect();
|
|
2361
|
+
const channel = new Channel(this, topic, payload, onMessage, {
|
|
2362
|
+
pingIntervalMs: opts.pingIntervalMs === void 0 ? this.channelPingIntervalMs : opts.pingIntervalMs,
|
|
2363
|
+
queueSize: this.queueSize
|
|
2364
|
+
});
|
|
2365
|
+
this.channels.set(topic, channel);
|
|
2366
|
+
try {
|
|
2367
|
+
await this.#join(channel);
|
|
2368
|
+
} catch (err) {
|
|
2369
|
+
this.channels.delete(topic);
|
|
2370
|
+
channel._close();
|
|
2371
|
+
throw err;
|
|
2372
|
+
}
|
|
2373
|
+
return channel;
|
|
2374
|
+
}
|
|
2375
|
+
async #joinAccount(name, payload, onMessage) {
|
|
2376
|
+
if (!this.rest.auth) {
|
|
2377
|
+
throw new STXConfigException(
|
|
2378
|
+
`The ${name} channel is private and needs an API key; the socket must be signed. Configure keyId and privateKey.`
|
|
2379
|
+
);
|
|
2380
|
+
}
|
|
2381
|
+
return this.join(`${name}:${await this.userId()}`, payload, onMessage);
|
|
2382
|
+
}
|
|
2383
|
+
async #join(channel) {
|
|
2384
|
+
const ref = this.#nextRef();
|
|
2385
|
+
channel.joinRef = ref;
|
|
2386
|
+
channel._resetForRejoin();
|
|
2387
|
+
const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
|
|
2388
|
+
channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
|
|
2389
|
+
if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
|
|
2390
|
+
channel.joined = true;
|
|
2391
|
+
if (channel.watches.length) await channel.push("watch", [...channel.watches]);
|
|
2392
|
+
channel._startPinger();
|
|
2393
|
+
}
|
|
2394
|
+
/** @internal */
|
|
2395
|
+
async _leave(channel) {
|
|
2396
|
+
channel.closed = true;
|
|
2397
|
+
if (channel.joined && this.connected) {
|
|
2398
|
+
await this._request(channel.topic, "phx_leave", {}, channel.joinRef, 5e3).catch(() => {
|
|
2399
|
+
});
|
|
2400
|
+
}
|
|
2401
|
+
channel._close();
|
|
2402
|
+
this.channels.delete(channel.topic);
|
|
2403
|
+
}
|
|
2404
|
+
// ------------------------------------------------------------------
|
|
2405
|
+
// Wire
|
|
2406
|
+
// ------------------------------------------------------------------
|
|
2407
|
+
#nextRef() {
|
|
2408
|
+
this.#ref += 1;
|
|
2409
|
+
return String(this.#ref);
|
|
2410
|
+
}
|
|
2411
|
+
/**
|
|
2412
|
+
* Open, and if the handshake is refused for its credentials (401/403) let
|
|
2413
|
+
* the auth provider recover once (refresh an OAuth token, re-mint an app
|
|
2414
|
+
* token) and try again at once.
|
|
2415
|
+
*/
|
|
2416
|
+
async #openAuthenticated(reconnect = false) {
|
|
2417
|
+
try {
|
|
2418
|
+
await this.#open(reconnect);
|
|
2419
|
+
} catch (err) {
|
|
2420
|
+
if (!await this.#recoverAuth(err)) throw err;
|
|
2421
|
+
await this.#open(true);
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
/** True when `err` is a refused handshake and the auth provider recovered. */
|
|
2425
|
+
async #recoverAuth(err) {
|
|
2426
|
+
if (!(err instanceof STXTransportException)) return false;
|
|
2427
|
+
if (err.statusCode !== 401 && err.statusCode !== 403) return false;
|
|
2428
|
+
const auth = this.rest.auth;
|
|
2429
|
+
if (!_optionalChain([auth, 'optionalAccess', _36 => _36.onUnauthorized])) return false;
|
|
2430
|
+
return auth.onUnauthorized();
|
|
2431
|
+
}
|
|
2432
|
+
async #open(reconnect = false) {
|
|
2433
|
+
const headers = { "User-Agent": USER_AGENT };
|
|
2434
|
+
if (_optionalChain([this, 'access', _37 => _37.rest, 'access', _38 => _38.auth, 'optionalAccess', _39 => _39.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
|
|
2435
|
+
const conn = new (0, _ws2.default)(this.url, {
|
|
2436
|
+
headers,
|
|
2437
|
+
rejectUnauthorized: this.rest.verifyTls,
|
|
2438
|
+
handshakeTimeout: 15e3
|
|
2439
|
+
});
|
|
2440
|
+
await new Promise((resolve, reject) => {
|
|
2441
|
+
const onError = (err) => {
|
|
2442
|
+
cleanup();
|
|
2443
|
+
reject(new STXTransportException(`Could not open ${this.url}: ${err.message}`, { cause: err }));
|
|
2444
|
+
};
|
|
2445
|
+
const onUnexpected = (_req, res) => {
|
|
2446
|
+
cleanup();
|
|
2447
|
+
conn.terminate();
|
|
2448
|
+
const reason = _optionalChain([res, 'access', _40 => _40.headers, 'optionalAccess', _41 => _41["x-stx-error"]]);
|
|
2449
|
+
reject(
|
|
2450
|
+
new STXTransportException(
|
|
2451
|
+
`Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
|
|
2452
|
+
{ statusCode: res.statusCode }
|
|
2453
|
+
)
|
|
2454
|
+
);
|
|
2455
|
+
};
|
|
2456
|
+
const onOpen = () => {
|
|
2457
|
+
cleanup();
|
|
2458
|
+
resolve();
|
|
2459
|
+
};
|
|
2460
|
+
const cleanup = () => {
|
|
2461
|
+
conn.off("error", onError);
|
|
2462
|
+
conn.off("open", onOpen);
|
|
2463
|
+
conn.off("unexpected-response", onUnexpected);
|
|
2464
|
+
};
|
|
2465
|
+
conn.on("error", onError);
|
|
2466
|
+
conn.on("open", onOpen);
|
|
2467
|
+
conn.on("unexpected-response", onUnexpected);
|
|
2468
|
+
});
|
|
2469
|
+
conn.on("error", (err) => this.logger.info(`socket error: ${err.message}`));
|
|
2470
|
+
conn.on("message", (data) => this.#onFrame(data.toString()));
|
|
2471
|
+
conn.on("close", () => this.#onConnClose(conn));
|
|
2472
|
+
this.#conn = conn;
|
|
2473
|
+
this.#pendingHeartbeat = null;
|
|
2474
|
+
this.#startHeartbeat();
|
|
2475
|
+
this.logger.debug(`connected to ${this.url}`);
|
|
2476
|
+
}
|
|
2477
|
+
#closeConn() {
|
|
2478
|
+
const conn = this.#conn;
|
|
2479
|
+
this.#conn = void 0;
|
|
2480
|
+
if (conn) {
|
|
2481
|
+
try {
|
|
2482
|
+
conn.terminate();
|
|
2483
|
+
} catch (e8) {
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
#send(frame) {
|
|
2488
|
+
if (!this.connected) throw new STXTransportException("socket is not connected");
|
|
2489
|
+
this.#conn.send(JSON.stringify(frame));
|
|
2490
|
+
}
|
|
2491
|
+
/** @internal Send a frame and resolve to the reply's `response`. */
|
|
2492
|
+
_request(topic, event, payload, joinRef, timeoutMs, ref) {
|
|
2493
|
+
const r = _nullishCoalesce(ref, () => ( this.#nextRef()));
|
|
2494
|
+
const wait = _nullishCoalesce(timeoutMs, () => ( this.joinTimeoutMs));
|
|
2495
|
+
return new Promise((resolve, reject) => {
|
|
2496
|
+
const timer = setTimeout(() => {
|
|
2497
|
+
this.#pending.delete(r);
|
|
2498
|
+
reject(new STXTimeoutException(`No reply to ${event} on ${topic} within ${wait / 1e3}s`, { topic }));
|
|
2499
|
+
}, wait);
|
|
2500
|
+
const done = (fn) => (v) => {
|
|
2501
|
+
clearTimeout(timer);
|
|
2502
|
+
this.#pending.delete(r);
|
|
2503
|
+
fn(v);
|
|
2504
|
+
};
|
|
2505
|
+
this.#pending.set(r, { resolve: done(resolve), reject: done(reject), topic, event });
|
|
2506
|
+
try {
|
|
2507
|
+
this.#send([joinRef, r, topic, event, payload]);
|
|
2508
|
+
} catch (err) {
|
|
2509
|
+
done(reject)(err);
|
|
2510
|
+
}
|
|
2511
|
+
});
|
|
2512
|
+
}
|
|
2513
|
+
#failPending(err) {
|
|
2514
|
+
const pending = [...this.#pending.values()];
|
|
2515
|
+
this.#pending.clear();
|
|
2516
|
+
for (const p of pending) p.reject(err);
|
|
2517
|
+
}
|
|
2518
|
+
#onFrame(raw) {
|
|
2519
|
+
let frame;
|
|
2520
|
+
try {
|
|
2521
|
+
frame = JSON.parse(raw);
|
|
2522
|
+
} catch (e9) {
|
|
2523
|
+
this.logger.warn(`unparseable frame: ${raw.slice(0, 200)}`);
|
|
2524
|
+
return;
|
|
2525
|
+
}
|
|
2526
|
+
if (!Array.isArray(frame) || frame.length !== 5) {
|
|
2527
|
+
this.logger.warn(`unexpected frame: ${raw.slice(0, 200)}`);
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
2530
|
+
const [joinRef, ref, topic, event, payload] = frame;
|
|
2531
|
+
this.#inbox = this.#inbox.then(() => this.#dispatch(joinRef, ref, topic, event, payload)).catch((err) => this.logger.error("frame handling failed", err));
|
|
2532
|
+
}
|
|
2533
|
+
async #dispatch(joinRef, ref, topic, event, payload) {
|
|
2534
|
+
if (event === "phx_reply") {
|
|
2535
|
+
if (topic === PHOENIX_TOPIC && ref === this.#pendingHeartbeat) this.#pendingHeartbeat = null;
|
|
2536
|
+
const pending = ref === null || ref === void 0 ? void 0 : this.#pending.get(String(ref));
|
|
2537
|
+
if (pending) {
|
|
2538
|
+
const status = payload && typeof payload === "object" ? payload.status : void 0;
|
|
2539
|
+
const response = payload && typeof payload === "object" ? payload.response : payload;
|
|
2540
|
+
if (status === "ok") {
|
|
2541
|
+
pending.resolve(response);
|
|
2542
|
+
} else {
|
|
2543
|
+
const reason = response && typeof response === "object" ? response.reason : void 0;
|
|
2544
|
+
pending.reject(
|
|
2545
|
+
new STXChannelException(`${pending.event} on ${topic} failed: ${_nullishCoalesce(reason, () => ( JSON.stringify(response)))}`, {
|
|
2546
|
+
topic,
|
|
2547
|
+
reply: response
|
|
2548
|
+
})
|
|
2549
|
+
);
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
return;
|
|
2553
|
+
}
|
|
2554
|
+
const channel = this.channels.get(topic);
|
|
2555
|
+
if (!channel) return;
|
|
2556
|
+
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
2557
|
+
return;
|
|
2558
|
+
}
|
|
2559
|
+
if (event === "phx_error" || event === "phx_close") {
|
|
2560
|
+
if (!channel.closed && !this.#closed) {
|
|
2561
|
+
this.logger.warn(`${topic}: server sent ${event}; rejoining`);
|
|
2562
|
+
channel._resetForRejoin();
|
|
2563
|
+
void this.#rejoinLater(channel);
|
|
2564
|
+
}
|
|
2565
|
+
return;
|
|
2566
|
+
}
|
|
2567
|
+
if (channel.name === "markets") payload = convertMarketsFrame(payload);
|
|
2568
|
+
else if (channel.name === "market") payload = convertMarketChannelPayload(payload);
|
|
2569
|
+
else if (channel.name === "market_updates" && payload && typeof payload === "object") {
|
|
2570
|
+
payload = convertMarketPayload(payload);
|
|
2571
|
+
}
|
|
2572
|
+
await channel._deliver(
|
|
2573
|
+
new ChannelMessage(
|
|
2574
|
+
topic,
|
|
2575
|
+
event,
|
|
2576
|
+
payload,
|
|
2577
|
+
ref === null || ref === void 0 ? null : String(ref),
|
|
2578
|
+
joinRef === null || joinRef === void 0 ? null : String(joinRef)
|
|
2579
|
+
)
|
|
2580
|
+
);
|
|
2581
|
+
}
|
|
2582
|
+
async #rejoinLater(channel) {
|
|
2583
|
+
let attempt = 1;
|
|
2584
|
+
while (!channel.closed && !this.#closed) {
|
|
2585
|
+
await sleep2(this.reconnectPolicy.delayMs(attempt));
|
|
2586
|
+
if (!this.connected) return;
|
|
2587
|
+
try {
|
|
2588
|
+
await this.#join(channel);
|
|
2589
|
+
return;
|
|
2590
|
+
} catch (err) {
|
|
2591
|
+
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
|
|
2592
|
+
const reply = err instanceof STXChannelException ? err.reply : void 0;
|
|
2593
|
+
if (_optionalChain([reply, 'optionalAccess', _42 => _42.reason]) === "unauthorized") {
|
|
2594
|
+
channel._close();
|
|
2595
|
+
return;
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
attempt += 1;
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
#startHeartbeat() {
|
|
2602
|
+
this.#stopHeartbeat();
|
|
2603
|
+
this.#heartbeat = setInterval(() => {
|
|
2604
|
+
if (!this.connected) return;
|
|
2605
|
+
if (this.#pendingHeartbeat !== null) {
|
|
2606
|
+
this.logger.warn("heartbeat unanswered; reconnecting");
|
|
2607
|
+
_optionalChain([this, 'access', _43 => _43.#conn, 'optionalAccess', _44 => _44.terminate, 'call', _45 => _45()]);
|
|
2608
|
+
return;
|
|
2609
|
+
}
|
|
2610
|
+
const ref = this.#nextRef();
|
|
2611
|
+
this.#pendingHeartbeat = ref;
|
|
2612
|
+
try {
|
|
2613
|
+
this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
|
|
2614
|
+
} catch (e10) {
|
|
2615
|
+
_optionalChain([this, 'access', _46 => _46.#conn, 'optionalAccess', _47 => _47.terminate, 'call', _48 => _48()]);
|
|
2616
|
+
}
|
|
2617
|
+
}, this.heartbeatIntervalMs);
|
|
2618
|
+
}
|
|
2619
|
+
#stopHeartbeat() {
|
|
2620
|
+
if (this.#heartbeat) clearInterval(this.#heartbeat);
|
|
2621
|
+
this.#heartbeat = void 0;
|
|
2622
|
+
}
|
|
2623
|
+
#onConnClose(conn) {
|
|
2624
|
+
if (conn !== this.#conn) return;
|
|
2625
|
+
this.#conn = void 0;
|
|
2626
|
+
this.#stopHeartbeat();
|
|
2627
|
+
this.#failPending(new STXTransportException("socket dropped"));
|
|
2628
|
+
for (const channel of this.channels.values()) channel._resetForRejoin();
|
|
2629
|
+
if (this.#closed || this.#reconnecting) return;
|
|
2630
|
+
if (!this.reconnect) {
|
|
2631
|
+
this.#shutdownAfterDrop();
|
|
2632
|
+
return;
|
|
2633
|
+
}
|
|
2634
|
+
void this.#reconnectLoop();
|
|
2635
|
+
}
|
|
2636
|
+
async #reconnectLoop() {
|
|
2637
|
+
this.#reconnecting = true;
|
|
2638
|
+
let ok = false;
|
|
2639
|
+
try {
|
|
2640
|
+
let attempt = 1;
|
|
2641
|
+
while (!this.#closed) {
|
|
2642
|
+
const max = this.reconnectPolicy.maxAttempts;
|
|
2643
|
+
if (max !== null && attempt > max) {
|
|
2644
|
+
this.logger.error(`giving up after ${attempt - 1} reconnect attempts`);
|
|
2645
|
+
this.#shutdownAfterDrop();
|
|
2646
|
+
return;
|
|
2647
|
+
}
|
|
2648
|
+
await sleep2(this.reconnectPolicy.delayMs(attempt));
|
|
2649
|
+
if (this.#closed) return;
|
|
2650
|
+
try {
|
|
2651
|
+
await this.#openAuthenticated(true);
|
|
2652
|
+
for (const channel of [...this.channels.values()]) {
|
|
2653
|
+
if (channel.closed) continue;
|
|
2654
|
+
try {
|
|
2655
|
+
await this.#join(channel);
|
|
2656
|
+
} catch (err) {
|
|
2657
|
+
if (!(err instanceof STXChannelException)) throw err;
|
|
2658
|
+
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}; retrying`);
|
|
2659
|
+
void this.#rejoinLater(channel);
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
this.reconnects += 1;
|
|
2663
|
+
this.logger.info(`reconnected (${this.reconnects})`);
|
|
2664
|
+
ok = true;
|
|
2665
|
+
if (this.onReconnect) await this.onReconnect();
|
|
2666
|
+
return;
|
|
2667
|
+
} catch (err) {
|
|
2668
|
+
this.#closeConn();
|
|
2669
|
+
this.#stopHeartbeat();
|
|
2670
|
+
if (err instanceof STXAuthenticationException || err instanceof STXConfigException) {
|
|
2671
|
+
this.logger.error(`giving up: ${err.message}`);
|
|
2672
|
+
this.#failAuth(err);
|
|
2673
|
+
return;
|
|
2674
|
+
}
|
|
2675
|
+
this.logger.warn(`reconnect attempt ${attempt} failed: ${err.message}`);
|
|
2676
|
+
attempt += 1;
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
} finally {
|
|
2680
|
+
this.#reconnecting = false;
|
|
2681
|
+
if (ok && !this.#closed && !this.connected) {
|
|
2682
|
+
for (const channel of this.channels.values()) channel._resetForRejoin();
|
|
2683
|
+
void this.#reconnectLoop();
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
#failAuth(err) {
|
|
2688
|
+
this.error = err;
|
|
2689
|
+
this.#shutdownAfterDrop();
|
|
2690
|
+
try {
|
|
2691
|
+
_optionalChain([this, 'access', _49 => _49.onAuthError, 'optionalCall', _50 => _50(err)]);
|
|
2692
|
+
} catch (hookErr) {
|
|
2693
|
+
this.logger.error("onAuthError threw", hookErr);
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
#shutdownAfterDrop() {
|
|
2697
|
+
for (const channel of this.channels.values()) channel._close();
|
|
2698
|
+
this.#closed = true;
|
|
2699
|
+
this.#stopHeartbeat();
|
|
2700
|
+
this.#notifyClosed();
|
|
2701
|
+
}
|
|
2702
|
+
#notifyClosed() {
|
|
2703
|
+
const waiters = this.#closedWaiters;
|
|
2704
|
+
this.#closedWaiters = [];
|
|
2705
|
+
for (const w of waiters) w();
|
|
2706
|
+
}
|
|
2707
|
+
}, _class5);
|
|
2708
|
+
function dropUndefined(payload) {
|
|
2709
|
+
return Object.fromEntries(
|
|
2710
|
+
Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
|
|
2711
|
+
);
|
|
2712
|
+
}
|
|
2713
|
+
|
|
2714
|
+
|
|
2715
|
+
|
|
2716
|
+
|
|
2717
|
+
|
|
2718
|
+
|
|
2719
|
+
|
|
2720
|
+
|
|
2721
|
+
|
|
2722
|
+
|
|
2723
|
+
|
|
2724
|
+
|
|
2725
|
+
|
|
2726
|
+
|
|
2727
|
+
|
|
2728
|
+
|
|
2729
|
+
|
|
2730
|
+
|
|
2731
|
+
|
|
2732
|
+
|
|
2733
|
+
|
|
2734
|
+
|
|
2735
|
+
|
|
2736
|
+
|
|
2737
|
+
|
|
2738
|
+
|
|
2739
|
+
|
|
2740
|
+
|
|
2741
|
+
|
|
2742
|
+
|
|
2743
|
+
|
|
2744
|
+
|
|
2745
|
+
|
|
2746
|
+
|
|
2747
|
+
|
|
2748
|
+
|
|
2749
|
+
|
|
2750
|
+
|
|
2751
|
+
|
|
2752
|
+
|
|
2753
|
+
|
|
2754
|
+
|
|
2755
|
+
|
|
2756
|
+
|
|
2757
|
+
|
|
2758
|
+
|
|
2759
|
+
|
|
2760
|
+
|
|
2761
|
+
|
|
2762
|
+
|
|
2763
|
+
|
|
2764
|
+
|
|
2765
|
+
|
|
2766
|
+
|
|
2767
|
+
|
|
2768
|
+
|
|
2769
|
+
|
|
2770
|
+
|
|
2771
|
+
|
|
2772
|
+
|
|
2773
|
+
exports.Region = Region; exports.Environment = Environment; exports.geoRejection = geoRejection; exports.STXException = STXException; exports.STXConfigException = STXConfigException; exports.STXAPIException = STXAPIException; exports.STXValidationException = STXValidationException; exports.STXAuthenticationException = STXAuthenticationException; exports.STXForbiddenException = STXForbiddenException; exports.STXInvalidTokenException = STXInvalidTokenException; exports.STXInsufficientScopeException = STXInsufficientScopeException; exports.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXGeoLocationException = STXGeoLocationException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.errorForStatus = errorForStatus; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; exports.Page = Page; exports.RetryPolicy = RetryPolicy; exports.NO_RETRY = NO_RETRY; exports.resolveSettings = resolveSettings; exports.KEY_HEADER = KEY_HEADER; exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER; exports.SIGNATURE_HEADER = SIGNATURE_HEADER; exports.buildMessage = buildMessage; exports.requestPath = requestPath; exports.handshakePath = handshakePath; exports.loadPrivateKey = loadPrivateKey; exports.signerFromPrivateKey = signerFromPrivateKey; exports.ApiKeyCredentials = ApiKeyCredentials; exports.VERSION = VERSION; exports.USER_AGENT = USER_AGENT; exports.TERMINAL_ORDER_STATUSES = TERMINAL_ORDER_STATUSES; exports.AccountView = AccountView; exports.centsToDollars = centsToDollars; exports.toDollarString = toDollarString; exports.toQuantity = toQuantity; exports.convertMarketPayload = convertMarketPayload; exports.convertMarketsFrame = convertMarketsFrame; exports.convertBook = convertBook; exports.convertMarketChannelPayload = convertMarketChannelPayload; exports.SNAPSHOT_EVENTS = SNAPSHOT_EVENTS; exports.ChannelMessage = ChannelMessage; exports.ReconnectPolicy = ReconnectPolicy; exports.Channel = Channel; exports.STXWebSocket = STXWebSocket; exports.orderBody = orderBody; exports.STX = STX;
|
|
2774
|
+
//# sourceMappingURL=chunk-R664LTIB.cjs.map
|