@xapy/orderbook 0.1.28 → 0.1.30

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 (48) hide show
  1. package/README.md +4 -0
  2. package/dist/exchanges/aster/index.cjs +610 -0
  3. package/dist/exchanges/aster/index.cjs.map +1 -0
  4. package/dist/exchanges/aster/index.d.cts +65 -0
  5. package/dist/exchanges/aster/index.d.ts +65 -0
  6. package/dist/exchanges/aster/index.js +602 -0
  7. package/dist/exchanges/aster/index.js.map +1 -0
  8. package/dist/exchanges/binance/index.d.cts +1 -1
  9. package/dist/exchanges/binance/index.d.ts +1 -1
  10. package/dist/exchanges/bingx/index.d.cts +1 -1
  11. package/dist/exchanges/bingx/index.d.ts +1 -1
  12. package/dist/exchanges/bitget/index.d.cts +1 -1
  13. package/dist/exchanges/bitget/index.d.ts +1 -1
  14. package/dist/exchanges/bybit/index.d.cts +1 -1
  15. package/dist/exchanges/bybit/index.d.ts +1 -1
  16. package/dist/exchanges/coinex/index.d.cts +1 -1
  17. package/dist/exchanges/coinex/index.d.ts +1 -1
  18. package/dist/exchanges/deribit/index.d.cts +1 -1
  19. package/dist/exchanges/deribit/index.d.ts +1 -1
  20. package/dist/exchanges/edgex/index.d.cts +1 -1
  21. package/dist/exchanges/edgex/index.d.ts +1 -1
  22. package/dist/exchanges/gate/index.d.cts +1 -1
  23. package/dist/exchanges/gate/index.d.ts +1 -1
  24. package/dist/exchanges/hyperliquid/index.d.cts +1 -1
  25. package/dist/exchanges/hyperliquid/index.d.ts +1 -1
  26. package/dist/exchanges/kucoin/index.d.cts +1 -1
  27. package/dist/exchanges/kucoin/index.d.ts +1 -1
  28. package/dist/exchanges/lighter/index.d.cts +1 -1
  29. package/dist/exchanges/lighter/index.d.ts +1 -1
  30. package/dist/exchanges/mexc/index.cjs +729 -0
  31. package/dist/exchanges/mexc/index.cjs.map +1 -0
  32. package/dist/exchanges/mexc/index.d.cts +57 -0
  33. package/dist/exchanges/mexc/index.d.ts +57 -0
  34. package/dist/exchanges/mexc/index.js +721 -0
  35. package/dist/exchanges/mexc/index.js.map +1 -0
  36. package/dist/exchanges/okx/index.d.cts +1 -1
  37. package/dist/exchanges/okx/index.d.ts +1 -1
  38. package/dist/exchanges/whitebit/index.d.cts +1 -1
  39. package/dist/exchanges/whitebit/index.d.ts +1 -1
  40. package/dist/index.cjs +544 -0
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +4 -2
  43. package/dist/index.d.ts +4 -2
  44. package/dist/index.js +543 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/{stream-D8ErAue9.d.cts → stream-Dyq24thx.d.cts} +1 -1
  47. package/dist/{stream-D8ErAue9.d.ts → stream-Dyq24thx.d.ts} +1 -1
  48. package/package.json +23 -1
