@xapy/orderbook 0.1.29 → 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 (44) hide show
  1. package/README.md +3 -0
  2. package/dist/exchanges/aster/index.d.cts +1 -1
  3. package/dist/exchanges/aster/index.d.ts +1 -1
  4. package/dist/exchanges/binance/index.d.cts +1 -1
  5. package/dist/exchanges/binance/index.d.ts +1 -1
  6. package/dist/exchanges/bingx/index.d.cts +1 -1
  7. package/dist/exchanges/bingx/index.d.ts +1 -1
  8. package/dist/exchanges/bitget/index.d.cts +1 -1
  9. package/dist/exchanges/bitget/index.d.ts +1 -1
  10. package/dist/exchanges/bybit/index.d.cts +1 -1
  11. package/dist/exchanges/bybit/index.d.ts +1 -1
  12. package/dist/exchanges/coinex/index.d.cts +1 -1
  13. package/dist/exchanges/coinex/index.d.ts +1 -1
  14. package/dist/exchanges/deribit/index.d.cts +1 -1
  15. package/dist/exchanges/deribit/index.d.ts +1 -1
  16. package/dist/exchanges/edgex/index.d.cts +1 -1
  17. package/dist/exchanges/edgex/index.d.ts +1 -1
  18. package/dist/exchanges/gate/index.d.cts +1 -1
  19. package/dist/exchanges/gate/index.d.ts +1 -1
  20. package/dist/exchanges/hyperliquid/index.d.cts +1 -1
  21. package/dist/exchanges/hyperliquid/index.d.ts +1 -1
  22. package/dist/exchanges/kucoin/index.d.cts +1 -1
  23. package/dist/exchanges/kucoin/index.d.ts +1 -1
  24. package/dist/exchanges/lighter/index.d.cts +1 -1
  25. package/dist/exchanges/lighter/index.d.ts +1 -1
  26. package/dist/exchanges/mexc/index.cjs +729 -0
  27. package/dist/exchanges/mexc/index.cjs.map +1 -0
  28. package/dist/exchanges/mexc/index.d.cts +57 -0
  29. package/dist/exchanges/mexc/index.d.ts +57 -0
  30. package/dist/exchanges/mexc/index.js +721 -0
  31. package/dist/exchanges/mexc/index.js.map +1 -0
  32. package/dist/exchanges/okx/index.d.cts +1 -1
  33. package/dist/exchanges/okx/index.d.ts +1 -1
  34. package/dist/exchanges/whitebit/index.d.cts +1 -1
  35. package/dist/exchanges/whitebit/index.d.ts +1 -1
  36. package/dist/index.cjs +325 -0
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +3 -2
  39. package/dist/index.d.ts +3 -2
  40. package/dist/index.js +325 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/{stream-D5-FyNGW.d.cts → stream-Dyq24thx.d.cts} +1 -1
  43. package/dist/{stream-D5-FyNGW.d.ts → stream-Dyq24thx.d.ts} +1 -1
  44. package/package.json +12 -1
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-D5-FyNGW.cjs';
2
- export { C as ClientOptions, E as ExchangeName, a as Orderbook, b as OrderbookOptions, c as OrderbookStream, S as Side, d as StreamEvents } from './stream-D5-FyNGW.cjs';
1
+ import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-Dyq24thx.cjs';
2
+ export { C as ClientOptions, E as ExchangeName, a as Orderbook, b as OrderbookOptions, c as OrderbookStream, S as Side, d as StreamEvents } from './stream-Dyq24thx.cjs';
3
3
  export { BybitClient } from './exchanges/bybit/index.cjs';
4
4
  export { BitgetClient } from './exchanges/bitget/index.cjs';
5
5
  export { GateClient } from './exchanges/gate/index.cjs';
@@ -14,6 +14,7 @@ export { LighterClient } from './exchanges/lighter/index.cjs';
14
14
  export { EdgexClient } from './exchanges/edgex/index.cjs';
15
15
  export { WhitebitClient } from './exchanges/whitebit/index.cjs';
