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