@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
@@ -0,0 +1,625 @@
1
+ 'use strict';
2
+
3
+ // src/core/symbol.ts
4
+ function parseSymbol(symbol) {
5
+ const [pair, settle] = symbol.split(":");
6
+ const parts = (pair ?? "").split("/");
7
+ const base = parts[0]?.toUpperCase();
8
+ const quote = parts[1]?.toUpperCase();
9
+ if (!base || !quote) {
10
+ throw new Error(
11
+ `invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
12
+ );
13
+ }
14
+ if (settle && settle.toUpperCase() !== quote) {
15
+ throw new Error(
16
+ `unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
17
+ );
18
+ }
19
+ return {
20
+ base,
21
+ quote,
22
+ market: settle ? "perpetual" : "spot",
23
+ pair: `${base}/${quote}`
24
+ };
25
+ }
26
+
27
+ // src/transport/http.ts
28
+ async function httpJson(req) {
29
+ const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
30
+ const controller = new AbortController();
31
+ const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
32
+ try {
33
+ const res = await fetch(url, {
34
+ method: req.method ?? "GET",
35
+ headers: req.headers,
36
+ body: req.body,
37
+ signal: controller.signal
38
+ });
39
+ if (!res.ok) {
40
+ const text = await res.text().catch(() => "");
41
+ throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
42
+ }
43
+ return await res.json();
44
+ } finally {
45
+ clearTimeout(timer);
46
+ }
47
+ }
48
+
49
+ // src/core/errors.ts
50
+ var ExchangeError = class extends Error {
51
+ constructor(exchange, message, cause) {
52
+ super(
53
+ `[${exchange}] ${message}`,
54
+ cause === void 0 ? void 0 : { cause }
55
+ );
56
+ this.exchange = exchange;
57
+ this.name = "ExchangeError";
58
+ }
59
+ exchange;
60
+ };
61
+
62
+ // src/exchanges/deribit/symbols.ts
63
+ function toDeribitSymbol(symbol, market) {
64
+ const [base, quote] = symbol.split("/");
65
+ if (!base || !quote) {
66
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
67
+ }
68
+ const pair = `${base}_${quote}`.toUpperCase();
69
+ if (market !== "perpetual") return pair;
70
+ if (quote.toUpperCase() !== "USDC") {
71
+ throw new Error(
72
+ `deribit linear perpetuals are USDC-margined; got "${quote}" (inverse contracts like BTC-PERPETUAL are unsupported)`
73
+ );
74
+ }
75
+ return `${pair}-PERPETUAL`;
76
+ }
77
+ function fromDeribitSymbol(instrument) {
78
+ let s = instrument.toUpperCase();
79
+ if (s.endsWith("-PERPETUAL")) s = s.slice(0, -"-PERPETUAL".length);
80
+ const [base, quote] = s.split("_");
81
+ return base && quote ? `${base}/${quote}` : s;
82
+ }
83
+
84
+ // src/exchanges/deribit/rest.ts
85
+ var BASE = "https://www.deribit.com";
86
+ var ALLOWED_DEPTHS = [1, 5, 10, 20, 50, 100, 1e3, 1e4];
87
+ function clampDepth(depth) {
88
+ return ALLOWED_DEPTHS.find((d) => d >= depth) ?? ALLOWED_DEPTHS[ALLOWED_DEPTHS.length - 1];
89
+ }
90
+ async function fetchDeribitOrderbook(opts) {
91
+ const instrument = toDeribitSymbol(opts.symbol, opts.market);
92
+ const depth = clampDepth(opts.depth ?? 50);
93
+ const url = `${BASE}/api/v2/public/get_order_book?instrument_name=${instrument}&depth=${depth}`;
94
+ const res = await httpJson({
95
+ url,
96
+ timeoutMs: opts.timeoutMs,
97
+ transformUrl: opts.transformUrl
98
+ });
99
+ if (res.error) {
100
+ throw new ExchangeError(
101
+ "deribit",
102
+ `${res.error.code}: ${res.error.message}`
103
+ );
104
+ }
105
+ const r = res.result;
106
+ if (!r) throw new ExchangeError("deribit", "empty orderbook response");
107
+ return {
108
+ exchange: "deribit",
109
+ symbol: fromDeribitSymbol(r.instrument_name ?? instrument),
110
+ market: opts.market,
111
+ bids: r.bids.map(([price, size]) => ({ price, size })),
112
+ asks: r.asks.map(([price, size]) => ({ price, size })),
113
+ timestamp: r.timestamp,
114
+ sequence: r.change_id
115
+ };
116
+ }
117
+
118
+ // src/core/book-merger.ts
119
+ var BookMerger = class {
120
+ bids = /* @__PURE__ */ new Map();
121
+ // price -> size
122
+ asks = /* @__PURE__ */ new Map();
123
+ sequence = -1;
124
+ timestamp = 0;
125
+ hasSnapshot = false;
126
+ apply(event) {
127
+ if (event.kind === "snapshot") {
128
+ this.bids.clear();
129
+ this.asks.clear();
130
+ for (const { price, size } of event.bids) {
131
+ if (size > 0) this.bids.set(price, size);
132
+ }
133
+ for (const { price, size } of event.asks) {
134
+ if (size > 0) this.asks.set(price, size);
135
+ }
136
+ this.sequence = event.sequence;
137
+ this.timestamp = event.timestamp;
138
+ this.hasSnapshot = true;
139
+ return this.emit();
140
+ }
141
+ if (!this.hasSnapshot) {
142
+ return { ok: false, reason: "no-snapshot" };
143
+ }
144
+ if (event.sequence <= this.sequence) {
145
+ return this.emit();
146
+ }
147
+ if (event.prevSequence !== void 0) {
148
+ if (event.prevSequence !== this.sequence) {
149
+ return {
150
+ ok: false,
151
+ reason: "gap",
152
+ expected: this.sequence,
153
+ received: event.prevSequence
154
+ };
155
+ }
156
+ } else if (event.sequence !== this.sequence + 1) {
157
+ return {
158
+ ok: false,
159
+ reason: "gap",
160
+ expected: this.sequence + 1,
161
+ received: event.sequence
162
+ };
163
+ }
164
+ for (const { price, size } of event.bids) {
165
+ if (size === 0) this.bids.delete(price);
166
+ else this.bids.set(price, size);
167
+ }
168
+ for (const { price, size } of event.asks) {
169
+ if (size === 0) this.asks.delete(price);
170
+ else this.asks.set(price, size);
171
+ }
172
+ this.sequence = event.sequence;
173
+ this.timestamp = event.timestamp;
174
+ return this.emit();
175
+ }
176
+ reset() {
177
+ this.bids.clear();
178
+ this.asks.clear();
179
+ this.sequence = -1;
180
+ this.timestamp = 0;
181
+ this.hasSnapshot = false;
182
+ }
183
+ /** Returns true once the merger has a usable book. */
184
+ isReady() {
185
+ return this.hasSnapshot;
186
+ }
187
+ emit() {
188
+ const bids = [];
189
+ for (const [price, size] of this.bids) bids.push({ price, size });
190
+ bids.sort((a, b) => b.price - a.price);
191
+ const asks = [];
192
+ for (const [price, size] of this.asks) asks.push({ price, size });
193
+ asks.sort((a, b) => a.price - b.price);
194
+ return {
195
+ ok: true,
196
+ bids,
197
+ asks,
198
+ sequence: this.sequence,
199
+ timestamp: this.timestamp
200
+ };
201
+ }
202
+ };
203
+
204
+ // src/core/event-emitter.ts
205
+ var TypedEmitter = class {
206
+ listeners = /* @__PURE__ */ new Map();
207
+ on(event, fn) {
208
+ let set = this.listeners.get(event);
209
+ if (!set) {
210
+ set = /* @__PURE__ */ new Set();
211
+ this.listeners.set(event, set);
212
+ }
213
+ set.add(fn);
214
+ return this;
215
+ }
216
+ off(event, fn) {
217
+ this.listeners.get(event)?.delete(fn);
218
+ return this;
219
+ }
220
+ emit(event, ...args) {
221
+ const set = this.listeners.get(event);
222
+ if (!set || set.size === 0) return false;
223
+ for (const fn of set) fn(...args);
224
+ return true;
225
+ }
226
+ removeAllListeners() {
227
+ this.listeners.clear();
228
+ }
229
+ };
230
+
231
+ // src/core/stream.ts
232
+ var OrderbookStream = class extends TypedEmitter {
233
+ constructor(onClose) {
234
+ super();
235
+ this.onClose = onClose;
236
+ }
237
+ onClose;
238
+ closed = false;
239
+ close() {
240
+ if (this.closed) return;
241
+ this.closed = true;
242
+ this.onClose();
243
+ this.removeAllListeners();
244
+ }
245
+ /** Yields each maintained book as it becomes available. */
246
+ async *iter() {
247
+ const queue = [];
248
+ let resolveNext = null;
249
+ let pendingError = null;
250
+ let ended = false;
251
+ const onUpdate = (b) => {
252
+ queue.push(b);
253
+ resolveNext?.();
254
+ };
255
+ const onError = (e) => {
256
+ pendingError = e;
257
+ resolveNext?.();
258
+ };
259
+ const onClose = () => {
260
+ ended = true;
261
+ resolveNext?.();
262
+ };
263
+ this.on("update", onUpdate);
264
+ this.on("error", onError);
265
+ this.on("disconnected", onClose);
266
+ try {
267
+ while (true) {
268
+ if (pendingError) throw pendingError;
269
+ const next = queue.shift();
270
+ if (next) {
271
+ yield next;
272
+ continue;
273
+ }
274
+ if (ended || this.closed) return;
275
+ await new Promise((r) => {
276
+ resolveNext = r;
277
+ });
278
+ resolveNext = null;
279
+ }
280
+ } finally {
281
+ this.off("update", onUpdate);
282
+ this.off("error", onError);
283
+ this.off("disconnected", onClose);
284
+ }
285
+ }
286
+ };
287
+
288
+ // src/core/reconnect.ts
289
+ var Backoff = class _Backoff {
290
+ attempt = 0;
291
+ opts;
292
+ constructor(opts) {
293
+ this.opts = opts;
294
+ }
295
+ static withDefaults(opts = {}) {
296
+ return new _Backoff({
297
+ initialMs: opts.initialMs ?? 500,
298
+ maxMs: opts.maxMs ?? 3e4,
299
+ factor: opts.factor ?? 2,
300
+ jitter: opts.jitter ?? 0.3,
301
+ maxAttempts: opts.maxAttempts ?? 0
302
+ });
303
+ }
304
+ next() {
305
+ if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
306
+ return null;
307
+ }
308
+ this.attempt += 1;
309
+ const base = Math.min(
310
+ this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
311
+ this.opts.maxMs
312
+ );
313
+ const jitterRange = base * this.opts.jitter;
314
+ const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
315
+ return { wait, attempt: this.attempt };
316
+ }
317
+ reset() {
318
+ this.attempt = 0;
319
+ }
320
+ };
321
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
322
+
323
+ // src/transport/ws.ts
324
+ function toError(value, fallback = "unknown error") {
325
+ if (value instanceof Error) {
326
+ return value.message ? value : new Error(`${value.name}: ${fallback}`);
327
+ }
328
+ if (typeof value === "string" && value) return new Error(value);
329
+ return new Error(fallback);
330
+ }
331
+ function normalizeWsError(ev) {
332
+ const detail = ev?.message || (ev?.error instanceof Error ? ev.error.message : void 0) || (typeof ev?.error === "string" ? ev.error : void 0);
333
+ return new Error(detail ? `WebSocket error: ${detail}` : "WebSocket error");
334
+ }
335
+ function describeClose(ev) {
336
+ if (ev?.reason) return ev.reason;
337
+ return ev?.code === void 0 ? "closed" : `closed (code ${ev.code})`;
338
+ }
339
+ var cachedCtor = null;
340
+ async function getWebSocketCtor() {
341
+ if (cachedCtor) return cachedCtor;
342
+ if (hasNativeWebSocket) {
343
+ cachedCtor = globalThis.WebSocket;
344
+ return cachedCtor;
345
+ }
346
+ try {
347
+ const mod = await import('ws');
348
+ const ctor = mod.default ?? mod.WebSocket;
349
+ if (!ctor) throw new Error("missing default export");
350
+ cachedCtor = ctor;
351
+ return cachedCtor;
352
+ } catch (err) {
353
+ throw new Error(
354
+ "WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
355
+ );
356
+ }
357
+ }
358
+ var WSClient = class extends TypedEmitter {
359
+ constructor(cfg) {
360
+ super();
361
+ this.cfg = cfg;
362
+ this.backoff = Backoff.withDefaults(cfg.reconnect);
363
+ }
364
+ cfg;
365
+ ws = null;
366
+ backoff;
367
+ closed = false;
368
+ pingTimer = null;
369
+ async connect() {
370
+ if (this.closed) return;
371
+ const WS = await getWebSocketCtor();
372
+ const url = typeof this.cfg.url === "function" ? await this.cfg.url() : this.cfg.url;
373
+ const ws = new WS(url);
374
+ ws.binaryType = "arraybuffer";
375
+ this.ws = ws;
376
+ ws.onopen = async () => {
377
+ this.backoff.reset();
378
+ this.startPing();
379
+ this.emit("open");
380
+ try {
381
+ await this.cfg.onOpen?.({
382
+ send: (d) => ws.send(d),
383
+ close: () => this.close()
384
+ });
385
+ } catch (err) {
386
+ this.emit("error", toError(err, "onOpen handler failed"));
387
+ }
388
+ };
389
+ ws.onmessage = (e) => {
390
+ let result;
391
+ try {
392
+ result = this.cfg.onMessage(e.data);
393
+ } catch (err) {
394
+ this.emit("error", toError(err, "onMessage handler failed"));
395
+ return;
396
+ }
397
+ if (result && typeof result.catch === "function") {
398
+ result.catch(
399
+ (err) => this.emit("error", toError(err, "onMessage handler failed"))
400
+ );
401
+ }
402
+ };
403
+ ws.onerror = (e) => {
404
+ this.emit("error", normalizeWsError(e));
405
+ };
406
+ ws.onclose = (e) => {
407
+ this.stopPing();
408
+ const reason = describeClose(e);
409
+ this.emit("close", reason);
410
+ if (!this.closed) this.scheduleReconnect();
411
+ };
412
+ }
413
+ send(data) {
414
+ this.ws?.send(data);
415
+ }
416
+ close() {
417
+ this.closed = true;
418
+ this.stopPing();
419
+ try {
420
+ this.ws?.close();
421
+ } catch {
422
+ }
423
+ }
424
+ startPing() {
425
+ if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
426
+ this.stopPing();
427
+ this.pingTimer = setInterval(() => {
428
+ try {
429
+ this.ws?.send(this.cfg.pingPayload());
430
+ } catch {
431
+ }
432
+ }, this.cfg.pingIntervalMs);
433
+ }
434
+ stopPing() {
435
+ if (this.pingTimer) {
436
+ clearInterval(this.pingTimer);
437
+ this.pingTimer = null;
438
+ }
439
+ }
440
+ scheduleReconnect() {
441
+ const next = this.backoff.next();
442
+ if (!next) {
443
+ this.emit("error", new Error("max reconnect attempts exceeded"));
444
+ return;
445
+ }
446
+ this.emit("reconnecting", next.attempt, next.wait);
447
+ setTimeout(() => {
448
+ this.connect().catch((e) => this.emit("error", toError(e, "reconnect failed")));
449
+ }, next.wait);
450
+ }
451
+ };
452
+
453
+ // src/exchanges/deribit/ws.ts
454
+ var WS_PUBLIC = "wss://www.deribit.com/ws/api/v2";
455
+ var HEARTBEAT_SECONDS = 30;
456
+ function streamDeribitOrderbook(opts) {
457
+ const instrument = toDeribitSymbol(opts.symbol, opts.market);
458
+ const channel = `book.${instrument}.${opts.interval ?? "100ms"}`;
459
+ const merger = new BookMerger();
460
+ let ws = null;
461
+ let sock = null;
462
+ let recovering = false;
463
+ const stream = new OrderbookStream(() => ws?.close());
464
+ let nextId = 1;
465
+ const subscribeIds = /* @__PURE__ */ new Set();
466
+ const rpc = (method, params) => {
467
+ const id = nextId++;
468
+ sock?.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
469
+ return id;
470
+ };
471
+ const subscribe = () => {
472
+ subscribeIds.add(rpc("public/subscribe", { channels: [channel] }));
473
+ };
474
+ const emit = (r) => {
475
+ const book = {
476
+ exchange: "deribit",
477
+ symbol: fromDeribitSymbol(instrument),
478
+ market: opts.market,
479
+ bids: r.bids,
480
+ asks: r.asks,
481
+ timestamp: r.timestamp,
482
+ sequence: r.sequence
483
+ };
484
+ stream.emit("update", book);
485
+ };
486
+ const resync = () => {
487
+ if (recovering) return;
488
+ recovering = true;
489
+ merger.reset();
490
+ rpc("public/unsubscribe", { channels: [channel] });
491
+ subscribe();
492
+ };
493
+ const toLevels = (entries) => entries.map(([action, price, amount]) => ({
494
+ price,
495
+ size: action === "delete" ? 0 : amount
496
+ }));
497
+ const buildEvent = (d) => {
498
+ const bids = toLevels(d.bids);
499
+ const asks = toLevels(d.asks);
500
+ if (d.type === "snapshot") {
501
+ return {
502
+ kind: "snapshot",
503
+ bids,
504
+ asks,
505
+ sequence: d.change_id,
506
+ timestamp: d.timestamp
507
+ };
508
+ }
509
+ return {
510
+ kind: "delta",
511
+ bids,
512
+ asks,
513
+ sequence: d.change_id,
514
+ prevSequence: d.prev_change_id,
515
+ timestamp: d.timestamp
516
+ };
517
+ };
518
+ const handleData = (d) => {
519
+ if (d.type === "snapshot") recovering = false;
520
+ else if (recovering) return;
521
+ const r = merger.apply(buildEvent(d));
522
+ if (r.ok) {
523
+ emit(r);
524
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
525
+ resync();
526
+ }
527
+ };
528
+ const onMessage = (raw) => {
529
+ if (typeof raw !== "string") return;
530
+ let msg;
531
+ try {
532
+ msg = JSON.parse(raw);
533
+ } catch {
534
+ return;
535
+ }
536
+ if (msg.method === "heartbeat") {
537
+ if (msg.params?.type === "test_request") rpc("public/test", {});
538
+ return;
539
+ }
540
+ if (msg.method === "subscription") {
541
+ if (msg.params?.channel !== channel || !msg.params.data) return;
542
+ handleData(msg.params.data);
543
+ return;
544
+ }
545
+ if (msg.id !== void 0) {
546
+ if (msg.error) {
547
+ stream.emit(
548
+ "error",
549
+ new ExchangeError(
550
+ "deribit",
551
+ `${msg.error.code}: ${msg.error.message}`
552
+ )
553
+ );
554
+ return;
555
+ }
556
+ if (subscribeIds.delete(msg.id)) {
557
+ const channels = Array.isArray(msg.result) ? msg.result : [];
558
+ if (!channels.includes(channel)) {
559
+ stream.emit(
560
+ "error",
561
+ new ExchangeError(
562
+ "deribit",
563
+ `subscribe rejected for "${channel}" \u2014 unknown instrument or interval`
564
+ )
565
+ );
566
+ }
567
+ }
568
+ }
569
+ };
570
+ ws = new WSClient({
571
+ url: WS_PUBLIC,
572
+ onOpen: (handle) => {
573
+ sock = handle;
574
+ merger.reset();
575
+ recovering = false;
576
+ subscribeIds.clear();
577
+ rpc("public/set_heartbeat", { interval: HEARTBEAT_SECONDS });
578
+ subscribe();
579
+ },
580
+ onMessage
581
+ });
582
+ ws.on("open", () => stream.emit("connected"));
583
+ ws.on("close", (r) => stream.emit("disconnected", r));
584
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
585
+ ws.on("error", (e) => stream.emit("error", e));
586
+ ws.connect().catch((e) => stream.emit("error", e));
587
+ return stream;
588
+ }
589
+
590
+ // src/exchanges/deribit/index.ts
591
+ var DeribitClient = class {
592
+ exchange = "deribit";
593
+ transformUrl;
594
+ timeoutMs;
595
+ constructor(opts = {}) {
596
+ this.transformUrl = opts.transformUrl;
597
+ this.timeoutMs = opts.timeoutMs;
598
+ }
599
+ fetchOrderbook(symbol, opts = {}) {
600
+ const { pair, market } = parseSymbol(symbol);
601
+ return fetchDeribitOrderbook({
602
+ symbol: pair,
603
+ market,
604
+ depth: opts.depth,
605
+ timeoutMs: this.timeoutMs,
606
+ transformUrl: this.transformUrl
607
+ });
608
+ }
609
+ streamOrderbook(symbol, opts = {}) {
610
+ const { pair, market } = parseSymbol(symbol);
611
+ return streamDeribitOrderbook({
612
+ symbol: pair,
613
+ market,
614
+ depth: opts.depth,
615
+ transformUrl: this.transformUrl,
616
+ timeoutMs: this.timeoutMs
617
+ });
618
+ }
619
+ };
620
+
621
+ exports.DeribitClient = DeribitClient;
622
+ exports.fetchDeribitOrderbook = fetchDeribitOrderbook;
623
+ exports.streamDeribitOrderbook = streamDeribitOrderbook;
624
+ //# sourceMappingURL=index.cjs.map
625
+ //# sourceMappingURL=index.cjs.map