@xapy/orderbook 0.1.22 → 0.1.24

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 (86) hide show
  1. package/README.md +15 -9
  2. package/dist/exchanges/binance/index.cjs +21 -6
  3. package/dist/exchanges/binance/index.cjs.map +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/binance/index.js +21 -6
  7. package/dist/exchanges/binance/index.js.map +1 -1
  8. package/dist/exchanges/bingx/index.cjs +38 -11
  9. package/dist/exchanges/bingx/index.cjs.map +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/bingx/index.js +38 -11
  13. package/dist/exchanges/bingx/index.js.map +1 -1
  14. package/dist/exchanges/bitget/index.cjs +21 -6
  15. package/dist/exchanges/bitget/index.cjs.map +1 -1
  16. package/dist/exchanges/bitget/index.d.cts +1 -1
  17. package/dist/exchanges/bitget/index.d.ts +1 -1
  18. package/dist/exchanges/bitget/index.js +21 -6
  19. package/dist/exchanges/bitget/index.js.map +1 -1
  20. package/dist/exchanges/bybit/index.cjs +21 -6
  21. package/dist/exchanges/bybit/index.cjs.map +1 -1
  22. package/dist/exchanges/bybit/index.d.cts +1 -1
  23. package/dist/exchanges/bybit/index.d.ts +1 -1
  24. package/dist/exchanges/bybit/index.js +21 -6
  25. package/dist/exchanges/bybit/index.js.map +1 -1
  26. package/dist/exchanges/coinex/index.cjs +21 -6
  27. package/dist/exchanges/coinex/index.cjs.map +1 -1
  28. package/dist/exchanges/coinex/index.d.cts +1 -1
  29. package/dist/exchanges/coinex/index.d.ts +1 -1
  30. package/dist/exchanges/coinex/index.js +21 -6
  31. package/dist/exchanges/coinex/index.js.map +1 -1
  32. package/dist/exchanges/deribit/index.cjs +625 -0
  33. package/dist/exchanges/deribit/index.cjs.map +1 -0
  34. package/dist/exchanges/deribit/index.d.cts +48 -0
  35. package/dist/exchanges/deribit/index.d.ts +48 -0
  36. package/dist/exchanges/deribit/index.js +621 -0
  37. package/dist/exchanges/deribit/index.js.map +1 -0
  38. package/dist/exchanges/gate/index.cjs +21 -6
  39. package/dist/exchanges/gate/index.cjs.map +1 -1
  40. package/dist/exchanges/gate/index.d.cts +1 -1
  41. package/dist/exchanges/gate/index.d.ts +1 -1
  42. package/dist/exchanges/gate/index.js +21 -6
  43. package/dist/exchanges/gate/index.js.map +1 -1
  44. package/dist/exchanges/{bitmart → grvt}/index.cjs +175 -147
  45. package/dist/exchanges/grvt/index.cjs.map +1 -0
  46. package/dist/exchanges/grvt/index.d.cts +47 -0
  47. package/dist/exchanges/grvt/index.d.ts +47 -0
  48. package/dist/exchanges/{bitmart → grvt}/index.js +173 -145
  49. package/dist/exchanges/grvt/index.js.map +1 -0
  50. package/dist/exchanges/huobi/index.cjs +21 -6
  51. package/dist/exchanges/huobi/index.cjs.map +1 -1
  52. package/dist/exchanges/huobi/index.d.cts +1 -1
  53. package/dist/exchanges/huobi/index.d.ts +1 -1
  54. package/dist/exchanges/huobi/index.js +21 -6
  55. package/dist/exchanges/huobi/index.js.map +1 -1
  56. package/dist/exchanges/hyperliquid/index.cjs +21 -6
  57. package/dist/exchanges/hyperliquid/index.cjs.map +1 -1
  58. package/dist/exchanges/hyperliquid/index.d.cts +1 -1
  59. package/dist/exchanges/hyperliquid/index.d.ts +1 -1
  60. package/dist/exchanges/hyperliquid/index.js +21 -6
  61. package/dist/exchanges/hyperliquid/index.js.map +1 -1
  62. package/dist/exchanges/kucoin/index.cjs +21 -6
  63. package/dist/exchanges/kucoin/index.cjs.map +1 -1
  64. package/dist/exchanges/kucoin/index.d.cts +1 -1
  65. package/dist/exchanges/kucoin/index.d.ts +1 -1
  66. package/dist/exchanges/kucoin/index.js +21 -6
  67. package/dist/exchanges/kucoin/index.js.map +1 -1
  68. package/dist/exchanges/okx/index.cjs +21 -6
  69. package/dist/exchanges/okx/index.cjs.map +1 -1
  70. package/dist/exchanges/okx/index.d.cts +1 -1
  71. package/dist/exchanges/okx/index.d.ts +1 -1
  72. package/dist/exchanges/okx/index.js +21 -6
  73. package/dist/exchanges/okx/index.js.map +1 -1
  74. package/dist/index.cjs +409 -115
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.d.cts +4 -3
  77. package/dist/index.d.ts +4 -3
  78. package/dist/index.js +408 -115
  79. package/dist/index.js.map +1 -1
  80. package/dist/{stream-L9MJjYbE.d.cts → stream-Con47OAp.d.cts} +1 -1
  81. package/dist/{stream-L9MJjYbE.d.ts → stream-Con47OAp.d.ts} +1 -1
  82. package/package.json +18 -6
  83. package/dist/exchanges/bitmart/index.cjs.map +0 -1
  84. package/dist/exchanges/bitmart/index.d.cts +0 -68
  85. package/dist/exchanges/bitmart/index.d.ts +0 -68
  86. package/dist/exchanges/bitmart/index.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -325,6 +325,21 @@ async function fetchBybitOrderbook(opts) {
325
325
  var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
326
326
 
327
327
  // src/transport/ws.ts
328
+ function toError(value, fallback = "unknown error") {
329
+ if (value instanceof Error) {
330
+ return value.message ? value : new Error(`${value.name}: ${fallback}`);
331
+ }
332
+ if (typeof value === "string" && value) return new Error(value);
333
+ return new Error(fallback);
334
+ }
335
+ function normalizeWsError(ev) {
336
+ const detail = ev?.message || (ev?.error instanceof Error ? ev.error.message : void 0) || (typeof ev?.error === "string" ? ev.error : void 0);
337
+ return new Error(detail ? `WebSocket error: ${detail}` : "WebSocket error");
338
+ }
339
+ function describeClose(ev) {
340
+ if (ev?.reason) return ev.reason;
341
+ return ev?.code === void 0 ? "closed" : `closed (code ${ev.code})`;
342
+ }
328
343
  var cachedCtor = null;
329
344
  async function getWebSocketCtor() {
330
345
  if (cachedCtor) return cachedCtor;
@@ -372,7 +387,7 @@ var WSClient = class extends TypedEmitter {
372
387
  close: () => this.close()
373
388
  });
374
389
  } catch (err) {
375
- this.emit("error", err);
390
+ this.emit("error", toError(err, "onOpen handler failed"));
376
391
  }
