@xapy/orderbook 0.1.23 → 0.1.25

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 (50) hide show
  1. package/README.md +3 -0
  2. package/dist/exchanges/binance/index.d.cts +1 -1
  3. package/dist/exchanges/binance/index.d.ts +1 -1
  4. package/dist/exchanges/bingx/index.d.cts +1 -1
  5. package/dist/exchanges/bingx/index.d.ts +1 -1
  6. package/dist/exchanges/bitget/index.d.cts +1 -1
  7. package/dist/exchanges/bitget/index.d.ts +1 -1
  8. package/dist/exchanges/bybit/index.d.cts +1 -1
  9. package/dist/exchanges/bybit/index.d.ts +1 -1
  10. package/dist/exchanges/coinex/index.d.cts +1 -1
  11. package/dist/exchanges/coinex/index.d.ts +1 -1
  12. package/dist/exchanges/deribit/index.d.cts +1 -1
  13. package/dist/exchanges/deribit/index.d.ts +1 -1
  14. package/dist/exchanges/edgex/index.cjs +648 -0
  15. package/dist/exchanges/edgex/index.cjs.map +1 -0
  16. package/dist/exchanges/edgex/index.d.cts +62 -0
  17. package/dist/exchanges/edgex/index.d.ts +62 -0
  18. package/dist/exchanges/edgex/index.js +642 -0
  19. package/dist/exchanges/edgex/index.js.map +1 -0
  20. package/dist/exchanges/gate/index.d.cts +1 -1
  21. package/dist/exchanges/gate/index.d.ts +1 -1
  22. package/dist/exchanges/grvt/index.cjs +627 -0
  23. package/dist/exchanges/grvt/index.cjs.map +1 -0
  24. package/dist/exchanges/grvt/index.d.cts +47 -0
  25. package/dist/exchanges/grvt/index.d.ts +47 -0
  26. package/dist/exchanges/grvt/index.js +623 -0
  27. package/dist/exchanges/grvt/index.js.map +1 -0
  28. package/dist/exchanges/huobi/index.d.cts +1 -1
  29. package/dist/exchanges/huobi/index.d.ts +1 -1
  30. package/dist/exchanges/hyperliquid/index.d.cts +1 -1
  31. package/dist/exchanges/hyperliquid/index.d.ts +1 -1
  32. package/dist/exchanges/kucoin/index.d.cts +1 -1
  33. package/dist/exchanges/kucoin/index.d.ts +1 -1
  34. package/dist/exchanges/lighter/index.cjs +664 -0
  35. package/dist/exchanges/lighter/index.cjs.map +1 -0
  36. package/dist/exchanges/lighter/index.d.cts +58 -0
  37. package/dist/exchanges/lighter/index.d.ts +58 -0
  38. package/dist/exchanges/lighter/index.js +658 -0
  39. package/dist/exchanges/lighter/index.js.map +1 -0
  40. package/dist/exchanges/okx/index.d.cts +1 -1
  41. package/dist/exchanges/okx/index.d.ts +1 -1
  42. package/dist/index.cjs +738 -3
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.cts +5 -2
  45. package/dist/index.d.ts +5 -2
  46. package/dist/index.js +736 -4
  47. package/dist/index.js.map +1 -1
  48. package/dist/{stream-CO3LD9jf.d.cts → stream-CrvepB6m.d.cts} +1 -1
  49. package/dist/{stream-CO3LD9jf.d.ts → stream-CrvepB6m.d.ts} +1 -1
  50. package/package.json +35 -2
package/dist/index.js CHANGED
@@ -2743,13 +2743,13 @@ function streamDeribitOrderbook(opts) {
2743
2743
  rpc("public/unsubscribe", { channels: [channel] });
2744
2744
  subscribe();
2745
2745
  };