16
16
  export { AsterClient } from './exchanges/aster/index.cjs';
17
+ export { MexcClient } from './exchanges/mexc/index.cjs';
17
18
 
18
19
  declare class ExchangeError extends Error {
19
20
  readonly exchange: string;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-D5-FyNGW.js';
2
- export { C as ClientOptions, E as ExchangeName, a as Orderbook, b as OrderbookOptions, c as OrderbookStream, S as Side, d as StreamEvents } from './stream-D5-FyNGW.js';
1
+ import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-Dyq24thx.js';
2
+ export { C as ClientOptions, E as ExchangeName, a as Orderbook, b as OrderbookOptions, c as OrderbookStream, S as Side, d as StreamEvents } from './stream-Dyq24thx.js';
3
3
  export { BybitClient } from './exchanges/bybit/index.js';
4
4
  export { BitgetClient } from './exchanges/bitget/index.js';
5
5
  export { GateClient } from './exchanges/gate/index.js';
@@ -14,6 +14,7 @@ export { LighterClient } from './exchanges/lighter/index.js';
14
14
  export { EdgexClient } from './exchanges/edgex/index.js';
15
15
  export { WhitebitClient } from './exchanges/whitebit/index.js';
16
16
  export { AsterClient } from './exchanges/aster/index.js';
17
+ export { MexcClient } from './exchanges/mexc/index.js';
17
18
 
18
19
  declare class ExchangeError extends Error {
19
20
  readonly exchange: string;
package/dist/index.js CHANGED
@@ -3653,6 +3653,330 @@ var AsterClient = class {
3653
3653
  }
3654
3654
  };
3655
3655
 
3656
- export { AsterClient, Backoff, BinanceClient, BingxClient, BitgetClient, BookMerger, BybitClient, CoinexClient, DeribitClient, EdgexClient, ExchangeError, GateClient, HyperliquidClient, KucoinClient, LighterClient, OkxClient, OrderbookStream, RateLimitError, SequenceGapError, WhitebitClient, parseSymbol };
3656
+ // src/exchanges/mexc/contracts.ts
3657
+ var MEXC_SPOT_REST = "https://api.mexc.com";
3658
+ var MEXC_FUTURES_REST = "https://contract.mexc.com";
3659
+ var cache2 = null;
3660
+ var inflight2 = null;
3661
+ async function fetchContracts2(opts) {
3662
+ const res = await httpJson({
3663
+ url: `${MEXC_FUTURES_REST}/api/v1/contract/detail`,
3664
+ timeoutMs: opts.timeoutMs,
3665
+ transformUrl: opts.transformUrl
3666
+ });
3667
+ const rows = res.data ?? [];
3668
+ if (rows.length === 0) {
3669
+ throw new ExchangeError(
3670
+ "mexc",
3671
+ res.message ? `${res.code}: ${res.message}` : "empty contract/detail response"
3672
+ );
3673
+ }
3674
+ const map = /* @__PURE__ */ new Map();
3675
+ for (const row of rows) map.set(row.symbol.toUpperCase(), row);
3676
+ return map;
3677
+ }
3678
+ function loadContracts2(opts) {
3679
+ inflight2 ??= fetchContracts2(opts).then(
3680
+ (m) => {
3681
+ cache2 = m;
3682
+ inflight2 = null;
3683
+ return m;
3684
+ },
3685
+ (err) => {
3686
+ inflight2 = null;
3687
+ throw err;
3688
+ }
3689
+ );
3690
+ return inflight2;
3691
+ }
3692
+ async function resolveContractSize(symbol, opts) {
3693
+ const k = symbol.toUpperCase();
3694
+ const hit = cache2?.get(k);
3695
+ const contract = hit ?? (await loadContracts2(opts)).get(k);
3696
+ if (!contract) {
3697
+ throw new ExchangeError(
3698
+ "mexc",
3699
+ `unknown futures contract "${symbol}" \u2014 not listed on mexc`
3700
+ );
3701
+ }
3702
+ const size = Number(contract.contractSize);
3703
+ if (!Number.isFinite(size) || size <= 0) {
3704
+ throw new ExchangeError(
3705
+ "mexc",
3706
+ `contract "${symbol}" has no usable contractSize (${contract.contractSize})`
3707
+ );
3708
+ }
3709
+ return size;
3710
+ }
3711
+
3712
+ // src/exchanges/mexc/symbols.ts
3713
+ var QUOTES6 = ["USDT", "USDC", "TUSD", "USD", "BTC", "ETH"];
3714
+ function toMexcSymbol(symbol, market) {
3715
+ const [base, quote] = symbol.split("/");
3716
+ if (!base || !quote) {
3717
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
3718
+ }
3719
+ return market === "perpetual" ? `${base.toUpperCase()}_${quote.toUpperCase()}` : `${base}${quote}`.toUpperCase();
3720
+ }
3721
+ function fromMexcSymbol(s, market) {
3722
+ const upper = s.toUpperCase();
3723
+ if (market === "perpetual") {
3724
+ const [base, quote] = upper.split("_");
3725
+ return base && quote ? `${base}/${quote}` : upper;
3726
+ }
3727
+ for (const q of QUOTES6) {
3728
+ if (upper.endsWith(q) && upper.length > q.length) {
3729
+ return `${upper.slice(0, -q.length)}/${q}`;
3730
+ }
3731
+ }
3732
+ return upper;
3733
+ }
3734
+
3735
+ // src/exchanges/mexc/rest.ts
3736
+ var toSpotLevels = (rows) => (rows ?? []).map(([p, s]) => ({ price: Number(p), size: Number(s) }));
3737
+ var toFuturesLevels = (rows, contractSize) => (rows ?? []).map(([price, vol]) => ({
3738
+ price: Number(price),
3739
+ size: Number(vol) * contractSize
3740
+ }));
3741
+ async function fetchMexcOrderbook(opts) {
3742
+ const symbol = toMexcSymbol(opts.symbol, opts.market);
3743
+ const depth = opts.depth ?? 50;
3744
+ if (opts.market === "spot") {
3745
+ const data = await httpJson({
3746
+ url: `${MEXC_SPOT_REST}/api/v3/depth?symbol=${symbol}&limit=${depth}`,
3747
+ timeoutMs: opts.timeoutMs,
3748
+ transformUrl: opts.transformUrl
3749
+ });
3750
+ return {
3751
+ exchange: "mexc",
3752
+ symbol: fromMexcSymbol(symbol, opts.market),
3753
+ market: opts.market,
3754
+ bids: toSpotLevels(data.bids),
3755
+ asks: toSpotLevels(data.asks),
3756
+ // The spot depth endpoint returns no timestamp of its own.
3757
+ timestamp: Date.now(),
3758
+ sequence: data.lastUpdateId
3759
+ };
3760
+ }
3761
+ const contractSize = await resolveContractSize(symbol, opts);
3762
+ const res = await httpJson({
3763
+ url: `${MEXC_FUTURES_REST}/api/v1/contract/depth/${symbol}?limit=${depth}`,
3764
+ timeoutMs: opts.timeoutMs,
3765
+ transformUrl: opts.transformUrl
3766
+ });
3767
+ if (!res.data) {
3768
+ throw new ExchangeError(
3769
+ "mexc",
3770
+ res.message ? `${res.code}: ${res.message}` : "empty orderbook response"
3771
+ );
3772
+ }
3773
+ return {
3774
+ exchange: "mexc",
3775
+ symbol: fromMexcSymbol(symbol, opts.market),
3776
+ market: opts.market,
3777
+ bids: toFuturesLevels(res.data.bids, contractSize),
3778
+ asks: toFuturesLevels(res.data.asks, contractSize),
3779
+ timestamp: res.data.timestamp ?? Date.now(),
3780
+ sequence: Number(res.data.version ?? 0)
3781
+ };
3782
+ }
3783
+
3784
+ // src/exchanges/mexc/ws.ts
3785
+ var WS_FUTURES5 = "wss://contract.mexc.com/edge";
3786
+ var PING_INTERVAL_MS3 = 2e4;
3787
+ function streamMexcOrderbook(opts) {
3788
+ if (opts.market !== "perpetual") {
3789
+ throw new Error(
3790
+ `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]}")`
3791
+ );
3792
+ }
3793
+ const symbol = toMexcSymbol(opts.symbol, opts.market);
3794
+ const unified = fromMexcSymbol(symbol, opts.market);
3795
+ const contractSize = resolveContractSize(symbol, opts);
3796
+ contractSize.catch(() => {
3797
+ });
3798
+ const merger = new BookMerger();
3799
+ let seedVersion = -1;
3800
+ let lastVersion = -1;
3801
+ let snapshotInFlight = false;
3802
+ let snapshotDone = false;
3803
+ let buffered = [];
3804
+ let recovering = false;
3805
+ let scale = 0;
3806
+ let ws = null;
3807
+ const stream = new OrderbookStream(() => ws?.close());
3808
+ const emit = (r) => {
3809
+ const book = {
3810
+ exchange: "mexc",
3811
+ symbol: unified,
3812
+ market: opts.market,
3813
+ bids: r.bids,
3814
+ asks: r.asks,
3815
+ timestamp: r.timestamp,
3816
+ sequence: r.sequence
3817
+ };
3818
+ stream.emit("update", book);
3819
+ };
3820
+ const triggerSnapshot = () => {
3821
+ if (snapshotInFlight) return;
3822
+ snapshotInFlight = true;
3823
+ contractSize.then(async (size) => {
3824
+ scale = size;
3825
+ return fetchMexcOrderbook({
3826
+ symbol: opts.symbol,
3827
+ market: opts.market,
3828
+ depth: opts.depth ?? 200,
3829
+ timeoutMs: opts.timeoutMs,
3830
+ transformUrl: opts.transformUrl
3831
+ });
3832
+ }).then((snap) => {
3833
+ seedVersion = snap.sequence;
3834
+ const r = merger.apply({
3835
+ kind: "snapshot",
3836
+ bids: snap.bids,
3837
+ asks: snap.asks,
3838
+ sequence: snap.sequence,
3839
+ timestamp: snap.timestamp
3840
+ });
3841
+ if (r.ok) emit(r);
3842
+ snapshotDone = true;
3843
+ lastVersion = -1;
3844
+ const pending2 = buffered;
3845
+ buffered = [];
3846
+ for (const d of pending2) processDelta(d);
3847
+ }).catch((err) => stream.emit("error", err)).finally(() => {
3848
+ snapshotInFlight = false;
3849
+ });
3850
+ };
3851
+ const resync = () => {
3852
+ if (recovering) return;
3853
+ recovering = true;
3854
+ merger.reset();
3855
+ seedVersion = -1;
3856
+ snapshotDone = false;
3857
+ lastVersion = -1;
3858
+ buffered = [];
3859
+ setTimeout(() => {
3860
+ recovering = false;
3861
+ triggerSnapshot();
3862
+ }, 100);
3863
+ };
3864
+ const processDelta = (d) => {
3865
+ const end = Number(d.end ?? d.version ?? 0);
3866
+ const begin = Number(d.begin ?? end);
3867
+ if (end <= seedVersion) return;
3868
+ let prevSequence;
3869
+ if (lastVersion < 0) {
3870
+ if (begin - 1 > seedVersion) {
3871
+ resync();
3872
+ return;
3873
+ }
3874
+ prevSequence = seedVersion;
3875
+ } else {
3876
+ prevSequence = begin - 1;
3877
+ }
3878
+ const r = merger.apply({
3879
+ kind: "delta",
3880
+ bids: toFuturesLevels(d.bids, scale),
3881
+ asks: toFuturesLevels(d.asks, scale),
3882
+ sequence: end,
3883
+ prevSequence,
3884
+ timestamp: d.timestamp ?? d.cts ?? Date.now()
3885
+ });
3886
+ if (r.ok) {
3887
+ lastVersion = end;
3888
+ emit(r);
3889
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
3890
+ resync();
3891
+ }
3892
+ };
3893
+ const onMessage = (raw) => {
3894
+ if (typeof raw !== "string") return;
3895
+ let msg;
3896
+ try {
3897
+ msg = JSON.parse(raw);
3898
+ } catch {
3899
+ return;
3900
+ }
3901
+ if (msg.channel === "push.depth") {
3902
+ if (msg.symbol && msg.symbol !== symbol) return;
3903
+ const d = msg.data;
3904
+ if (!d) return;
3905
+ if (!snapshotDone) {
3906
+ buffered.push(d);
3907
+ if (!snapshotInFlight) triggerSnapshot();
3908
+ return;
3909
+ }
3910
+ processDelta(d);
3911
+ return;
3912
+ }
3913
+ if (msg.channel === "rs.error" || msg.channel?.startsWith("rs.error")) {
3914
+ stream.emit("error", new ExchangeError("mexc", String(msg.data)));
3915
+ return;
3916
+ }
3917
+ if (msg.channel === "rs.sub.depth" && msg.data !== "success") {
3918
+ stream.emit(
3919
+ "error",
3920
+ new ExchangeError("mexc", `subscribe rejected: ${String(msg.data)}`)
3921
+ );
3922
+ }
3923
+ };
3924
+ ws = new WSClient({
3925
+ url: WS_FUTURES5,
3926
+ onOpen: (handle) => {
3927
+ merger.reset();
3928
+ seedVersion = -1;
3929
+ snapshotDone = false;
3930
+ lastVersion = -1;
3931
+ buffered = [];
3932
+ handle.send(
3933
+ JSON.stringify({ method: "sub.depth", param: { symbol } })
3934
+ );
3935
+ },
3936
+ onMessage,
3937
+ pingIntervalMs: PING_INTERVAL_MS3,
3938
+ pingPayload: () => JSON.stringify({ method: "ping" })
3939
+ });
3940
+ ws.on("open", () => stream.emit("connected"));
3941
+ ws.on("close", (r) => stream.emit("disconnected", r));
3942
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
3943
+ ws.on("error", (e) => stream.emit("error", e));
3944
+ ws.connect().catch((e) => stream.emit("error", e));
3945
+ return stream;
3946
+ }
3947
+
3948
+ // src/exchanges/mexc/index.ts
3949
+ var MexcClient = class {
3950
+ exchange = "mexc";
3951
+ transformUrl;
3952
+ timeoutMs;
3953
+ constructor(opts = {}) {
3954
+ this.transformUrl = opts.transformUrl;
3955
+ this.timeoutMs = opts.timeoutMs;
3956
+ }
3957
+ fetchOrderbook(symbol, opts = {}) {
3958
+ const { pair, market } = parseSymbol(symbol);
3959
+ return fetchMexcOrderbook({
3960
+ symbol: pair,
3961
+ market,
3962
+ depth: opts.depth,
3963
+ timeoutMs: this.timeoutMs,
3964
+ transformUrl: this.transformUrl
3965
+ });
3966
+ }
3967
+ /** Perpetuals only — see the class note on spot. */
3968
+ streamOrderbook(symbol, opts = {}) {
3969
+ const { pair, market } = parseSymbol(symbol);
3970
+ return streamMexcOrderbook({
3971
+ symbol: pair,
3972
+ market,
3973
+ depth: opts.depth,
3974
+ transformUrl: this.transformUrl,
3975
+ timeoutMs: this.timeoutMs
3976
+ });
3977
+ }
3978
+ };
3979
+
3980
+ export { AsterClient, Backoff, BinanceClient, BingxClient, BitgetClient, BookMerger, BybitClient, CoinexClient, DeribitClient, EdgexClient, ExchangeError, GateClient, HyperliquidClient, KucoinClient, LighterClient, MexcClient, OkxClient, OrderbookStream, RateLimitError, SequenceGapError, WhitebitClient, parseSymbol };
3657
3981
  //# sourceMappingURL=index.js.map
3658
3982
  //# sourceMappingURL=index.js.map