377
392
  };
378
393
  ws.onmessage = (e) => {
@@ -380,21 +395,21 @@ var WSClient = class extends TypedEmitter {
380
395
  try {
381
396
  result = this.cfg.onMessage(e.data);
382
397
  } catch (err) {
383
- this.emit("error", err);
398
+ this.emit("error", toError(err, "onMessage handler failed"));
384
399
  return;
385
400
  }
386
401
  if (result && typeof result.catch === "function") {
387
402
  result.catch(
388
- (err) => this.emit("error", err)
403
+ (err) => this.emit("error", toError(err, "onMessage handler failed"))
389
404
  );
390
405
  }
391
406
  };
392
407
  ws.onerror = (e) => {
393
- this.emit("error", new Error(e?.message ?? "WebSocket error"));
408
+ this.emit("error", normalizeWsError(e));
394
409
  };
395
410
  ws.onclose = (e) => {
396
411
  this.stopPing();
397
- const reason = e?.reason ?? "closed";
412
+ const reason = describeClose(e);
398
413
  this.emit("close", reason);
399
414
  if (!this.closed) this.scheduleReconnect();
400
415
  };
@@ -434,7 +449,7 @@ var WSClient = class extends TypedEmitter {
434
449
  }
435
450
  this.emit("reconnecting", next.attempt, next.wait);
436
451
  setTimeout(() => {
437
- this.connect().catch((e) => this.emit("error", e));
452
+ this.connect().catch((e) => this.emit("error", toError(e, "reconnect failed")));
438
453
  }, next.wait);
439
454
  }
440
455
  };