@@ -0,0 +1,721 @@
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/mexc/contracts.ts
61
+ var MEXC_SPOT_REST = "https://api.mexc.com";
62
+ var MEXC_FUTURES_REST = "https://contract.mexc.com";
63
+ var cache = null;
64
+ var inflight = null;
65
+ async function fetchContracts(opts) {
66
+ const res = await httpJson({
67
+ url: `${MEXC_FUTURES_REST}/api/v1/contract/detail`,
68
+ timeoutMs: opts.timeoutMs,
69
+ transformUrl: opts.transformUrl
70
+ });
71
+ const rows = res.data ?? [];
72
+ if (rows.length === 0) {
73
+ throw new ExchangeError(
74
+ "mexc",
75
+ res.message ? `${res.code}: ${res.message}` : "empty contract/detail response"
76
+ );
77
+ }
78
+ const map = /* @__PURE__ */ new Map();
79
+ for (const row of rows) map.set(row.symbol.toUpperCase(), row);
80
+ return map;
81
+ }
82
+ function loadContracts(opts) {
83
+ inflight ??= fetchContracts(opts).then(
84
+ (m) => {
85
+ cache = m;
86
+ inflight = null;
87
+ return m;
88
+ },
89
+ (err) => {
90
+ inflight = null;
91
+ throw err;
92
+ }
93
+ );
94
+ return inflight;
95
+ }
96
+ async function resolveContractSize(symbol, opts) {
97
+ const k = symbol.toUpperCase();
98
+ const hit = cache?.get(k);
99
+ const contract = hit ?? (await loadContracts(opts)).get(k);
100
+ if (!contract) {
101
+ throw new ExchangeError(
102
+ "mexc",
103
+ `unknown futures contract "${symbol}" \u2014 not listed on mexc`
104
+ );
105
+ }
106
+ const size = Number(contract.contractSize);
107
+ if (!Number.isFinite(size) || size <= 0) {
108
+ throw new ExchangeError(
109
+ "mexc",
110
+ `contract "${symbol}" has no usable contractSize (${contract.contractSize})`
111
+ );
112
+ }
113
+ return size;
114
+ }
115
+
116
+ // src/exchanges/mexc/symbols.ts
117
+ var QUOTES = ["USDT", "USDC", "TUSD", "USD", "BTC", "ETH"];
118
+ function toMexcSymbol(symbol, market) {
119
+ const [base, quote] = symbol.split("/");
120
+ if (!base || !quote) {
121
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
122
+ }
123
+ return market === "perpetual" ? `${base.toUpperCase()}_${quote.toUpperCase()}` : `${base}${quote}`.toUpperCase();
124
+ }
125
+ function fromMexcSymbol(s, market) {
126
+ const upper = s.toUpperCase();
127
+ if (market === "perpetual") {
128
+ const [base, quote] = upper.split("_");
129
+ return base && quote ? `${base}/${quote}` : upper;
130
+ }
131
+ for (const q of QUOTES) {
132
+ if (upper.endsWith(q) && upper.length > q.length) {
133
+ return `${upper.slice(0, -q.length)}/${q}`;
134
+ }
135
+ }
136
+ return upper;
137
+ }
138
+
139
+ // src/exchanges/mexc/rest.ts
140
+ var toSpotLevels = (rows) => (rows ?? []).map(([p, s]) => ({ price: Number(p), size: Number(s) }));
141
+ var toFuturesLevels = (rows, contractSize) => (rows ?? []).map(([price, vol]) => ({
142
+ price: Number(price),
143
+ size: Number(vol) * contractSize
144
+ }));
145
+ async function fetchMexcOrderbook(opts) {
146
+ const symbol = toMexcSymbol(opts.symbol, opts.market);
147
+ const depth = opts.depth ?? 50;
148
+ if (opts.market === "spot") {
149
+ const data = await httpJson({
150
+ url: `${MEXC_SPOT_REST}/api/v3/depth?symbol=${symbol}&limit=${depth}`,
151
+ timeoutMs: opts.timeoutMs,
152
+ transformUrl: opts.transformUrl
153
+ });
154
+ return {
155
+ exchange: "mexc",
156
+ symbol: fromMexcSymbol(symbol, opts.market),
157
+ market: opts.market,
158
+ bids: toSpotLevels(data.bids),
159
+ asks: toSpotLevels(data.asks),
160
+ // The spot depth endpoint returns no timestamp of its own.
161
+ timestamp: Date.now(),
162
+ sequence: data.lastUpdateId
163
+ };
164
+ }
165
+ const contractSize = await resolveContractSize(symbol, opts);
166
+ const res = await httpJson({
167
+ url: `${MEXC_FUTURES_REST}/api/v1/contract/depth/${symbol}?limit=${depth}`,
168
+ timeoutMs: opts.timeoutMs,
169
+ transformUrl: opts.transformUrl
170
+ });
171
+ if (!res.data) {
172
+ throw new ExchangeError(
173
+ "mexc",
174
+ res.message ? `${res.code}: ${res.message}` : "empty orderbook response"
175
+ );
176
+ }
177
+ return {
178
+ exchange: "mexc",
179
+ symbol: fromMexcSymbol(symbol, opts.market),
180
+ market: opts.market,
181
+ bids: toFuturesLevels(res.data.bids, contractSize),
182
+ asks: toFuturesLevels(res.data.asks, contractSize),
183
+ timestamp: res.data.timestamp ?? Date.now(),
184
+ sequence: Number(res.data.version ?? 0)
185
+ };
186
+ }
187
+
188
+ // src/core/book-merger.ts
189
+ var BookMerger = class {
190
+ bids = /* @__PURE__ */ new Map();
191
+ // price -> size
192
+ asks = /* @__PURE__ */ new Map();
193
+ sequence = -1;
194
+ timestamp = 0;
195
+ hasSnapshot = false;
196
+ apply(event) {
197
+ if (event.kind === "snapshot") {
198
+ this.bids.clear();
199
+ this.asks.clear();
200
+ for (const { price, size } of event.bids) {
201
+ if (size > 0) this.bids.set(price, size);
202
+ }
203
+ for (const { price, size } of event.asks) {
204
+ if (size > 0) this.asks.set(price, size);
205
+ }
206
+ this.sequence = event.sequence;
207
+ this.timestamp = event.timestamp;
208
+ this.hasSnapshot = true;
209
+ return this.emit();
210
+ }
211
+ if (!this.hasSnapshot) {
212
+ return { ok: false, reason: "no-snapshot" };
213
+ }
214
+ if (event.sequence <= this.sequence) {
215
+ return this.emit();
216
+ }
217
+ if (event.prevSequence !== void 0) {
218
+ if (event.prevSequence !== this.sequence) {
219
+ return {
220
+ ok: false,
221
+ reason: "gap",
222
+ expected: this.sequence,
223
+ received: event.prevSequence
224
+ };
225
+ }
226
+ } else if (event.sequence !== this.sequence + 1) {
227
+ return {
228
+ ok: false,
229
+ reason: "gap",
230
+ expected: this.sequence + 1,
231
+ received: event.sequence
232
+ };
233
+ }
234
+ for (const { price, size } of event.bids) {
235
+ if (size === 0) this.bids.delete(price);
236
+ else this.bids.set(price, size);
237
+ }
238
+ for (const { price, size } of event.asks) {
239
+ if (size === 0) this.asks.delete(price);
240
+ else this.asks.set(price, size);
241
+ }
242
+ this.sequence = event.sequence;
243
+ this.timestamp = event.timestamp;
244
+ return this.emit();
245
+ }
246
+ reset() {
247
+ this.bids.clear();
248
+ this.asks.clear();
249
+ this.sequence = -1;
250
+ this.timestamp = 0;
251
+ this.hasSnapshot = false;
252
+ }
253
+ /** Returns true once the merger has a usable book. */
254
+ isReady() {
255
+ return this.hasSnapshot;
256
+ }
257
+ emit() {
258
+ const bids = [];
259
+ for (const [price, size] of this.bids) bids.push({ price, size });
260
+ bids.sort((a, b) => b.price - a.price);
261
+ const asks = [];
262
+ for (const [price, size] of this.asks) asks.push({ price, size });
263
+ asks.sort((a, b) => a.price - b.price);
264
+ return {
265
+ ok: true,
266
+ bids,
267
+ asks,
268
+ sequence: this.sequence,
269
+ timestamp: this.timestamp
270
+ };
271
+ }
272
+ };
273
+
274
+ // src/core/event-emitter.ts
275
+ var TypedEmitter = class {
276
+ listeners = /* @__PURE__ */ new Map();
277
+ on(event, fn) {
278
+ let set = this.listeners.get(event);
279
+ if (!set) {
280
+ set = /* @__PURE__ */ new Set();
281
+ this.listeners.set(event, set);
282
+ }
283
+ set.add(fn);
284
+ return this;
285
+ }
286
+ off(event, fn) {
287
+ this.listeners.get(event)?.delete(fn);
288
+ return this;
289
+ }
290
+ emit(event, ...args) {
291
+ const set = this.listeners.get(event);
292
+ if (!set || set.size === 0) return false;
293
+ for (const fn of set) fn(...args);
294
+ return true;
295
+ }
296
+ removeAllListeners() {
297
+ this.listeners.clear();
298
+ }
299
+ };
300
+
301
+ // src/core/stream.ts
302
+ var OrderbookStream = class extends TypedEmitter {
303
+ constructor(onClose) {
304
+ super();
305
+ this.onClose = onClose;
306
+ }
307
+ onClose;
308
+ closed = false;
309
+ close() {
310
+ if (this.closed) return;
311
+ this.closed = true;
312
+ this.onClose();
313
+ this.removeAllListeners();
314
+ }
315
+ /** Yields each maintained book as it becomes available. */
316
+ async *iter() {
317
+ const queue = [];
318
+ let resolveNext = null;
319
+ let pendingError = null;
320
+ let ended = false;
321
+ const onUpdate = (b) => {
322
+ queue.push(b);
323
+ resolveNext?.();
324
+ };
325
+ const onError = (e) => {
326
+ pendingError = e;
327
+ resolveNext?.();
328
+ };
329
+ const onClose = () => {
330
+ ended = true;
331
+ resolveNext?.();
332
+ };
333
+ this.on("update", onUpdate);
334
+ this.on("error", onError);
335
+ this.on("disconnected", onClose);
336
+ try {
337
+ while (true) {
338
+ if (pendingError) throw pendingError;
339
+ const next = queue.shift();
340
+ if (next) {
341
+ yield next;
342
+ continue;
343
+ }
344
+ if (ended || this.closed) return;
345
+ await new Promise((r) => {
346
+ resolveNext = r;
347
+ });
348
+ resolveNext = null;
349
+ }
350
+ } finally {
351
+ this.off("update", onUpdate);
352
+ this.off("error", onError);
353
+ this.off("disconnected", onClose);
354
+ }
355
+ }
356
+ };
357
+
358
+ // src/core/reconnect.ts
359
+ var Backoff = class _Backoff {
360
+ attempt = 0;
361
+ opts;
362
+ constructor(opts) {
363
+ this.opts = opts;
364
+ }
365
+ static withDefaults(opts = {}) {
366
+ return new _Backoff({
367
+ initialMs: opts.initialMs ?? 500,
368
+ maxMs: opts.maxMs ?? 3e4,
369
+ factor: opts.factor ?? 2,
370
+ jitter: opts.jitter ?? 0.3,
371
+ maxAttempts: opts.maxAttempts ?? 0
372
+ });
373
+ }
374
+ next() {
375
+ if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
376
+ return null;
377
+ }
378
+ this.attempt += 1;
379
+ const base = Math.min(
380
+ this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
381
+ this.opts.maxMs
382
+ );
383
+ const jitterRange = base * this.opts.jitter;
384
+ const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
385
+ return { wait, attempt: this.attempt };
386
+ }
387
+ reset() {
388
+ this.attempt = 0;
389
+ }
390
+ };
391
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
392
+
393
+ // src/transport/ws.ts
394
+ function toError(value, fallback = "unknown error") {
395
+ if (value instanceof Error) {
396
+ return value.message ? value : new Error(`${value.name}: ${fallback}`);
397
+ }
398
+ if (typeof value === "string" && value) return new Error(value);
399
+ return new Error(fallback);
400
+ }
401
+ function normalizeWsError(ev) {
402
+ const detail = ev?.message || (ev?.error instanceof Error ? ev.error.message : void 0) || (typeof ev?.error === "string" ? ev.error : void 0);
403
+ return new Error(detail ? `WebSocket error: ${detail}` : "WebSocket error");
404
+ }
405
+ function describeClose(ev) {
406
+ if (ev?.reason) return ev.reason;
407
+ return ev?.code === void 0 ? "closed" : `closed (code ${ev.code})`;
408
+ }
409
+ var cachedCtor = null;
410
+ async function getWebSocketCtor() {
411
+ if (cachedCtor) return cachedCtor;
412
+ if (hasNativeWebSocket) {
413
+ cachedCtor = globalThis.WebSocket;
414
+ return cachedCtor;
415
+ }
416
+ try {
417
+ const mod = await import('ws');
418
+ const ctor = mod.default ?? mod.WebSocket;
419
+ if (!ctor) throw new Error("missing default export");
420
+ cachedCtor = ctor;
421
+ return cachedCtor;
422
+ } catch (err) {
423
+ throw new Error(
424
+ "WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
425
+ );
426
+ }
427
+ }
428
+ var WSClient = class extends TypedEmitter {
429
+ constructor(cfg) {
430
+ super();
431
+ this.cfg = cfg;
432
+ this.backoff = Backoff.withDefaults(cfg.reconnect);
433
+ }
434
+ cfg;
435
+ ws = null;
436
+ backoff;
437
+ closed = false;
438
+ pingTimer = null;
439
+ async connect() {
440
+ if (this.closed) return;
441
+ const WS = await getWebSocketCtor();
442
+ const url = typeof this.cfg.url === "function" ? await this.cfg.url() : this.cfg.url;
443
+ const ws = new WS(url);
444
+ ws.binaryType = "arraybuffer";
445
+ this.ws = ws;
446
+ ws.onopen = async () => {
447
+ this.backoff.reset();
448
+ this.startPing();
449
+ this.emit("open");
450
+ try {
451
+ await this.cfg.onOpen?.({
452
+ send: (d) => ws.send(d),
453
+ close: () => this.close()
454
+ });
455
+ } catch (err) {
456
+ this.emit("error", toError(err, "onOpen handler failed"));
457
+ }
458
+ };
459
+ ws.onmessage = (e) => {
460
+ let result;
461
+ try {
462
+ result = this.cfg.onMessage(e.data);
463
+ } catch (err) {
464
+ this.emit("error", toError(err, "onMessage handler failed"));
465
+ return;
466
+ }
467
+ if (result && typeof result.catch === "function") {
468
+ result.catch(
469
+ (err) => this.emit("error", toError(err, "onMessage handler failed"))
470
+ );
471
+ }
472
+ };
473
+ ws.onerror = (e) => {
474
+ this.emit("error", normalizeWsError(e));
475
+ };
476
+ ws.onclose = (e) => {
477
+ this.stopPing();
478
+ const reason = describeClose(e);
479
+ this.emit("close", reason);
480
+ if (!this.closed) this.scheduleReconnect();
481
+ };
482
+ }
483
+ send(data) {
484
+ this.ws?.send(data);
485
+ }
486
+ close() {
487
+ this.closed = true;
488
+ this.stopPing();
489
+ try {
490
+ this.ws?.close();
491
+ } catch {
492
+ }
493
+ }
494
+ startPing() {
495
+ if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
496
+ this.stopPing();
497
+ this.pingTimer = setInterval(() => {
498
+ try {
499
+ this.ws?.send(this.cfg.pingPayload());
500
+ } catch {
501
+ }
502
+ }, this.cfg.pingIntervalMs);
503
+ }
504
+ stopPing() {
505
+ if (this.pingTimer) {
506
+ clearInterval(this.pingTimer);
507
+ this.pingTimer = null;
508
+ }
509
+ }
510
+ scheduleReconnect() {
511
+ const next = this.backoff.next();
512
+ if (!next) {
513
+ this.emit("error", new Error("max reconnect attempts exceeded"));
514
+ return;
515
+ }
516
+ this.emit("reconnecting", next.attempt, next.wait);
517
+ setTimeout(() => {
518
+ this.connect().catch((e) => this.emit("error", toError(e, "reconnect failed")));
519
+ }, next.wait);
520
+ }
521
+ };
522
+
523
+ // src/exchanges/mexc/ws.ts
524
+ var WS_FUTURES = "wss://contract.mexc.com/edge";
525
+ var PING_INTERVAL_MS = 2e4;
526
+ function streamMexcOrderbook(opts) {
527
+ if (opts.market !== "perpetual") {
528
+ throw new Error(
529
+ `mexc spot streaming requires the protobuf WS feed, which this adapter does not decode \u2014 use fetchOrderbook("${opts.symbol}") for a REST snapshot, or stream the perpetual ("${opts.symbol}:${opts.symbol.split("/")[1]}")`
530
+ );
531
+ }
532
+ const symbol = toMexcSymbol(opts.symbol, opts.market);
533
+ const unified = fromMexcSymbol(symbol, opts.market);
534
+ const contractSize = resolveContractSize(symbol, opts);
535
+ contractSize.catch(() => {
536
+ });
537
+ const merger = new BookMerger();
538
+ let seedVersion = -1;
539
+ let lastVersion = -1;
540
+ let snapshotInFlight = false;
541
+ let snapshotDone = false;
542
+ let buffered = [];
543
+ let recovering = false;
544
+ let scale = 0;
545
+ let ws = null;
546
+ const stream = new OrderbookStream(() => ws?.close());
547
+ const emit = (r) => {
548
+ const book = {
549
+ exchange: "mexc",
550
+ symbol: unified,
551
+ market: opts.market,
552
+ bids: r.bids,
553
+ asks: r.asks,
554
+ timestamp: r.timestamp,
555
+ sequence: r.sequence
556
+ };
557
+ stream.emit("update", book);
558
+ };
559
+ const triggerSnapshot = () => {
560
+ if (snapshotInFlight) return;
561
+ snapshotInFlight = true;
562
+ contractSize.then(async (size) => {
563
+ scale = size;
564
+ return fetchMexcOrderbook({
565
+ symbol: opts.symbol,
566
+ market: opts.market,
567
+ depth: opts.depth ?? 200,
568
+ timeoutMs: opts.timeoutMs,
569
+ transformUrl: opts.transformUrl
570
+ });
571
+ }).then((snap) => {
572
+ seedVersion = snap.sequence;
573
+ const r = merger.apply({
574
+ kind: "snapshot",
575
+ bids: snap.bids,
576
+ asks: snap.asks,
577
+ sequence: snap.sequence,
578
+ timestamp: snap.timestamp
579
+ });
580
+ if (r.ok) emit(r);
581
+ snapshotDone = true;
582
+ lastVersion = -1;
583
+ const pending = buffered;
584
+ buffered = [];
585
+ for (const d of pending) processDelta(d);
586
+ }).catch((err) => stream.emit("error", err)).finally(() => {
587
+ snapshotInFlight = false;
588
+ });
589
+ };
590
+ const resync = () => {
591
+ if (recovering) return;
592
+ recovering = true;
593
+ merger.reset();
594
+ seedVersion = -1;
595
+ snapshotDone = false;
596
+ lastVersion = -1;
597
+ buffered = [];
598
+ setTimeout(() => {
599
+ recovering = false;
600
+ triggerSnapshot();
601
+ }, 100);
602
+ };
603
+ const processDelta = (d) => {
604
+ const end = Number(d.end ?? d.version ?? 0);
605
+ const begin = Number(d.begin ?? end);
606
+ if (end <= seedVersion) return;
607
+ let prevSequence;
608
+ if (lastVersion < 0) {
609
+ if (begin - 1 > seedVersion) {
610
+ resync();
611
+ return;
612
+ }
613
+ prevSequence = seedVersion;
614
+ } else {
615
+ prevSequence = begin - 1;
616
+ }
617
+ const r = merger.apply({
618
+ kind: "delta",
619
+ bids: toFuturesLevels(d.bids, scale),
620
+ asks: toFuturesLevels(d.asks, scale),
621
+ sequence: end,
622
+ prevSequence,
623
+ timestamp: d.timestamp ?? d.cts ?? Date.now()
624
+ });
625
+ if (r.ok) {
626
+ lastVersion = end;
627
+ emit(r);
628
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
629
+ resync();
630
+ }
631
+ };
632
+ const onMessage = (raw) => {
633
+ if (typeof raw !== "string") return;
634
+ let msg;
635
+ try {
636
+ msg = JSON.parse(raw);
637
+ } catch {
638
+ return;
639
+ }
640
+ if (msg.channel === "push.depth") {
641
+ if (msg.symbol && msg.symbol !== symbol) return;
642
+ const d = msg.data;
643
+ if (!d) return;
644
+ if (!snapshotDone) {
645
+ buffered.push(d);
646
+ if (!snapshotInFlight) triggerSnapshot();
647
+ return;
648
+ }
649
+ processDelta(d);
650
+ return;
651
+ }
652
+ if (msg.channel === "rs.error" || msg.channel?.startsWith("rs.error")) {
653
+ stream.emit("error", new ExchangeError("mexc", String(msg.data)));
654
+ return;
655
+ }
656
+ if (msg.channel === "rs.sub.depth" && msg.data !== "success") {
657
+ stream.emit(
658
+ "error",
659
+ new ExchangeError("mexc", `subscribe rejected: ${String(msg.data)}`)
660
+ );
661
+ }
662
+ };
663
+ ws = new WSClient({
664
+ url: WS_FUTURES,
665
+ onOpen: (handle) => {
666
+ merger.reset();
667
+ seedVersion = -1;
668
+ snapshotDone = false;
669
+ lastVersion = -1;
670
+ buffered = [];
671
+ handle.send(
672
+ JSON.stringify({ method: "sub.depth", param: { symbol } })
673
+ );
674
+ },
675
+ onMessage,
676
+ pingIntervalMs: PING_INTERVAL_MS,
677
+ pingPayload: () => JSON.stringify({ method: "ping" })
678
+ });
679
+ ws.on("open", () => stream.emit("connected"));
680
+ ws.on("close", (r) => stream.emit("disconnected", r));
681
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
682
+ ws.on("error", (e) => stream.emit("error", e));
683
+ ws.connect().catch((e) => stream.emit("error", e));
684
+ return stream;
685
+ }
686
+
687
+ // src/exchanges/mexc/index.ts
688
+ var MexcClient = class {
689
+ exchange = "mexc";
690
+ transformUrl;
691
+ timeoutMs;
692
+ constructor(opts = {}) {
693
+ this.transformUrl = opts.transformUrl;
694
+ this.timeoutMs = opts.timeoutMs;
695
+ }
696
+ fetchOrderbook(symbol, opts = {}) {
697
+ const { pair, market } = parseSymbol(symbol);
698
+ return fetchMexcOrderbook({
699
+ symbol: pair,
700
+ market,
701
+ depth: opts.depth,
702
+ timeoutMs: this.timeoutMs,
703
+ transformUrl: this.transformUrl
704
+ });
705
+ }
706
+ /** Perpetuals only — see the class note on spot. */
707
+ streamOrderbook(symbol, opts = {}) {
708
+ const { pair, market } = parseSymbol(symbol);
709
+ return streamMexcOrderbook({
710
+ symbol: pair,
711
+ market,
712
+ depth: opts.depth,
713
+ transformUrl: this.transformUrl,
714
+ timeoutMs: this.timeoutMs
715
+ });
716
+ }
717
+ };
718
+
719
+ export { MEXC_FUTURES_REST, MEXC_SPOT_REST, MexcClient, fetchMexcOrderbook, fromMexcSymbol, streamMexcOrderbook, toMexcSymbol };
720
+ //# sourceMappingURL=index.js.map
721
+ //# sourceMappingURL=index.js.map