@xapy/orderbook 0.1.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.
Files changed (52) hide show
  1. package/README.md +134 -0
  2. package/dist/exchanges/bingx/index.cjs +559 -0
  3. package/dist/exchanges/bingx/index.cjs.map +1 -0
  4. package/dist/exchanges/bingx/index.d.cts +35 -0
  5. package/dist/exchanges/bingx/index.d.ts +35 -0
  6. package/dist/exchanges/bingx/index.js +555 -0
  7. package/dist/exchanges/bingx/index.js.map +1 -0
  8. package/dist/exchanges/bitget/index.cjs +590 -0
  9. package/dist/exchanges/bitget/index.cjs.map +1 -0
  10. package/dist/exchanges/bitget/index.d.cts +30 -0
  11. package/dist/exchanges/bitget/index.d.ts +30 -0
  12. package/dist/exchanges/bitget/index.js +586 -0
  13. package/dist/exchanges/bitget/index.js.map +1 -0
  14. package/dist/exchanges/bybit/index.cjs +574 -0
  15. package/dist/exchanges/bybit/index.cjs.map +1 -0
  16. package/dist/exchanges/bybit/index.d.cts +36 -0
  17. package/dist/exchanges/bybit/index.d.ts +36 -0
  18. package/dist/exchanges/bybit/index.js +570 -0
  19. package/dist/exchanges/bybit/index.js.map +1 -0
  20. package/dist/exchanges/coinex/index.cjs +563 -0
  21. package/dist/exchanges/coinex/index.cjs.map +1 -0
  22. package/dist/exchanges/coinex/index.d.cts +37 -0
  23. package/dist/exchanges/coinex/index.d.ts +37 -0
  24. package/dist/exchanges/coinex/index.js +559 -0
  25. package/dist/exchanges/coinex/index.js.map +1 -0
  26. package/dist/exchanges/gate/index.cjs +634 -0
  27. package/dist/exchanges/gate/index.cjs.map +1 -0
  28. package/dist/exchanges/gate/index.d.cts +45 -0
  29. package/dist/exchanges/gate/index.d.ts +45 -0
  30. package/dist/exchanges/gate/index.js +630 -0
  31. package/dist/exchanges/gate/index.js.map +1 -0
  32. package/dist/exchanges/huobi/index.cjs +573 -0
  33. package/dist/exchanges/huobi/index.cjs.map +1 -0
  34. package/dist/exchanges/huobi/index.d.cts +37 -0
  35. package/dist/exchanges/huobi/index.d.ts +37 -0
  36. package/dist/exchanges/huobi/index.js +569 -0
  37. package/dist/exchanges/huobi/index.js.map +1 -0
  38. package/dist/exchanges/okx/index.cjs +579 -0
  39. package/dist/exchanges/okx/index.cjs.map +1 -0
  40. package/dist/exchanges/okx/index.d.cts +37 -0
  41. package/dist/exchanges/okx/index.d.ts +37 -0
  42. package/dist/exchanges/okx/index.js +575 -0
  43. package/dist/exchanges/okx/index.js.map +1 -0
  44. package/dist/index.cjs +1744 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.d.cts +101 -0
  47. package/dist/index.d.ts +101 -0
  48. package/dist/index.js +1729 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/stream-BKpWmRYN.d.cts +86 -0
  51. package/dist/stream-BKpWmRYN.d.ts +86 -0
  52. package/package.json +133 -0