@@ -1234,7 +1249,7 @@ function streamBingxOrderbook(opts) {
1234
1249
  const wsSymbol = opts.symbol.toUpperCase().replace("/", "-");
1235
1250
  const level = opts.depth ?? 20;
1236
1251
  const interval = opts.interval ?? "500ms";
1237
- const depthDataType = `${wsSymbol}@depth${level}@${interval}`;
1252
+ const depthDataType = isSpot ? `${wsSymbol}@depth${level}` : `${wsSymbol}@depth${level}@${interval}`;
1238
1253
  const tickerDataType = `${wsSymbol}@bookTicker`;
1239
1254
  const merger = new BookMerger();
1240
1255
  let ws = null;
@@ -1277,8 +1292,8 @@ function streamBingxOrderbook(opts) {
1277
1292
  };
1278
1293
  stream.emit("update", book);
1279
1294
  };
1280
- const handleDepth = (d) => {
1281
- const ts = d.T ?? d.ts ?? Date.now();
1295
+ const handleDepth = (d, frameTs) => {
1296
+ const ts = d.T ?? d.ts ?? frameTs ?? Date.now();
1282
1297
  const event = {
1283
1298
  kind: "snapshot",
1284
1299
  bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
@@ -1320,10 +1335,22 @@ function streamBingxOrderbook(opts) {
1320
1335
  } catch {
1321
1336
  return;
1322
1337
  }
1323
- if (msg.id && !msg.data) return;
1338
+ if (msg.id && !msg.data) {
1339
+ if (msg.code) {
1340
+ stream.emit(
1341
+ "error",
1342
+ new ExchangeError(
1343
+ "bingx",
1344
+ `subscribe failed (${msg.id}): ${msg.code}${msg.msg ? ` ${msg.msg}` : ""}`
1345
+ )
1346
+ );
1347
+ }
1348
+ return;
1349
+ }
1324
1350
  if (!msg.dataType || !msg.data) return;
1351
+ const frameTs = msg.ts ?? msg.timestamp;
1325
1352
  if (msg.dataType === depthDataType) {
1326
- handleDepth(msg.data);
1353
+ handleDepth(msg.data, frameTs);
1327
1354
  } else if (msg.dataType === tickerDataType) {
1328
1355
  handleTicker(msg.data);
1329
1356
  }
@@ -2622,98 +2649,323 @@ var KucoinClient = class {
2622
2649
  }
2623
2650
  };
2624
2651
 
2625
- // src/exchanges/bitmart/symbols.ts
2626
- var QUOTES6 = ["USDT", "USDC", "USD"];
2627
- function toBitmartSymbol(symbol) {
2652
+ // src/exchanges/deribit/symbols.ts
2653
+ function toDeribitSymbol(symbol, market) {
2628
2654
  const [base, quote] = symbol.split("/");
2629
2655
  if (!base || !quote) {
2630
2656
  throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
2631
2657
  }
2632
- return `${base}${quote}`.toUpperCase();
2633
- }
2634
- function fromBitmartSymbol(s) {
2635
- const upper = s.toUpperCase();
2636
- for (const q of QUOTES6) {
2637
- if (upper.endsWith(q) && upper.length > q.length) {
2638
- return `${upper.slice(0, -q.length)}/${q}`;
2639
- }
2658
+ const pair = `${base}_${quote}`.toUpperCase();
2659
+ if (market !== "perpetual") return pair;
2660
+ if (quote.toUpperCase() !== "USDC") {
2661
+ throw new Error(
2662
+ `deribit linear perpetuals are USDC-margined; got "${quote}" (inverse contracts like BTC-PERPETUAL are unsupported)`
2663
+ );
2640
2664
  }
2641
- return upper;
2665
+ return `${pair}-PERPETUAL`;
2666
+ }
2667
+ function fromDeribitSymbol(instrument) {
2668
+ let s = instrument.toUpperCase();
2669
+ if (s.endsWith("-PERPETUAL")) s = s.slice(0, -"-PERPETUAL".length);
2670
+ const [base, quote] = s.split("_");
2671
+ return base && quote ? `${base}/${quote}` : s;
2642
2672
  }
2643
2673
 
2644
- // src/exchanges/bitmart/rest.ts
2645
- var BASE8 = "https://api-cloud-v2.bitmart.com";
2646
- async function fetchBitmartOrderbook(opts) {
2647
- if (opts.market !== "perpetual") {
2648
- throw new ExchangeError(
2649
- "bitmart",
2650
- "spot is not supported \u2014 only USDT-M perpetual"
2651
- );
2652
- }
2653
- const symbol = toBitmartSymbol(opts.symbol);
2654
- const url = `${BASE8}/contract/public/depth?symbol=${symbol}`;
2674
+ // src/exchanges/deribit/rest.ts
2675
+ var BASE8 = "https://www.deribit.com";
2676
+ var ALLOWED_DEPTHS = [1, 5, 10, 20, 50, 100, 1e3, 1e4];
2677
+ function clampDepth(depth) {
2678
+ return ALLOWED_DEPTHS.find((d) => d >= depth) ?? ALLOWED_DEPTHS[ALLOWED_DEPTHS.length - 1];
2679
+ }
2680
+ async function fetchDeribitOrderbook(opts) {
2681
+ const instrument = toDeribitSymbol(opts.symbol, opts.market);
2682
+ const depth = clampDepth(opts.depth ?? 50);
2683
+ const url = `${BASE8}/api/v2/public/get_order_book?instrument_name=${instrument}&depth=${depth}`;
2655
2684
  const res = await httpJson({
2656
2685
  url,
2657
2686
  timeoutMs: opts.timeoutMs,
2658
2687
  transformUrl: opts.transformUrl
2659
2688
  });
2660
- if (res.code !== 1e3) {
2661
- throw new ExchangeError("bitmart", `${res.code}: ${res.message ?? ""}`);
2689
+ if (res.error) {
2690
+ throw new ExchangeError(
2691
+ "deribit",
2692
+ `${res.error.code}: ${res.error.message}`
2693
+ );
2662
2694
  }
2695
+ const r = res.result;
2696
+ if (!r) throw new ExchangeError("deribit", "empty orderbook response");
2663
2697
  return {
2664
- exchange: "bitmart",
2665
- symbol: fromBitmartSymbol(res.data.symbol),
2666
- market: "perpetual",
2667
- bids: parseLevels2(res.data.bids),
2668
- asks: parseLevels2(res.data.asks),
2669
- timestamp: res.data.timestamp,
2670
- sequence: res.data.timestamp
2698
+ exchange: "deribit",
2699
+ symbol: fromDeribitSymbol(r.instrument_name ?? instrument),
2700
+ market: opts.market,
2701
+ bids: r.bids.map(([price, size]) => ({ price, size })),
2702
+ asks: r.asks.map(([price, size]) => ({ price, size })),
2703
+ timestamp: r.timestamp,
2704
+ sequence: r.change_id
2671
2705
  };
2672
2706
  }
2673
- function parseLevels2(rows) {
2674
- const out = [];
2675
- for (const row of rows) {
2676
- out.push({ price: Number(row[0]), size: Number(row[1]) });
2707
+
2708
+ // src/exchanges/deribit/ws.ts
2709
+ var WS_PUBLIC3 = "wss://www.deribit.com/ws/api/v2";
2710
+ var HEARTBEAT_SECONDS = 30;
2711
+ function streamDeribitOrderbook(opts) {
2712
+ const instrument = toDeribitSymbol(opts.symbol, opts.market);
2713
+ const channel = `book.${instrument}.${opts.interval ?? "100ms"}`;
2714
+ const merger = new BookMerger();
2715
+ let ws = null;
2716
+ let sock = null;
2717
+ let recovering = false;
2718
+ const stream = new OrderbookStream(() => ws?.close());
2719
+ let nextId = 1;
2720
+ const subscribeIds = /* @__PURE__ */ new Set();
2721
+ const rpc = (method, params) => {
2722
+ const id = nextId++;
2723
+ sock?.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
2724
+ return id;
2725
+ };
2726
+ const subscribe = () => {
2727
+ subscribeIds.add(rpc("public/subscribe", { channels: [channel] }));
2728
+ };
2729
+ const emit = (r) => {
2730
+ const book = {
2731
+ exchange: "deribit",
2732
+ symbol: fromDeribitSymbol(instrument),
2733
+ market: opts.market,
2734
+ bids: r.bids,
2735
+ asks: r.asks,
2736
+ timestamp: r.timestamp,
2737
+ sequence: r.sequence
2738
+ };
2739
+ stream.emit("update", book);
2740
+ };
2741
+ const resync = () => {
2742
+ if (recovering) return;
2743
+ recovering = true;
2744
+ merger.reset();
2745
+ rpc("public/unsubscribe", { channels: [channel] });
2746
+ subscribe();
2747
+ };
2748
+ const toLevels2 = (entries) => entries.map(([action, price, amount]) => ({
2749
+ price,
2750
+ size: action === "delete" ? 0 : amount
2751
+ }));
2752
+ const buildEvent2 = (d) => {
2753
+ const bids = toLevels2(d.bids);
2754
+ const asks = toLevels2(d.asks);
2755
+ if (d.type === "snapshot") {
2756
+ return {
2757
+ kind: "snapshot",
2758
+ bids,
2759
+ asks,
2760
+ sequence: d.change_id,
2761
+ timestamp: d.timestamp
2762
+ };
2763
+ }
2764
+ return {
2765
+ kind: "delta",
2766
+ bids,
2767
+ asks,
2768
+ sequence: d.change_id,
2769
+ prevSequence: d.prev_change_id,
2770
+ timestamp: d.timestamp
2771
+ };
2772
+ };
2773
+ const handleData = (d) => {
2774
+ if (d.type === "snapshot") recovering = false;
2775
+ else if (recovering) return;
2776
+ const r = merger.apply(buildEvent2(d));
2777
+ if (r.ok) {
2778
+ emit(r);
2779
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
2780
+ resync();
2781
+ }
2782
+ };
2783
+ const onMessage = (raw) => {
2784
+ if (typeof raw !== "string") return;
2785
+ let msg;
2786
+ try {
2787
+ msg = JSON.parse(raw);
2788
+ } catch {
2789
+ return;
2790
+ }
2791
+ if (msg.method === "heartbeat") {
2792
+ if (msg.params?.type === "test_request") rpc("public/test", {});
2793
+ return;
2794
+ }
2795
+ if (msg.method === "subscription") {
2796
+ if (msg.params?.channel !== channel || !msg.params.data) return;
2797
+ handleData(msg.params.data);
2798
+ return;
2799
+ }
2800
+ if (msg.id !== void 0) {
2801
+ if (msg.error) {
2802
+ stream.emit(
2803
+ "error",
2804
+ new ExchangeError(
2805
+ "deribit",
2806
+ `${msg.error.code}: ${msg.error.message}`
2807
+ )
2808
+ );
2809
+ return;
2810
+ }
2811
+ if (subscribeIds.delete(msg.id)) {
2812
+ const channels = Array.isArray(msg.result) ? msg.result : [];
2813
+ if (!channels.includes(channel)) {
2814
+ stream.emit(
2815
+ "error",
2816
+ new ExchangeError(
2817
+ "deribit",
2818
+ `subscribe rejected for "${channel}" \u2014 unknown instrument or interval`
2819
+ )
2820
+ );
2821
+ }
2822
+ }
2823
+ }
2824
+ };
2825
+ ws = new WSClient({
2826
+ url: WS_PUBLIC3,
2827
+ onOpen: (handle) => {
2828
+ sock = handle;
2829
+ merger.reset();
2830
+ recovering = false;
2831
+ subscribeIds.clear();
2832
+ rpc("public/set_heartbeat", { interval: HEARTBEAT_SECONDS });
2833
+ subscribe();
2834
+ },
2835
+ onMessage
2836
+ });
2837
+ ws.on("open", () => stream.emit("connected"));
2838
+ ws.on("close", (r) => stream.emit("disconnected", r));
2839
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
2840
+ ws.on("error", (e) => stream.emit("error", e));
2841
+ ws.connect().catch((e) => stream.emit("error", e));
2842
+ return stream;
2843
+ }
2844
+
2845
+ // src/exchanges/deribit/index.ts
2846
+ var DeribitClient = class {
2847
+ exchange = "deribit";
2848
+ transformUrl;
2849
+ timeoutMs;
2850
+ constructor(opts = {}) {
2851
+ this.transformUrl = opts.transformUrl;
2852
+ this.timeoutMs = opts.timeoutMs;
2677
2853
  }
2678
- return out;
2854
+ fetchOrderbook(symbol, opts = {}) {
2855
+ const { pair, market } = parseSymbol(symbol);
2856
+ return fetchDeribitOrderbook({
2857
+ symbol: pair,
2858
+ market,
2859
+ depth: opts.depth,
2860
+ timeoutMs: this.timeoutMs,
2861
+ transformUrl: this.transformUrl
2862
+ });
2863
+ }
2864
+ streamOrderbook(symbol, opts = {}) {
2865
+ const { pair, market } = parseSymbol(symbol);
2866
+ return streamDeribitOrderbook({
2867
+ symbol: pair,
2868
+ market,
2869
+ depth: opts.depth,
2870
+ transformUrl: this.transformUrl,
2871
+ timeoutMs: this.timeoutMs
2872
+ });
2873
+ }
2874
+ };
2875
+
2876
+ // src/exchanges/grvt/symbols.ts
2877
+ function toGrvtSymbol(symbol, market) {
2878
+ const [base, quote] = symbol.split("/");
2879
+ if (!base || !quote) {
2880
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
2881
+ }
2882
+ if (market !== "perpetual") {
2883
+ throw new Error(
2884
+ `grvt only lists perpetuals; use "${base.toUpperCase()}/${quote.toUpperCase()}:${quote.toUpperCase()}"`
2885
+ );
2886
+ }
2887
+ return `${base.toUpperCase()}_${quote.toUpperCase()}_Perp`;
2888
+ }
2889
+ function fromGrvtSymbol(instrument) {
2890
+ const parts = instrument.split("_");
2891
+ const [base, quote] = parts;
2892
+ return base && quote ? `${base.toUpperCase()}/${quote.toUpperCase()}` : instrument;
2679
2893
  }
2680
2894
 
2681
- // src/exchanges/bitmart/ws.ts
2682
- var WS_FUTURES4 = "wss://openapi-ws-v2.bitmart.com/api?protocol=1.1";
2683
- function streamBitmartOrderbook(opts) {
2684
- if (opts.market !== "perpetual") {
2895
+ // src/exchanges/grvt/rest.ts
2896
+ var BASE9 = "https://market-data.grvt.io";
2897
+ var ALLOWED_DEPTHS2 = [10, 50, 100, 500];
2898
+ function snapDepth(depth) {
2899
+ return ALLOWED_DEPTHS2.find((d) => d >= depth) ?? ALLOWED_DEPTHS2[ALLOWED_DEPTHS2.length - 1];
2900
+ }
2901
+ function nsToMs(ns) {
2902
+ const n = Number(ns);
2903
+ return Number.isFinite(n) && n > 0 ? Math.floor(n / 1e6) : Date.now();
2904
+ }
2905
+ var toLevels = (rows) => (rows ?? []).map((l) => ({ price: Number(l.price), size: Number(l.size) }));
2906
+ async function fetchGrvtOrderbook(opts) {
2907
+ const instrument = toGrvtSymbol(opts.symbol, opts.market);
2908
+ const depth = snapDepth(opts.depth ?? 50);
2909
+ const res = await httpJson({
2910
+ url: `${BASE9}/full/v1/book`,
2911
+ method: "POST",
2912
+ headers: { "Content-Type": "application/json" },
2913
+ body: JSON.stringify({ instrument, depth }),
2914
+ timeoutMs: opts.timeoutMs,
2915
+ transformUrl: opts.transformUrl
2916
+ });
2917
+ if (!res.result) {
2685
2918
  throw new ExchangeError(
2686
- "bitmart",
2687
- "spot is not supported \u2014 only USDT-M perpetual"
2919
+ "grvt",
2920
+ res.code ? `${res.code}: ${res.message}` : "empty orderbook response"
2688
2921
  );
2689
2922
  }
2690
- const symbol = toBitmartSymbol(opts.symbol);
2691
- const level = snapLevel(opts.depth);
2692
- const interval = opts.interval ?? "200ms";
2693
- const channelArg = `futures/depthAll${level}:${symbol}@${interval}`;
2923
+ const ts = nsToMs(res.result.event_time);
2924
+ return {
2925
+ exchange: "grvt",
2926
+ symbol: fromGrvtSymbol(res.result.instrument ?? instrument),
2927
+ market: opts.market,
2928
+ bids: toLevels(res.result.bids),
2929
+ asks: toLevels(res.result.asks),
2930
+ timestamp: ts,
2931
+ sequence: ts
2932
+ };
2933
+ }
2934
+
2935
+ // src/exchanges/grvt/ws.ts
2936
+ var WS_FULL = "wss://market-data.grvt.io/ws/full";
2937
+ var STREAM = "v1.book.d";
2938
+ function streamGrvtOrderbook(opts) {
2939
+ const instrument = toGrvtSymbol(opts.symbol, opts.market);
2940
+ const selector = `${instrument}@${opts.rate ?? 500}`;
2694
2941
  const merger = new BookMerger();
2695
2942
  let ws = null;
2943
+ let sock = null;
2944
+ let recovering = false;
2945
+ let awaitingFirstDelta = false;
2946
+ let snapshotSequence = 0;
2947
+ let ackSequence = null;
2696
2948
  const stream = new OrderbookStream(() => ws?.close());
2697
- const subscribePayload = JSON.stringify({
2698
- action: "subscribe",
2699
- args: [channelArg]
2700
- });
2701
- const pingPayload = () => JSON.stringify({ action: "ping" });
2702
- const handleFrame = (frame) => {
2703
- if (frame.symbol !== symbol) return;
2704
- const event = {
2705
- kind: "snapshot",
2706
- bids: parseLevels3(frame.bids),
2707
- asks: parseLevels3(frame.asks),
2708
- sequence: frame.ms_t,
2709
- timestamp: frame.ms_t
2710
- };
2711
- const r = merger.apply(event);
2712
- if (!r.ok) return;
2949
+ let nextId = 1;
2950
+ const subscribeIds = /* @__PURE__ */ new Set();
2951
+ const rpc = (method) => {
2952
+ const id = nextId++;
2953
+ sock?.send(
2954
+ JSON.stringify({
2955
+ jsonrpc: "2.0",
2956
+ method,
2957
+ params: { stream: STREAM, selectors: [selector] },
2958
+ id
2959
+ })
2960
+ );
2961
+ return id;
2962
+ };
2963
+ const subscribe = () => subscribeIds.add(rpc("subscribe"));
2964
+ const emit = (r) => {
2713
2965
  const book = {
2714
- exchange: "bitmart",
2715
- symbol: fromBitmartSymbol(symbol),
2716
- market: "perpetual",
2966
+ exchange: "grvt",
2967
+ symbol: fromGrvtSymbol(instrument),
2968
+ market: opts.market,
2717
2969
  bids: r.bids,
2718
2970
  asks: r.asks,
2719
2971
  timestamp: r.timestamp,
@@ -2721,41 +2973,92 @@ function streamBitmartOrderbook(opts) {
2721
2973
  };
2722
2974
  stream.emit("update", book);
2723
2975
  };
2724
- const handlePayload = (text) => {
2976
+ const resync = () => {
2977
+ if (recovering) return;
2978
+ recovering = true;
2979
+ merger.reset();
2980
+ rpc("unsubscribe");
2981
+ subscribe();
2982
+ };
2983
+ const buildEvent2 = (feed, seq) => {
2984
+ const bids = toLevels(feed.bids);
2985
+ const asks = toLevels(feed.asks);
2986
+ const timestamp = nsToMs(feed.event_time);
2987
+ if (seq === 0) {
2988
+ snapshotSequence = ackSequence ?? 0;
2989
+ awaitingFirstDelta = true;
2990
+ return {
2991
+ kind: "snapshot",
2992
+ bids,
2993
+ asks,
2994
+ sequence: snapshotSequence,
2995
+ timestamp
2996
+ };
2997
+ }
2998
+ const prevSequence = awaitingFirstDelta ? snapshotSequence : seq - 1;
2999
+ awaitingFirstDelta = false;
3000
+ return { kind: "delta", bids, asks, sequence: seq, prevSequence, timestamp };
3001
+ };
3002
+ const handleFeed = (msg) => {
3003
+ if (!msg.feed) return;
3004
+ const seq = Number(msg.sequence_number ?? 0);
3005
+ if (!Number.isFinite(seq)) return;
3006
+ if (seq === 0) recovering = false;
3007
+ else if (recovering) return;
3008
+ const r = merger.apply(buildEvent2(msg.feed, seq));
3009
+ if (r.ok) {
3010
+ emit(r);
3011
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
3012
+ resync();
3013
+ }
3014
+ };
3015
+ const onMessage = (raw) => {
3016
+ if (typeof raw !== "string") return;
2725
3017
  let msg;
2726
3018
  try {
2727
- msg = JSON.parse(text);
3019
+ msg = JSON.parse(raw);
2728
3020
  } catch {
2729
3021
  return;
2730
3022
  }
2731
- if (msg.action === "subscribe" || msg.action === "pong") return;
2732
- if (msg.errorCode) {
3023
+ if (msg.feed) {
3024
+ if (msg.selector && msg.selector !== selector) return;
3025
+ handleFeed(msg);
3026
+ return;
3027
+ }
3028
+ if (msg.id === void 0) return;
3029
+ if (msg.error) {
2733
3030
  stream.emit(
2734
3031
  "error",
2735
- new Error(`bitmart: ${msg.errorCode} ${msg.errorMessage ?? ""}`)
3032
+ new ExchangeError("grvt", `${msg.error.code}: ${msg.error.message}`)
2736
3033
  );
2737
3034
  return;
2738
3035
  }
2739
- if (msg.group !== channelArg || !msg.data) return;
2740
- handleFrame(msg.data);
2741
- };
2742
- const onMessage = async (raw) => {
2743
- if (typeof raw === "string") {
2744
- handlePayload(raw);
2745
- return;
3036
+ if (subscribeIds.delete(msg.id)) {
3037
+ const subs = msg.result?.subs ?? [];
3038
+ const latest = Number(msg.result?.latest_sequence_number?.[0]);
3039
+ ackSequence = Number.isFinite(latest) ? latest : null;
3040
+ if (!subs.includes(selector)) {
3041
+ stream.emit(
3042
+ "error",
3043
+ new ExchangeError(
3044
+ "grvt",
3045
+ `subscribe rejected for "${STREAM}" selector "${selector}"`
3046
+ )
3047
+ );
3048
+ }
2746
3049
  }
2747
- const inflate = await getGzipInflate();
2748
- handlePayload(inflate(raw));
2749
3050
  };
2750
3051
  ws = new WSClient({
2751
- url: WS_FUTURES4,
2752
- onOpen: (sock) => {
3052
+ url: WS_FULL,
3053
+ onOpen: (handle) => {
3054
+ sock = handle;
2753
3055
  merger.reset();
2754
- sock.send(subscribePayload);
3056
+ recovering = false;
3057
+ awaitingFirstDelta = false;
3058
+ subscribeIds.clear();
3059
+ subscribe();
2755
3060
  },
2756
- onMessage,
2757
- pingIntervalMs: 15e3,
2758
- pingPayload
3061
+ onMessage
2759
3062
  });
2760
3063
  ws.on("open", () => stream.emit("connected"));
2761
3064
  ws.on("close", (r) => stream.emit("disconnected", r));
@@ -2764,21 +3067,10 @@ function streamBitmartOrderbook(opts) {
2764
3067
  ws.connect().catch((e) => stream.emit("error", e));
2765
3068
  return stream;
2766
3069
  }
2767
- function snapLevel(depth) {
2768
- if (depth === 5) return 5;
2769
- if (depth === 20) return 20;
2770
- return 50;
2771
- }
2772
- function parseLevels3(rows) {
2773
- if (!rows) return [];
2774
- const out = [];
2775
- for (const r of rows) out.push({ price: Number(r.price), size: Number(r.vol) });
2776
- return out;
2777
- }
2778
3070
 
2779
- // src/exchanges/bitmart/index.ts
2780
- var BitmartClient = class {
2781
- exchange = "bitmart";
3071
+ // src/exchanges/grvt/index.ts
3072
+ var GrvtClient = class {
3073
+ exchange = "grvt";
2782
3074
  transformUrl;
2783
3075
  timeoutMs;
2784
3076
  constructor(opts = {}) {
@@ -2787,7 +3079,7 @@ var BitmartClient = class {
2787
3079
  }
2788
3080
  fetchOrderbook(symbol, opts = {}) {
2789
3081
  const { pair, market } = parseSymbol(symbol);
2790
- return fetchBitmartOrderbook({
3082
+ return fetchGrvtOrderbook({
2791
3083
  symbol: pair,
2792
3084
  market,
2793
3085
  depth: opts.depth,
@@ -2795,11 +3087,12 @@ var BitmartClient = class {
2795
3087
  transformUrl: this.transformUrl
2796
3088
  });
2797
3089
  }
2798
- streamOrderbook(symbol, _opts = {}) {
3090
+ streamOrderbook(symbol, opts = {}) {
2799
3091
  const { pair, market } = parseSymbol(symbol);
2800
- return streamBitmartOrderbook({
3092
+ return streamGrvtOrderbook({
2801
3093
  symbol: pair,
2802
3094
  market,
3095
+ depth: opts.depth,
2803
3096
  transformUrl: this.transformUrl,
2804
3097
  timeoutMs: this.timeoutMs
2805
3098
  });
@@ -2810,12 +3103,13 @@ exports.Backoff = Backoff;
2810
3103
  exports.BinanceClient = BinanceClient;
2811
3104
  exports.BingxClient = BingxClient;
2812
3105
  exports.BitgetClient = BitgetClient;
2813
- exports.BitmartClient = BitmartClient;
2814
3106
  exports.BookMerger = BookMerger;
2815
3107
  exports.BybitClient = BybitClient;
2816
3108
  exports.CoinexClient = CoinexClient;
3109
+ exports.DeribitClient = DeribitClient;
2817
3110
  exports.ExchangeError = ExchangeError;
2818
3111
  exports.GateClient = GateClient;
3112
+ exports.GrvtClient = GrvtClient;
2819
3113
  exports.HuobiClient = HuobiClient;
2820
3114
  exports.HyperliquidClient = HyperliquidClient;
2821
3115
  exports.KucoinClient = KucoinClient;