@xapy/orderbook 0.1.24 → 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 (46) hide show
  1. package/README.md +2 -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.d.cts +1 -1
  23. package/dist/exchanges/grvt/index.d.ts +1 -1
  24. package/dist/exchanges/huobi/index.d.cts +1 -1
  25. package/dist/exchanges/huobi/index.d.ts +1 -1
  26. package/dist/exchanges/hyperliquid/index.d.cts +1 -1
  27. package/dist/exchanges/hyperliquid/index.d.ts +1 -1
  28. package/dist/exchanges/kucoin/index.d.cts +1 -1
  29. package/dist/exchanges/kucoin/index.d.ts +1 -1
  30. package/dist/exchanges/lighter/index.cjs +664 -0
  31. package/dist/exchanges/lighter/index.cjs.map +1 -0
  32. package/dist/exchanges/lighter/index.d.cts +58 -0
  33. package/dist/exchanges/lighter/index.d.ts +58 -0
  34. package/dist/exchanges/lighter/index.js +658 -0
  35. package/dist/exchanges/lighter/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/index.cjs +511 -3
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +4 -2
  41. package/dist/index.d.ts +4 -2
  42. package/dist/index.js +510 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/{stream-Con47OAp.d.cts → stream-CrvepB6m.d.cts} +1 -1
  45. package/dist/{stream-Con47OAp.d.ts → stream-CrvepB6m.d.ts} +1 -1
  46. package/package.json +24 -2
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-Con47OAp.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-Con47OAp.cjs';
1
+ import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-CrvepB6m.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-CrvepB6m.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';
@@ -12,6 +12,8 @@ export { HyperliquidClient } from './exchanges/hyperliquid/index.cjs';
12
12
  export { KucoinClient } from './exchanges/kucoin/index.cjs';
13
13
  export { DeribitClient } from './exchanges/deribit/index.cjs';
14
14
  export { GrvtClient } from './exchanges/grvt/index.cjs';
15
+ export { LighterClient } from './exchanges/lighter/index.cjs';
16
+ export { EdgexClient } from './exchanges/edgex/index.cjs';
15
17
 
16
18
  declare class ExchangeError extends Error {
17
19
  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-Con47OAp.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-Con47OAp.js';
1
+ import { B as BookEvent, O as OrderbookLevel, M as Market } from './stream-CrvepB6m.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-CrvepB6m.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';
@@ -12,6 +12,8 @@ export { HyperliquidClient } from './exchanges/hyperliquid/index.js';
12
12
  export { KucoinClient } from './exchanges/kucoin/index.js';
13
13
  export { DeribitClient } from './exchanges/deribit/index.js';
14
14
  export { GrvtClient } from './exchanges/grvt/index.js';
15
+ export { LighterClient } from './exchanges/lighter/index.js';
16
+ export { EdgexClient } from './exchanges/edgex/index.js';
15
17
 
16
18
  declare class ExchangeError extends Error {
17
19
  readonly exchange: string;
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 toLevels2 = (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 = toLevels2(d.bids);
2752
- const asks = toLevels2(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",
@@ -3097,6 +3097,512 @@ var GrvtClient = class {
3097
3097
  }
3098
3098
  };
3099
3099
 
3100
- export { Backoff, BinanceClient, BingxClient, BitgetClient, BookMerger, BybitClient, CoinexClient, DeribitClient, ExchangeError, GateClient, GrvtClient, HuobiClient, HyperliquidClient, KucoinClient, OkxClient, OrderbookStream, RateLimitError, SequenceGapError, parseSymbol };
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 };
3101
3607
  //# sourceMappingURL=index.js.map
3102
3608
  //# sourceMappingURL=index.js.map