@tribulnation/terminal 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +231 -2
- package/dist/answer.d.ts +3 -0
- package/dist/answer.js +1 -0
- package/dist/client.d.ts +73 -0
- package/dist/client.js +218 -0
- package/dist/errors.d.ts +76 -0
- package/dist/errors.js +143 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +58 -0
- package/dist/live.d.ts +74 -0
- package/dist/live.js +60 -0
- package/dist/livestream.d.ts +99 -0
- package/dist/livestream.js +390 -0
- package/dist/me.d.ts +66 -0
- package/dist/me.js +34 -0
- package/dist/pages.d.ts +21 -0
- package/dist/pages.js +35 -0
- package/dist/types.gen.d.ts +5716 -0
- package/dist/types.gen.js +24 -0
- package/dist/v1.d.ts +154 -0
- package/dist/v1.js +113 -0
- package/dist/v2.d.ts +75 -0
- package/dist/v2.js +25 -0
- package/package.json +55 -4
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live socket `wss://<API host>/live/<topic>` (scope `market:read`, Ultra), as the
|
|
3
|
+
* Python client's `livestream.py`: frames for as long as the caller iterates.
|
|
4
|
+
*
|
|
5
|
+
* The server closes every socket within a minute (4001: the key and its owner's plan are
|
|
6
|
+
* checked again on the reconnect); the stream reconnects at once, and the reconnect's
|
|
7
|
+
* first frame is the topic's latest build, so nothing is lost. A revoked key (4401), a
|
|
8
|
+
* topic outside the plan (4003) or an unknown topic (4004) ends the stream with
|
|
9
|
+
* `LiveClosed`; other closes are retried with exponential backoff (capped at 30 s). A
|
|
10
|
+
* refusal before the upgrade throws the `ApiError` of its status; 429 and 5xx are retried
|
|
11
|
+
* after their `Retry-After`.
|
|
12
|
+
*
|
|
13
|
+
* Browsers cannot send `Authorization` on a WebSocket, so they are not a runtime for the
|
|
14
|
+
* socket: Node 22+, Deno and Bun open it with their global `WebSocket` (which takes
|
|
15
|
+
* `{headers}`), Cloudflare Workers with a fetch upgrade, anything else with an injected
|
|
16
|
+
* constructor.
|
|
17
|
+
*/
|
|
18
|
+
import { apiErrorFrom, LiveClosed, Redirected, TerminalError } from "./errors.js";
|
|
19
|
+
import { LIVE_CLOSE } from "./types.gen.js";
|
|
20
|
+
export const DEFAULT_BACKOFF = { base: 1, cap: 30, jitter: 0.2 };
|
|
21
|
+
/** How often `ping` is sent, so proxies do not idle the socket out. */
|
|
22
|
+
export const PING_EVERY_MS = 20_000;
|
|
23
|
+
const STOP_CLOSES = {
|
|
24
|
+
[LIVE_CLOSE.revoked]: 'the key was revoked',
|
|
25
|
+
[LIVE_CLOSE.notInPlan]: 'the topic is not in the plan',
|
|
26
|
+
[LIVE_CLOSE.unknownTopic]: 'unknown topic'
|
|
27
|
+
};
|
|
28
|
+
/** The wait before reconnect number `attempt` (0: the first after a failure), seconds. */
|
|
29
|
+
export function backoffDelay(b, attempt, random = Math.random) {
|
|
30
|
+
const d = Math.min(b.cap, b.base * 2 ** Math.max(0, attempt));
|
|
31
|
+
return d + d * b.jitter * random();
|
|
32
|
+
}
|
|
33
|
+
const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
34
|
+
/** `wss://<API host>/live/<topic>[?depth=n]` for an `https://` host; `ws://` only for a
|
|
35
|
+
* local `http://` one (the key would travel in clear text otherwise). */
|
|
36
|
+
export function socketUrl(baseUrl, topic, depth) {
|
|
37
|
+
const u = new URL(baseUrl);
|
|
38
|
+
if (u.protocol === 'http:' && !LOCAL.has(u.hostname))
|
|
39
|
+
throw new TypeError(`refusing to send the key over ws:// to ${u.hostname}: use https://`);
|
|
40
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:')
|
|
41
|
+
throw new TypeError(`the API base URL must be https://, not ${baseUrl}`);
|
|
42
|
+
if (typeof topic !== 'string' || !/^[a-z0-9][a-z0-9:._-]{0,127}$/.test(topic))
|
|
43
|
+
throw new TypeError(`not a live topic: ${JSON.stringify(topic)}`);
|
|
44
|
+
const ws = (u.protocol === 'https:' ? 'wss://' : 'ws://') + u.host;
|
|
45
|
+
return `${ws}/live/${topic}${depth !== undefined ? `?depth=${depth}` : ''}`;
|
|
46
|
+
}
|
|
47
|
+
/** The upgrade was answered with an HTTP status. */
|
|
48
|
+
export class Refused extends Error {
|
|
49
|
+
status;
|
|
50
|
+
body;
|
|
51
|
+
retryAfter;
|
|
52
|
+
constructor(status, body, retryAfter) {
|
|
53
|
+
super(`refused ${status}`);
|
|
54
|
+
this.status = status;
|
|
55
|
+
this.body = body;
|
|
56
|
+
this.retryAfter = retryAfter;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** The socket closed (`code`; null without a close frame) or could not be opened. */
|
|
60
|
+
export class Dropped extends Error {
|
|
61
|
+
code;
|
|
62
|
+
reason;
|
|
63
|
+
constructor(code, reason = '') {
|
|
64
|
+
super(`dropped ${code}`);
|
|
65
|
+
this.code = code;
|
|
66
|
+
this.reason = reason;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** The upgrade failed, yet the same request over `node:http` is upgraded: this runtime's
|
|
70
|
+
* `WebSocket` does not send the `authorization` header. */
|
|
71
|
+
export class HeadersLost extends Dropped {
|
|
72
|
+
constructor() {
|
|
73
|
+
super(null, 'the WebSocket opened without the authorization header');
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Failed opens in a row after which a stream that never opened gives up. */
|
|
77
|
+
export const MAX_FAILED_FIRST_OPENS = 5;
|
|
78
|
+
/** Opens in a row refused for a missing header after which the stream gives up. */
|
|
79
|
+
export const MAX_HEADERS_LOST = 3;
|
|
80
|
+
const decoder = new TextDecoder();
|
|
81
|
+
/** A socket's events as a `Conn`; listeners attach at once, so no frame is lost. */
|
|
82
|
+
function adapt(ws) {
|
|
83
|
+
const queue = [];
|
|
84
|
+
const waiters = [];
|
|
85
|
+
let closed = null;
|
|
86
|
+
let open = false;
|
|
87
|
+
let settle;
|
|
88
|
+
const opened = new Promise((resolve, reject) => (settle = { resolve, reject }));
|
|
89
|
+
const finish = (d) => {
|
|
90
|
+
if (closed)
|
|
91
|
+
return;
|
|
92
|
+
closed = d;
|
|
93
|
+
if (!open)
|
|
94
|
+
settle.reject(d);
|
|
95
|
+
for (const w of waiters.splice(0))
|
|
96
|
+
w.reject(d);
|
|
97
|
+
};
|
|
98
|
+
ws.addEventListener('open', () => {
|
|
99
|
+
open = true;
|
|
100
|
+
settle.resolve();
|
|
101
|
+
});
|
|
102
|
+
ws.addEventListener('message', (e) => {
|
|
103
|
+
const d = e.data;
|
|
104
|
+
const text = typeof d === 'string'
|
|
105
|
+
? d
|
|
106
|
+
: d instanceof ArrayBuffer
|
|
107
|
+
? decoder.decode(d)
|
|
108
|
+
: ArrayBuffer.isView(d)
|
|
109
|
+
? decoder.decode(d)
|
|
110
|
+
: null;
|
|
111
|
+
if (text === null)
|
|
112
|
+
return;
|
|
113
|
+
const w = waiters.shift();
|
|
114
|
+
if (w)
|
|
115
|
+
w.resolve(text);
|
|
116
|
+
else
|
|
117
|
+
queue.push(text);
|
|
118
|
+
});
|
|
119
|
+
ws.addEventListener('close', (e) => finish(new Dropped(typeof e.code === 'number' && e.code !== 1005 ? e.code : null, e.reason ?? '')));
|
|
120
|
+
ws.addEventListener('error', () => {
|
|
121
|
+
if (!open)
|
|
122
|
+
finish(new Dropped(null, 'error'));
|
|
123
|
+
});
|
|
124
|
+
return {
|
|
125
|
+
opened,
|
|
126
|
+
recv: () => {
|
|
127
|
+
const next = queue.shift();
|
|
128
|
+
if (next !== undefined)
|
|
129
|
+
return Promise.resolve(next);
|
|
130
|
+
if (closed)
|
|
131
|
+
return Promise.reject(closed);
|
|
132
|
+
return new Promise((resolve, reject) => waiters.push({ resolve, reject }));
|
|
133
|
+
},
|
|
134
|
+
send: (text) => {
|
|
135
|
+
if (closed)
|
|
136
|
+
return;
|
|
137
|
+
try {
|
|
138
|
+
ws.send(text);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// closing: the close event follows
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
close: () => {
|
|
145
|
+
try {
|
|
146
|
+
ws.close(1000);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// already closed
|
|
150
|
+
}
|
|
151
|
+
finish(new Dropped(1000, 'closed by the client'));
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** Ask the upgrade again over `node:http(s)` to learn why it was refused (a WHATWG
|
|
156
|
+
* `WebSocket` hides the status). `'upgraded'` when the upgrade now succeeds (that socket is
|
|
157
|
+
* dropped at once), null where the runtime has no `node:http` or nothing answered. */
|
|
158
|
+
export const nodeProbe = async (url, headers) => {
|
|
159
|
+
const u = new URL(url.replace(/^ws/, 'http'));
|
|
160
|
+
let mod;
|
|
161
|
+
try {
|
|
162
|
+
// Literal imports: tsc leaves them as they are, so the bundler hints survive the build
|
|
163
|
+
// (a computed specifier gets wrapped and loses them). No @types/node here: untyped.
|
|
164
|
+
if (u.protocol === 'https:')
|
|
165
|
+
// @ts-ignore -- node:https has no types in this package
|
|
166
|
+
mod = await import(/* @vite-ignore */ /* webpackIgnore: true */ 'node:https');
|
|
167
|
+
// @ts-ignore -- node:http has no types in this package
|
|
168
|
+
else
|
|
169
|
+
mod = await import(/* @vite-ignore */ /* webpackIgnore: true */ 'node:http');
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
// The handshake's nonce, not a secret (Node 18 has no global `crypto`).
|
|
175
|
+
const key = btoa(String.fromCharCode(...Array.from({ length: 16 }, () => (Math.random() * 256) | 0)));
|
|
176
|
+
return new Promise((resolve) => {
|
|
177
|
+
const req = mod.request(u, {
|
|
178
|
+
method: 'GET',
|
|
179
|
+
headers: {
|
|
180
|
+
...headers,
|
|
181
|
+
connection: 'Upgrade',
|
|
182
|
+
upgrade: 'websocket',
|
|
183
|
+
'sec-websocket-version': '13',
|
|
184
|
+
'sec-websocket-key': key
|
|
185
|
+
},
|
|
186
|
+
timeout: 15_000
|
|
187
|
+
});
|
|
188
|
+
req.on('upgrade', (_res, socket) => {
|
|
189
|
+
socket.destroy();
|
|
190
|
+
resolve('upgraded');
|
|
191
|
+
});
|
|
192
|
+
req.on('response', (res) => {
|
|
193
|
+
let body = '';
|
|
194
|
+
res.setEncoding('utf8');
|
|
195
|
+
res.on('data', (c) => {
|
|
196
|
+
if (body.length < 65_536)
|
|
197
|
+
body += c;
|
|
198
|
+
});
|
|
199
|
+
res.on('end', () => {
|
|
200
|
+
const ra = res.headers['retry-after'];
|
|
201
|
+
resolve({ status: res.statusCode, body, retryAfter: typeof ra === 'string' ? ra : null });
|
|
202
|
+
});
|
|
203
|
+
res.on('error', () => resolve({ status: res.statusCode, body: null, retryAfter: null }));
|
|
204
|
+
});
|
|
205
|
+
req.on('timeout', () => req.destroy());
|
|
206
|
+
req.on('error', () => resolve(null));
|
|
207
|
+
req.end();
|
|
208
|
+
});
|
|
209
|
+
};
|
|
210
|
+
/** Open with a `WebSocket` constructor; a failure before the open is probed for a status. */
|
|
211
|
+
export function constructorConnect(Ctor, probe = nodeProbe) {
|
|
212
|
+
return async (url, headers) => {
|
|
213
|
+
let ws;
|
|
214
|
+
try {
|
|
215
|
+
ws = new Ctor(url, { headers });
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
throw new Dropped(null, String(e?.message ?? e));
|
|
219
|
+
}
|
|
220
|
+
const conn = adapt(ws);
|
|
221
|
+
try {
|
|
222
|
+
await conn.opened;
|
|
223
|
+
}
|
|
224
|
+
catch (e) {
|
|
225
|
+
const r = await probe(url, headers).catch(() => null);
|
|
226
|
+
if (r === 'upgraded')
|
|
227
|
+
throw new HeadersLost();
|
|
228
|
+
if (r)
|
|
229
|
+
throw new Refused(r.status, r.body, r.retryAfter);
|
|
230
|
+
throw e;
|
|
231
|
+
}
|
|
232
|
+
return conn;
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** Open with a fetch upgrade (Cloudflare Workers: `res.webSocket.accept()`). */
|
|
236
|
+
export function fetchConnect(fetchFn) {
|
|
237
|
+
return async (url, headers) => {
|
|
238
|
+
let res;
|
|
239
|
+
try {
|
|
240
|
+
res = await fetchFn(url.replace(/^ws/, 'http'), {
|
|
241
|
+
headers: { ...headers, upgrade: 'websocket' },
|
|
242
|
+
redirect: 'manual'
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
throw new Dropped(null, String(e?.message ?? e));
|
|
247
|
+
}
|
|
248
|
+
const ws = res.webSocket;
|
|
249
|
+
if (res.status !== 101 || !ws) {
|
|
250
|
+
const body = await res.text().catch(() => null);
|
|
251
|
+
throw new Refused(res.status, body, res.headers.get('retry-after'));
|
|
252
|
+
}
|
|
253
|
+
const conn = adapt(ws);
|
|
254
|
+
ws.accept?.();
|
|
255
|
+
return conn;
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/** The default way to open a socket in this runtime. */
|
|
259
|
+
export function defaultConnect(webSocket, fetchFn) {
|
|
260
|
+
if (webSocket === 'fetch')
|
|
261
|
+
return fetchConnect(fetchFn());
|
|
262
|
+
if (webSocket)
|
|
263
|
+
return constructorConnect(webSocket);
|
|
264
|
+
const ua = globalThis.navigator?.userAgent;
|
|
265
|
+
if (ua === 'Cloudflare-Workers')
|
|
266
|
+
return fetchConnect(fetchFn());
|
|
267
|
+
const Global = globalThis.WebSocket;
|
|
268
|
+
if (typeof Global !== 'function')
|
|
269
|
+
throw new TerminalError('no WebSocket in this runtime: use Node 22+, Deno or Bun, or pass { webSocket } (e.g. the ws package)');
|
|
270
|
+
return constructorConnect(Global);
|
|
271
|
+
}
|
|
272
|
+
/** A sleep that ends early (resolving) when `signal` aborts. */
|
|
273
|
+
function sleep(ms, signal) {
|
|
274
|
+
return new Promise((resolve) => {
|
|
275
|
+
if (signal?.aborted)
|
|
276
|
+
return resolve();
|
|
277
|
+
const t = setTimeout(done, ms);
|
|
278
|
+
function done() {
|
|
279
|
+
clearTimeout(t);
|
|
280
|
+
signal?.removeEventListener('abort', done);
|
|
281
|
+
resolve();
|
|
282
|
+
}
|
|
283
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
/** Frames of `topic` for as long as the caller iterates; `pong` is not yielded.
|
|
287
|
+
*
|
|
288
|
+
* @throws LiveClosed: the server ended the stream (4401, 4003, 4004).
|
|
289
|
+
* @throws ApiError: the upgrade was refused for good (401, 403, 404, 400, 410). */
|
|
290
|
+
export async function* openStream(args) {
|
|
291
|
+
const url = socketUrl(args.baseUrl, args.topic, args.depth);
|
|
292
|
+
const headers = { authorization: `Bearer ${args.key}` };
|
|
293
|
+
const backoff = { ...DEFAULT_BACKOFF, ...args.backoff };
|
|
294
|
+
const wait = args.sleep ?? sleep;
|
|
295
|
+
const random = args.random ?? Math.random;
|
|
296
|
+
const signal = args.signal;
|
|
297
|
+
const delayMs = (attempt) => backoffDelay(backoff, attempt, random) * 1000;
|
|
298
|
+
let attempt = 0;
|
|
299
|
+
let everOpened = false;
|
|
300
|
+
let failedOpens = 0;
|
|
301
|
+
let headersLost = 0;
|
|
302
|
+
while (!signal?.aborted) {
|
|
303
|
+
let conn;
|
|
304
|
+
try {
|
|
305
|
+
conn = await args.connect(url, headers);
|
|
306
|
+
}
|
|
307
|
+
catch (e) {
|
|
308
|
+
if (e instanceof Refused) {
|
|
309
|
+
if (e.status >= 300 && e.status < 400)
|
|
310
|
+
throw new Redirected(`the live socket answered a redirect (${e.status}); not followed`);
|
|
311
|
+
let body = null;
|
|
312
|
+
try {
|
|
313
|
+
body = e.body ? JSON.parse(e.body) : null;
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
// not JSON
|
|
317
|
+
}
|
|
318
|
+
const err = apiErrorFrom(e.status, body, e.retryAfter);
|
|
319
|
+
if (err.status !== 429 && err.status < 500)
|
|
320
|
+
throw err;
|
|
321
|
+
await wait(err.retryAfter !== undefined ? err.retryAfter * 1000 : delayMs(attempt), signal);
|
|
322
|
+
attempt++;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (e instanceof Dropped) {
|
|
326
|
+
failedOpens++;
|
|
327
|
+
headersLost = e instanceof HeadersLost ? headersLost + 1 : 0;
|
|
328
|
+
if (headersLost >= MAX_HEADERS_LOST)
|
|
329
|
+
throw new TerminalError("the live socket was refused because this runtime's WebSocket does not send the " +
|
|
330
|
+
'authorization header: pass { webSocket } (e.g. the ws package) to the Terminal');
|
|
331
|
+
if (!everOpened && failedOpens >= MAX_FAILED_FIRST_OPENS)
|
|
332
|
+
throw new TerminalError(`the live socket did not open in ${failedOpens} tries (${e.reason || 'no reason given'}): ` +
|
|
333
|
+
'check the network, or pass { webSocket } (e.g. the ws package) to the Terminal');
|
|
334
|
+
await wait(delayMs(attempt), signal);
|
|
335
|
+
attempt++;
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
throw e;
|
|
339
|
+
}
|
|
340
|
+
everOpened = true;
|
|
341
|
+
failedOpens = 0;
|
|
342
|
+
headersLost = 0;
|
|
343
|
+
const onAbort = () => conn.close();
|
|
344
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
345
|
+
const pinger = setInterval(() => conn.send('ping'), args.pingEveryMs ?? PING_EVERY_MS);
|
|
346
|
+
let code = null;
|
|
347
|
+
try {
|
|
348
|
+
for (;;) {
|
|
349
|
+
let text;
|
|
350
|
+
try {
|
|
351
|
+
text = await conn.recv();
|
|
352
|
+
}
|
|
353
|
+
catch (d) {
|
|
354
|
+
if (!(d instanceof Dropped))
|
|
355
|
+
throw d;
|
|
356
|
+
code = d.code;
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
if (text === 'pong')
|
|
360
|
+
continue;
|
|
361
|
+
let frame;
|
|
362
|
+
try {
|
|
363
|
+
frame = JSON.parse(text);
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
continue; // a frame that does not parse is skipped; the stream goes on
|
|
367
|
+
}
|
|
368
|
+
const t = frame?.t;
|
|
369
|
+
if (t === 'view' || t === 'control') {
|
|
370
|
+
attempt = 0;
|
|
371
|
+
yield frame;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
clearInterval(pinger);
|
|
377
|
+
signal?.removeEventListener('abort', onAbort);
|
|
378
|
+
conn.close();
|
|
379
|
+
}
|
|
380
|
+
if (signal?.aborted)
|
|
381
|
+
return;
|
|
382
|
+
if (code === LIVE_CLOSE.grant)
|
|
383
|
+
continue;
|
|
384
|
+
const stop = code === null ? undefined : STOP_CLOSES[code];
|
|
385
|
+
if (stop !== undefined && code !== null)
|
|
386
|
+
throw new LiveClosed(code, stop);
|
|
387
|
+
await wait(delayMs(attempt), signal);
|
|
388
|
+
attempt++;
|
|
389
|
+
}
|
|
390
|
+
}
|
package/dist/me.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** `/me`: your own data (scope `me:read`, every plan). */
|
|
2
|
+
import type { Answer } from './answer.js';
|
|
3
|
+
import { type Instant, type Transport } from './client.js';
|
|
4
|
+
/** A window of the portfolio, half-open: `start` (default 24 hours ago) to `end`
|
|
5
|
+
* (exclusive, default now), each a day or an instant. */
|
|
6
|
+
export type Window = {
|
|
7
|
+
/** The window start (`from`). */
|
|
8
|
+
start?: Instant;
|
|
9
|
+
/** The window end (`to`, exclusive). */
|
|
10
|
+
end?: Instant;
|
|
11
|
+
/** A profile id (default: your default profile; see `me.profiles()`). */
|
|
12
|
+
profile?: string;
|
|
13
|
+
};
|
|
14
|
+
/** A page of fills, funding payments or transfers. */
|
|
15
|
+
export type ActivityOptions = Window & {
|
|
16
|
+
/** Only these assets (ids or symbols). */
|
|
17
|
+
assets?: string | readonly string[];
|
|
18
|
+
/** Only these segment ids (`binance:usdm`). */
|
|
19
|
+
segments?: string | readonly string[];
|
|
20
|
+
/** Only these markets, as the venue names them. */
|
|
21
|
+
markets?: string | readonly string[];
|
|
22
|
+
/** `buy` (received, in) or `sell` (paid, out). */
|
|
23
|
+
side?: 'buy' | 'sell';
|
|
24
|
+
/** The previous page's `meta.page.next_cursor`. */
|
|
25
|
+
cursor?: string;
|
|
26
|
+
/** Rows per page. */
|
|
27
|
+
limit?: number;
|
|
28
|
+
};
|
|
29
|
+
export type PortfolioApi = {
|
|
30
|
+
/** A profile's history and positions over a window (`GET /me/portfolio`). When the live
|
|
31
|
+
* sync failed or was slow, the stored last answer (`onLastAnswer` is called). */
|
|
32
|
+
get(opts?: Window): Promise<Answer<'get_me_portfolio'>>;
|
|
33
|
+
/** One asset's drill-down over a window (`GET /me/portfolio/asset`). */
|
|
34
|
+
asset(asset: string, opts?: Window): Promise<Answer<'get_me_portfolio_asset'>>;
|
|
35
|
+
/** Every fill in the window, newest first, a page at a time (`GET /me/portfolio/fills`;
|
|
36
|
+
* `meta.page.next_cursor` is the following page's `cursor`; `pages()` follows it). */
|
|
37
|
+
fills(opts?: ActivityOptions): Promise<Answer<'get_me_portfolio_fills'>>;
|
|
38
|
+
/** Every funding payment in the window, paged as the fills (`GET /me/portfolio/funding`). */
|
|
39
|
+
funding(opts?: ActivityOptions): Promise<Answer<'get_me_portfolio_funding'>>;
|
|
40
|
+
/** Every on-chain wallet transfer in the window, paged as the fills
|
|
41
|
+
* (`GET /me/portfolio/transfers`). */
|
|
42
|
+
transfers(opts?: ActivityOptions): Promise<Answer<'get_me_portfolio_transfers'>>;
|
|
43
|
+
};
|
|
44
|
+
export type ChartsApi = {
|
|
45
|
+
/** Every saved Charts plot (`GET /me/charts`). */
|
|
46
|
+
list(): Promise<Answer<'get_me_charts'>>;
|
|
47
|
+
/** One saved plot by its 16-character id (`GET /me/charts/{id}`); someone else's is
|
|
48
|
+
* `NotFound`. */
|
|
49
|
+
get(id: string): Promise<Answer<'get_me_charts_id'>>;
|
|
50
|
+
};
|
|
51
|
+
export type MeApi = {
|
|
52
|
+
/** The key itself (scopes, source, expiry) and your plan now (`GET /me`). */
|
|
53
|
+
get(): Promise<Answer<'get_me'>>;
|
|
54
|
+
/** Your connected accounts and venues (`GET /me/accounts`): names and statuses, never key
|
|
55
|
+
* material. */
|
|
56
|
+
accounts(): Promise<Answer<'get_me_accounts'>>;
|
|
57
|
+
/** Your portfolio profiles (`GET /me/profiles`). */
|
|
58
|
+
profiles(): Promise<Answer<'get_me_profiles'>>;
|
|
59
|
+
/** One asset's position and 24h P&L in your default profile (`GET /me/position`). */
|
|
60
|
+
position(asset: string): Promise<Answer<'get_me_position'>>;
|
|
61
|
+
/** Your portfolio over a window, one asset's drill-down, and its activity. */
|
|
62
|
+
portfolio: PortfolioApi;
|
|
63
|
+
/** Your saved Charts plots (Charts is part of Pro). */
|
|
64
|
+
charts: ChartsApi;
|
|
65
|
+
};
|
|
66
|
+
export declare function meApi(http: Transport): MeApi;
|
package/dist/me.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { instant, segment } from "./client.js";
|
|
2
|
+
const windowParams = (w = {}) => ({
|
|
3
|
+
from: instant(w.start),
|
|
4
|
+
to: instant(w.end),
|
|
5
|
+
profile: w.profile
|
|
6
|
+
});
|
|
7
|
+
export function meApi(http) {
|
|
8
|
+
const activity = (path) => (o = {}) => http.get(path, {
|
|
9
|
+
...windowParams(o),
|
|
10
|
+
assets: o.assets,
|
|
11
|
+
segments: o.segments,
|
|
12
|
+
markets: o.markets,
|
|
13
|
+
side: o.side,
|
|
14
|
+
cursor: o.cursor,
|
|
15
|
+
limit: o.limit
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
get: () => http.get('/me'),
|
|
19
|
+
accounts: () => http.get('/me/accounts'),
|
|
20
|
+
profiles: () => http.get('/me/profiles'),
|
|
21
|
+
position: (asset) => http.get('/me/position', { asset }),
|
|
22
|
+
portfolio: {
|
|
23
|
+
get: (o) => http.get('/me/portfolio', windowParams(o)),
|
|
24
|
+
asset: (asset, o) => http.get('/me/portfolio/asset', { asset, ...windowParams(o) }),
|
|
25
|
+
fills: activity('/me/portfolio/fills'),
|
|
26
|
+
funding: activity('/me/portfolio/funding'),
|
|
27
|
+
transfers: activity('/me/portfolio/transfers')
|
|
28
|
+
},
|
|
29
|
+
charts: {
|
|
30
|
+
list: () => http.get('/me/charts'),
|
|
31
|
+
get: (id) => http.get(`/me/charts/${segment(id)}`)
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
package/dist/pages.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Pagination: follow a cursor-paged read to its end. */
|
|
2
|
+
type Paged = {
|
|
3
|
+
cursor?: string | null;
|
|
4
|
+
};
|
|
5
|
+
/** The cursor of the page after `page`: `meta.page.next_cursor`, on every paged route;
|
|
6
|
+
* null at the end. */
|
|
7
|
+
export declare function nextCursor(page: unknown): string | null;
|
|
8
|
+
/**
|
|
9
|
+
* Every page of a cursor-paged read, the first with `params` as given:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* for await (const page of pages(t.v1.candles, { asset: 'bitcoin', start, end })) {
|
|
13
|
+
* rows.push(...page.data)
|
|
14
|
+
* }
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* For a read with a positional argument, wrap it:
|
|
18
|
+
* `pages((p) => t.v2.series.data('perp.funding.settlements', p), { asset: 'bitcoin' })`.
|
|
19
|
+
*/
|
|
20
|
+
export declare function pages<P extends Paged, R>(call: (params: P) => Promise<R>, params: P): AsyncGenerator<R, void, undefined>;
|
|
21
|
+
export {};
|
package/dist/pages.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Pagination: follow a cursor-paged read to its end. */
|
|
2
|
+
/** The cursor of the page after `page`: `meta.page.next_cursor`, on every paged route;
|
|
3
|
+
* null at the end. */
|
|
4
|
+
export function nextCursor(page) {
|
|
5
|
+
if (page === null || typeof page !== 'object')
|
|
6
|
+
return null;
|
|
7
|
+
const p = page;
|
|
8
|
+
const next = p.meta?.page?.next_cursor;
|
|
9
|
+
return typeof next === 'string' && next !== '' ? next : null;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Every page of a cursor-paged read, the first with `params` as given:
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* for await (const page of pages(t.v1.candles, { asset: 'bitcoin', start, end })) {
|
|
16
|
+
* rows.push(...page.data)
|
|
17
|
+
* }
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* For a read with a positional argument, wrap it:
|
|
21
|
+
* `pages((p) => t.v2.series.data('perp.funding.settlements', p), { asset: 'bitcoin' })`.
|
|
22
|
+
*/
|
|
23
|
+
export async function* pages(call, params) {
|
|
24
|
+
let cursor = params.cursor;
|
|
25
|
+
const seen = new Set();
|
|
26
|
+
for (;;) {
|
|
27
|
+
const page = await call(cursor ? { ...params, cursor } : params);
|
|
28
|
+
yield page;
|
|
29
|
+
const next = nextCursor(page);
|
|
30
|
+
if (next === null || seen.has(next))
|
|
31
|
+
return;
|
|
32
|
+
seen.add(next);
|
|
33
|
+
cursor = next;
|
|
34
|
+
}
|
|
35
|
+
}
|