2746
- const toLevels = (entries) => entries.map(([action, price, amount]) => ({
2746
+ const toLevels4 = (entries) => entries.map(([action, price, amount]) => ({
2747
2747
  price,
2748
2748
  size: action === "delete" ? 0 : amount
2749
2749
  }));
2750
2750
  const buildEvent2 = (d) => {
2751
- const bids = toLevels(d.bids);
2752
- const asks = toLevels(d.asks);
2751
+ const bids = toLevels4(d.bids);
2752
+ const asks = toLevels4(d.asks);
2753
2753
  if (d.type === "snapshot") {
2754
2754
  return {
2755
2755
  kind: "snapshot",
@@ -2871,6 +2871,738 @@ var DeribitClient = class {
2871
2871
  }
2872
2872
  };
2873
2873
 
2874
- export { Backoff, BinanceClient, BingxClient, BitgetClient, BookMerger, BybitClient, CoinexClient, DeribitClient, ExchangeError, GateClient, HuobiClient, HyperliquidClient, KucoinClient, OkxClient, OrderbookStream, RateLimitError, SequenceGapError, parseSymbol };
2874
+ // src/exchanges/grvt/symbols.ts
2875
+ function toGrvtSymbol(symbol, market) {
2876
+ const [base, quote] = symbol.split("/");
2877
+ if (!base || !quote) {
2878
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
2879
+ }
2880
+ if (market !== "perpetual") {
2881
+ throw new Error(
2882
+ `grvt only lists perpetuals; use "${base.toUpperCase()}/${quote.toUpperCase()}:${quote.toUpperCase()}"`
2883
+ );
2884
+ }
2885
+ return `${base.toUpperCase()}_${quote.toUpperCase()}_Perp`;
2886
+ }
2887
+ function fromGrvtSymbol(instrument) {
2888
+ const parts = instrument.split("_");
2889
+ const [base, quote] = parts;
2890
+ return base && quote ? `${base.toUpperCase()}/${quote.toUpperCase()}` : instrument;
2891
+ }
2892
+
2893
+ // src/exchanges/grvt/rest.ts
2894
+ var BASE9 = "https://market-data.grvt.io";
2895
+ var ALLOWED_DEPTHS2 = [10, 50, 100, 500];
2896
+ function snapDepth(depth) {
2897
+ return ALLOWED_DEPTHS2.find((d) => d >= depth) ?? ALLOWED_DEPTHS2[ALLOWED_DEPTHS2.length - 1];
2898
+ }
2899
+ function nsToMs(ns) {
2900
+ const n = Number(ns);
2901
+ return Number.isFinite(n) && n > 0 ? Math.floor(n / 1e6) : Date.now();
2902
+ }
2903
+ var toLevels = (rows) => (rows ?? []).map((l) => ({ price: Number(l.price), size: Number(l.size) }));
2904
+ async function fetchGrvtOrderbook(opts) {
2905
+ const instrument = toGrvtSymbol(opts.symbol, opts.market);
2906
+ const depth = snapDepth(opts.depth ?? 50);
2907
+ const res = await httpJson({
2908
+ url: `${BASE9}/full/v1/book`,
2909
+ method: "POST",
2910
+ headers: { "Content-Type": "application/json" },
2911
+ body: JSON.stringify({ instrument, depth }),
2912
+ timeoutMs: opts.timeoutMs,
2913
+ transformUrl: opts.transformUrl
2914
+ });
2915
+ if (!res.result) {
2916
+ throw new ExchangeError(
2917
+ "grvt",
2918
+ res.code ? `${res.code}: ${res.message}` : "empty orderbook response"
2919
+ );
2920
+ }
2921
+ const ts = nsToMs(res.result.event_time);
2922
+ return {
2923
+ exchange: "grvt",
2924
+ symbol: fromGrvtSymbol(res.result.instrument ?? instrument),
2925
+ market: opts.market,
2926
+ bids: toLevels(res.result.bids),
2927
+ asks: toLevels(res.result.asks),
2928
+ timestamp: ts,
2929
+ sequence: ts
2930
+ };
2931
+ }
2932
+
2933
+ // src/exchanges/grvt/ws.ts
2934
+ var WS_FULL = "wss://market-data.grvt.io/ws/full";
2935
+ var STREAM = "v1.book.d";
2936
+ function streamGrvtOrderbook(opts) {
2937
+ const instrument = toGrvtSymbol(opts.symbol, opts.market);
2938
+ const selector = `${instrument}@${opts.rate ?? 500}`;
2939
+ const merger = new BookMerger();
2940
+ let ws = null;
2941
+ let sock = null;
2942
+ let recovering = false;
2943
+ let awaitingFirstDelta = false;
2944
+ let snapshotSequence = 0;
2945
+ let ackSequence = null;
2946
+ const stream = new OrderbookStream(() => ws?.close());
2947
+ let nextId = 1;
2948
+ const subscribeIds = /* @__PURE__ */ new Set();
2949
+ const rpc = (method) => {
2950
+ const id = nextId++;
2951
+ sock?.send(
2952
+ JSON.stringify({
2953
+ jsonrpc: "2.0",
2954
+ method,
2955
+ params: { stream: STREAM, selectors: [selector] },
2956
+ id
2957
+ })
2958
+ );
2959
+ return id;
2960
+ };
2961
+ const subscribe = () => subscribeIds.add(rpc("subscribe"));
2962
+ const emit = (r) => {
2963
+ const book = {
2964
+ exchange: "grvt",
2965
+ symbol: fromGrvtSymbol(instrument),
2966
+ market: opts.market,
2967
+ bids: r.bids,
2968
+ asks: r.asks,
2969
+ timestamp: r.timestamp,
2970
+ sequence: r.sequence
2971
+ };
2972
+ stream.emit("update", book);
2973
+ };
2974
+ const resync = () => {
2975
+ if (recovering) return;
2976
+ recovering = true;
2977
+ merger.reset();
2978
+ rpc("unsubscribe");
2979
+ subscribe();
2980
+ };
2981
+ const buildEvent2 = (feed, seq) => {
2982
+ const bids = toLevels(feed.bids);
2983
+ const asks = toLevels(feed.asks);
2984
+ const timestamp = nsToMs(feed.event_time);
2985
+ if (seq === 0) {
2986
+ snapshotSequence = ackSequence ?? 0;
2987
+ awaitingFirstDelta = true;
2988
+ return {
2989
+ kind: "snapshot",
2990
+ bids,
2991
+ asks,
2992
+ sequence: snapshotSequence,
2993
+ timestamp
2994
+ };
2995
+ }
2996
+ const prevSequence = awaitingFirstDelta ? snapshotSequence : seq - 1;
2997
+ awaitingFirstDelta = false;
2998
+ return { kind: "delta", bids, asks, sequence: seq, prevSequence, timestamp };
2999
+ };
3000
+ const handleFeed = (msg) => {
3001
+ if (!msg.feed) return;
3002
+ const seq = Number(msg.sequence_number ?? 0);
3003
+ if (!Number.isFinite(seq)) return;
3004
+ if (seq === 0) recovering = false;
3005
+ else if (recovering) return;
3006
+ const r = merger.apply(buildEvent2(msg.feed, seq));
3007
+ if (r.ok) {
3008
+ emit(r);
3009
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
3010
+ resync();
3011
+ }
3012
+ };
3013
+ const onMessage = (raw) => {
3014
+ if (typeof raw !== "string") return;
3015
+ let msg;
3016
+ try {
3017
+ msg = JSON.parse(raw);
3018
+ } catch {
3019
+ return;
3020
+ }
3021
+ if (msg.feed) {
3022
+ if (msg.selector && msg.selector !== selector) return;
3023
+ handleFeed(msg);
3024
+ return;
3025
+ }
3026
+ if (msg.id === void 0) return;
3027
+ if (msg.error) {
3028
+ stream.emit(
3029
+ "error",
3030
+ new ExchangeError("grvt", `${msg.error.code}: ${msg.error.message}`)
3031
+ );
3032
+ return;
3033
+ }
3034
+ if (subscribeIds.delete(msg.id)) {
3035
+ const subs = msg.result?.subs ?? [];
3036
+ const latest = Number(msg.result?.latest_sequence_number?.[0]);
3037
+ ackSequence = Number.isFinite(latest) ? latest : null;
3038
+ if (!subs.includes(selector)) {
3039
+ stream.emit(
3040
+ "error",
3041
+ new ExchangeError(
3042
+ "grvt",
3043
+ `subscribe rejected for "${STREAM}" selector "${selector}"`
3044
+ )
3045
+ );
3046
+ }
3047
+ }
3048
+ };
3049
+ ws = new WSClient({
3050
+ url: WS_FULL,
3051
+ onOpen: (handle) => {
3052
+ sock = handle;
3053
+ merger.reset();
3054
+ recovering = false;
3055
+ awaitingFirstDelta = false;
3056
+ subscribeIds.clear();
3057
+ subscribe();
3058
+ },
3059
+ onMessage
3060
+ });
3061
+ ws.on("open", () => stream.emit("connected"));
3062
+ ws.on("close", (r) => stream.emit("disconnected", r));
3063
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
3064
+ ws.on("error", (e) => stream.emit("error", e));
3065
+ ws.connect().catch((e) => stream.emit("error", e));
3066
+ return stream;
3067
+ }
3068
+
3069
+ // src/exchanges/grvt/index.ts
3070
+ var GrvtClient = class {
3071
+ exchange = "grvt";
3072
+ transformUrl;
3073
+ timeoutMs;
3074
+ constructor(opts = {}) {
3075
+ this.transformUrl = opts.transformUrl;
3076
+ this.timeoutMs = opts.timeoutMs;
3077
+ }
3078
+ fetchOrderbook(symbol, opts = {}) {
3079
+ const { pair, market } = parseSymbol(symbol);
3080
+ return fetchGrvtOrderbook({
3081
+ symbol: pair,
3082
+ market,
3083
+ depth: opts.depth,
3084
+ timeoutMs: this.timeoutMs,
3085
+ transformUrl: this.transformUrl
3086
+ });
3087
+ }
3088
+ streamOrderbook(symbol, opts = {}) {
3089
+ const { pair, market } = parseSymbol(symbol);
3090
+ return streamGrvtOrderbook({
3091
+ symbol: pair,
3092
+ market,
3093
+ depth: opts.depth,
3094
+ transformUrl: this.transformUrl,
3095
+ timeoutMs: this.timeoutMs
3096
+ });
3097
+ }
3098
+ };
3099
+
3100
+ // src/exchanges/lighter/markets.ts
3101
+ var LIGHTER_REST = "https://mainnet.zklighter.elliot.ai";
3102
+ var cache = null;
3103
+ var inflight = null;
3104
+ var key = (name, market) => `${market}:${name.toUpperCase()}`;
3105
+ async function fetchMarkets(opts) {
3106
+ const res = await httpJson({
3107
+ url: `${LIGHTER_REST}/api/v1/orderBooks`,
3108
+ timeoutMs: opts.timeoutMs,
3109
+ transformUrl: opts.transformUrl
3110
+ });
3111
+ const rows = res.order_books ?? [];
3112
+ if (rows.length === 0) {
3113
+ throw new ExchangeError(
3114
+ "lighter",
3115
+ res.message ? `${res.code}: ${res.message}` : "empty orderBooks response"
3116
+ );
3117
+ }
3118
+ const map = /* @__PURE__ */ new Map();
3119
+ for (const row of rows) {
3120
+ map.set(key(row.symbol, row.market_type === "spot" ? "spot" : "perpetual"), row);
3121
+ }
3122
+ return map;
3123
+ }
3124
+ function loadMarkets(opts) {
3125
+ inflight ??= fetchMarkets(opts).then(
3126
+ (m) => {
3127
+ cache = m;
3128
+ inflight = null;
3129
+ return m;
3130
+ },
3131
+ (err) => {
3132
+ inflight = null;
3133
+ throw err;
3134
+ }
3135
+ );
3136
+ return inflight;
3137
+ }
3138
+ async function resolveLighterMarket(name, market, opts) {
3139
+ const k = key(name, market);
3140
+ const hit = cache?.get(k);
3141
+ const meta = hit ?? (await loadMarkets(opts)).get(k);
3142
+ if (!meta) {
3143
+ throw new ExchangeError(
3144
+ "lighter",
3145
+ `unknown ${market} market "${name}" \u2014 not listed on lighter`
3146
+ );
3147
+ }
3148
+ if (meta.status && meta.status !== "active") {
3149
+ throw new ExchangeError(
3150
+ "lighter",
3151
+ `market "${name}" is ${meta.status} \u2014 no book is published for it`
3152
+ );
3153
+ }
3154
+ return meta;
3155
+ }
3156
+
3157
+ // src/exchanges/lighter/symbols.ts
3158
+ function toLighterSymbol(symbol, market) {
3159
+ const [base, quote] = symbol.split("/");
3160
+ if (!base || !quote) {
3161
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
3162
+ }
3163
+ if (quote.toUpperCase() !== "USDC") {
3164
+ throw new Error(`lighter only supports USDC-quoted pairs; got "${quote}"`);
3165
+ }
3166
+ return market === "perpetual" ? base.toUpperCase() : `${base.toUpperCase()}/${quote.toUpperCase()}`;
3167
+ }
3168
+ function fromLighterSymbol(name) {
3169
+ return name.includes("/") ? name.toUpperCase() : `${name.toUpperCase()}/USDC`;
3170
+ }
3171
+
3172
+ // src/exchanges/lighter/rest.ts
3173
+ var MAX_ORDERS = 250;
3174
+ function usToMs(us) {
3175
+ return Number.isFinite(us) && us > 0 ? Math.floor(us / 1e3) : Date.now();
3176
+ }
3177
+ function aggregate(orders, side, capped) {
3178
+ const byPrice = /* @__PURE__ */ new Map();
3179
+ for (const o of orders ?? []) {
3180
+ const price = Number(o.price);
3181
+ const size = Number(o.remaining_base_amount);
3182
+ if (!Number.isFinite(price) || !Number.isFinite(size)) continue;
3183
+ byPrice.set(price, (byPrice.get(price) ?? 0) + size);
3184
+ }
3185
+ const levels = [];
3186
+ for (const [price, size] of byPrice) levels.push({ price, size });
3187
+ levels.sort((a, b) => side === "bid" ? b.price - a.price : a.price - b.price);
3188
+ if (capped) levels.pop();
3189
+ return levels;
3190
+ }
3191
+ async function fetchLighterOrderbook(opts) {
3192
+ const name = toLighterSymbol(opts.symbol, opts.market);
3193
+ const meta = await resolveLighterMarket(name, opts.market, opts);
3194
+ const res = await httpJson({
3195
+ url: `${LIGHTER_REST}/api/v1/orderBookOrders?market_id=${meta.market_id}&limit=${MAX_ORDERS}`,
3196
+ timeoutMs: opts.timeoutMs,
3197
+ transformUrl: opts.transformUrl
3198
+ });
3199
+ if (!res.asks && !res.bids) {
3200
+ throw new ExchangeError(
3201
+ "lighter",
3202
+ res.message ? `${res.code}: ${res.message}` : "empty orderbook response"
3203
+ );
3204
+ }
3205
+ const depth = opts.depth ?? 50;
3206
+ const bids = aggregate(res.bids, "bid", res.total_bids === MAX_ORDERS);
3207
+ const asks = aggregate(res.asks, "ask", res.total_asks === MAX_ORDERS);
3208
+ const timestamp = Date.now();
3209
+ return {
3210
+ exchange: "lighter",
3211
+ symbol: fromLighterSymbol(name),
3212
+ market: opts.market,
3213
+ bids: bids.slice(0, depth),
3214
+ asks: asks.slice(0, depth),
3215
+ timestamp,
3216
+ // The L3 endpoint publishes no sequence of its own — the WS `nonce` chain
3217
+ // is where ordering is enforced.
3218
+ sequence: timestamp
3219
+ };
3220
+ }
3221
+
3222
+ // src/exchanges/lighter/ws.ts
3223
+ var WS_URL2 = "wss://mainnet.zklighter.elliot.ai/stream";
3224
+ var PING_INTERVAL_MS = 6e4;
3225
+ var toLevels2 = (rows) => (rows ?? []).map((l) => ({ price: Number(l.price), size: Number(l.size) }));
3226
+ function streamLighterOrderbook(opts) {
3227
+ const name = toLighterSymbol(opts.symbol, opts.market);
3228
+ const symbol = fromLighterSymbol(name);
3229
+ const marketId = resolveLighterMarket(name, opts.market, opts).then(
3230
+ (m) => m.market_id
3231
+ );
3232
+ marketId.catch(() => {
3233
+ });
3234
+ const merger = new BookMerger();
3235
+ let ws = null;
3236
+ let sock = null;
3237
+ let channel = null;
3238
+ let recovering = false;
3239
+ const stream = new OrderbookStream(() => ws?.close());
3240
+ const send = (type) => {
3241
+ if (channel) sock?.send(JSON.stringify({ type, channel }));
3242
+ };
3243
+ const emit = (r) => {
3244
+ const book = {
3245
+ exchange: "lighter",
3246
+ symbol,
3247
+ market: opts.market,
3248
+ bids: r.bids,
3249
+ asks: r.asks,
3250
+ timestamp: r.timestamp,
3251
+ sequence: r.sequence
3252
+ };
3253
+ stream.emit("update", book);
3254
+ };
3255
+ const resync = () => {
3256
+ if (recovering) return;
3257
+ recovering = true;
3258
+ merger.reset();
3259
+ send("unsubscribe");
3260
+ send("subscribe");
3261
+ };
3262
+ const buildEvent2 = (msg, snapshot) => {
3263
+ const ob = msg.order_book ?? {};
3264
+ const bids = toLevels2(ob.bids);
3265
+ const asks = toLevels2(ob.asks);
3266
+ const timestamp = msg.timestamp ?? usToMs(ob.last_updated_at);
3267
+ const sequence = Number(ob.nonce ?? 0);
3268
+ return snapshot ? { kind: "snapshot", bids, asks, sequence, timestamp } : {
3269
+ kind: "delta",
3270
+ bids,
3271
+ asks,
3272
+ sequence,
3273
+ prevSequence: Number(ob.begin_nonce ?? 0),
3274
+ timestamp
3275
+ };
3276
+ };
3277
+ const handleBook = (msg, snapshot) => {
3278
+ if (snapshot) recovering = false;
3279
+ else if (recovering) return;
3280
+ const r = merger.apply(buildEvent2(msg, snapshot));
3281
+ if (r.ok) {
3282
+ emit(r);
3283
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
3284
+ resync();
3285
+ }
3286
+ };
3287
+ const onMessage = (raw) => {
3288
+ if (typeof raw !== "string") return;
3289
+ let msg;
3290
+ try {
3291
+ msg = JSON.parse(raw);
3292
+ } catch {
3293
+ return;
3294
+ }
3295
+ if (msg.error) {
3296
+ stream.emit(
3297
+ "error",
3298
+ new ExchangeError("lighter", `${msg.error.code}: ${msg.error.message}`)
3299
+ );
3300
+ return;
3301
+ }
3302
+ if (!msg.order_book) return;
3303
+ if (msg.channel && channel && msg.channel !== channel.replace("/", ":")) {
3304
+ return;
3305
+ }
3306
+ if (msg.type === "subscribed/order_book") handleBook(msg, true);
3307
+ else if (msg.type === "update/order_book") handleBook(msg, false);
3308
+ };
3309
+ ws = new WSClient({
3310
+ url: WS_URL2,
3311
+ onOpen: async (handle) => {
3312
+ sock = handle;
3313
+ merger.reset();
3314
+ recovering = false;
3315
+ channel = `order_book/${await marketId}`;
3316
+ send("subscribe");
3317
+ },
3318
+ onMessage,
3319
+ pingIntervalMs: PING_INTERVAL_MS,
3320
+ pingPayload: () => JSON.stringify({ type: "ping" })
3321
+ });
3322
+ ws.on("open", () => stream.emit("connected"));
3323
+ ws.on("close", (r) => stream.emit("disconnected", r));
3324
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
3325
+ ws.on("error", (e) => stream.emit("error", e));
3326
+ ws.connect().catch((e) => stream.emit("error", e));
3327
+ return stream;
3328
+ }
3329
+
3330
+ // src/exchanges/lighter/index.ts
3331
+ var LighterClient = class {
3332
+ exchange = "lighter";
3333
+ transformUrl;
3334
+ timeoutMs;
3335
+ constructor(opts = {}) {
3336
+ this.transformUrl = opts.transformUrl;
3337
+ this.timeoutMs = opts.timeoutMs;
3338
+ }
3339
+ fetchOrderbook(symbol, opts = {}) {
3340
+ const { pair, market } = parseSymbol(symbol);
3341
+ return fetchLighterOrderbook({
3342
+ symbol: pair,
3343
+ market,
3344
+ depth: opts.depth,
3345
+ timeoutMs: this.timeoutMs,
3346
+ transformUrl: this.transformUrl
3347
+ });
3348
+ }
3349
+ streamOrderbook(symbol, opts = {}) {
3350
+ const { pair, market } = parseSymbol(symbol);
3351
+ return streamLighterOrderbook({
3352
+ symbol: pair,
3353
+ market,
3354
+ depth: opts.depth,
3355
+ transformUrl: this.transformUrl,
3356
+ timeoutMs: this.timeoutMs
3357
+ });
3358
+ }
3359
+ };
3360
+
3361
+ // src/exchanges/edgex/markets.ts
3362
+ var EDGEX_REST = "https://edgex-prod-v2.edgex.exchange";
3363
+ var EDGEX_WS = "wss://edgex-quote-prod-v2.edgex.exchange";
3364
+ var cache2 = null;
3365
+ var inflight2 = null;
3366
+ async function fetchContracts(opts) {
3367
+ const res = await httpJson({
3368
+ url: `${EDGEX_REST}/api/v2/public/meta/getMetaData`,
3369
+ timeoutMs: opts.timeoutMs,
3370
+ transformUrl: opts.transformUrl
3371
+ });
3372
+ const rows = res.data?.contractList ?? [];
3373
+ if (rows.length === 0) {
3374
+ throw new ExchangeError(
3375
+ "edgex",
3376
+ res.msg ? `${res.code}: ${res.msg}` : "empty metadata response"
3377
+ );
3378
+ }
3379
+ const map = /* @__PURE__ */ new Map();
3380
+ for (const row of rows) map.set(row.contractName.toUpperCase(), row);
3381
+ return map;
3382
+ }
3383
+ function loadContracts(opts) {
3384
+ inflight2 ??= fetchContracts(opts).then(
3385
+ (m) => {
3386
+ cache2 = m;
3387
+ inflight2 = null;
3388
+ return m;
3389
+ },
3390
+ (err) => {
3391
+ inflight2 = null;
3392
+ throw err;
3393
+ }
3394
+ );
3395
+ return inflight2;
3396
+ }
3397
+ async function resolveEdgexContract(contractName, opts) {
3398
+ const k = contractName.toUpperCase();
3399
+ const hit = cache2?.get(k);
3400
+ const contract = hit ?? (await loadContracts(opts)).get(k);
3401
+ if (!contract) {
3402
+ throw new ExchangeError(
3403
+ "edgex",
3404
+ `unknown contract "${contractName}" \u2014 not listed on edgex`
3405
+ );
3406
+ }
3407
+ return contract;
3408
+ }
3409
+
3410
+ // src/exchanges/edgex/symbols.ts
3411
+ function toEdgexSymbol(symbol, market) {
3412
+ const [base, quote] = symbol.split("/");
3413
+ if (!base || !quote) {
3414
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
3415
+ }
3416
+ if (market !== "perpetual") {
3417
+ throw new Error(
3418
+ `edgex only lists perpetuals; use "${base.toUpperCase()}/${quote.toUpperCase()}:${quote.toUpperCase()}"`
3419
+ );
3420
+ }
3421
+ if (quote.toUpperCase() !== "USDC") {
3422
+ throw new Error(`edgex only supports USDC-quoted pairs; got "${quote}"`);
3423
+ }
3424
+ return `${base.toUpperCase()}${quote.toUpperCase()}`;
3425
+ }
3426
+ function fromEdgexSymbol(contractName) {
3427
+ const name = contractName.toUpperCase();
3428
+ return name.endsWith("USDC") ? `${name.slice(0, -4)}/USDC` : name;
3429
+ }
3430
+
3431
+ // src/exchanges/edgex/rest.ts
3432
+ var ALLOWED_LEVELS = [15, 200];
3433
+ function snapLevel(depth) {
3434
+ return ALLOWED_LEVELS.find((l) => l >= depth) ?? ALLOWED_LEVELS[ALLOWED_LEVELS.length - 1];
3435
+ }
3436
+ var toLevels3 = (rows) => (rows ?? []).map((l) => ({ price: Number(l.price), size: Number(l.size) }));
3437
+ async function fetchEdgexOrderbook(opts) {
3438
+ const contractName = toEdgexSymbol(opts.symbol, opts.market);
3439
+ const contract = await resolveEdgexContract(contractName, opts);
3440
+ const level = snapLevel(opts.depth ?? 50);
3441
+ const res = await httpJson({
3442
+ url: `${EDGEX_REST}/api/v2/public/quote/getDepth?contractId=${contract.contractId}&level=${level}`,
3443
+ timeoutMs: opts.timeoutMs,
3444
+ transformUrl: opts.transformUrl
3445
+ });
3446
+ const depth = res.data?.[0];
3447
+ if (!depth) {
3448
+ throw new ExchangeError(
3449
+ "edgex",
3450
+ res.msg ? `${res.code}: ${res.msg}` : "empty orderbook response"
3451
+ );
3452
+ }
3453
+ const timestamp = Date.now();
3454
+ return {
3455
+ exchange: "edgex",
3456
+ symbol: fromEdgexSymbol(depth.contractName ?? contractName),
3457
+ market: opts.market,
3458
+ bids: toLevels3(depth.bids),
3459
+ asks: toLevels3(depth.asks),
3460
+ timestamp,
3461
+ sequence: Number(depth.endVersion ?? 0)
3462
+ };
3463
+ }
3464
+
3465
+ // src/exchanges/edgex/ws.ts
3466
+ var WS_URL3 = `${EDGEX_WS}/api/v1/public/ws`;
3467
+ function streamEdgexOrderbook(opts) {
3468
+ const contractName = toEdgexSymbol(opts.symbol, opts.market);
3469
+ const symbol = fromEdgexSymbol(contractName);
3470
+ const level = snapLevel(opts.depth ?? 50);
3471
+ const contractId = resolveEdgexContract(contractName, opts).then(
3472
+ (c) => c.contractId
3473
+ );
3474
+ contractId.catch(() => {
3475
+ });
3476
+ const merger = new BookMerger();
3477
+ let ws = null;
3478
+ let sock = null;
3479
+ let channel = null;
3480
+ let recovering = false;
3481
+ const stream = new OrderbookStream(() => ws?.close());
3482
+ const send = (type) => {
3483
+ if (channel) sock?.send(JSON.stringify({ type, channel }));
3484
+ };
3485
+ const emit = (r) => {
3486
+ const book = {
3487
+ exchange: "edgex",
3488
+ symbol,
3489
+ market: opts.market,
3490
+ bids: r.bids,
3491
+ asks: r.asks,
3492
+ timestamp: r.timestamp,
3493
+ sequence: r.sequence
3494
+ };
3495
+ stream.emit("update", book);
3496
+ };
3497
+ const resync = () => {
3498
+ if (recovering) return;
3499
+ recovering = true;
3500
+ merger.reset();
3501
+ send("unsubscribe");
3502
+ send("subscribe");
3503
+ };
3504
+ const buildEvent2 = (d, snapshot) => {
3505
+ const bids = toLevels3(d.bids);
3506
+ const asks = toLevels3(d.asks);
3507
+ const timestamp = Date.now();
3508
+ const sequence = Number(d.endVersion ?? 0);
3509
+ return snapshot ? { kind: "snapshot", bids, asks, sequence, timestamp } : {
3510
+ kind: "delta",
3511
+ bids,
3512
+ asks,
3513
+ sequence,
3514
+ prevSequence: Number(d.startVersion ?? 0),
3515
+ timestamp
3516
+ };
3517
+ };
3518
+ const handleDepth = (d, snapshot) => {
3519
+ if (snapshot) recovering = false;
3520
+ else if (recovering) return;
3521
+ const r = merger.apply(buildEvent2(d, snapshot));
3522
+ if (r.ok) {
3523
+ emit(r);
3524
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
3525
+ resync();
3526
+ }
3527
+ };
3528
+ const onMessage = (raw) => {
3529
+ if (typeof raw !== "string") return;
3530
+ let msg;
3531
+ try {
3532
+ msg = JSON.parse(raw);
3533
+ } catch {
3534
+ return;
3535
+ }
3536
+ if (msg.type === "ping") {
3537
+ sock?.send(JSON.stringify({ type: "pong", time: msg.time }));
3538
+ return;
3539
+ }
3540
+ if (msg.type === "error") {
3541
+ const { code, msg: detail } = msg.content ?? {};
3542
+ stream.emit(
3543
+ "error",
3544
+ new ExchangeError(
3545
+ "edgex",
3546
+ code ? `${code}: ${detail ?? ""}`.trim() : "subscribe rejected"
3547
+ )
3548
+ );
3549
+ return;
3550
+ }
3551
+ if (msg.type !== "quote-event") return;
3552
+ if (channel && (msg.channel ?? msg.content?.channel) !== channel) return;
3553
+ const snapshot = msg.content?.dataType?.toLowerCase() === "snapshot";
3554
+ for (const d of msg.content?.data ?? []) handleDepth(d, snapshot);
3555
+ };
3556
+ ws = new WSClient({
3557
+ url: WS_URL3,
3558
+ onOpen: async (handle) => {
3559
+ sock = handle;
3560
+ merger.reset();
3561
+ recovering = false;
3562
+ channel = `depth.${await contractId}.${level}`;
3563
+ send("subscribe");
3564
+ },
3565
+ onMessage
3566
+ });
3567
+ ws.on("open", () => stream.emit("connected"));
3568
+ ws.on("close", (r) => stream.emit("disconnected", r));
3569
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
3570
+ ws.on("error", (e) => stream.emit("error", e));
3571
+ ws.connect().catch((e) => stream.emit("error", e));
3572
+ return stream;
3573
+ }
3574
+
3575
+ // src/exchanges/edgex/index.ts
3576
+ var EdgexClient = class {
3577
+ exchange = "edgex";
3578
+ transformUrl;
3579
+ timeoutMs;
3580
+ constructor(opts = {}) {
3581
+ this.transformUrl = opts.transformUrl;
3582
+ this.timeoutMs = opts.timeoutMs;
3583
+ }
3584
+ fetchOrderbook(symbol, opts = {}) {
3585
+ const { pair, market } = parseSymbol(symbol);
3586
+ return fetchEdgexOrderbook({
3587
+ symbol: pair,
3588
+ market,
3589
+ depth: opts.depth,
3590
+ timeoutMs: this.timeoutMs,
3591
+ transformUrl: this.transformUrl
3592
+ });
3593
+ }
3594
+ streamOrderbook(symbol, opts = {}) {
3595
+ const { pair, market } = parseSymbol(symbol);
3596
+ return streamEdgexOrderbook({
3597
+ symbol: pair,
3598
+ market,
3599
+ depth: opts.depth,
3600
+ transformUrl: this.transformUrl,
3601
+ timeoutMs: this.timeoutMs
3602
+ });
3603
+ }
3604
+ };
3605
+
3606
+ export { Backoff, BinanceClient, BingxClient, BitgetClient, BookMerger, BybitClient, CoinexClient, DeribitClient, EdgexClient, ExchangeError, GateClient, GrvtClient, HuobiClient, HyperliquidClient, KucoinClient, LighterClient, OkxClient, OrderbookStream, RateLimitError, SequenceGapError, parseSymbol };
2875
3607
  //# sourceMappingURL=index.js.map
2876
3608
  //# sourceMappingURL=index.js.map