@@ -0,0 +1,37 @@
1
+ import { M as Market, a as Orderbook, c as OrderbookStream, C as ClientOptions, b as OrderbookOptions } from '../../stream-BKpWmRYN.cjs';
2
+
3
+ interface FetchCoinexOrderbookOptions {
4
+ symbol: string;
5
+ market: Market;
6
+ depth?: number;
7
+ timeoutMs?: number;
8
+ transformUrl?: (url: string) => string;
9
+ }
10
+ declare function fetchCoinexOrderbook(opts: FetchCoinexOrderbookOptions): Promise<Orderbook>;
11
+
12
+ interface StreamCoinexOrderbookOptions {
13
+ symbol: string;
14
+ market: Market;
15
+ /** CoinEx supports 5/10/20/50. */
16
+ depth?: 5 | 10 | 20 | 50;
17
+ transformUrl?: (url: string) => string;
18
+ timeoutMs?: number;
19
+ }
20
+ /**
21
+ * CoinEx V2 WS sends gzipped JSON frames. Subscribe with `diff_flag=false` to
22
+ * receive full snapshots on every change — no merging required. Native WS
23
+ * ping/pong control frames keep the connection alive (auto-handled by the
24
+ * browser / `ws` package), so no app-level ping is needed.
25
+ */
26
+ declare function streamCoinexOrderbook(opts: StreamCoinexOrderbookOptions): OrderbookStream;
27
+
28
+ declare class CoinexClient {
29
+ readonly exchange: "coinex";
30
+ private readonly transformUrl?;
31
+ private readonly timeoutMs?;
32
+ constructor(opts?: ClientOptions);
33
+ fetchOrderbook(symbol: string, opts?: OrderbookOptions): Promise<Orderbook>;
34
+ streamOrderbook(symbol: string, opts?: OrderbookOptions): OrderbookStream;
35
+ }
36
+
37
+ export { CoinexClient, fetchCoinexOrderbook, streamCoinexOrderbook };
@@ -0,0 +1,37 @@
1
+ import { M as Market, a as Orderbook, c as OrderbookStream, C as ClientOptions, b as OrderbookOptions } from '../../stream-BKpWmRYN.js';
2
+
3
+ interface FetchCoinexOrderbookOptions {
4
+ symbol: string;
5
+ market: Market;
6
+ depth?: number;
7
+ timeoutMs?: number;
8
+ transformUrl?: (url: string) => string;
9
+ }
10
+ declare function fetchCoinexOrderbook(opts: FetchCoinexOrderbookOptions): Promise<Orderbook>;
11
+
12
+ interface StreamCoinexOrderbookOptions {
13
+ symbol: string;
14
+ market: Market;
15
+ /** CoinEx supports 5/10/20/50. */
16
+ depth?: 5 | 10 | 20 | 50;
17
+ transformUrl?: (url: string) => string;
18
+ timeoutMs?: number;
19
+ }
20
+ /**
21
+ * CoinEx V2 WS sends gzipped JSON frames. Subscribe with `diff_flag=false` to
22
+ * receive full snapshots on every change — no merging required. Native WS
23
+ * ping/pong control frames keep the connection alive (auto-handled by the
24
+ * browser / `ws` package), so no app-level ping is needed.
25
+ */
26
+ declare function streamCoinexOrderbook(opts: StreamCoinexOrderbookOptions): OrderbookStream;
27
+
28
+ declare class CoinexClient {
29
+ readonly exchange: "coinex";
30
+ private readonly transformUrl?;
31
+ private readonly timeoutMs?;
32
+ constructor(opts?: ClientOptions);
33
+ fetchOrderbook(symbol: string, opts?: OrderbookOptions): Promise<Orderbook>;
34
+ streamOrderbook(symbol: string, opts?: OrderbookOptions): OrderbookStream;
35
+ }
36
+
37
+ export { CoinexClient, fetchCoinexOrderbook, streamCoinexOrderbook };
@@ -0,0 +1,559 @@
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/coinex/symbols.ts
61
+ var QUOTES = ["USDT", "USDC", "USD"];
62
+ function toCoinexSymbol(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}${quote}`.toUpperCase();
68
+ }
69
+ function fromCoinexSymbol(s) {
70
+ const upper = s.toUpperCase();
71
+ for (const q of QUOTES) {
72
+ if (upper.endsWith(q)) {
73
+ return `${upper.slice(0, -q.length)}/${q}`;
74
+ }
75
+ }
76
+ return upper;
77
+ }
78
+
79
+ // src/exchanges/coinex/rest.ts
80
+ var BASE = "https://api.coinex.com";
81
+ async function fetchCoinexOrderbook(opts) {
82
+ const market = toCoinexSymbol(opts.symbol);
83
+ const limit = opts.depth ?? 50;
84
+ const url = opts.market === "spot" ? `${BASE}/v2/spot/depth?market=${market}&limit=${limit}&interval=0` : `${BASE}/v2/futures/depth?market=${market}&limit=${limit}&interval=0`;
85
+ const res = await httpJson({
86
+ url,
87
+ timeoutMs: opts.timeoutMs,
88
+ transformUrl: opts.transformUrl
89
+ });
90
+ if (res.code !== 0) {
91
+ throw new ExchangeError("coinex", `${res.code}: ${res.message}`);
92
+ }
93
+ const d = res.data.depth;
94
+ return {
95
+ exchange: "coinex",
96
+ symbol: fromCoinexSymbol(market),
97
+ market: opts.market,
98
+ bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
99
+ asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
100
+ timestamp: d.updated_at,
101
+ sequence: d.updated_at
102
+ };
103
+ }
104
+
105
+ // src/core/book-merger.ts
106
+ var BookMerger = class {
107
+ bids = /* @__PURE__ */ new Map();
108
+ // price -> size
109
+ asks = /* @__PURE__ */ new Map();
110
+ sequence = -1;
111
+ timestamp = 0;
112
+ hasSnapshot = false;
113
+ apply(event) {
114
+ if (event.kind === "snapshot") {
115
+ this.bids.clear();
116
+ this.asks.clear();
117
+ for (const { price, size } of event.bids) {
118
+ if (size > 0) this.bids.set(price, size);
119
+ }
120
+ for (const { price, size } of event.asks) {
121
+ if (size > 0) this.asks.set(price, size);
122
+ }
123
+ this.sequence = event.sequence;
124
+ this.timestamp = event.timestamp;
125
+ this.hasSnapshot = true;
126
+ return this.emit();
127
+ }
128
+ if (!this.hasSnapshot) {
129
+ return { ok: false, reason: "no-snapshot" };
130
+ }
131
+ if (event.sequence <= this.sequence) {
132
+ return this.emit();
133
+ }
134
+ if (event.prevSequence !== void 0) {
135
+ if (event.prevSequence !== this.sequence) {
136
+ return {
137
+ ok: false,
138
+ reason: "gap",
139
+ expected: this.sequence,
140
+ received: event.prevSequence
141
+ };
142
+ }
143
+ } else if (event.sequence !== this.sequence + 1) {
144
+ return {
145
+ ok: false,
146
+ reason: "gap",
147
+ expected: this.sequence + 1,
148
+ received: event.sequence
149
+ };
150
+ }
151
+ for (const { price, size } of event.bids) {
152
+ if (size === 0) this.bids.delete(price);
153
+ else this.bids.set(price, size);
154
+ }
155
+ for (const { price, size } of event.asks) {
156
+ if (size === 0) this.asks.delete(price);
157
+ else this.asks.set(price, size);
158
+ }
159
+ this.sequence = event.sequence;
160
+ this.timestamp = event.timestamp;
161
+ return this.emit();
162
+ }
163
+ reset() {
164
+ this.bids.clear();
165
+ this.asks.clear();
166
+ this.sequence = -1;
167
+ this.timestamp = 0;
168
+ this.hasSnapshot = false;
169
+ }
170
+ /** Returns true once the merger has a usable book. */
171
+ isReady() {
172
+ return this.hasSnapshot;
173
+ }
174
+ emit() {
175
+ const bids = [];
176
+ for (const [price, size] of this.bids) bids.push({ price, size });
177
+ bids.sort((a, b) => b.price - a.price);
178
+ const asks = [];
179
+ for (const [price, size] of this.asks) asks.push({ price, size });
180
+ asks.sort((a, b) => a.price - b.price);
181
+ return {
182
+ ok: true,
183
+ bids,
184
+ asks,
185
+ sequence: this.sequence,
186
+ timestamp: this.timestamp
187
+ };
188
+ }
189
+ };
190
+
191
+ // src/core/event-emitter.ts
192
+ var TypedEmitter = class {
193
+ listeners = /* @__PURE__ */ new Map();
194
+ on(event, fn) {
195
+ let set = this.listeners.get(event);
196
+ if (!set) {
197
+ set = /* @__PURE__ */ new Set();
198
+ this.listeners.set(event, set);
199
+ }
200
+ set.add(fn);
201
+ return this;
202
+ }
203
+ off(event, fn) {
204
+ this.listeners.get(event)?.delete(fn);
205
+ return this;
206
+ }
207
+ emit(event, ...args) {
208
+ const set = this.listeners.get(event);
209
+ if (!set || set.size === 0) return false;
210
+ for (const fn of set) fn(...args);
211
+ return true;
212
+ }
213
+ removeAllListeners() {
214
+ this.listeners.clear();
215
+ }
216
+ };
217
+
218
+ // src/core/stream.ts
219
+ var OrderbookStream = class extends TypedEmitter {
220
+ constructor(onClose) {
221
+ super();
222
+ this.onClose = onClose;
223
+ }
224
+ onClose;
225
+ closed = false;
226
+ close() {
227
+ if (this.closed) return;
228
+ this.closed = true;
229
+ this.onClose();
230
+ this.removeAllListeners();
231
+ }
232
+ /** Yields each maintained book as it becomes available. */
233
+ async *iter() {
234
+ const queue = [];
235
+ let resolveNext = null;
236
+ let pendingError = null;
237
+ let ended = false;
238
+ const onUpdate = (b) => {
239
+ queue.push(b);
240
+ resolveNext?.();
241
+ };
242
+ const onError = (e) => {
243
+ pendingError = e;
244
+ resolveNext?.();
245
+ };
246
+ const onClose = () => {
247
+ ended = true;
248
+ resolveNext?.();
249
+ };
250
+ this.on("update", onUpdate);
251
+ this.on("error", onError);
252
+ this.on("disconnected", onClose);
253
+ try {
254
+ while (true) {
255
+ if (pendingError) throw pendingError;
256
+ const next = queue.shift();
257
+ if (next) {
258
+ yield next;
259
+ continue;
260
+ }
261
+ if (ended || this.closed) return;
262
+ await new Promise((r) => {
263
+ resolveNext = r;
264
+ });
265
+ resolveNext = null;
266
+ }
267
+ } finally {
268
+ this.off("update", onUpdate);
269
+ this.off("error", onError);
270
+ this.off("disconnected", onClose);
271
+ }
272
+ }
273
+ };
274
+
275
+ // src/core/reconnect.ts
276
+ var Backoff = class _Backoff {
277
+ attempt = 0;
278
+ opts;
279
+ constructor(opts) {
280
+ this.opts = opts;
281
+ }
282
+ static withDefaults(opts = {}) {
283
+ return new _Backoff({
284
+ initialMs: opts.initialMs ?? 500,
285
+ maxMs: opts.maxMs ?? 3e4,
286
+ factor: opts.factor ?? 2,
287
+ jitter: opts.jitter ?? 0.3,
288
+ maxAttempts: opts.maxAttempts ?? 0
289
+ });
290
+ }
291
+ next() {
292
+ if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
293
+ return null;
294
+ }
295
+ this.attempt += 1;
296
+ const base = Math.min(
297
+ this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
298
+ this.opts.maxMs
299
+ );
300
+ const jitterRange = base * this.opts.jitter;
301
+ const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
302
+ return { wait, attempt: this.attempt };
303
+ }
304
+ reset() {
305
+ this.attempt = 0;
306
+ }
307
+ };
308
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
309
+
310
+ // src/transport/ws.ts
311
+ var cachedCtor = null;
312
+ async function getWebSocketCtor() {
313
+ if (cachedCtor) return cachedCtor;
314
+ if (hasNativeWebSocket) {
315
+ cachedCtor = globalThis.WebSocket;
316
+ return cachedCtor;
317
+ }
318
+ try {
319
+ const mod = await import('ws');
320
+ const ctor = mod.default ?? mod.WebSocket;
321
+ if (!ctor) throw new Error("missing default export");
322
+ cachedCtor = ctor;
323
+ return cachedCtor;
324
+ } catch (err) {
325
+ throw new Error(
326
+ "WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
327
+ );
328
+ }
329
+ }
330
+ var WSClient = class extends TypedEmitter {
331
+ constructor(cfg) {
332
+ super();
333
+ this.cfg = cfg;
334
+ this.backoff = Backoff.withDefaults(cfg.reconnect);
335
+ }
336
+ cfg;
337
+ ws = null;
338
+ backoff;
339
+ closed = false;
340
+ pingTimer = null;
341
+ async connect() {
342
+ if (this.closed) return;
343
+ const WS = await getWebSocketCtor();
344
+ const ws = new WS(this.cfg.url);
345
+ ws.binaryType = "arraybuffer";
346
+ this.ws = ws;
347
+ ws.onopen = async () => {
348
+ this.backoff.reset();
349
+ this.startPing();
350
+ this.emit("open");
351
+ try {
352
+ await this.cfg.onOpen?.({
353
+ send: (d) => ws.send(d),
354
+ close: () => this.close()
355
+ });
356
+ } catch (err) {
357
+ this.emit("error", err);
358
+ }
359
+ };
360
+ ws.onmessage = (e) => {
361
+ let result;
362
+ try {
363
+ result = this.cfg.onMessage(e.data);
364
+ } catch (err) {
365
+ this.emit("error", err);
366
+ return;
367
+ }
368
+ if (result && typeof result.catch === "function") {
369
+ result.catch(
370
+ (err) => this.emit("error", err)
371
+ );
372
+ }
373
+ };
374
+ ws.onerror = (e) => {
375
+ this.emit("error", new Error(e?.message ?? "WebSocket error"));
376
+ };
377
+ ws.onclose = (e) => {
378
+ this.stopPing();
379
+ const reason = e?.reason ?? "closed";
380
+ this.emit("close", reason);
381
+ if (!this.closed) this.scheduleReconnect();
382
+ };
383
+ }
384
+ send(data) {
385
+ this.ws?.send(data);
386
+ }
387
+ close() {
388
+ this.closed = true;
389
+ this.stopPing();
390
+ try {
391
+ this.ws?.close();
392
+ } catch {
393
+ }
394
+ }
395
+ startPing() {
396
+ if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
397
+ this.stopPing();
398
+ this.pingTimer = setInterval(() => {
399
+ try {
400
+ this.ws?.send(this.cfg.pingPayload());
401
+ } catch {
402
+ }
403
+ }, this.cfg.pingIntervalMs);
404
+ }
405
+ stopPing() {
406
+ if (this.pingTimer) {
407
+ clearInterval(this.pingTimer);
408
+ this.pingTimer = null;
409
+ }
410
+ }
411
+ scheduleReconnect() {
412
+ const next = this.backoff.next();
413
+ if (!next) {
414
+ this.emit("error", new Error("max reconnect attempts exceeded"));
415
+ return;
416
+ }
417
+ this.emit("reconnecting", next.attempt, next.wait);
418
+ setTimeout(() => {
419
+ this.connect().catch((e) => this.emit("error", e));
420
+ }, next.wait);
421
+ }
422
+ };
423
+
424
+ // src/utils/gzip.ts
425
+ var cached = null;
426
+ var pending = null;
427
+ function getGzipInflate() {
428
+ if (cached) return Promise.resolve(cached);
429
+ if (pending) return pending;
430
+ pending = (async () => {
431
+ let pako;
432
+ try {
433
+ pako = await import('pako');
434
+ } catch (err) {
435
+ throw new Error(
436
+ "gzip decompression requires the `pako` peer dependency. " + (err instanceof Error ? err.message : String(err))
437
+ );
438
+ }
439
+ const inflate = (data) => {
440
+ const buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
441
+ try {
442
+ return pako.ungzip(buf, { to: "string" });
443
+ } catch {
444
+ return pako.inflate(buf, { to: "string" });
445
+ }
446
+ };
447
+ cached = inflate;
448
+ return inflate;
449
+ })();
450
+ return pending;
451
+ }
452
+
453
+ // src/exchanges/coinex/ws.ts
454
+ var WS_SPOT = "wss://socket.coinex.com/v2/spot";
455
+ var WS_FUTURES = "wss://socket.coinex.com/v2/futures";
456
+ function streamCoinexOrderbook(opts) {
457
+ const market = toCoinexSymbol(opts.symbol);
458
+ const depth = opts.depth ?? 50;
459
+ const merger = new BookMerger();
460
+ let ws = null;
461
+ const stream = new OrderbookStream(() => ws?.close());
462
+ const subscribePayload = JSON.stringify({
463
+ method: "depth.subscribe",
464
+ params: {
465
+ // [market, limit, interval, diff_flag] — diff_flag=false → full snapshots
466
+ market_list: [[market, depth, "0", true]]
467
+ },
468
+ id: 1
469
+ });
470
+ const handlePayload = (text) => {
471
+ let msg;
472
+ try {
473
+ msg = JSON.parse(text);
474
+ } catch {
475
+ return;
476
+ }
477
+ if (msg.id != null && !msg.method) return;
478
+ if (msg.method !== "depth.update" || !msg.data) return;
479
+ if (msg.data.market !== market) return;
480
+ const d = msg.data.depth;
481
+ const event = {
482
+ kind: "snapshot",
483
+ bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
484
+ asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
485
+ sequence: d.updated_at,
486
+ timestamp: d.updated_at
487
+ };
488
+ const r = merger.apply(event);
489
+ if (!r.ok) return;
490
+ const book = {
491
+ exchange: "coinex",
492
+ symbol: fromCoinexSymbol(market),
493
+ market: opts.market,
494
+ bids: r.bids,
495
+ asks: r.asks,
496
+ timestamp: r.timestamp,
497
+ sequence: r.sequence
498
+ };
499
+ stream.emit("update", book);
500
+ };
501
+ const onMessage = async (raw) => {
502
+ if (typeof raw === "string") {
503
+ handlePayload(raw);
504
+ return;
505
+ }
506
+ const inflate = await getGzipInflate();
507
+ handlePayload(inflate(raw));
508
+ };
509
+ ws = new WSClient({
510
+ url: opts.market === "spot" ? WS_SPOT : WS_FUTURES,
511
+ onOpen: (sock) => {
512
+ merger.reset();
513
+ sock.send(subscribePayload);
514
+ },
515
+ onMessage
516
+ // Native WS ping/pong frames keep the connection alive — no app-level ping.
517
+ });
518
+ ws.on("open", () => stream.emit("connected"));
519
+ ws.on("close", (r) => stream.emit("disconnected", r));
520
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
521
+ ws.on("error", (e) => stream.emit("error", e));
522
+ ws.connect().catch((e) => stream.emit("error", e));
523
+ return stream;
524
+ }
525
+
526
+ // src/exchanges/coinex/index.ts
527
+ var CoinexClient = class {
528
+ exchange = "coinex";
529
+ transformUrl;
530
+ timeoutMs;
531
+ constructor(opts = {}) {
532
+ this.transformUrl = opts.transformUrl;
533
+ this.timeoutMs = opts.timeoutMs;
534
+ }
535
+ fetchOrderbook(symbol, opts = {}) {
536
+ const { pair, market } = parseSymbol(symbol);
537
+ return fetchCoinexOrderbook({
538
+ symbol: pair,
539
+ market,
540
+ depth: opts.depth,
541
+ timeoutMs: this.timeoutMs,
542
+ transformUrl: this.transformUrl
543
+ });
544
+ }
545
+ streamOrderbook(symbol, opts = {}) {
546
+ const { pair, market } = parseSymbol(symbol);
547
+ return streamCoinexOrderbook({
548
+ symbol: pair,
549
+ market,
550
+ depth: opts.depth,
551
+ transformUrl: this.transformUrl,
552
+ timeoutMs: this.timeoutMs
553
+ });
554
+ }
555
+ };
556
+
557
+ export { CoinexClient, fetchCoinexOrderbook, streamCoinexOrderbook };
558
+ //# sourceMappingURL=index.js.map
559
+ //# sourceMappingURL=index.js.map