@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
package/README.md ADDED
@@ -0,0 +1,134 @@
1
+ # @xapy/orderbook
2
+
3
+ Lightweight multi-exchange orderbook SDK — REST snapshot + WebSocket maintained stream.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i @xapy/orderbook
9
+ # Optional, only needed on Node < 22:
10
+ npm i ws
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { BybitClient } from "@xapy/orderbook/bybit";
17
+
18
+ const bybit = new BybitClient({ market: "perpetual" });
19
+
20
+ // One-shot REST snapshot
21
+ const snapshot = await bybit.fetchOrderbook("BTC/USDT", { depth: 50 });
22
+ console.log(snapshot.bids[0], snapshot.asks[0]);
23
+
24
+ // Maintained live stream (snapshot + deltas → always the latest book)
25
+ const stream = bybit.streamOrderbook("BTC/USDT", { depth: 50 });
26
+ stream.on("update", (book) => {
27
+ console.log(book.exchange, book.symbol, book.bids[0], book.asks[0]);
28
+ });
29
+ stream.on("reconnecting", (attempt, waitMs) => {
30
+ console.log(`reconnect attempt ${attempt} in ${waitMs}ms`);
31
+ });
32
+
33
+ // Or async-iterator
34
+ for await (const book of stream.iter()) {
35
+ console.log(book.sequence, book.bids[0]);
36
+ }
37
+
38
+ stream.close();
39
+ ```
40
+
41
+ ### Browser + CORS
42
+
43
+ Several exchanges block direct browser requests. Use `transformUrl` to route through your proxy:
44
+
45
+ ```ts
46
+ const bybit = new BybitClient({
47
+ market: "perpetual",
48
+ transformUrl: (url) =>
49
+ `https://my-proxy.example/${url.replace(/^https?:\/\//, "")}`,
50
+ });
51
+ ```
52
+
53
+ WebSocket connections are not subject to CORS and work directly in the browser.
54
+
55
+ ## What you get
56
+
57
+ - **Maintained orderbook** — the lib applies WS deltas internally; consumers always see a sorted, latest snapshot.
58
+ - **Gap recovery** — sequence numbers are verified; on a gap the lib re-fetches a REST snapshot and resumes without you noticing.
59
+ - **Auto-reconnect** — exponential backoff with jitter; the subscription replays on each reconnect.
60
+ - **Cross-runtime** — Node ≥ 18 (with `ws` peer for < 22) and modern browsers.
61
+ - **Tree-shakeable** — `import "@xapy/orderbook/bybit"` doesn't pull in other adapters.
62
+
63
+ ## Supported exchanges
64
+
65
+ | Exchange | Spot | Perpetual | Status |
66
+ | --- | --- | --- | --- |
67
+ | Bybit | ✅ | ✅ | available (0.1) |
68
+ | OKX | | | planned (0.2) |
69
+ | Bitget | | | planned (0.2) |
70
+ | Gate | | | planned (0.3) |
71
+ | CoinEx | | | planned (0.3) |
72
+ | BingX | | | planned (0.4) |
73
+ | Huobi | | | planned (0.4) |
74
+ | KuCoin | | | planned (0.5) |
75
+
76
+ ## API
77
+
78
+ ### `new BybitClient(options)`
79
+
80
+ ```ts
81
+ interface ClientOptions {
82
+ market: "spot" | "perpetual";
83
+ transformUrl?: (url: string) => string;
84
+ timeoutMs?: number; // default 10_000
85
+ }
86
+ ```
87
+
88
+ ### `client.fetchOrderbook(symbol, opts?)`
89
+
90
+ REST snapshot. Returns a `Promise<Orderbook>`.
91
+
92
+ ### `client.streamOrderbook(symbol, opts?)`
93
+
94
+ WebSocket stream. Returns an `OrderbookStream` exposing:
95
+
96
+ ```ts
97
+ stream.on("update", (book: Orderbook) => {});
98
+ stream.on("connected", () => {});
99
+ stream.on("disconnected", (reason?: string) => {});
100
+ stream.on("reconnecting", (attempt: number, waitMs: number) => {});
101
+ stream.on("error", (err: Error) => {});
102
+
103
+ for await (const book of stream.iter()) { /* … */ }
104
+
105
+ stream.close();
106
+ ```
107
+
108
+ ### `Orderbook` shape
109
+
110
+ ```ts
111
+ interface Orderbook {
112
+ exchange: ExchangeName;
113
+ symbol: string; // "BTC/USDT"
114
+ market: "spot" | "perpetual";
115
+ bids: { price: number; size: number }[]; // descending
116
+ asks: { price: number; size: number }[]; // ascending
117
+ timestamp: number; // ms epoch
118
+ sequence: number; // last applied seq
119
+ }
120
+ ```
121
+
122
+ Sizes are in **base coin** (e.g. BTC). Conversion to quote (USDT) is left to the caller.
123
+
124
+ ## Development
125
+
126
+ ```bash
127
+ npm install
128
+ npm run build
129
+ npm test
130
+ ```
131
+
132
+ ## License
133
+
134
+ MIT
@@ -0,0 +1,559 @@
1
+ 'use strict';
2
+
3
+ // src/core/symbol.ts
4
+ function parseSymbol(symbol) {
5
+ const [pair, settle] = symbol.split(":");
6
+ const parts = (pair ?? "").split("/");
7
+ const base = parts[0]?.toUpperCase();
8
+ const quote = parts[1]?.toUpperCase();
9
+ if (!base || !quote) {
10
+ throw new Error(
11
+ `invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
12
+ );
13
+ }
14
+ if (settle && settle.toUpperCase() !== quote) {
15
+ throw new Error(
16
+ `unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
17
+ );
18
+ }
19
+ return {
20
+ base,
21
+ quote,
22
+ market: settle ? "perpetual" : "spot",
23
+ pair: `${base}/${quote}`
24
+ };
25
+ }
26
+
27
+ // src/transport/http.ts
28
+ async function httpJson(req) {
29
+ const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
30
+ const controller = new AbortController();
31
+ const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
32
+ try {
33
+ const res = await fetch(url, {
34
+ method: req.method ?? "GET",
35
+ headers: req.headers,
36
+ body: req.body,
37
+ signal: controller.signal
38
+ });
39
+ if (!res.ok) {
40
+ const text = await res.text().catch(() => "");
41
+ throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
42
+ }
43
+ return await res.json();
44
+ } finally {
45
+ clearTimeout(timer);
46
+ }
47
+ }
48
+
49
+ // src/core/errors.ts
50
+ var ExchangeError = class extends Error {
51
+ constructor(exchange, message, cause) {
52
+ super(
53
+ `[${exchange}] ${message}`,
54
+ cause === void 0 ? void 0 : { cause }
55
+ );
56
+ this.exchange = exchange;
57
+ this.name = "ExchangeError";
58
+ }
59
+ exchange;
60
+ };
61
+
62
+ // src/exchanges/bingx/symbols.ts
63
+ function toBingxSymbol(symbol) {
64
+ const [base, quote] = symbol.split("/");
65
+ if (!base || !quote) {
66
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
67
+ }
68
+ return `${base}-${quote}`.toUpperCase();
69
+ }
70
+ function fromBingxSymbol(s) {
71
+ return s.toUpperCase().replace("-", "/");
72
+ }
73
+
74
+ // src/exchanges/bingx/rest.ts
75
+ var BASE = "https://open-api.bingx.com";
76
+ async function fetchBingxOrderbook(opts) {
77
+ const symbol = toBingxSymbol(opts.symbol);
78
+ const limit = opts.depth ?? 50;
79
+ const url = opts.market === "spot" ? `${BASE}/openApi/spot/v1/market/depth?symbol=${symbol}&limit=${limit}` : `${BASE}/openApi/swap/v2/quote/depth?symbol=${symbol}&limit=${limit}`;
80
+ const res = await httpJson({
81
+ url,
82
+ timeoutMs: opts.timeoutMs,
83
+ transformUrl: opts.transformUrl
84
+ });
85
+ if (res.code !== 0) {
86
+ throw new ExchangeError("bingx", `${res.code}: ${res.msg}`);
87
+ }
88
+ const ts = res.data.T ?? res.data.ts ?? Date.now();
89
+ return {
90
+ exchange: "bingx",
91
+ symbol: fromBingxSymbol(symbol),
92
+ market: opts.market,
93
+ bids: res.data.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
94
+ asks: res.data.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
95
+ timestamp: ts,
96
+ sequence: ts
97
+ };
98
+ }
99
+
100
+ // src/core/book-merger.ts
101
+ var BookMerger = class {
102
+ bids = /* @__PURE__ */ new Map();
103
+ // price -> size
104
+ asks = /* @__PURE__ */ new Map();
105
+ sequence = -1;
106
+ timestamp = 0;
107
+ hasSnapshot = false;
108
+ apply(event) {
109
+ if (event.kind === "snapshot") {
110
+ this.bids.clear();
111
+ this.asks.clear();
112
+ for (const { price, size } of event.bids) {
113
+ if (size > 0) this.bids.set(price, size);
114
+ }
115
+ for (const { price, size } of event.asks) {
116
+ if (size > 0) this.asks.set(price, size);
117
+ }
118
+ this.sequence = event.sequence;
119
+ this.timestamp = event.timestamp;
120
+ this.hasSnapshot = true;
121
+ return this.emit();
122
+ }
123
+ if (!this.hasSnapshot) {
124
+ return { ok: false, reason: "no-snapshot" };
125
+ }
126
+ if (event.sequence <= this.sequence) {
127
+ return this.emit();
128
+ }
129
+ if (event.prevSequence !== void 0) {
130
+ if (event.prevSequence !== this.sequence) {
131
+ return {
132
+ ok: false,
133
+ reason: "gap",
134
+ expected: this.sequence,
135
+ received: event.prevSequence
136
+ };
137
+ }
138
+ } else if (event.sequence !== this.sequence + 1) {
139
+ return {
140
+ ok: false,
141
+ reason: "gap",
142
+ expected: this.sequence + 1,
143
+ received: event.sequence
144
+ };
145
+ }
146
+ for (const { price, size } of event.bids) {
147
+ if (size === 0) this.bids.delete(price);
148
+ else this.bids.set(price, size);
149
+ }
150
+ for (const { price, size } of event.asks) {
151
+ if (size === 0) this.asks.delete(price);
152
+ else this.asks.set(price, size);
153
+ }
154
+ this.sequence = event.sequence;
155
+ this.timestamp = event.timestamp;
156
+ return this.emit();
157
+ }
158
+ reset() {
159
+ this.bids.clear();
160
+ this.asks.clear();
161
+ this.sequence = -1;
162
+ this.timestamp = 0;
163
+ this.hasSnapshot = false;
164
+ }
165
+ /** Returns true once the merger has a usable book. */
166
+ isReady() {
167
+ return this.hasSnapshot;
168
+ }
169
+ emit() {
170
+ const bids = [];
171
+ for (const [price, size] of this.bids) bids.push({ price, size });
172
+ bids.sort((a, b) => b.price - a.price);
173
+ const asks = [];
174
+ for (const [price, size] of this.asks) asks.push({ price, size });
175
+ asks.sort((a, b) => a.price - b.price);
176
+ return {
177
+ ok: true,
178
+ bids,
179
+ asks,
180
+ sequence: this.sequence,
181
+ timestamp: this.timestamp
182
+ };
183
+ }
184
+ };
185
+
186
+ // src/core/event-emitter.ts
187
+ var TypedEmitter = class {
188
+ listeners = /* @__PURE__ */ new Map();
189
+ on(event, fn) {
190
+ let set = this.listeners.get(event);
191
+ if (!set) {
192
+ set = /* @__PURE__ */ new Set();
193
+ this.listeners.set(event, set);
194
+ }
195
+ set.add(fn);
196
+ return this;
197
+ }
198
+ off(event, fn) {
199
+ this.listeners.get(event)?.delete(fn);
200
+ return this;
201
+ }
202
+ emit(event, ...args) {
203
+ const set = this.listeners.get(event);
204
+ if (!set || set.size === 0) return false;
205
+ for (const fn of set) fn(...args);
206
+ return true;
207
+ }
208
+ removeAllListeners() {
209
+ this.listeners.clear();
210
+ }
211
+ };
212
+
213
+ // src/core/stream.ts
214
+ var OrderbookStream = class extends TypedEmitter {
215
+ constructor(onClose) {
216
+ super();
217
+ this.onClose = onClose;
218
+ }
219
+ onClose;
220
+ closed = false;
221
+ close() {
222
+ if (this.closed) return;
223
+ this.closed = true;
224
+ this.onClose();
225
+ this.removeAllListeners();
226
+ }
227
+ /** Yields each maintained book as it becomes available. */
228
+ async *iter() {
229
+ const queue = [];
230
+ let resolveNext = null;
231
+ let pendingError = null;
232
+ let ended = false;
233
+ const onUpdate = (b) => {
234
+ queue.push(b);
235
+ resolveNext?.();
236
+ };
237
+ const onError = (e) => {
238
+ pendingError = e;
239
+ resolveNext?.();
240
+ };
241
+ const onClose = () => {
242
+ ended = true;
243
+ resolveNext?.();
244
+ };
245
+ this.on("update", onUpdate);
246
+ this.on("error", onError);
247
+ this.on("disconnected", onClose);
248
+ try {
249
+ while (true) {
250
+ if (pendingError) throw pendingError;
251
+ const next = queue.shift();
252
+ if (next) {
253
+ yield next;
254
+ continue;
255
+ }
256
+ if (ended || this.closed) return;
257
+ await new Promise((r) => {
258
+ resolveNext = r;
259
+ });
260
+ resolveNext = null;
261
+ }
262
+ } finally {
263
+ this.off("update", onUpdate);
264
+ this.off("error", onError);
265
+ this.off("disconnected", onClose);
266
+ }
267
+ }
268
+ };
269
+
270
+ // src/core/reconnect.ts
271
+ var Backoff = class _Backoff {
272
+ attempt = 0;
273
+ opts;
274
+ constructor(opts) {
275
+ this.opts = opts;
276
+ }
277
+ static withDefaults(opts = {}) {
278
+ return new _Backoff({
279
+ initialMs: opts.initialMs ?? 500,
280
+ maxMs: opts.maxMs ?? 3e4,
281
+ factor: opts.factor ?? 2,
282
+ jitter: opts.jitter ?? 0.3,
283
+ maxAttempts: opts.maxAttempts ?? 0
284
+ });
285
+ }
286
+ next() {
287
+ if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
288
+ return null;
289
+ }
290
+ this.attempt += 1;
291
+ const base = Math.min(
292
+ this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
293
+ this.opts.maxMs
294
+ );
295
+ const jitterRange = base * this.opts.jitter;
296
+ const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
297
+ return { wait, attempt: this.attempt };
298
+ }
299
+ reset() {
300
+ this.attempt = 0;
301
+ }
302
+ };
303
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
304
+
305
+ // src/transport/ws.ts
306
+ var cachedCtor = null;
307
+ async function getWebSocketCtor() {
308
+ if (cachedCtor) return cachedCtor;
309
+ if (hasNativeWebSocket) {
310
+ cachedCtor = globalThis.WebSocket;
311
+ return cachedCtor;
312
+ }
313
+ try {
314
+ const mod = await import('ws');
315
+ const ctor = mod.default ?? mod.WebSocket;
316
+ if (!ctor) throw new Error("missing default export");
317
+ cachedCtor = ctor;
318
+ return cachedCtor;
319
+ } catch (err) {
320
+ throw new Error(
321
+ "WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
322
+ );
323
+ }
324
+ }
325
+ var WSClient = class extends TypedEmitter {
326
+ constructor(cfg) {
327
+ super();
328
+ this.cfg = cfg;
329
+ this.backoff = Backoff.withDefaults(cfg.reconnect);
330
+ }
331
+ cfg;
332
+ ws = null;
333
+ backoff;
334
+ closed = false;
335
+ pingTimer = null;
336
+ async connect() {
337
+ if (this.closed) return;
338
+ const WS = await getWebSocketCtor();
339
+ const ws = new WS(this.cfg.url);
340
+ ws.binaryType = "arraybuffer";
341
+ this.ws = ws;
342
+ ws.onopen = async () => {
343
+ this.backoff.reset();
344
+ this.startPing();
345
+ this.emit("open");
346
+ try {
347
+ await this.cfg.onOpen?.({
348
+ send: (d) => ws.send(d),
349
+ close: () => this.close()
350
+ });
351
+ } catch (err) {
352
+ this.emit("error", err);
353
+ }
354
+ };
355
+ ws.onmessage = (e) => {
356
+ let result;
357
+ try {
358
+ result = this.cfg.onMessage(e.data);
359
+ } catch (err) {
360
+ this.emit("error", err);
361
+ return;
362
+ }
363
+ if (result && typeof result.catch === "function") {
364
+ result.catch(
365
+ (err) => this.emit("error", err)
366
+ );
367
+ }
368
+ };
369
+ ws.onerror = (e) => {
370
+ this.emit("error", new Error(e?.message ?? "WebSocket error"));
371
+ };
372
+ ws.onclose = (e) => {
373
+ this.stopPing();
374
+ const reason = e?.reason ?? "closed";
375
+ this.emit("close", reason);
376
+ if (!this.closed) this.scheduleReconnect();
377
+ };
378
+ }
379
+ send(data) {
380
+ this.ws?.send(data);
381
+ }
382
+ close() {
383
+ this.closed = true;
384
+ this.stopPing();
385
+ try {
386
+ this.ws?.close();
387
+ } catch {
388
+ }
389
+ }
390
+ startPing() {
391
+ if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
392
+ this.stopPing();
393
+ this.pingTimer = setInterval(() => {
394
+ try {
395
+ this.ws?.send(this.cfg.pingPayload());
396
+ } catch {
397
+ }
398
+ }, this.cfg.pingIntervalMs);
399
+ }
400
+ stopPing() {
401
+ if (this.pingTimer) {
402
+ clearInterval(this.pingTimer);
403
+ this.pingTimer = null;
404
+ }
405
+ }
406
+ scheduleReconnect() {
407
+ const next = this.backoff.next();
408
+ if (!next) {
409
+ this.emit("error", new Error("max reconnect attempts exceeded"));
410
+ return;
411
+ }
412
+ this.emit("reconnecting", next.attempt, next.wait);
413
+ setTimeout(() => {
414
+ this.connect().catch((e) => this.emit("error", e));
415
+ }, next.wait);
416
+ }
417
+ };
418
+
419
+ // src/utils/gzip.ts
420
+ var cached = null;
421
+ var pending = null;
422
+ function getGzipInflate() {
423
+ if (cached) return Promise.resolve(cached);
424
+ if (pending) return pending;
425
+ pending = (async () => {
426
+ let pako;
427
+ try {
428
+ pako = await import('pako');
429
+ } catch (err) {
430
+ throw new Error(
431
+ "gzip decompression requires the `pako` peer dependency. " + (err instanceof Error ? err.message : String(err))
432
+ );
433
+ }
434
+ const inflate = (data) => {
435
+ const buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
436
+ try {
437
+ return pako.ungzip(buf, { to: "string" });
438
+ } catch {
439
+ return pako.inflate(buf, { to: "string" });
440
+ }
441
+ };
442
+ cached = inflate;
443
+ return inflate;
444
+ })();
445
+ return pending;
446
+ }
447
+
448
+ // src/exchanges/bingx/ws.ts
449
+ var WS_SPOT = "wss://open-api-ws.bingx.com/market";
450
+ var WS_SWAP = "wss://open-api-swap.bingx.com/swap-market";
451
+ function streamBingxOrderbook(opts) {
452
+ const isSpot = opts.market === "spot";
453
+ const bingxSymbol = toBingxSymbol(opts.symbol);
454
+ const depth = opts.depth ?? 20;
455
+ const dataType = `${bingxSymbol}@depth${depth}`;
456
+ const merger = new BookMerger();
457
+ let ws = null;
458
+ const stream = new OrderbookStream(() => ws?.close());
459
+ const subscribePayload = JSON.stringify({
460
+ id: `sub-${Date.now()}`,
461
+ reqType: "sub",
462
+ dataType
463
+ });
464
+ const handlePayload = (text) => {
465
+ if (text === "Ping" || text === "ping") {
466
+ ws?.send(text === "Ping" ? "Pong" : "pong");
467
+ return;
468
+ }
469
+ let msg;
470
+ try {
471
+ msg = JSON.parse(text);
472
+ } catch {
473
+ return;
474
+ }
475
+ if (msg.id && !msg.data) return;
476
+ if (msg.dataType !== dataType || !msg.data) return;
477
+ const d = msg.data;
478
+ const ts = d.T ?? d.ts ?? Date.now();
479
+ const event = {
480
+ kind: "snapshot",
481
+ bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
482
+ asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
483
+ sequence: ts,
484
+ timestamp: ts
485
+ };
486
+ const r = merger.apply(event);
487
+ if (!r.ok) return;
488
+ const book = {
489
+ exchange: "bingx",
490
+ symbol: fromBingxSymbol(bingxSymbol),
491
+ market: opts.market,
492
+ bids: r.bids,
493
+ asks: r.asks,
494
+ timestamp: r.timestamp,
495
+ sequence: r.sequence
496
+ };
497
+ stream.emit("update", book);
498
+ };
499
+ const onMessage = async (raw) => {
500
+ if (typeof raw === "string") {
501
+ handlePayload(raw);
502
+ return;
503
+ }
504
+ const inflate = await getGzipInflate();
505
+ handlePayload(inflate(raw));
506
+ };
507
+ ws = new WSClient({
508
+ url: isSpot ? WS_SPOT : WS_SWAP,
509
+ onOpen: (sock) => {
510
+ merger.reset();
511
+ sock.send(subscribePayload);
512
+ },
513
+ onMessage
514
+ // bingx server is the one that sends Ping frames; we don't need client pings.
515
+ });
516
+ ws.on("open", () => stream.emit("connected"));
517
+ ws.on("close", (r) => stream.emit("disconnected", r));
518
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
519
+ ws.on("error", (e) => stream.emit("error", e));
520
+ ws.connect().catch((e) => stream.emit("error", e));
521
+ return stream;
522
+ }
523
+
524
+ // src/exchanges/bingx/index.ts
525
+ var BingxClient = class {
526
+ exchange = "bingx";
527
+ transformUrl;
528
+ timeoutMs;
529
+ constructor(opts = {}) {
530
+ this.transformUrl = opts.transformUrl;
531
+ this.timeoutMs = opts.timeoutMs;
532
+ }
533
+ fetchOrderbook(symbol, opts = {}) {
534
+ const { pair, market } = parseSymbol(symbol);
535
+ return fetchBingxOrderbook({
536
+ symbol: pair,
537
+ market,
538
+ depth: opts.depth,
539
+ timeoutMs: this.timeoutMs,
540
+ transformUrl: this.transformUrl
541
+ });
542
+ }
543
+ streamOrderbook(symbol, opts = {}) {
544
+ const { pair, market } = parseSymbol(symbol);
545
+ return streamBingxOrderbook({
546
+ symbol: pair,
547
+ market,
548
+ depth: opts.depth,
549
+ transformUrl: this.transformUrl,
550
+ timeoutMs: this.timeoutMs
551
+ });
552
+ }
553
+ };
554
+
555
+ exports.BingxClient = BingxClient;
556
+ exports.fetchBingxOrderbook = fetchBingxOrderbook;
557
+ exports.streamBingxOrderbook = streamBingxOrderbook;
558
+ //# sourceMappingURL=index.cjs.map
559
+ //# sourceMappingURL=index.cjs.map