@xapy/orderbook 0.1.4 → 0.1.5

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.
Files changed (69) hide show
  1. package/dist/exchanges/binance/index.cjs +605 -0
  2. package/dist/exchanges/binance/index.cjs.map +1 -0
  3. package/dist/exchanges/binance/index.d.cts +60 -0
  4. package/dist/exchanges/binance/index.d.ts +60 -0
  5. package/dist/exchanges/binance/index.js +601 -0
  6. package/dist/exchanges/binance/index.js.map +1 -0
  7. package/dist/exchanges/bingx/index.cjs +2 -1
  8. package/dist/exchanges/bingx/index.cjs.map +1 -1
  9. package/dist/exchanges/bingx/index.d.cts +1 -1
  10. package/dist/exchanges/bingx/index.d.ts +1 -1
  11. package/dist/exchanges/bingx/index.js +2 -1
  12. package/dist/exchanges/bingx/index.js.map +1 -1
  13. package/dist/exchanges/bitget/index.cjs +2 -1
  14. package/dist/exchanges/bitget/index.cjs.map +1 -1
  15. package/dist/exchanges/bitget/index.d.cts +1 -1
  16. package/dist/exchanges/bitget/index.d.ts +1 -1
  17. package/dist/exchanges/bitget/index.js +2 -1
  18. package/dist/exchanges/bitget/index.js.map +1 -1
  19. package/dist/exchanges/bybit/index.cjs +2 -1
  20. package/dist/exchanges/bybit/index.cjs.map +1 -1
  21. package/dist/exchanges/bybit/index.d.cts +1 -1
  22. package/dist/exchanges/bybit/index.d.ts +1 -1
  23. package/dist/exchanges/bybit/index.js +2 -1
  24. package/dist/exchanges/bybit/index.js.map +1 -1
  25. package/dist/exchanges/coinex/index.cjs +2 -1
  26. package/dist/exchanges/coinex/index.cjs.map +1 -1
  27. package/dist/exchanges/coinex/index.d.cts +1 -1
  28. package/dist/exchanges/coinex/index.d.ts +1 -1
  29. package/dist/exchanges/coinex/index.js +2 -1
  30. package/dist/exchanges/coinex/index.js.map +1 -1
  31. package/dist/exchanges/gate/index.cjs +2 -1
  32. package/dist/exchanges/gate/index.cjs.map +1 -1
  33. package/dist/exchanges/gate/index.d.cts +1 -1
  34. package/dist/exchanges/gate/index.d.ts +1 -1
  35. package/dist/exchanges/gate/index.js +2 -1
  36. package/dist/exchanges/gate/index.js.map +1 -1
  37. package/dist/exchanges/huobi/index.cjs +2 -1
  38. package/dist/exchanges/huobi/index.cjs.map +1 -1
  39. package/dist/exchanges/huobi/index.d.cts +1 -1
  40. package/dist/exchanges/huobi/index.d.ts +1 -1
  41. package/dist/exchanges/huobi/index.js +2 -1
  42. package/dist/exchanges/huobi/index.js.map +1 -1
  43. package/dist/exchanges/hyperliquid/index.cjs +536 -0
  44. package/dist/exchanges/hyperliquid/index.cjs.map +1 -0
  45. package/dist/exchanges/hyperliquid/index.d.cts +45 -0
  46. package/dist/exchanges/hyperliquid/index.d.ts +45 -0
  47. package/dist/exchanges/hyperliquid/index.js +532 -0
  48. package/dist/exchanges/hyperliquid/index.js.map +1 -0
  49. package/dist/exchanges/kucoin/index.cjs +614 -0
  50. package/dist/exchanges/kucoin/index.cjs.map +1 -0
  51. package/dist/exchanges/kucoin/index.d.cts +60 -0
  52. package/dist/exchanges/kucoin/index.d.ts +60 -0
  53. package/dist/exchanges/kucoin/index.js +609 -0
  54. package/dist/exchanges/kucoin/index.js.map +1 -0
  55. package/dist/exchanges/okx/index.cjs +2 -1
  56. package/dist/exchanges/okx/index.cjs.map +1 -1
  57. package/dist/exchanges/okx/index.d.cts +1 -1
  58. package/dist/exchanges/okx/index.d.ts +1 -1
  59. package/dist/exchanges/okx/index.js +2 -1
  60. package/dist/exchanges/okx/index.js.map +1 -1
  61. package/dist/index.cjs +627 -1
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.d.cts +5 -2
  64. package/dist/index.d.ts +5 -2
  65. package/dist/index.js +625 -2
  66. package/dist/index.js.map +1 -1
  67. package/dist/{stream-BKpWmRYN.d.cts → stream-C73HPYqT.d.cts} +1 -1
  68. package/dist/{stream-BKpWmRYN.d.ts → stream-C73HPYqT.d.ts} +1 -1
  69. package/package.json +34 -1
