@xapy/orderbook 0.1.0
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.
- package/README.md +134 -0
- package/dist/exchanges/bingx/index.cjs +559 -0
- package/dist/exchanges/bingx/index.cjs.map +1 -0
- package/dist/exchanges/bingx/index.d.cts +35 -0
- package/dist/exchanges/bingx/index.d.ts +35 -0
- package/dist/exchanges/bingx/index.js +555 -0
- package/dist/exchanges/bingx/index.js.map +1 -0
- package/dist/exchanges/bitget/index.cjs +590 -0
- package/dist/exchanges/bitget/index.cjs.map +1 -0
- package/dist/exchanges/bitget/index.d.cts +30 -0
- package/dist/exchanges/bitget/index.d.ts +30 -0
- package/dist/exchanges/bitget/index.js +586 -0
- package/dist/exchanges/bitget/index.js.map +1 -0
- package/dist/exchanges/bybit/index.cjs +574 -0
- package/dist/exchanges/bybit/index.cjs.map +1 -0
- package/dist/exchanges/bybit/index.d.cts +36 -0
- package/dist/exchanges/bybit/index.d.ts +36 -0
- package/dist/exchanges/bybit/index.js +570 -0
- package/dist/exchanges/bybit/index.js.map +1 -0
- package/dist/exchanges/coinex/index.cjs +563 -0
- package/dist/exchanges/coinex/index.cjs.map +1 -0
- package/dist/exchanges/coinex/index.d.cts +37 -0
- package/dist/exchanges/coinex/index.d.ts +37 -0
- package/dist/exchanges/coinex/index.js +559 -0
- package/dist/exchanges/coinex/index.js.map +1 -0
- package/dist/exchanges/gate/index.cjs +634 -0
- package/dist/exchanges/gate/index.cjs.map +1 -0
- package/dist/exchanges/gate/index.d.cts +45 -0
- package/dist/exchanges/gate/index.d.ts +45 -0
- package/dist/exchanges/gate/index.js +630 -0
- package/dist/exchanges/gate/index.js.map +1 -0
- package/dist/exchanges/huobi/index.cjs +573 -0
- package/dist/exchanges/huobi/index.cjs.map +1 -0
- package/dist/exchanges/huobi/index.d.cts +37 -0
- package/dist/exchanges/huobi/index.d.ts +37 -0
- package/dist/exchanges/huobi/index.js +569 -0
- package/dist/exchanges/huobi/index.js.map +1 -0
- package/dist/exchanges/okx/index.cjs +579 -0
- package/dist/exchanges/okx/index.cjs.map +1 -0
- package/dist/exchanges/okx/index.d.cts +37 -0
- package/dist/exchanges/okx/index.d.ts +37 -0
- package/dist/exchanges/okx/index.js +575 -0
- package/dist/exchanges/okx/index.js.map +1 -0
- package/dist/index.cjs +1744 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +101 -0
- package/dist/index.d.ts +101 -0
- package/dist/index.js +1729 -0
- package/dist/index.js.map +1 -0
- package/dist/stream-BKpWmRYN.d.cts +86 -0
- package/dist/stream-BKpWmRYN.d.ts +86 -0
- package/package.json +133 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1744 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/core/errors.ts
|
|
4
|
+
var ExchangeError = class extends Error {
|
|
5
|
+
constructor(exchange, message, cause) {
|
|
6
|
+
super(
|
|
7
|
+
`[${exchange}] ${message}`,
|
|
8
|
+
cause === void 0 ? void 0 : { cause }
|
|
9
|
+
);
|
|
10
|
+
this.exchange = exchange;
|
|
11
|
+
this.name = "ExchangeError";
|
|
12
|
+
}
|
|
13
|
+
exchange;
|
|
14
|
+
};
|
|
15
|
+
var RateLimitError = class extends ExchangeError {
|
|
16
|
+
constructor(exchange, message = "rate limited") {
|
|
17
|
+
super(exchange, message);
|
|
18
|
+
this.name = "RateLimitError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var SequenceGapError = class extends Error {
|
|
22
|
+
constructor(expected, received) {
|
|
23
|
+
super(`sequence gap: expected ${expected}, received ${received}`);
|
|
24
|
+
this.expected = expected;
|
|
25
|
+
this.received = received;
|
|
26
|
+
this.name = "SequenceGapError";
|
|
27
|
+
}
|
|
28
|
+
expected;
|
|
29
|
+
received;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/core/book-merger.ts
|
|
33
|
+
var BookMerger = class {
|
|
34
|
+
bids = /* @__PURE__ */ new Map();
|
|
35
|
+
// price -> size
|
|
36
|
+
asks = /* @__PURE__ */ new Map();
|
|
37
|
+
sequence = -1;
|
|
38
|
+
timestamp = 0;
|
|
39
|
+
hasSnapshot = false;
|
|
40
|
+
apply(event) {
|
|
41
|
+
if (event.kind === "snapshot") {
|
|
42
|
+
this.bids.clear();
|
|
43
|
+
this.asks.clear();
|
|
44
|
+
for (const { price, size } of event.bids) {
|
|
45
|
+
if (size > 0) this.bids.set(price, size);
|
|
46
|
+
}
|
|
47
|
+
for (const { price, size } of event.asks) {
|
|
48
|
+
if (size > 0) this.asks.set(price, size);
|
|
49
|
+
}
|
|
50
|
+
this.sequence = event.sequence;
|
|
51
|
+
this.timestamp = event.timestamp;
|
|
52
|
+
this.hasSnapshot = true;
|
|
53
|
+
return this.emit();
|
|
54
|
+
}
|
|
55
|
+
if (!this.hasSnapshot) {
|
|
56
|
+
return { ok: false, reason: "no-snapshot" };
|
|
57
|
+
}
|
|
58
|
+
if (event.sequence <= this.sequence) {
|
|
59
|
+
return this.emit();
|
|
60
|
+
}
|
|
61
|
+
if (event.prevSequence !== void 0) {
|
|
62
|
+
if (event.prevSequence !== this.sequence) {
|
|
63
|
+
return {
|
|
64
|
+
ok: false,
|
|
65
|
+
reason: "gap",
|
|
66
|
+
expected: this.sequence,
|
|
67
|
+
received: event.prevSequence
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
} else if (event.sequence !== this.sequence + 1) {
|
|
71
|
+
return {
|
|
72
|
+
ok: false,
|
|
73
|
+
reason: "gap",
|
|
74
|
+
expected: this.sequence + 1,
|
|
75
|
+
received: event.sequence
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
for (const { price, size } of event.bids) {
|
|
79
|
+
if (size === 0) this.bids.delete(price);
|
|
80
|
+
else this.bids.set(price, size);
|
|
81
|
+
}
|
|
82
|
+
for (const { price, size } of event.asks) {
|
|
83
|
+
if (size === 0) this.asks.delete(price);
|
|
84
|
+
else this.asks.set(price, size);
|
|
85
|
+
}
|
|
86
|
+
this.sequence = event.sequence;
|
|
87
|
+
this.timestamp = event.timestamp;
|
|
88
|
+
return this.emit();
|
|
89
|
+
}
|
|
90
|
+
reset() {
|
|
91
|
+
this.bids.clear();
|
|
92
|
+
this.asks.clear();
|
|
93
|
+
this.sequence = -1;
|
|
94
|
+
this.timestamp = 0;
|
|
95
|
+
this.hasSnapshot = false;
|
|
96
|
+
}
|
|
97
|
+
/** Returns true once the merger has a usable book. */
|
|
98
|
+
isReady() {
|
|
99
|
+
return this.hasSnapshot;
|
|
100
|
+
}
|
|
101
|
+
emit() {
|
|
102
|
+
const bids = [];
|
|
103
|
+
for (const [price, size] of this.bids) bids.push({ price, size });
|
|
104
|
+
bids.sort((a, b) => b.price - a.price);
|
|
105
|
+
const asks = [];
|
|
106
|
+
for (const [price, size] of this.asks) asks.push({ price, size });
|
|
107
|
+
asks.sort((a, b) => a.price - b.price);
|
|
108
|
+
return {
|
|
109
|
+
ok: true,
|
|
110
|
+
bids,
|
|
111
|
+
asks,
|
|
112
|
+
sequence: this.sequence,
|
|
113
|
+
timestamp: this.timestamp
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// src/core/event-emitter.ts
|
|
119
|
+
var TypedEmitter = class {
|
|
120
|
+
listeners = /* @__PURE__ */ new Map();
|
|
121
|
+
on(event, fn) {
|
|
122
|
+
let set = this.listeners.get(event);
|
|
123
|
+
if (!set) {
|
|
124
|
+
set = /* @__PURE__ */ new Set();
|
|
125
|
+
this.listeners.set(event, set);
|
|
126
|
+
}
|
|
127
|
+
set.add(fn);
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
off(event, fn) {
|
|
131
|
+
this.listeners.get(event)?.delete(fn);
|
|
132
|
+
return this;
|
|
133
|
+
}
|
|
134
|
+
emit(event, ...args) {
|
|
135
|
+
const set = this.listeners.get(event);
|
|
136
|
+
if (!set || set.size === 0) return false;
|
|
137
|
+
for (const fn of set) fn(...args);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
removeAllListeners() {
|
|
141
|
+
this.listeners.clear();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/core/stream.ts
|
|
146
|
+
var OrderbookStream = class extends TypedEmitter {
|
|
147
|
+
constructor(onClose) {
|
|
148
|
+
super();
|
|
149
|
+
this.onClose = onClose;
|
|
150
|
+
}
|
|
151
|
+
onClose;
|
|
152
|
+
closed = false;
|
|
153
|
+
close() {
|
|
154
|
+
if (this.closed) return;
|
|
155
|
+
this.closed = true;
|
|
156
|
+
this.onClose();
|
|
157
|
+
this.removeAllListeners();
|
|
158
|
+
}
|
|
159
|
+
/** Yields each maintained book as it becomes available. */
|
|
160
|
+
async *iter() {
|
|
161
|
+
const queue = [];
|
|
162
|
+
let resolveNext = null;
|
|
163
|
+
let pendingError = null;
|
|
164
|
+
let ended = false;
|
|
165
|
+
const onUpdate = (b) => {
|
|
166
|
+
queue.push(b);
|
|
167
|
+
resolveNext?.();
|
|
168
|
+
};
|
|
169
|
+
const onError = (e) => {
|
|
170
|
+
pendingError = e;
|
|
171
|
+
resolveNext?.();
|
|
172
|
+
};
|
|
173
|
+
const onClose = () => {
|
|
174
|
+
ended = true;
|
|
175
|
+
resolveNext?.();
|
|
176
|
+
};
|
|
177
|
+
this.on("update", onUpdate);
|
|
178
|
+
this.on("error", onError);
|
|
179
|
+
this.on("disconnected", onClose);
|
|
180
|
+
try {
|
|
181
|
+
while (true) {
|
|
182
|
+
if (pendingError) throw pendingError;
|
|
183
|
+
const next = queue.shift();
|
|
184
|
+
if (next) {
|
|
185
|
+
yield next;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (ended || this.closed) return;
|
|
189
|
+
await new Promise((r) => {
|
|
190
|
+
resolveNext = r;
|
|
191
|
+
});
|
|
192
|
+
resolveNext = null;
|
|
193
|
+
}
|
|
194
|
+
} finally {
|
|
195
|
+
this.off("update", onUpdate);
|
|
196
|
+
this.off("error", onError);
|
|
197
|
+
this.off("disconnected", onClose);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// src/core/reconnect.ts
|
|
203
|
+
var Backoff = class _Backoff {
|
|
204
|
+
attempt = 0;
|
|
205
|
+
opts;
|
|
206
|
+
constructor(opts) {
|
|
207
|
+
this.opts = opts;
|
|
208
|
+
}
|
|
209
|
+
static withDefaults(opts = {}) {
|
|
210
|
+
return new _Backoff({
|
|
211
|
+
initialMs: opts.initialMs ?? 500,
|
|
212
|
+
maxMs: opts.maxMs ?? 3e4,
|
|
213
|
+
factor: opts.factor ?? 2,
|
|
214
|
+
jitter: opts.jitter ?? 0.3,
|
|
215
|
+
maxAttempts: opts.maxAttempts ?? 0
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
next() {
|
|
219
|
+
if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
this.attempt += 1;
|
|
223
|
+
const base = Math.min(
|
|
224
|
+
this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
|
|
225
|
+
this.opts.maxMs
|
|
226
|
+
);
|
|
227
|
+
const jitterRange = base * this.opts.jitter;
|
|
228
|
+
const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
|
|
229
|
+
return { wait, attempt: this.attempt };
|
|
230
|
+
}
|
|
231
|
+
reset() {
|
|
232
|
+
this.attempt = 0;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// src/core/symbol.ts
|
|
237
|
+
function parseSymbol(symbol) {
|
|
238
|
+
const [pair, settle] = symbol.split(":");
|
|
239
|
+
const parts = (pair ?? "").split("/");
|
|
240
|
+
const base = parts[0]?.toUpperCase();
|
|
241
|
+
const quote = parts[1]?.toUpperCase();
|
|
242
|
+
if (!base || !quote) {
|
|
243
|
+
throw new Error(
|
|
244
|
+
`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
if (settle && settle.toUpperCase() !== quote) {
|
|
248
|
+
throw new Error(
|
|
249
|
+
`unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
return {
|
|
253
|
+
base,
|
|
254
|
+
quote,
|
|
255
|
+
market: settle ? "perpetual" : "spot",
|
|
256
|
+
pair: `${base}/${quote}`
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// src/transport/http.ts
|
|
261
|
+
async function httpJson(req) {
|
|
262
|
+
const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
|
|
263
|
+
const controller = new AbortController();
|
|
264
|
+
const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
|
|
265
|
+
try {
|
|
266
|
+
const res = await fetch(url, {
|
|
267
|
+
method: req.method ?? "GET",
|
|
268
|
+
headers: req.headers,
|
|
269
|
+
body: req.body,
|
|
270
|
+
signal: controller.signal
|
|
271
|
+
});
|
|
272
|
+
if (!res.ok) {
|
|
273
|
+
const text = await res.text().catch(() => "");
|
|
274
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
|
|
275
|
+
}
|
|
276
|
+
return await res.json();
|
|
277
|
+
} finally {
|
|
278
|
+
clearTimeout(timer);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/exchanges/bybit/symbols.ts
|
|
283
|
+
var QUOTES = ["USDT", "USDC", "USD"];
|
|
284
|
+
function toBybitSymbol(symbol) {
|
|
285
|
+
const [base, quote] = symbol.split("/");
|
|
286
|
+
if (!base || !quote) {
|
|
287
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
288
|
+
}
|
|
289
|
+
return `${base}${quote}`.toUpperCase();
|
|
290
|
+
}
|
|
291
|
+
function fromBybitSymbol(s) {
|
|
292
|
+
const upper = s.toUpperCase();
|
|
293
|
+
for (const q of QUOTES) {
|
|
294
|
+
if (upper.endsWith(q)) {
|
|
295
|
+
return `${upper.slice(0, -q.length)}/${q}`;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return upper;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/exchanges/bybit/rest.ts
|
|
302
|
+
var BASE = "https://api.bybit.com";
|
|
303
|
+
async function fetchBybitOrderbook(opts) {
|
|
304
|
+
const category = opts.market === "spot" ? "spot" : "linear";
|
|
305
|
+
const limit = opts.depth ?? 50;
|
|
306
|
+
const url = `${BASE}/v5/market/orderbook?category=${category}&symbol=${toBybitSymbol(opts.symbol)}&limit=${limit}`;
|
|
307
|
+
const res = await httpJson({
|
|
308
|
+
url,
|
|
309
|
+
timeoutMs: opts.timeoutMs,
|
|
310
|
+
transformUrl: opts.transformUrl
|
|
311
|
+
});
|
|
312
|
+
if (res.retCode !== 0) {
|
|
313
|
+
throw new ExchangeError("bybit", `${res.retCode}: ${res.retMsg}`);
|
|
314
|
+
}
|
|
315
|
+
return {
|
|
316
|
+
exchange: "bybit",
|
|
317
|
+
symbol: fromBybitSymbol(res.result.s),
|
|
318
|
+
market: opts.market,
|
|
319
|
+
bids: res.result.b.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
320
|
+
asks: res.result.a.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
321
|
+
timestamp: res.result.ts,
|
|
322
|
+
sequence: res.result.u
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
|
|
326
|
+
|
|
327
|
+
// src/transport/ws.ts
|
|
328
|
+
var cachedCtor = null;
|
|
329
|
+
async function getWebSocketCtor() {
|
|
330
|
+
if (cachedCtor) return cachedCtor;
|
|
331
|
+
if (hasNativeWebSocket) {
|
|
332
|
+
cachedCtor = globalThis.WebSocket;
|
|
333
|
+
return cachedCtor;
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
const mod = await import('ws');
|
|
337
|
+
const ctor = mod.default ?? mod.WebSocket;
|
|
338
|
+
if (!ctor) throw new Error("missing default export");
|
|
339
|
+
cachedCtor = ctor;
|
|
340
|
+
return cachedCtor;
|
|
341
|
+
} catch (err) {
|
|
342
|
+
throw new Error(
|
|
343
|
+
"WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
var WSClient = class extends TypedEmitter {
|
|
348
|
+
constructor(cfg) {
|
|
349
|
+
super();
|
|
350
|
+
this.cfg = cfg;
|
|
351
|
+
this.backoff = Backoff.withDefaults(cfg.reconnect);
|
|
352
|
+
}
|
|
353
|
+
cfg;
|
|
354
|
+
ws = null;
|
|
355
|
+
backoff;
|
|
356
|
+
closed = false;
|
|
357
|
+
pingTimer = null;
|
|
358
|
+
async connect() {
|
|
359
|
+
if (this.closed) return;
|
|
360
|
+
const WS = await getWebSocketCtor();
|
|
361
|
+
const ws = new WS(this.cfg.url);
|
|
362
|
+
ws.binaryType = "arraybuffer";
|
|
363
|
+
this.ws = ws;
|
|
364
|
+
ws.onopen = async () => {
|
|
365
|
+
this.backoff.reset();
|
|
366
|
+
this.startPing();
|
|
367
|
+
this.emit("open");
|
|
368
|
+
try {
|
|
369
|
+
await this.cfg.onOpen?.({
|
|
370
|
+
send: (d) => ws.send(d),
|
|
371
|
+
close: () => this.close()
|
|
372
|
+
});
|
|
373
|
+
} catch (err) {
|
|
374
|
+
this.emit("error", err);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
ws.onmessage = (e) => {
|
|
378
|
+
let result;
|
|
379
|
+
try {
|
|
380
|
+
result = this.cfg.onMessage(e.data);
|
|
381
|
+
} catch (err) {
|
|
382
|
+
this.emit("error", err);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (result && typeof result.catch === "function") {
|
|
386
|
+
result.catch(
|
|
387
|
+
(err) => this.emit("error", err)
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
ws.onerror = (e) => {
|
|
392
|
+
this.emit("error", new Error(e?.message ?? "WebSocket error"));
|
|
393
|
+
};
|
|
394
|
+
ws.onclose = (e) => {
|
|
395
|
+
this.stopPing();
|
|
396
|
+
const reason = e?.reason ?? "closed";
|
|
397
|
+
this.emit("close", reason);
|
|
398
|
+
if (!this.closed) this.scheduleReconnect();
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
send(data) {
|
|
402
|
+
this.ws?.send(data);
|
|
403
|
+
}
|
|
404
|
+
close() {
|
|
405
|
+
this.closed = true;
|
|
406
|
+
this.stopPing();
|
|
407
|
+
try {
|
|
408
|
+
this.ws?.close();
|
|
409
|
+
} catch {
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
startPing() {
|
|
413
|
+
if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
|
|
414
|
+
this.stopPing();
|
|
415
|
+
this.pingTimer = setInterval(() => {
|
|
416
|
+
try {
|
|
417
|
+
this.ws?.send(this.cfg.pingPayload());
|
|
418
|
+
} catch {
|
|
419
|
+
}
|
|
420
|
+
}, this.cfg.pingIntervalMs);
|
|
421
|
+
}
|
|
422
|
+
stopPing() {
|
|
423
|
+
if (this.pingTimer) {
|
|
424
|
+
clearInterval(this.pingTimer);
|
|
425
|
+
this.pingTimer = null;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
scheduleReconnect() {
|
|
429
|
+
const next = this.backoff.next();
|
|
430
|
+
if (!next) {
|
|
431
|
+
this.emit("error", new Error("max reconnect attempts exceeded"));
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
this.emit("reconnecting", next.attempt, next.wait);
|
|
435
|
+
setTimeout(() => {
|
|
436
|
+
this.connect().catch((e) => this.emit("error", e));
|
|
437
|
+
}, next.wait);
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
// src/exchanges/bybit/ws.ts
|
|
442
|
+
var WS_SPOT = "wss://stream.bybit.com/v5/public/spot";
|
|
443
|
+
var WS_LINEAR = "wss://stream.bybit.com/v5/public/linear";
|
|
444
|
+
function streamBybitOrderbook(opts) {
|
|
445
|
+
const wsUrl = opts.market === "spot" ? WS_SPOT : WS_LINEAR;
|
|
446
|
+
const depth = opts.depth ?? 50;
|
|
447
|
+
const bybitSymbol = toBybitSymbol(opts.symbol);
|
|
448
|
+
const topic = `orderbook.${depth}.${bybitSymbol}`;
|
|
449
|
+
const merger = new BookMerger();
|
|
450
|
+
let recovering = false;
|
|
451
|
+
let ws = null;
|
|
452
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
453
|
+
const handleMergeResult = (data, timestamp) => {
|
|
454
|
+
const r = merger.apply(buildEvent(
|
|
455
|
+
data,
|
|
456
|
+
timestamp,
|
|
457
|
+
/*isSnapshot*/
|
|
458
|
+
false
|
|
459
|
+
));
|
|
460
|
+
if (r.ok) {
|
|
461
|
+
stream.emit("update", buildBook(opts, data.s, r));
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (r.reason === "no-snapshot" || r.reason === "gap") {
|
|
465
|
+
triggerResnapshot();
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
const triggerResnapshot = () => {
|
|
469
|
+
if (recovering) return;
|
|
470
|
+
recovering = true;
|
|
471
|
+
merger.reset();
|
|
472
|
+
fetchBybitOrderbook({
|
|
473
|
+
symbol: opts.symbol,
|
|
474
|
+
market: opts.market,
|
|
475
|
+
depth,
|
|
476
|
+
timeoutMs: opts.timeoutMs,
|
|
477
|
+
transformUrl: opts.transformUrl
|
|
478
|
+
}).then((snap) => {
|
|
479
|
+
const r = merger.apply({
|
|
480
|
+
kind: "snapshot",
|
|
481
|
+
bids: snap.bids,
|
|
482
|
+
asks: snap.asks,
|
|
483
|
+
sequence: snap.sequence,
|
|
484
|
+
timestamp: snap.timestamp
|
|
485
|
+
});
|
|
486
|
+
if (r.ok) {
|
|
487
|
+
stream.emit("update", { ...snap, bids: r.bids, asks: r.asks });
|
|
488
|
+
}
|
|
489
|
+
}).catch((err) => stream.emit("error", err)).finally(() => {
|
|
490
|
+
recovering = false;
|
|
491
|
+
});
|
|
492
|
+
};
|
|
493
|
+
const onMessage = (raw) => {
|
|
494
|
+
if (typeof raw !== "string") return;
|
|
495
|
+
let msg;
|
|
496
|
+
try {
|
|
497
|
+
msg = JSON.parse(raw);
|
|
498
|
+
} catch {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (msg.op === "ping" || msg.op === "pong") return;
|
|
502
|
+
if (msg.op === "subscribe") return;
|
|
503
|
+
if (!msg.topic || msg.topic !== topic || !msg.data) return;
|
|
504
|
+
const ts = msg.ts ?? Date.now();
|
|
505
|
+
const data = msg.data;
|
|
506
|
+
if (msg.type === "snapshot") {
|
|
507
|
+
const r = merger.apply(buildEvent(
|
|
508
|
+
data,
|
|
509
|
+
ts,
|
|
510
|
+
/*isSnapshot*/
|
|
511
|
+
true
|
|
512
|
+
));
|
|
513
|
+
if (r.ok) stream.emit("update", buildBook(opts, data.s, r));
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
handleMergeResult(data, ts);
|
|
517
|
+
};
|
|
518
|
+
ws = new WSClient({
|
|
519
|
+
url: wsUrl,
|
|
520
|
+
onOpen: (sock) => {
|
|
521
|
+
merger.reset();
|
|
522
|
+
sock.send(JSON.stringify({ op: "subscribe", args: [topic] }));
|
|
523
|
+
},
|
|
524
|
+
onMessage,
|
|
525
|
+
pingIntervalMs: 2e4,
|
|
526
|
+
pingPayload: () => JSON.stringify({ op: "ping" })
|
|
527
|
+
});
|
|
528
|
+
ws.on("open", () => stream.emit("connected"));
|
|
529
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
530
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
531
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
532
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
533
|
+
return stream;
|
|
534
|
+
}
|
|
535
|
+
function buildEvent(data, timestamp, isSnapshot) {
|
|
536
|
+
const bids = data.b.map(([p, s]) => ({ price: Number(p), size: Number(s) }));
|
|
537
|
+
const asks = data.a.map(([p, s]) => ({ price: Number(p), size: Number(s) }));
|
|
538
|
+
if (isSnapshot) {
|
|
539
|
+
return { kind: "snapshot", bids, asks, sequence: data.u, timestamp };
|
|
540
|
+
}
|
|
541
|
+
return { kind: "delta", bids, asks, sequence: data.u, timestamp };
|
|
542
|
+
}
|
|
543
|
+
function buildBook(opts, rawSymbol, merged) {
|
|
544
|
+
return {
|
|
545
|
+
exchange: "bybit",
|
|
546
|
+
symbol: fromBybitSymbol(rawSymbol),
|
|
547
|
+
market: opts.market,
|
|
548
|
+
bids: merged.bids,
|
|
549
|
+
asks: merged.asks,
|
|
550
|
+
timestamp: merged.timestamp,
|
|
551
|
+
sequence: merged.sequence
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// src/exchanges/bybit/index.ts
|
|
556
|
+
var BybitClient = class {
|
|
557
|
+
exchange = "bybit";
|
|
558
|
+
transformUrl;
|
|
559
|
+
timeoutMs;
|
|
560
|
+
constructor(opts = {}) {
|
|
561
|
+
this.transformUrl = opts.transformUrl;
|
|
562
|
+
this.timeoutMs = opts.timeoutMs;
|
|
563
|
+
}
|
|
564
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
565
|
+
const { pair, market } = parseSymbol(symbol);
|
|
566
|
+
return fetchBybitOrderbook({
|
|
567
|
+
symbol: pair,
|
|
568
|
+
market,
|
|
569
|
+
depth: opts.depth,
|
|
570
|
+
timeoutMs: this.timeoutMs,
|
|
571
|
+
transformUrl: this.transformUrl
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
streamOrderbook(symbol, opts = {}) {
|
|
575
|
+
const { pair, market } = parseSymbol(symbol);
|
|
576
|
+
return streamBybitOrderbook({
|
|
577
|
+
symbol: pair,
|
|
578
|
+
market,
|
|
579
|
+
depth: opts.depth,
|
|
580
|
+
transformUrl: this.transformUrl,
|
|
581
|
+
timeoutMs: this.timeoutMs
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
// src/exchanges/bitget/symbols.ts
|
|
587
|
+
var QUOTES2 = ["USDT", "USDC", "USD"];
|
|
588
|
+
function toBitgetSymbol(symbol) {
|
|
589
|
+
const [base, quote] = symbol.split("/");
|
|
590
|
+
if (!base || !quote) {
|
|
591
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
592
|
+
}
|
|
593
|
+
return `${base}${quote}`.toUpperCase();
|
|
594
|
+
}
|
|
595
|
+
function fromBitgetSymbol(s) {
|
|
596
|
+
const upper = s.toUpperCase();
|
|
597
|
+
for (const q of QUOTES2) {
|
|
598
|
+
if (upper.endsWith(q)) {
|
|
599
|
+
return `${upper.slice(0, -q.length)}/${q}`;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return upper;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// src/exchanges/bitget/rest.ts
|
|
606
|
+
var BASE2 = "https://api.bitget.com";
|
|
607
|
+
async function fetchBitgetOrderbook(opts) {
|
|
608
|
+
const symbol = toBitgetSymbol(opts.symbol);
|
|
609
|
+
const limit = opts.depth ?? 50;
|
|
610
|
+
const url = opts.market === "spot" ? `${BASE2}/api/v2/spot/market/orderbook?symbol=${symbol}&limit=${limit}` : `${BASE2}/api/v2/mix/market/merge-depth?symbol=${symbol}&productType=USDT-FUTURES&limit=${limit}`;
|
|
611
|
+
const res = await httpJson({
|
|
612
|
+
url,
|
|
613
|
+
timeoutMs: opts.timeoutMs,
|
|
614
|
+
transformUrl: opts.transformUrl
|
|
615
|
+
});
|
|
616
|
+
if (res.code !== "00000") {
|
|
617
|
+
throw new ExchangeError("bitget", `${res.code}: ${res.msg}`);
|
|
618
|
+
}
|
|
619
|
+
const ts = Number(res.data.ts);
|
|
620
|
+
return {
|
|
621
|
+
exchange: "bitget",
|
|
622
|
+
symbol: fromBitgetSymbol(symbol),
|
|
623
|
+
market: opts.market,
|
|
624
|
+
bids: res.data.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
625
|
+
asks: res.data.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
626
|
+
timestamp: ts,
|
|
627
|
+
sequence: ts
|
|
628
|
+
// REST endpoint doesn't expose a seq; ts is monotonic in practice
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// src/exchanges/bitget/ws.ts
|
|
633
|
+
var WS_PUBLIC = "wss://ws.bitget.com/v2/ws/public";
|
|
634
|
+
function streamBitgetOrderbook(opts) {
|
|
635
|
+
const bitgetSymbol = toBitgetSymbol(opts.symbol);
|
|
636
|
+
const instType = opts.market === "spot" ? "SPOT" : "USDT-FUTURES";
|
|
637
|
+
const channel = "books";
|
|
638
|
+
const merger = new BookMerger();
|
|
639
|
+
let lastSeq = -1;
|
|
640
|
+
let recovering = false;
|
|
641
|
+
let ws = null;
|
|
642
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
643
|
+
const subscribePayload = JSON.stringify({
|
|
644
|
+
op: "subscribe",
|
|
645
|
+
args: [{ instType, channel, instId: bitgetSymbol }]
|
|
646
|
+
});
|
|
647
|
+
const handleEntry = (entry, isSnapshot) => {
|
|
648
|
+
const ts = Number(entry.ts);
|
|
649
|
+
const sequence = entry.seq ?? ts;
|
|
650
|
+
const event = isSnapshot ? {
|
|
651
|
+
kind: "snapshot",
|
|
652
|
+
bids: entry.bids.map(([p, s]) => ({
|
|
653
|
+
price: Number(p),
|
|
654
|
+
size: Number(s)
|
|
655
|
+
})),
|
|
656
|
+
asks: entry.asks.map(([p, s]) => ({
|
|
657
|
+
price: Number(p),
|
|
658
|
+
size: Number(s)
|
|
659
|
+
})),
|
|
660
|
+
sequence,
|
|
661
|
+
timestamp: ts
|
|
662
|
+
} : {
|
|
663
|
+
kind: "delta",
|
|
664
|
+
bids: entry.bids.map(([p, s]) => ({
|
|
665
|
+
price: Number(p),
|
|
666
|
+
size: Number(s)
|
|
667
|
+
})),
|
|
668
|
+
asks: entry.asks.map(([p, s]) => ({
|
|
669
|
+
price: Number(p),
|
|
670
|
+
size: Number(s)
|
|
671
|
+
})),
|
|
672
|
+
// bitget doesn't publish prevSeq; pass it ourselves so merger checks
|
|
673
|
+
// consecutive ordering without assuming the seq jumps by exactly 1.
|
|
674
|
+
prevSequence: lastSeq >= 0 ? lastSeq : void 0,
|
|
675
|
+
sequence,
|
|
676
|
+
timestamp: ts
|
|
677
|
+
};
|
|
678
|
+
const r = merger.apply(event);
|
|
679
|
+
if (r.ok) {
|
|
680
|
+
lastSeq = r.sequence;
|
|
681
|
+
stream.emit("update", {
|
|
682
|
+
exchange: "bitget",
|
|
683
|
+
symbol: fromBitgetSymbol(bitgetSymbol),
|
|
684
|
+
market: opts.market,
|
|
685
|
+
bids: r.bids,
|
|
686
|
+
asks: r.asks,
|
|
687
|
+
timestamp: r.timestamp,
|
|
688
|
+
sequence: r.sequence
|
|
689
|
+
});
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
if (r.reason === "no-snapshot" || r.reason === "gap") {
|
|
693
|
+
triggerResnapshot();
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
const triggerResnapshot = () => {
|
|
697
|
+
if (recovering) return;
|
|
698
|
+
recovering = true;
|
|
699
|
+
merger.reset();
|
|
700
|
+
lastSeq = -1;
|
|
701
|
+
fetchBitgetOrderbook({
|
|
702
|
+
symbol: opts.symbol,
|
|
703
|
+
market: opts.market,
|
|
704
|
+
depth: opts.depth,
|
|
705
|
+
timeoutMs: opts.timeoutMs,
|
|
706
|
+
transformUrl: opts.transformUrl
|
|
707
|
+
}).then((snap) => {
|
|
708
|
+
const r = merger.apply({
|
|
709
|
+
kind: "snapshot",
|
|
710
|
+
bids: snap.bids,
|
|
711
|
+
asks: snap.asks,
|
|
712
|
+
sequence: snap.sequence,
|
|
713
|
+
timestamp: snap.timestamp
|
|
714
|
+
});
|
|
715
|
+
if (r.ok) {
|
|
716
|
+
lastSeq = r.sequence;
|
|
717
|
+
stream.emit("update", { ...snap, bids: r.bids, asks: r.asks });
|
|
718
|
+
}
|
|
719
|
+
}).catch((err) => stream.emit("error", err)).finally(() => {
|
|
720
|
+
recovering = false;
|
|
721
|
+
});
|
|
722
|
+
};
|
|
723
|
+
const onMessage = (raw) => {
|
|
724
|
+
if (typeof raw !== "string") return;
|
|
725
|
+
if (raw === "pong") return;
|
|
726
|
+
let msg;
|
|
727
|
+
try {
|
|
728
|
+
msg = JSON.parse(raw);
|
|
729
|
+
} catch {
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
if (msg.event === "subscribe" || msg.event === "error") return;
|
|
733
|
+
if (!msg.action || !msg.data?.length) return;
|
|
734
|
+
if (msg.arg?.channel !== channel || msg.arg?.instId !== bitgetSymbol) return;
|
|
735
|
+
const isSnapshot = msg.action === "snapshot";
|
|
736
|
+
for (const entry of msg.data) {
|
|
737
|
+
handleEntry(entry, isSnapshot);
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
ws = new WSClient({
|
|
741
|
+
url: WS_PUBLIC,
|
|
742
|
+
onOpen: (sock) => {
|
|
743
|
+
merger.reset();
|
|
744
|
+
lastSeq = -1;
|
|
745
|
+
sock.send(subscribePayload);
|
|
746
|
+
},
|
|
747
|
+
onMessage,
|
|
748
|
+
pingIntervalMs: 25e3,
|
|
749
|
+
// bitget idle-closes at 30s
|
|
750
|
+
pingPayload: () => "ping"
|
|
751
|
+
});
|
|
752
|
+
ws.on("open", () => stream.emit("connected"));
|
|
753
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
754
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
755
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
756
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
757
|
+
return stream;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// src/exchanges/bitget/index.ts
|
|
761
|
+
var BitgetClient = class {
|
|
762
|
+
exchange = "bitget";
|
|
763
|
+
transformUrl;
|
|
764
|
+
timeoutMs;
|
|
765
|
+
constructor(opts = {}) {
|
|
766
|
+
this.transformUrl = opts.transformUrl;
|
|
767
|
+
this.timeoutMs = opts.timeoutMs;
|
|
768
|
+
}
|
|
769
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
770
|
+
const { pair, market } = parseSymbol(symbol);
|
|
771
|
+
return fetchBitgetOrderbook({
|
|
772
|
+
symbol: pair,
|
|
773
|
+
market,
|
|
774
|
+
depth: opts.depth,
|
|
775
|
+
timeoutMs: this.timeoutMs,
|
|
776
|
+
transformUrl: this.transformUrl
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
streamOrderbook(symbol, opts = {}) {
|
|
780
|
+
const { pair, market } = parseSymbol(symbol);
|
|
781
|
+
return streamBitgetOrderbook({
|
|
782
|
+
symbol: pair,
|
|
783
|
+
market,
|
|
784
|
+
depth: opts.depth,
|
|
785
|
+
transformUrl: this.transformUrl,
|
|
786
|
+
timeoutMs: this.timeoutMs
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
|
|
791
|
+
// src/exchanges/gate/symbols.ts
|
|
792
|
+
function toGateSymbol(symbol) {
|
|
793
|
+
const [base, quote] = symbol.split("/");
|
|
794
|
+
if (!base || !quote) {
|
|
795
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
796
|
+
}
|
|
797
|
+
return `${base}_${quote}`.toUpperCase();
|
|
798
|
+
}
|
|
799
|
+
function fromGateSymbol(s) {
|
|
800
|
+
return s.toUpperCase().replace("_", "/");
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// src/exchanges/gate/rest.ts
|
|
804
|
+
var BASE3 = "https://api.gateio.ws";
|
|
805
|
+
async function fetchGateOrderbook(opts) {
|
|
806
|
+
const symbol = toGateSymbol(opts.symbol);
|
|
807
|
+
const limit = opts.depth ?? 50;
|
|
808
|
+
if (opts.market === "spot") {
|
|
809
|
+
const url2 = `${BASE3}/api/v4/spot/order_book?currency_pair=${symbol}&limit=${limit}&with_id=true`;
|
|
810
|
+
const data2 = await httpJson({
|
|
811
|
+
url: url2,
|
|
812
|
+
timeoutMs: opts.timeoutMs,
|
|
813
|
+
transformUrl: opts.transformUrl
|
|
814
|
+
});
|
|
815
|
+
return {
|
|
816
|
+
exchange: "gate",
|
|
817
|
+
symbol: fromGateSymbol(symbol),
|
|
818
|
+
market: "spot",
|
|
819
|
+
bids: parseArrayLevels(data2.bids),
|
|
820
|
+
asks: parseArrayLevels(data2.asks),
|
|
821
|
+
timestamp: data2.update,
|
|
822
|
+
sequence: data2.id
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
const url = `${BASE3}/api/v4/futures/usdt/order_book?contract=${symbol}&limit=${limit}&with_id=true`;
|
|
826
|
+
const data = await httpJson({
|
|
827
|
+
url,
|
|
828
|
+
timeoutMs: opts.timeoutMs,
|
|
829
|
+
transformUrl: opts.transformUrl
|
|
830
|
+
});
|
|
831
|
+
return {
|
|
832
|
+
exchange: "gate",
|
|
833
|
+
symbol: fromGateSymbol(symbol),
|
|
834
|
+
market: "perpetual",
|
|
835
|
+
bids: parseObjectLevels(data.bids),
|
|
836
|
+
asks: parseObjectLevels(data.asks),
|
|
837
|
+
timestamp: data.update,
|
|
838
|
+
sequence: data.id ?? data.update
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
function parseArrayLevels(rows) {
|
|
842
|
+
return rows.map(([p, s]) => ({ price: Number(p), size: Number(s) }));
|
|
843
|
+
}
|
|
844
|
+
function parseObjectLevels(rows) {
|
|
845
|
+
return rows.map((r) => ({ price: Number(r.p), size: Number(r.s) }));
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/exchanges/gate/ws.ts
|
|
849
|
+
var WS_SPOT2 = "wss://api.gateio.ws/ws/v4/";
|
|
850
|
+
var WS_FUTURES = "wss://fx-ws.gateio.ws/v4/ws/usdt";
|
|
851
|
+
function streamGateOrderbook(opts) {
|
|
852
|
+
const isFutures = opts.market === "perpetual";
|
|
853
|
+
const gateSymbol = toGateSymbol(opts.symbol);
|
|
854
|
+
const channel = isFutures ? "futures.order_book_update" : "spot.order_book_update";
|
|
855
|
+
const interval = `${opts.intervalMs ?? 100}ms`;
|
|
856
|
+
const depth = String(opts.depth ?? 100);
|
|
857
|
+
const merger = new BookMerger();
|
|
858
|
+
let snapshotSequence = -1;
|
|
859
|
+
let lastU = -1;
|
|
860
|
+
let snapshotInFlight = false;
|
|
861
|
+
let snapshotDone = false;
|
|
862
|
+
let buffered = [];
|
|
863
|
+
let recovering = false;
|
|
864
|
+
let ws = null;
|
|
865
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
866
|
+
const payload = isFutures ? [gateSymbol, interval, depth] : [gateSymbol, depth, interval];
|
|
867
|
+
const subscribeMsg = () => JSON.stringify({
|
|
868
|
+
time: Math.floor(Date.now() / 1e3),
|
|
869
|
+
channel,
|
|
870
|
+
event: "subscribe",
|
|
871
|
+
payload
|
|
872
|
+
});
|
|
873
|
+
const pingMsg = () => JSON.stringify({
|
|
874
|
+
time: Math.floor(Date.now() / 1e3),
|
|
875
|
+
channel: isFutures ? "futures.ping" : "spot.ping"
|
|
876
|
+
});
|
|
877
|
+
const emitBook = (bids, asks, sequence, timestamp) => {
|
|
878
|
+
const book = {
|
|
879
|
+
exchange: "gate",
|
|
880
|
+
symbol: fromGateSymbol(gateSymbol),
|
|
881
|
+
market: opts.market,
|
|
882
|
+
bids,
|
|
883
|
+
asks,
|
|
884
|
+
timestamp,
|
|
885
|
+
sequence
|
|
886
|
+
};
|
|
887
|
+
stream.emit("update", book);
|
|
888
|
+
};
|
|
889
|
+
const triggerSnapshot = () => {
|
|
890
|
+
if (snapshotInFlight || recovering) return;
|
|
891
|
+
snapshotInFlight = true;
|
|
892
|
+
fetchGateOrderbook({
|
|
893
|
+
symbol: opts.symbol,
|
|
894
|
+
market: opts.market,
|
|
895
|
+
depth: opts.depth ?? 100,
|
|
896
|
+
timeoutMs: opts.timeoutMs,
|
|
897
|
+
transformUrl: opts.transformUrl
|
|
898
|
+
}).then((snap) => {
|
|
899
|
+
snapshotSequence = snap.sequence;
|
|
900
|
+
const r = merger.apply({
|
|
901
|
+
kind: "snapshot",
|
|
902
|
+
bids: snap.bids,
|
|
903
|
+
asks: snap.asks,
|
|
904
|
+
sequence: snap.sequence,
|
|
905
|
+
timestamp: snap.timestamp
|
|
906
|
+
});
|
|
907
|
+
if (r.ok) emitBook(r.bids, r.asks, r.sequence, r.timestamp);
|
|
908
|
+
snapshotDone = true;
|
|
909
|
+
lastU = -1;
|
|
910
|
+
const pending2 = buffered;
|
|
911
|
+
buffered = [];
|
|
912
|
+
for (const ev of pending2) processDelta(ev);
|
|
913
|
+
}).catch((err) => stream.emit("error", err)).finally(() => {
|
|
914
|
+
snapshotInFlight = false;
|
|
915
|
+
});
|
|
916
|
+
};
|
|
917
|
+
const resync = () => {
|
|
918
|
+
if (recovering) return;
|
|
919
|
+
recovering = true;
|
|
920
|
+
merger.reset();
|
|
921
|
+
snapshotSequence = -1;
|
|
922
|
+
snapshotDone = false;
|
|
923
|
+
lastU = -1;
|
|
924
|
+
buffered = [];
|
|
925
|
+
setTimeout(() => {
|
|
926
|
+
recovering = false;
|
|
927
|
+
triggerSnapshot();
|
|
928
|
+
}, 100);
|
|
929
|
+
};
|
|
930
|
+
const processDelta = (ev) => {
|
|
931
|
+
if (ev.u <= snapshotSequence) return;
|
|
932
|
+
let prevSequence;
|
|
933
|
+
if (lastU < 0) {
|
|
934
|
+
if (ev.U > snapshotSequence + 1) {
|
|
935
|
+
resync();
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
prevSequence = snapshotSequence;
|
|
939
|
+
} else {
|
|
940
|
+
prevSequence = lastU;
|
|
941
|
+
}
|
|
942
|
+
const r = merger.apply({
|
|
943
|
+
kind: "delta",
|
|
944
|
+
bids: ev.bids,
|
|
945
|
+
asks: ev.asks,
|
|
946
|
+
sequence: ev.u,
|
|
947
|
+
prevSequence,
|
|
948
|
+
timestamp: ev.t
|
|
949
|
+
});
|
|
950
|
+
if (r.ok) {
|
|
951
|
+
lastU = ev.u;
|
|
952
|
+
emitBook(r.bids, r.asks, r.sequence, r.timestamp);
|
|
953
|
+
} else if (r.reason === "gap") {
|
|
954
|
+
resync();
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
const onMessage = (raw) => {
|
|
958
|
+
if (typeof raw !== "string") return;
|
|
959
|
+
let msg;
|
|
960
|
+
try {
|
|
961
|
+
msg = JSON.parse(raw);
|
|
962
|
+
} catch {
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
if (msg.event === "subscribe" || msg.event === "pong") return;
|
|
966
|
+
if (msg.error) {
|
|
967
|
+
stream.emit("error", new Error(`gate: ${msg.error.message}`));
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
if (msg.channel !== channel || !msg.result) return;
|
|
971
|
+
if (msg.event !== "update") return;
|
|
972
|
+
const ev = normalize(msg.result, isFutures);
|
|
973
|
+
if (!snapshotDone) {
|
|
974
|
+
buffered.push(ev);
|
|
975
|
+
if (!snapshotInFlight) triggerSnapshot();
|
|
976
|
+
return;
|
|
977
|
+
}
|
|
978
|
+
processDelta(ev);
|
|
979
|
+
};
|
|
980
|
+
ws = new WSClient({
|
|
981
|
+
url: isFutures ? WS_FUTURES : WS_SPOT2,
|
|
982
|
+
onOpen: (sock) => {
|
|
983
|
+
merger.reset();
|
|
984
|
+
snapshotSequence = -1;
|
|
985
|
+
snapshotDone = false;
|
|
986
|
+
lastU = -1;
|
|
987
|
+
buffered = [];
|
|
988
|
+
sock.send(subscribeMsg());
|
|
989
|
+
},
|
|
990
|
+
onMessage,
|
|
991
|
+
pingIntervalMs: 15e3,
|
|
992
|
+
pingPayload: pingMsg
|
|
993
|
+
});
|
|
994
|
+
ws.on("open", () => stream.emit("connected"));
|
|
995
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
996
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
997
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
998
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
999
|
+
return stream;
|
|
1000
|
+
}
|
|
1001
|
+
function normalize(ev, isFutures) {
|
|
1002
|
+
if (isFutures) {
|
|
1003
|
+
const f = ev;
|
|
1004
|
+
return {
|
|
1005
|
+
U: f.U,
|
|
1006
|
+
u: f.u,
|
|
1007
|
+
t: f.t,
|
|
1008
|
+
bids: f.b.map((row) => ({ price: Number(row.p), size: Number(row.s) })),
|
|
1009
|
+
asks: f.a.map((row) => ({ price: Number(row.p), size: Number(row.s) }))
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
const s = ev;
|
|
1013
|
+
return {
|
|
1014
|
+
U: s.U,
|
|
1015
|
+
u: s.u,
|
|
1016
|
+
t: s.t,
|
|
1017
|
+
bids: s.b.map(([p, sz]) => ({ price: Number(p), size: Number(sz) })),
|
|
1018
|
+
asks: s.a.map(([p, sz]) => ({ price: Number(p), size: Number(sz) }))
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// src/exchanges/gate/index.ts
|
|
1023
|
+
var GateClient = class {
|
|
1024
|
+
exchange = "gate";
|
|
1025
|
+
transformUrl;
|
|
1026
|
+
timeoutMs;
|
|
1027
|
+
constructor(opts = {}) {
|
|
1028
|
+
this.transformUrl = opts.transformUrl;
|
|
1029
|
+
this.timeoutMs = opts.timeoutMs;
|
|
1030
|
+
}
|
|
1031
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
1032
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1033
|
+
return fetchGateOrderbook({
|
|
1034
|
+
symbol: pair,
|
|
1035
|
+
market,
|
|
1036
|
+
depth: opts.depth,
|
|
1037
|
+
timeoutMs: this.timeoutMs,
|
|
1038
|
+
transformUrl: this.transformUrl
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
streamOrderbook(symbol, opts = {}) {
|
|
1042
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1043
|
+
return streamGateOrderbook({
|
|
1044
|
+
symbol: pair,
|
|
1045
|
+
market,
|
|
1046
|
+
depth: opts.depth,
|
|
1047
|
+
transformUrl: this.transformUrl,
|
|
1048
|
+
timeoutMs: this.timeoutMs
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
// src/exchanges/bingx/symbols.ts
|
|
1054
|
+
function toBingxSymbol(symbol) {
|
|
1055
|
+
const [base, quote] = symbol.split("/");
|
|
1056
|
+
if (!base || !quote) {
|
|
1057
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
1058
|
+
}
|
|
1059
|
+
return `${base}-${quote}`.toUpperCase();
|
|
1060
|
+
}
|
|
1061
|
+
function fromBingxSymbol(s) {
|
|
1062
|
+
return s.toUpperCase().replace("-", "/");
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// src/exchanges/bingx/rest.ts
|
|
1066
|
+
var BASE4 = "https://open-api.bingx.com";
|
|
1067
|
+
async function fetchBingxOrderbook(opts) {
|
|
1068
|
+
const symbol = toBingxSymbol(opts.symbol);
|
|
1069
|
+
const limit = opts.depth ?? 50;
|
|
1070
|
+
const url = opts.market === "spot" ? `${BASE4}/openApi/spot/v1/market/depth?symbol=${symbol}&limit=${limit}` : `${BASE4}/openApi/swap/v2/quote/depth?symbol=${symbol}&limit=${limit}`;
|
|
1071
|
+
const res = await httpJson({
|
|
1072
|
+
url,
|
|
1073
|
+
timeoutMs: opts.timeoutMs,
|
|
1074
|
+
transformUrl: opts.transformUrl
|
|
1075
|
+
});
|
|
1076
|
+
if (res.code !== 0) {
|
|
1077
|
+
throw new ExchangeError("bingx", `${res.code}: ${res.msg}`);
|
|
1078
|
+
}
|
|
1079
|
+
const ts = res.data.T ?? res.data.ts ?? Date.now();
|
|
1080
|
+
return {
|
|
1081
|
+
exchange: "bingx",
|
|
1082
|
+
symbol: fromBingxSymbol(symbol),
|
|
1083
|
+
market: opts.market,
|
|
1084
|
+
bids: res.data.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1085
|
+
asks: res.data.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1086
|
+
timestamp: ts,
|
|
1087
|
+
sequence: ts
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// src/utils/gzip.ts
|
|
1092
|
+
var cached = null;
|
|
1093
|
+
var pending = null;
|
|
1094
|
+
function getGzipInflate() {
|
|
1095
|
+
if (cached) return Promise.resolve(cached);
|
|
1096
|
+
if (pending) return pending;
|
|
1097
|
+
pending = (async () => {
|
|
1098
|
+
let pako;
|
|
1099
|
+
try {
|
|
1100
|
+
pako = await import('pako');
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
throw new Error(
|
|
1103
|
+
"gzip decompression requires the `pako` peer dependency. " + (err instanceof Error ? err.message : String(err))
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
const inflate = (data) => {
|
|
1107
|
+
const buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
1108
|
+
try {
|
|
1109
|
+
return pako.ungzip(buf, { to: "string" });
|
|
1110
|
+
} catch {
|
|
1111
|
+
return pako.inflate(buf, { to: "string" });
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
cached = inflate;
|
|
1115
|
+
return inflate;
|
|
1116
|
+
})();
|
|
1117
|
+
return pending;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// src/exchanges/bingx/ws.ts
|
|
1121
|
+
var WS_SPOT3 = "wss://open-api-ws.bingx.com/market";
|
|
1122
|
+
var WS_SWAP = "wss://open-api-swap.bingx.com/swap-market";
|
|
1123
|
+
function streamBingxOrderbook(opts) {
|
|
1124
|
+
const isSpot = opts.market === "spot";
|
|
1125
|
+
const bingxSymbol = toBingxSymbol(opts.symbol);
|
|
1126
|
+
const depth = opts.depth ?? 20;
|
|
1127
|
+
const dataType = `${bingxSymbol}@depth${depth}`;
|
|
1128
|
+
const merger = new BookMerger();
|
|
1129
|
+
let ws = null;
|
|
1130
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
1131
|
+
const subscribePayload = JSON.stringify({
|
|
1132
|
+
id: `sub-${Date.now()}`,
|
|
1133
|
+
reqType: "sub",
|
|
1134
|
+
dataType
|
|
1135
|
+
});
|
|
1136
|
+
const handlePayload = (text) => {
|
|
1137
|
+
if (text === "Ping" || text === "ping") {
|
|
1138
|
+
ws?.send(text === "Ping" ? "Pong" : "pong");
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
let msg;
|
|
1142
|
+
try {
|
|
1143
|
+
msg = JSON.parse(text);
|
|
1144
|
+
} catch {
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
if (msg.id && !msg.data) return;
|
|
1148
|
+
if (msg.dataType !== dataType || !msg.data) return;
|
|
1149
|
+
const d = msg.data;
|
|
1150
|
+
const ts = d.T ?? d.ts ?? Date.now();
|
|
1151
|
+
const event = {
|
|
1152
|
+
kind: "snapshot",
|
|
1153
|
+
bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1154
|
+
asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1155
|
+
sequence: ts,
|
|
1156
|
+
timestamp: ts
|
|
1157
|
+
};
|
|
1158
|
+
const r = merger.apply(event);
|
|
1159
|
+
if (!r.ok) return;
|
|
1160
|
+
const book = {
|
|
1161
|
+
exchange: "bingx",
|
|
1162
|
+
symbol: fromBingxSymbol(bingxSymbol),
|
|
1163
|
+
market: opts.market,
|
|
1164
|
+
bids: r.bids,
|
|
1165
|
+
asks: r.asks,
|
|
1166
|
+
timestamp: r.timestamp,
|
|
1167
|
+
sequence: r.sequence
|
|
1168
|
+
};
|
|
1169
|
+
stream.emit("update", book);
|
|
1170
|
+
};
|
|
1171
|
+
const onMessage = async (raw) => {
|
|
1172
|
+
if (typeof raw === "string") {
|
|
1173
|
+
handlePayload(raw);
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
const inflate = await getGzipInflate();
|
|
1177
|
+
handlePayload(inflate(raw));
|
|
1178
|
+
};
|
|
1179
|
+
ws = new WSClient({
|
|
1180
|
+
url: isSpot ? WS_SPOT3 : WS_SWAP,
|
|
1181
|
+
onOpen: (sock) => {
|
|
1182
|
+
merger.reset();
|
|
1183
|
+
sock.send(subscribePayload);
|
|
1184
|
+
},
|
|
1185
|
+
onMessage
|
|
1186
|
+
// bingx server is the one that sends Ping frames; we don't need client pings.
|
|
1187
|
+
});
|
|
1188
|
+
ws.on("open", () => stream.emit("connected"));
|
|
1189
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
1190
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
1191
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
1192
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
1193
|
+
return stream;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
// src/exchanges/bingx/index.ts
|
|
1197
|
+
var BingxClient = class {
|
|
1198
|
+
exchange = "bingx";
|
|
1199
|
+
transformUrl;
|
|
1200
|
+
timeoutMs;
|
|
1201
|
+
constructor(opts = {}) {
|
|
1202
|
+
this.transformUrl = opts.transformUrl;
|
|
1203
|
+
this.timeoutMs = opts.timeoutMs;
|
|
1204
|
+
}
|
|
1205
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
1206
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1207
|
+
return fetchBingxOrderbook({
|
|
1208
|
+
symbol: pair,
|
|
1209
|
+
market,
|
|
1210
|
+
depth: opts.depth,
|
|
1211
|
+
timeoutMs: this.timeoutMs,
|
|
1212
|
+
transformUrl: this.transformUrl
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
streamOrderbook(symbol, opts = {}) {
|
|
1216
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1217
|
+
return streamBingxOrderbook({
|
|
1218
|
+
symbol: pair,
|
|
1219
|
+
market,
|
|
1220
|
+
depth: opts.depth,
|
|
1221
|
+
transformUrl: this.transformUrl,
|
|
1222
|
+
timeoutMs: this.timeoutMs
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
|
|
1227
|
+
// src/exchanges/huobi/symbols.ts
|
|
1228
|
+
var QUOTES3 = ["USDT", "USDC", "USD", "BTC", "ETH"];
|
|
1229
|
+
function toHuobiSymbol(symbol, market) {
|
|
1230
|
+
const [base, quote] = symbol.split("/");
|
|
1231
|
+
if (!base || !quote) {
|
|
1232
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
1233
|
+
}
|
|
1234
|
+
return market === "spot" ? `${base}${quote}`.toLowerCase() : `${base}-${quote}`.toUpperCase();
|
|
1235
|
+
}
|
|
1236
|
+
function fromHuobiSymbol(s, market) {
|
|
1237
|
+
if (market === "spot") {
|
|
1238
|
+
const upper = s.toUpperCase();
|
|
1239
|
+
for (const q of QUOTES3) {
|
|
1240
|
+
if (upper.endsWith(q)) return `${upper.slice(0, -q.length)}/${q}`;
|
|
1241
|
+
}
|
|
1242
|
+
return upper;
|
|
1243
|
+
}
|
|
1244
|
+
return s.toUpperCase().replace("-", "/");
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
// src/exchanges/huobi/rest.ts
|
|
1248
|
+
var SPOT_BASE = "https://api.huobi.pro";
|
|
1249
|
+
var PERP_BASE = "https://api.hbdm.com";
|
|
1250
|
+
async function fetchHuobiOrderbook(opts) {
|
|
1251
|
+
const symbol = toHuobiSymbol(opts.symbol, opts.market);
|
|
1252
|
+
const step = opts.step ?? "step0";
|
|
1253
|
+
const url = opts.market === "spot" ? `${SPOT_BASE}/market/depth?symbol=${symbol}&type=${step}` : `${PERP_BASE}/linear-swap-ex/market/depth?contract_code=${symbol}&type=${step}`;
|
|
1254
|
+
const res = await httpJson({
|
|
1255
|
+
url,
|
|
1256
|
+
timeoutMs: opts.timeoutMs,
|
|
1257
|
+
transformUrl: opts.transformUrl
|
|
1258
|
+
});
|
|
1259
|
+
if (res.status !== "ok" || !res.tick) {
|
|
1260
|
+
throw new ExchangeError(
|
|
1261
|
+
"huobi",
|
|
1262
|
+
res["err-msg"] ?? res["err-code"] ?? "missing tick"
|
|
1263
|
+
);
|
|
1264
|
+
}
|
|
1265
|
+
const ts = res.tick.ts;
|
|
1266
|
+
return {
|
|
1267
|
+
exchange: "huobi",
|
|
1268
|
+
symbol: fromHuobiSymbol(symbol, opts.market),
|
|
1269
|
+
market: opts.market,
|
|
1270
|
+
bids: res.tick.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1271
|
+
asks: res.tick.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1272
|
+
timestamp: ts,
|
|
1273
|
+
sequence: res.tick.version ?? ts
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
// src/exchanges/huobi/ws.ts
|
|
1278
|
+
var WS_SPOT4 = "wss://api.huobi.pro/ws";
|
|
1279
|
+
var WS_PERP = "wss://api.hbdm.com/linear-swap-ws";
|
|
1280
|
+
function streamHuobiOrderbook(opts) {
|
|
1281
|
+
const huobiSymbol = toHuobiSymbol(opts.symbol, opts.market);
|
|
1282
|
+
const step = opts.step ?? "step0";
|
|
1283
|
+
const channel = `market.${huobiSymbol}.depth.${step}`;
|
|
1284
|
+
const merger = new BookMerger();
|
|
1285
|
+
let ws = null;
|
|
1286
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
1287
|
+
const subscribePayload = JSON.stringify({
|
|
1288
|
+
sub: channel,
|
|
1289
|
+
id: `sub-${Date.now()}`
|
|
1290
|
+
});
|
|
1291
|
+
const handlePayload = (text) => {
|
|
1292
|
+
let msg;
|
|
1293
|
+
try {
|
|
1294
|
+
msg = JSON.parse(text);
|
|
1295
|
+
} catch {
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
if (typeof msg.ping === "number") {
|
|
1299
|
+
ws?.send(JSON.stringify({ pong: msg.ping }));
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
if (msg.status === "ok" && msg.subbed) return;
|
|
1303
|
+
if (msg.ch !== channel || !msg.tick) return;
|
|
1304
|
+
const ts = msg.tick.ts;
|
|
1305
|
+
const sequence = msg.tick.version ?? ts;
|
|
1306
|
+
const event = {
|
|
1307
|
+
kind: "snapshot",
|
|
1308
|
+
bids: msg.tick.bids.map(([p, s]) => ({
|
|
1309
|
+
price: Number(p),
|
|
1310
|
+
size: Number(s)
|
|
1311
|
+
})),
|
|
1312
|
+
asks: msg.tick.asks.map(([p, s]) => ({
|
|
1313
|
+
price: Number(p),
|
|
1314
|
+
size: Number(s)
|
|
1315
|
+
})),
|
|
1316
|
+
sequence,
|
|
1317
|
+
timestamp: ts
|
|
1318
|
+
};
|
|
1319
|
+
const r = merger.apply(event);
|
|
1320
|
+
if (!r.ok) return;
|
|
1321
|
+
const book = {
|
|
1322
|
+
exchange: "huobi",
|
|
1323
|
+
symbol: fromHuobiSymbol(huobiSymbol, opts.market),
|
|
1324
|
+
market: opts.market,
|
|
1325
|
+
bids: r.bids,
|
|
1326
|
+
asks: r.asks,
|
|
1327
|
+
timestamp: r.timestamp,
|
|
1328
|
+
sequence: r.sequence
|
|
1329
|
+
};
|
|
1330
|
+
stream.emit("update", book);
|
|
1331
|
+
};
|
|
1332
|
+
const onMessage = async (raw) => {
|
|
1333
|
+
if (typeof raw === "string") {
|
|
1334
|
+
handlePayload(raw);
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
const inflate = await getGzipInflate();
|
|
1338
|
+
handlePayload(inflate(raw));
|
|
1339
|
+
};
|
|
1340
|
+
ws = new WSClient({
|
|
1341
|
+
url: opts.market === "spot" ? WS_SPOT4 : WS_PERP,
|
|
1342
|
+
onOpen: (sock) => {
|
|
1343
|
+
merger.reset();
|
|
1344
|
+
sock.send(subscribePayload);
|
|
1345
|
+
},
|
|
1346
|
+
onMessage
|
|
1347
|
+
// Huobi heartbeat is server-initiated; we reply inline above. No client ping.
|
|
1348
|
+
});
|
|
1349
|
+
ws.on("open", () => stream.emit("connected"));
|
|
1350
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
1351
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
1352
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
1353
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
1354
|
+
return stream;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// src/exchanges/huobi/index.ts
|
|
1358
|
+
var HuobiClient = class {
|
|
1359
|
+
exchange = "huobi";
|
|
1360
|
+
transformUrl;
|
|
1361
|
+
timeoutMs;
|
|
1362
|
+
constructor(opts = {}) {
|
|
1363
|
+
this.transformUrl = opts.transformUrl;
|
|
1364
|
+
this.timeoutMs = opts.timeoutMs;
|
|
1365
|
+
}
|
|
1366
|
+
fetchOrderbook(symbol, _opts = {}) {
|
|
1367
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1368
|
+
return fetchHuobiOrderbook({
|
|
1369
|
+
symbol: pair,
|
|
1370
|
+
market,
|
|
1371
|
+
timeoutMs: this.timeoutMs,
|
|
1372
|
+
transformUrl: this.transformUrl
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
1375
|
+
streamOrderbook(symbol, _opts = {}) {
|
|
1376
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1377
|
+
return streamHuobiOrderbook({
|
|
1378
|
+
symbol: pair,
|
|
1379
|
+
market,
|
|
1380
|
+
transformUrl: this.transformUrl,
|
|
1381
|
+
timeoutMs: this.timeoutMs
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
};
|
|
1385
|
+
|
|
1386
|
+
// src/exchanges/coinex/symbols.ts
|
|
1387
|
+
var QUOTES4 = ["USDT", "USDC", "USD"];
|
|
1388
|
+
function toCoinexSymbol(symbol) {
|
|
1389
|
+
const [base, quote] = symbol.split("/");
|
|
1390
|
+
if (!base || !quote) {
|
|
1391
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
1392
|
+
}
|
|
1393
|
+
return `${base}${quote}`.toUpperCase();
|
|
1394
|
+
}
|
|
1395
|
+
function fromCoinexSymbol(s) {
|
|
1396
|
+
const upper = s.toUpperCase();
|
|
1397
|
+
for (const q of QUOTES4) {
|
|
1398
|
+
if (upper.endsWith(q)) {
|
|
1399
|
+
return `${upper.slice(0, -q.length)}/${q}`;
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
return upper;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
// src/exchanges/coinex/rest.ts
|
|
1406
|
+
var BASE5 = "https://api.coinex.com";
|
|
1407
|
+
async function fetchCoinexOrderbook(opts) {
|
|
1408
|
+
const market = toCoinexSymbol(opts.symbol);
|
|
1409
|
+
const limit = opts.depth ?? 50;
|
|
1410
|
+
const url = opts.market === "spot" ? `${BASE5}/v2/spot/depth?market=${market}&limit=${limit}&interval=0` : `${BASE5}/v2/futures/depth?market=${market}&limit=${limit}&interval=0`;
|
|
1411
|
+
const res = await httpJson({
|
|
1412
|
+
url,
|
|
1413
|
+
timeoutMs: opts.timeoutMs,
|
|
1414
|
+
transformUrl: opts.transformUrl
|
|
1415
|
+
});
|
|
1416
|
+
if (res.code !== 0) {
|
|
1417
|
+
throw new ExchangeError("coinex", `${res.code}: ${res.message}`);
|
|
1418
|
+
}
|
|
1419
|
+
const d = res.data.depth;
|
|
1420
|
+
return {
|
|
1421
|
+
exchange: "coinex",
|
|
1422
|
+
symbol: fromCoinexSymbol(market),
|
|
1423
|
+
market: opts.market,
|
|
1424
|
+
bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1425
|
+
asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1426
|
+
timestamp: d.updated_at,
|
|
1427
|
+
sequence: d.updated_at
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
// src/exchanges/coinex/ws.ts
|
|
1432
|
+
var WS_SPOT5 = "wss://socket.coinex.com/v2/spot";
|
|
1433
|
+
var WS_FUTURES2 = "wss://socket.coinex.com/v2/futures";
|
|
1434
|
+
function streamCoinexOrderbook(opts) {
|
|
1435
|
+
const market = toCoinexSymbol(opts.symbol);
|
|
1436
|
+
const depth = opts.depth ?? 50;
|
|
1437
|
+
const merger = new BookMerger();
|
|
1438
|
+
let ws = null;
|
|
1439
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
1440
|
+
const subscribePayload = JSON.stringify({
|
|
1441
|
+
method: "depth.subscribe",
|
|
1442
|
+
params: {
|
|
1443
|
+
// [market, limit, interval, diff_flag] — diff_flag=false → full snapshots
|
|
1444
|
+
market_list: [[market, depth, "0", true]]
|
|
1445
|
+
},
|
|
1446
|
+
id: 1
|
|
1447
|
+
});
|
|
1448
|
+
const handlePayload = (text) => {
|
|
1449
|
+
let msg;
|
|
1450
|
+
try {
|
|
1451
|
+
msg = JSON.parse(text);
|
|
1452
|
+
} catch {
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
if (msg.id != null && !msg.method) return;
|
|
1456
|
+
if (msg.method !== "depth.update" || !msg.data) return;
|
|
1457
|
+
if (msg.data.market !== market) return;
|
|
1458
|
+
const d = msg.data.depth;
|
|
1459
|
+
const event = {
|
|
1460
|
+
kind: "snapshot",
|
|
1461
|
+
bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1462
|
+
asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1463
|
+
sequence: d.updated_at,
|
|
1464
|
+
timestamp: d.updated_at
|
|
1465
|
+
};
|
|
1466
|
+
const r = merger.apply(event);
|
|
1467
|
+
if (!r.ok) return;
|
|
1468
|
+
const book = {
|
|
1469
|
+
exchange: "coinex",
|
|
1470
|
+
symbol: fromCoinexSymbol(market),
|
|
1471
|
+
market: opts.market,
|
|
1472
|
+
bids: r.bids,
|
|
1473
|
+
asks: r.asks,
|
|
1474
|
+
timestamp: r.timestamp,
|
|
1475
|
+
sequence: r.sequence
|
|
1476
|
+
};
|
|
1477
|
+
stream.emit("update", book);
|
|
1478
|
+
};
|
|
1479
|
+
const onMessage = async (raw) => {
|
|
1480
|
+
if (typeof raw === "string") {
|
|
1481
|
+
handlePayload(raw);
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
const inflate = await getGzipInflate();
|
|
1485
|
+
handlePayload(inflate(raw));
|
|
1486
|
+
};
|
|
1487
|
+
ws = new WSClient({
|
|
1488
|
+
url: opts.market === "spot" ? WS_SPOT5 : WS_FUTURES2,
|
|
1489
|
+
onOpen: (sock) => {
|
|
1490
|
+
merger.reset();
|
|
1491
|
+
sock.send(subscribePayload);
|
|
1492
|
+
},
|
|
1493
|
+
onMessage
|
|
1494
|
+
// Native WS ping/pong frames keep the connection alive — no app-level ping.
|
|
1495
|
+
});
|
|
1496
|
+
ws.on("open", () => stream.emit("connected"));
|
|
1497
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
1498
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
1499
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
1500
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
1501
|
+
return stream;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// src/exchanges/coinex/index.ts
|
|
1505
|
+
var CoinexClient = class {
|
|
1506
|
+
exchange = "coinex";
|
|
1507
|
+
transformUrl;
|
|
1508
|
+
timeoutMs;
|
|
1509
|
+
constructor(opts = {}) {
|
|
1510
|
+
this.transformUrl = opts.transformUrl;
|
|
1511
|
+
this.timeoutMs = opts.timeoutMs;
|
|
1512
|
+
}
|
|
1513
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
1514
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1515
|
+
return fetchCoinexOrderbook({
|
|
1516
|
+
symbol: pair,
|
|
1517
|
+
market,
|
|
1518
|
+
depth: opts.depth,
|
|
1519
|
+
timeoutMs: this.timeoutMs,
|
|
1520
|
+
transformUrl: this.transformUrl
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
streamOrderbook(symbol, opts = {}) {
|
|
1524
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1525
|
+
return streamCoinexOrderbook({
|
|
1526
|
+
symbol: pair,
|
|
1527
|
+
market,
|
|
1528
|
+
depth: opts.depth,
|
|
1529
|
+
transformUrl: this.transformUrl,
|
|
1530
|
+
timeoutMs: this.timeoutMs
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
};
|
|
1534
|
+
|
|
1535
|
+
// src/exchanges/okx/symbols.ts
|
|
1536
|
+
function toOkxSymbol(symbol, market) {
|
|
1537
|
+
const [base, quote] = symbol.split("/");
|
|
1538
|
+
if (!base || !quote) {
|
|
1539
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
1540
|
+
}
|
|
1541
|
+
const upper = `${base}-${quote}`.toUpperCase();
|
|
1542
|
+
return market === "perpetual" ? `${upper}-SWAP` : upper;
|
|
1543
|
+
}
|
|
1544
|
+
function fromOkxSymbol(instId, market) {
|
|
1545
|
+
let s = instId.toUpperCase();
|
|
1546
|
+
if (market === "perpetual" && s.endsWith("-SWAP")) {
|
|
1547
|
+
s = s.slice(0, -"-SWAP".length);
|
|
1548
|
+
}
|
|
1549
|
+
const [base, quote] = s.split("-");
|
|
1550
|
+
if (base && quote) return `${base}/${quote}`;
|
|
1551
|
+
return s;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// src/exchanges/okx/rest.ts
|
|
1555
|
+
var BASE6 = "https://www.okx.com";
|
|
1556
|
+
async function fetchOkxOrderbook(opts) {
|
|
1557
|
+
const instId = toOkxSymbol(opts.symbol, opts.market);
|
|
1558
|
+
const sz = opts.depth ?? 50;
|
|
1559
|
+
const url = `${BASE6}/api/v5/market/books?instId=${instId}&sz=${sz}`;
|
|
1560
|
+
const res = await httpJson({
|
|
1561
|
+
url,
|
|
1562
|
+
timeoutMs: opts.timeoutMs,
|
|
1563
|
+
transformUrl: opts.transformUrl
|
|
1564
|
+
});
|
|
1565
|
+
if (res.code !== "0") {
|
|
1566
|
+
throw new ExchangeError("okx", `${res.code}: ${res.msg}`);
|
|
1567
|
+
}
|
|
1568
|
+
const d = res.data[0];
|
|
1569
|
+
if (!d) throw new ExchangeError("okx", "empty orderbook response");
|
|
1570
|
+
const ts = Number(d.ts);
|
|
1571
|
+
return {
|
|
1572
|
+
exchange: "okx",
|
|
1573
|
+
symbol: fromOkxSymbol(instId, opts.market),
|
|
1574
|
+
market: opts.market,
|
|
1575
|
+
bids: d.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1576
|
+
asks: d.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
1577
|
+
timestamp: ts,
|
|
1578
|
+
sequence: ts
|
|
1579
|
+
};
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
// src/exchanges/okx/ws.ts
|
|
1583
|
+
var WS_PUBLIC2 = "wss://ws.okx.com:8443/ws/v5/public";
|
|
1584
|
+
function streamOkxOrderbook(opts) {
|
|
1585
|
+
const instId = toOkxSymbol(opts.symbol, opts.market);
|
|
1586
|
+
const channel = "books";
|
|
1587
|
+
const merger = new BookMerger();
|
|
1588
|
+
let recovering = false;
|
|
1589
|
+
let ws = null;
|
|
1590
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
1591
|
+
const subscribePayload = JSON.stringify({
|
|
1592
|
+
op: "subscribe",
|
|
1593
|
+
args: [{ channel, instId }]
|
|
1594
|
+
});
|
|
1595
|
+
const emit = (r) => {
|
|
1596
|
+
const book = {
|
|
1597
|
+
exchange: "okx",
|
|
1598
|
+
symbol: fromOkxSymbol(instId, opts.market),
|
|
1599
|
+
market: opts.market,
|
|
1600
|
+
bids: r.bids,
|
|
1601
|
+
asks: r.asks,
|
|
1602
|
+
timestamp: r.timestamp,
|
|
1603
|
+
sequence: r.sequence
|
|
1604
|
+
};
|
|
1605
|
+
stream.emit("update", book);
|
|
1606
|
+
};
|
|
1607
|
+
const triggerResnapshot = () => {
|
|
1608
|
+
if (recovering) return;
|
|
1609
|
+
recovering = true;
|
|
1610
|
+
merger.reset();
|
|
1611
|
+
fetchOkxOrderbook({
|
|
1612
|
+
symbol: opts.symbol,
|
|
1613
|
+
market: opts.market,
|
|
1614
|
+
depth: opts.depth ?? 50,
|
|
1615
|
+
timeoutMs: opts.timeoutMs,
|
|
1616
|
+
transformUrl: opts.transformUrl
|
|
1617
|
+
}).then((snap) => {
|
|
1618
|
+
const r = merger.apply({
|
|
1619
|
+
kind: "snapshot",
|
|
1620
|
+
bids: snap.bids,
|
|
1621
|
+
asks: snap.asks,
|
|
1622
|
+
sequence: snap.sequence,
|
|
1623
|
+
timestamp: snap.timestamp
|
|
1624
|
+
});
|
|
1625
|
+
if (r.ok) emit(r);
|
|
1626
|
+
}).catch((err) => stream.emit("error", err)).finally(() => {
|
|
1627
|
+
recovering = false;
|
|
1628
|
+
});
|
|
1629
|
+
};
|
|
1630
|
+
const buildEvent2 = (d, isSnapshot) => {
|
|
1631
|
+
const bids = d.bids.map(([p, s]) => ({
|
|
1632
|
+
price: Number(p),
|
|
1633
|
+
size: Number(s)
|
|
1634
|
+
}));
|
|
1635
|
+
const asks = d.asks.map(([p, s]) => ({
|
|
1636
|
+
price: Number(p),
|
|
1637
|
+
size: Number(s)
|
|
1638
|
+
}));
|
|
1639
|
+
const timestamp = Number(d.ts);
|
|
1640
|
+
if (isSnapshot) {
|
|
1641
|
+
return { kind: "snapshot", bids, asks, sequence: d.seqId, timestamp };
|
|
1642
|
+
}
|
|
1643
|
+
return {
|
|
1644
|
+
kind: "delta",
|
|
1645
|
+
bids,
|
|
1646
|
+
asks,
|
|
1647
|
+
sequence: d.seqId,
|
|
1648
|
+
prevSequence: d.prevSeqId,
|
|
1649
|
+
timestamp
|
|
1650
|
+
};
|
|
1651
|
+
};
|
|
1652
|
+
const onMessage = (raw) => {
|
|
1653
|
+
if (typeof raw !== "string") return;
|
|
1654
|
+
if (raw === "pong") return;
|
|
1655
|
+
let msg;
|
|
1656
|
+
try {
|
|
1657
|
+
msg = JSON.parse(raw);
|
|
1658
|
+
} catch {
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
if (msg.event === "subscribe") return;
|
|
1662
|
+
if (msg.event === "error") {
|
|
1663
|
+
stream.emit("error", new Error(`okx: ${msg.msg ?? msg.code}`));
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
if (msg.arg?.channel !== channel || msg.arg?.instId !== instId || !msg.data?.length) {
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
1669
|
+
const isSnapshot = msg.action === "snapshot";
|
|
1670
|
+
for (const d of msg.data) {
|
|
1671
|
+
const r = merger.apply(buildEvent2(d, isSnapshot));
|
|
1672
|
+
if (r.ok) {
|
|
1673
|
+
emit(r);
|
|
1674
|
+
} else if (r.reason === "gap" || r.reason === "no-snapshot") {
|
|
1675
|
+
triggerResnapshot();
|
|
1676
|
+
return;
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
};
|
|
1680
|
+
ws = new WSClient({
|
|
1681
|
+
url: WS_PUBLIC2,
|
|
1682
|
+
onOpen: (sock) => {
|
|
1683
|
+
merger.reset();
|
|
1684
|
+
sock.send(subscribePayload);
|
|
1685
|
+
},
|
|
1686
|
+
onMessage,
|
|
1687
|
+
pingIntervalMs: 25e3,
|
|
1688
|
+
pingPayload: () => "ping"
|
|
1689
|
+
});
|
|
1690
|
+
ws.on("open", () => stream.emit("connected"));
|
|
1691
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
1692
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
1693
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
1694
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
1695
|
+
return stream;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
// src/exchanges/okx/index.ts
|
|
1699
|
+
var OkxClient = class {
|
|
1700
|
+
exchange = "okx";
|
|
1701
|
+
transformUrl;
|
|
1702
|
+
timeoutMs;
|
|
1703
|
+
constructor(opts = {}) {
|
|
1704
|
+
this.transformUrl = opts.transformUrl;
|
|
1705
|
+
this.timeoutMs = opts.timeoutMs;
|
|
1706
|
+
}
|
|
1707
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
1708
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1709
|
+
return fetchOkxOrderbook({
|
|
1710
|
+
symbol: pair,
|
|
1711
|
+
market,
|
|
1712
|
+
depth: opts.depth,
|
|
1713
|
+
timeoutMs: this.timeoutMs,
|
|
1714
|
+
transformUrl: this.transformUrl
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
streamOrderbook(symbol, opts = {}) {
|
|
1718
|
+
const { pair, market } = parseSymbol(symbol);
|
|
1719
|
+
return streamOkxOrderbook({
|
|
1720
|
+
symbol: pair,
|
|
1721
|
+
market,
|
|
1722
|
+
depth: opts.depth,
|
|
1723
|
+
transformUrl: this.transformUrl,
|
|
1724
|
+
timeoutMs: this.timeoutMs
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
};
|
|
1728
|
+
|
|
1729
|
+
exports.Backoff = Backoff;
|
|
1730
|
+
exports.BingxClient = BingxClient;
|
|
1731
|
+
exports.BitgetClient = BitgetClient;
|
|
1732
|
+
exports.BookMerger = BookMerger;
|
|
1733
|
+
exports.BybitClient = BybitClient;
|
|
1734
|
+
exports.CoinexClient = CoinexClient;
|
|
1735
|
+
exports.ExchangeError = ExchangeError;
|
|
1736
|
+
exports.GateClient = GateClient;
|
|
1737
|
+
exports.HuobiClient = HuobiClient;
|
|
1738
|
+
exports.OkxClient = OkxClient;
|
|
1739
|
+
exports.OrderbookStream = OrderbookStream;
|
|
1740
|
+
exports.RateLimitError = RateLimitError;
|
|
1741
|
+
exports.SequenceGapError = SequenceGapError;
|
|
1742
|
+
exports.parseSymbol = parseSymbol;
|
|
1743
|
+
//# sourceMappingURL=index.cjs.map
|
|
1744
|
+
//# sourceMappingURL=index.cjs.map
|