@@ -0,0 +1,609 @@
1
+ // src/core/symbol.ts
2
+ function parseSymbol(symbol) {
3
+ const [pair, settle] = symbol.split(":");
4
+ const parts = (pair ?? "").split("/");
5
+ const base = parts[0]?.toUpperCase();
6
+ const quote = parts[1]?.toUpperCase();
7
+ if (!base || !quote) {
8
+ throw new Error(
9
+ `invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
10
+ );
11
+ }
12
+ if (settle && settle.toUpperCase() !== quote) {
13
+ throw new Error(
14
+ `unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
15
+ );
16
+ }
17
+ return {
18
+ base,
19
+ quote,
20
+ market: settle ? "perpetual" : "spot",
21
+ pair: `${base}/${quote}`
22
+ };
23
+ }
24
+
25
+ // src/transport/http.ts
26
+ async function httpJson(req) {
27
+ const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
28
+ const controller = new AbortController();
29
+ const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
30
+ try {
31
+ const res = await fetch(url, {
32
+ method: req.method ?? "GET",
33
+ headers: req.headers,
34
+ body: req.body,
35
+ signal: controller.signal
36
+ });
37
+ if (!res.ok) {
38
+ const text = await res.text().catch(() => "");
39
+ throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
40
+ }
41
+ return await res.json();
42
+ } finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+
47
+ // src/core/errors.ts
48
+ var ExchangeError = class extends Error {
49
+ constructor(exchange, message, cause) {
50
+ super(
51
+ `[${exchange}] ${message}`,
52
+ cause === void 0 ? void 0 : { cause }
53
+ );
54
+ this.exchange = exchange;
55
+ this.name = "ExchangeError";
56
+ }
57
+ exchange;
58
+ };
59
+
60
+ // src/exchanges/kucoin/symbols.ts
61
+ var FUTURES_QUOTES = ["USDT", "USDC", "USD"];
62
+ function toKucoinSpotSymbol(symbol) {
63
+ const [base, quote] = symbol.split("/");
64
+ if (!base || !quote) {
65
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
66
+ }
67
+ return `${base.toUpperCase()}-${quote.toUpperCase()}`;
68
+ }
69
+ function fromKucoinSpotSymbol(s) {
70
+ return s.toUpperCase().replace("-", "/");
71
+ }
72
+ function toKucoinFuturesSymbol(symbol) {
73
+ const [base, quote] = symbol.split("/");
74
+ if (!base || !quote) {
75
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
76
+ }
77
+ const b = base.toUpperCase() === "BTC" ? "XBT" : base.toUpperCase();
78
+ return `${b}${quote.toUpperCase()}M`;
79
+ }
80
+ function fromKucoinFuturesSymbol(s) {
81
+ const upper = s.toUpperCase();
82
+ const stripped = upper.endsWith("M") ? upper.slice(0, -1) : upper;
83
+ for (const q of FUTURES_QUOTES) {
84
+ if (stripped.endsWith(q) && stripped.length > q.length) {
85
+ let base = stripped.slice(0, -q.length);
86
+ if (base === "XBT") base = "BTC";
87
+ return `${base}/${q}`;
88
+ }
89
+ }
90
+ return upper;
91
+ }
92
+
93
+ // src/exchanges/kucoin/rest.ts
94
+ var BASE_SPOT = "https://api.kucoin.com";
95
+ var BASE_FUTURES = "https://api-futures.kucoin.com";
96
+ async function fetchKucoinBullet(opts) {
97
+ const base = opts.market === "spot" ? BASE_SPOT : BASE_FUTURES;
98
+ const res = await httpJson({
99
+ url: `${base}/api/v1/bullet-public`,
100
+ method: "POST",
101
+ timeoutMs: opts.timeoutMs,
102
+ transformUrl: opts.transformUrl
103
+ });
104
+ if (res.code !== "200000") {
105
+ throw new ExchangeError("kucoin", `bullet failed: ${res.code}`);
106
+ }
107
+ const server = res.data.instanceServers[0];
108
+ if (!server) {
109
+ throw new ExchangeError("kucoin", "bullet returned no instance servers");
110
+ }
111
+ return {
112
+ endpoint: server.endpoint,
113
+ token: res.data.token,
114
+ pingInterval: server.pingInterval,
115
+ pingTimeout: server.pingTimeout
116
+ };
117
+ }
118
+ async function fetchKucoinOrderbook(opts) {
119
+ const tier = (opts.depth ?? 100) <= 20 ? 20 : 100;
120
+ if (opts.market === "spot") {
121
+ const symbol2 = toKucoinSpotSymbol(opts.symbol);
122
+ const url2 = `${BASE_SPOT}/api/v1/market/orderbook/level2_${tier}?symbol=${symbol2}`;
123
+ const res2 = await httpJson({
124
+ url: url2,
125
+ timeoutMs: opts.timeoutMs,
126
+ transformUrl: opts.transformUrl
127
+ });
128
+ if (res2.code !== "200000") {
129
+ throw new ExchangeError("kucoin", `orderbook failed: ${res2.code}`);
130
+ }
131
+ return {
132
+ exchange: "kucoin",
133
+ symbol: fromKucoinSpotSymbol(symbol2),
134
+ market: "spot",
135
+ bids: parseLevels(res2.data.bids),
136
+ asks: parseLevels(res2.data.asks),
137
+ timestamp: res2.data.time,
138
+ sequence: Number(res2.data.sequence)
139
+ };
140
+ }
141
+ const symbol = toKucoinFuturesSymbol(opts.symbol);
142
+ const url = `${BASE_FUTURES}/api/v1/level2/depth${tier}?symbol=${symbol}`;
143
+ const res = await httpJson({
144
+ url,
145
+ timeoutMs: opts.timeoutMs,
146
+ transformUrl: opts.transformUrl
147
+ });
148
+ if (res.code !== "200000") {
149
+ throw new ExchangeError("kucoin", `orderbook failed: ${res.code}`);
150
+ }
151
+ return {
152
+ exchange: "kucoin",
153
+ symbol: fromKucoinFuturesSymbol(symbol),
154
+ market: "perpetual",
155
+ bids: parseLevels(res.data.bids),
156
+ asks: parseLevels(res.data.asks),
157
+ timestamp: res.data.ts,
158
+ sequence: res.data.sequence
159
+ };
160
+ }
161
+ function parseLevels(rows) {
162
+ return rows.map(([p, s]) => ({ price: Number(p), size: Number(s) }));
163
+ }
164
+
165
+ // src/core/book-merger.ts
166
+ var BookMerger = class {
167
+ bids = /* @__PURE__ */ new Map();
168
+ // price -> size
169
+ asks = /* @__PURE__ */ new Map();
170
+ sequence = -1;
171
+ timestamp = 0;
172
+ hasSnapshot = false;
173
+ apply(event) {
174
+ if (event.kind === "snapshot") {
175
+ this.bids.clear();
176
+ this.asks.clear();
177
+ for (const { price, size } of event.bids) {
178
+ if (size > 0) this.bids.set(price, size);
179
+ }
180
+ for (const { price, size } of event.asks) {
181
+ if (size > 0) this.asks.set(price, size);
182
+ }
183
+ this.sequence = event.sequence;
184
+ this.timestamp = event.timestamp;
185
+ this.hasSnapshot = true;
186
+ return this.emit();
187
+ }
188
+ if (!this.hasSnapshot) {
189
+ return { ok: false, reason: "no-snapshot" };
190
+ }
191
+ if (event.sequence <= this.sequence) {
192
+ return this.emit();
193
+ }
194
+ if (event.prevSequence !== void 0) {
195
+ if (event.prevSequence !== this.sequence) {
196
+ return {
197
+ ok: false,
198
+ reason: "gap",
199
+ expected: this.sequence,
200
+ received: event.prevSequence
201
+ };
202
+ }
203
+ } else if (event.sequence !== this.sequence + 1) {
204
+ return {
205
+ ok: false,
206
+ reason: "gap",
207
+ expected: this.sequence + 1,
208
+ received: event.sequence
209
+ };
210
+ }
211
+ for (const { price, size } of event.bids) {
212
+ if (size === 0) this.bids.delete(price);
213
+ else this.bids.set(price, size);
214
+ }
215
+ for (const { price, size } of event.asks) {
216
+ if (size === 0) this.asks.delete(price);
217
+ else this.asks.set(price, size);
218
+ }
219
+ this.sequence = event.sequence;
220
+ this.timestamp = event.timestamp;
221
+ return this.emit();
222
+ }
223
+ reset() {
224
+ this.bids.clear();
225
+ this.asks.clear();
226
+ this.sequence = -1;
227
+ this.timestamp = 0;
228
+ this.hasSnapshot = false;
229
+ }
230
+ /** Returns true once the merger has a usable book. */
231
+ isReady() {
232
+ return this.hasSnapshot;
233
+ }
234
+ emit() {
235
+ const bids = [];
236
+ for (const [price, size] of this.bids) bids.push({ price, size });
237
+ bids.sort((a, b) => b.price - a.price);
238
+ const asks = [];
239
+ for (const [price, size] of this.asks) asks.push({ price, size });
240
+ asks.sort((a, b) => a.price - b.price);
241
+ return {
242
+ ok: true,
243
+ bids,
244
+ asks,
245
+ sequence: this.sequence,
246
+ timestamp: this.timestamp
247
+ };
248
+ }
249
+ };
250
+
251
+ // src/core/event-emitter.ts
252
+ var TypedEmitter = class {
253
+ listeners = /* @__PURE__ */ new Map();
254
+ on(event, fn) {
255
+ let set = this.listeners.get(event);
256
+ if (!set) {
257
+ set = /* @__PURE__ */ new Set();
258
+ this.listeners.set(event, set);
259
+ }
260
+ set.add(fn);
261
+ return this;
262
+ }
263
+ off(event, fn) {
264
+ this.listeners.get(event)?.delete(fn);
265
+ return this;
266
+ }
267
+ emit(event, ...args) {
268
+ const set = this.listeners.get(event);
269
+ if (!set || set.size === 0) return false;
270
+ for (const fn of set) fn(...args);
271
+ return true;
272
+ }
273
+ removeAllListeners() {
274
+ this.listeners.clear();
275
+ }
276
+ };
277
+
278
+ // src/core/stream.ts
279
+ var OrderbookStream = class extends TypedEmitter {
280
+ constructor(onClose) {
281
+ super();
282
+ this.onClose = onClose;
283
+ }
284
+ onClose;
285
+ closed = false;
286
+ close() {
287
+ if (this.closed) return;
288
+ this.closed = true;
289
+ this.onClose();
290
+ this.removeAllListeners();
291
+ }
292
+ /** Yields each maintained book as it becomes available. */
293
+ async *iter() {
294
+ const queue = [];
295
+ let resolveNext = null;
296
+ let pendingError = null;
297
+ let ended = false;
298
+ const onUpdate = (b) => {
299
+ queue.push(b);
300
+ resolveNext?.();
301
+ };
302
+ const onError = (e) => {
303
+ pendingError = e;
304
+ resolveNext?.();
305
+ };
306
+ const onClose = () => {
307
+ ended = true;
308
+ resolveNext?.();
309
+ };
310
+ this.on("update", onUpdate);
311
+ this.on("error", onError);
312
+ this.on("disconnected", onClose);
313
+ try {
314
+ while (true) {
315
+ if (pendingError) throw pendingError;
316
+ const next = queue.shift();
317
+ if (next) {
318
+ yield next;
319
+ continue;
320
+ }
321
+ if (ended || this.closed) return;
322
+ await new Promise((r) => {
323
+ resolveNext = r;
324
+ });
325
+ resolveNext = null;
326
+ }
327
+ } finally {
328
+ this.off("update", onUpdate);
329
+ this.off("error", onError);
330
+ this.off("disconnected", onClose);
331
+ }
332
+ }
333
+ };
334
+
335
+ // src/core/reconnect.ts
336
+ var Backoff = class _Backoff {
337
+ attempt = 0;
338
+ opts;
339
+ constructor(opts) {
340
+ this.opts = opts;
341
+ }
342
+ static withDefaults(opts = {}) {
343
+ return new _Backoff({
344
+ initialMs: opts.initialMs ?? 500,
345
+ maxMs: opts.maxMs ?? 3e4,
346
+ factor: opts.factor ?? 2,
347
+ jitter: opts.jitter ?? 0.3,
348
+ maxAttempts: opts.maxAttempts ?? 0
349
+ });
350
+ }
351
+ next() {
352
+ if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
353
+ return null;
354
+ }
355
+ this.attempt += 1;
356
+ const base = Math.min(
357
+ this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
358
+ this.opts.maxMs
359
+ );
360
+ const jitterRange = base * this.opts.jitter;
361
+ const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
362
+ return { wait, attempt: this.attempt };
363
+ }
364
+ reset() {
365
+ this.attempt = 0;
366
+ }
367
+ };
368
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
369
+
370
+ // src/transport/ws.ts
371
+ var cachedCtor = null;
372
+ async function getWebSocketCtor() {
373
+ if (cachedCtor) return cachedCtor;
374
+ if (hasNativeWebSocket) {
375
+ cachedCtor = globalThis.WebSocket;
376
+ return cachedCtor;
377
+ }
378
+ try {
379
+ const mod = await import('ws');
380
+ const ctor = mod.default ?? mod.WebSocket;
381
+ if (!ctor) throw new Error("missing default export");
382
+ cachedCtor = ctor;
383
+ return cachedCtor;
384
+ } catch (err) {
385
+ throw new Error(
386
+ "WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
387
+ );
388
+ }
389
+ }
390
+ var WSClient = class extends TypedEmitter {
391
+ constructor(cfg) {
392
+ super();
393
+ this.cfg = cfg;
394
+ this.backoff = Backoff.withDefaults(cfg.reconnect);
395
+ }
396
+ cfg;
397
+ ws = null;
398
+ backoff;
399
+ closed = false;
400
+ pingTimer = null;
401
+ async connect() {
402
+ if (this.closed) return;
403
+ const WS = await getWebSocketCtor();
404
+ const url = typeof this.cfg.url === "function" ? await this.cfg.url() : this.cfg.url;
405
+ const ws = new WS(url);
406
+ ws.binaryType = "arraybuffer";
407
+ this.ws = ws;
408
+ ws.onopen = async () => {
409
+ this.backoff.reset();
410
+ this.startPing();
411
+ this.emit("open");
412
+ try {
413
+ await this.cfg.onOpen?.({
414
+ send: (d) => ws.send(d),
415
+ close: () => this.close()
416
+ });
417
+ } catch (err) {
418
+ this.emit("error", err);
419
+ }
420
+ };
421
+ ws.onmessage = (e) => {
422
+ let result;
423
+ try {
424
+ result = this.cfg.onMessage(e.data);
425
+ } catch (err) {
426
+ this.emit("error", err);
427
+ return;
428
+ }
429
+ if (result && typeof result.catch === "function") {
430
+ result.catch(
431
+ (err) => this.emit("error", err)
432
+ );
433
+ }
434
+ };
435
+ ws.onerror = (e) => {
436
+ this.emit("error", new Error(e?.message ?? "WebSocket error"));
437
+ };
438
+ ws.onclose = (e) => {
439
+ this.stopPing();
440
+ const reason = e?.reason ?? "closed";
441
+ this.emit("close", reason);
442
+ if (!this.closed) this.scheduleReconnect();
443
+ };
444
+ }
445
+ send(data) {
446
+ this.ws?.send(data);
447
+ }
448
+ close() {
449
+ this.closed = true;
450
+ this.stopPing();
451
+ try {
452
+ this.ws?.close();
453
+ } catch {
454
+ }
455
+ }
456
+ startPing() {
457
+ if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
458
+ this.stopPing();
459
+ this.pingTimer = setInterval(() => {
460
+ try {
461
+ this.ws?.send(this.cfg.pingPayload());
462
+ } catch {
463
+ }
464
+ }, this.cfg.pingIntervalMs);
465
+ }
466
+ stopPing() {
467
+ if (this.pingTimer) {
468
+ clearInterval(this.pingTimer);
469
+ this.pingTimer = null;
470
+ }
471
+ }
472
+ scheduleReconnect() {
473
+ const next = this.backoff.next();
474
+ if (!next) {
475
+ this.emit("error", new Error("max reconnect attempts exceeded"));
476
+ return;
477
+ }
478
+ this.emit("reconnecting", next.attempt, next.wait);
479
+ setTimeout(() => {
480
+ this.connect().catch((e) => this.emit("error", e));
481
+ }, next.wait);
482
+ }
483
+ };
484
+
485
+ // src/exchanges/kucoin/ws.ts
486
+ function streamKucoinOrderbook(opts) {
487
+ const isSpot = opts.market === "spot";
488
+ const symbol = isSpot ? toKucoinSpotSymbol(opts.symbol) : toKucoinFuturesSymbol(opts.symbol);
489
+ const level = (opts.depth ?? 50) <= 5 ? 5 : 50;
490
+ const topic = isSpot ? `/spotMarket/level2Depth${level}:${symbol}` : `/contractMarket/level2Depth${level}:${symbol}`;
491
+ const merger = new BookMerger();
492
+ let ws = null;
493
+ const stream = new OrderbookStream(() => ws?.close());
494
+ const urlProvider = async () => {
495
+ const bullet = await fetchKucoinBullet({
496
+ market: opts.market,
497
+ timeoutMs: opts.timeoutMs,
498
+ transformUrl: opts.transformUrl
499
+ });
500
+ const connectId = `xapy-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
501
+ return `${bullet.endpoint}?token=${encodeURIComponent(bullet.token)}&connectId=${connectId}`;
502
+ };
503
+ const subscribePayload = () => JSON.stringify({
504
+ id: `sub-${Date.now()}`,
505
+ type: "subscribe",
506
+ topic,
507
+ privateChannel: false,
508
+ response: true
509
+ });
510
+ const pingPayload = () => JSON.stringify({ id: `${Date.now()}`, type: "ping" });
511
+ const handleDepth = (d) => {
512
+ const ts = d.timestamp ?? d.ts ?? Date.now();
513
+ const event = {
514
+ kind: "snapshot",
515
+ bids: (d.bids ?? []).map(([p, s]) => ({
516
+ price: Number(p),
517
+ size: Number(s)
518
+ })),
519
+ asks: (d.asks ?? []).map(([p, s]) => ({
520
+ price: Number(p),
521
+ size: Number(s)
522
+ })),
523
+ sequence: ts,
524
+ timestamp: ts
525
+ };
526
+ const r = merger.apply(event);
527
+ if (!r.ok) return;
528
+ const book = {
529
+ exchange: "kucoin",
530
+ symbol: isSpot ? fromKucoinSpotSymbol(symbol) : fromKucoinFuturesSymbol(symbol),
531
+ market: opts.market,
532
+ bids: r.bids,
533
+ asks: r.asks,
534
+ timestamp: r.timestamp,
535
+ sequence: r.sequence
536
+ };
537
+ stream.emit("update", book);
538
+ };
539
+ const onMessage = (raw) => {
540
+ if (typeof raw !== "string") return;
541
+ let msg;
542
+ try {
543
+ msg = JSON.parse(raw);
544
+ } catch {
545
+ return;
546
+ }
547
+ if (msg.type === "welcome" || msg.type === "ack" || msg.type === "pong") {
548
+ return;
549
+ }
550
+ if (msg.type === "error") {
551
+ stream.emit("error", new Error(`kucoin: ${JSON.stringify(msg)}`));
552
+ return;
553
+ }
554
+ if (msg.type !== "message" || msg.topic !== topic || !msg.data) return;
555
+ handleDepth(msg.data);
556
+ };
557
+ ws = new WSClient({
558
+ url: urlProvider,
559
+ onOpen: (sock) => {
560
+ merger.reset();
561
+ sock.send(subscribePayload());
562
+ },
563
+ onMessage,
564
+ // KuCoin's documented bullet `pingInterval` is 18000ms — stay under it.
565
+ pingIntervalMs: 15e3,
566
+ pingPayload
567
+ });
568
+ ws.on("open", () => stream.emit("connected"));
569
+ ws.on("close", (r) => stream.emit("disconnected", r));
570
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
571
+ ws.on("error", (e) => stream.emit("error", e));
572
+ ws.connect().catch((e) => stream.emit("error", e));
573
+ return stream;
574
+ }
575
+
576
+ // src/exchanges/kucoin/index.ts
577
+ var KucoinClient = class {
578
+ exchange = "kucoin";
579
+ transformUrl;
580
+ timeoutMs;
581
+ constructor(opts = {}) {
582
+ this.transformUrl = opts.transformUrl;
583
+ this.timeoutMs = opts.timeoutMs;
584
+ }
585
+ fetchOrderbook(symbol, opts = {}) {
586
+ const { pair, market } = parseSymbol(symbol);
587
+ return fetchKucoinOrderbook({
588
+ symbol: pair,
589
+ market,
590
+ depth: opts.depth,
591
+ timeoutMs: this.timeoutMs,
592
+ transformUrl: this.transformUrl
593
+ });
594
+ }
595
+ streamOrderbook(symbol, opts = {}) {
596
+ const { pair, market } = parseSymbol(symbol);
597
+ return streamKucoinOrderbook({
598
+ symbol: pair,
599
+ market,
600
+ depth: opts.depth,
601
+ transformUrl: this.transformUrl,
602
+ timeoutMs: this.timeoutMs
603
+ });
604
+ }
605
+ };
606
+
607
+ export { KucoinClient, fetchKucoinBullet, fetchKucoinOrderbook, streamKucoinOrderbook };
608
+ //# sourceMappingURL=index.js.map
609
+ //# sourceMappingURL=index.js.map