@xapy/orderbook 0.1.3 → 0.1.5
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/dist/exchanges/binance/index.cjs +605 -0
- package/dist/exchanges/binance/index.cjs.map +1 -0
- package/dist/exchanges/binance/index.d.cts +60 -0
- package/dist/exchanges/binance/index.d.ts +60 -0
- package/dist/exchanges/binance/index.js +601 -0
- package/dist/exchanges/binance/index.js.map +1 -0
- package/dist/exchanges/bingx/index.cjs +104 -24
- package/dist/exchanges/bingx/index.cjs.map +1 -1
- package/dist/exchanges/bingx/index.d.cts +10 -3
- package/dist/exchanges/bingx/index.d.ts +10 -3
- package/dist/exchanges/bingx/index.js +104 -24
- package/dist/exchanges/bingx/index.js.map +1 -1
- package/dist/exchanges/bitget/index.cjs +2 -1
- package/dist/exchanges/bitget/index.cjs.map +1 -1
- package/dist/exchanges/bitget/index.d.cts +1 -1
- package/dist/exchanges/bitget/index.d.ts +1 -1
- package/dist/exchanges/bitget/index.js +2 -1
- package/dist/exchanges/bitget/index.js.map +1 -1
- package/dist/exchanges/bybit/index.cjs +2 -1
- package/dist/exchanges/bybit/index.cjs.map +1 -1
- package/dist/exchanges/bybit/index.d.cts +1 -1
- package/dist/exchanges/bybit/index.d.ts +1 -1
- package/dist/exchanges/bybit/index.js +2 -1
- package/dist/exchanges/bybit/index.js.map +1 -1
- package/dist/exchanges/coinex/index.cjs +2 -1
- package/dist/exchanges/coinex/index.cjs.map +1 -1
- package/dist/exchanges/coinex/index.d.cts +1 -1
- package/dist/exchanges/coinex/index.d.ts +1 -1
- package/dist/exchanges/coinex/index.js +2 -1
- package/dist/exchanges/coinex/index.js.map +1 -1
- package/dist/exchanges/gate/index.cjs +2 -1
- package/dist/exchanges/gate/index.cjs.map +1 -1
- package/dist/exchanges/gate/index.d.cts +1 -1
- package/dist/exchanges/gate/index.d.ts +1 -1
- package/dist/exchanges/gate/index.js +2 -1
- package/dist/exchanges/gate/index.js.map +1 -1
- package/dist/exchanges/huobi/index.cjs +2 -1
- package/dist/exchanges/huobi/index.cjs.map +1 -1
- package/dist/exchanges/huobi/index.d.cts +1 -1
- package/dist/exchanges/huobi/index.d.ts +1 -1
- package/dist/exchanges/huobi/index.js +2 -1
- package/dist/exchanges/huobi/index.js.map +1 -1
- package/dist/exchanges/hyperliquid/index.cjs +536 -0
- package/dist/exchanges/hyperliquid/index.cjs.map +1 -0
- package/dist/exchanges/hyperliquid/index.d.cts +45 -0
- package/dist/exchanges/hyperliquid/index.d.ts +45 -0
- package/dist/exchanges/hyperliquid/index.js +532 -0
- package/dist/exchanges/hyperliquid/index.js.map +1 -0
- package/dist/exchanges/kucoin/index.cjs +614 -0
- package/dist/exchanges/kucoin/index.cjs.map +1 -0
- package/dist/exchanges/kucoin/index.d.cts +60 -0
- package/dist/exchanges/kucoin/index.d.ts +60 -0
- package/dist/exchanges/kucoin/index.js +609 -0
- package/dist/exchanges/kucoin/index.js.map +1 -0
- package/dist/exchanges/okx/index.cjs +2 -1
- package/dist/exchanges/okx/index.cjs.map +1 -1
- package/dist/exchanges/okx/index.d.cts +1 -1
- package/dist/exchanges/okx/index.d.ts +1 -1
- package/dist/exchanges/okx/index.js +2 -1
- package/dist/exchanges/okx/index.js.map +1 -1
- package/dist/index.cjs +729 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.js +727 -25
- package/dist/index.js.map +1 -1
- package/dist/{stream-BKpWmRYN.d.cts → stream-C73HPYqT.d.cts} +1 -1
- package/dist/{stream-BKpWmRYN.d.ts → stream-C73HPYqT.d.ts} +1 -1
- package/package.json +34 -1
|
@@ -0,0 +1,605 @@
|
|
|
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/exchanges/binance/symbols.ts
|
|
50
|
+
var QUOTES = [
|
|
51
|
+
"USDT",
|
|
52
|
+
"USDC",
|
|
53
|
+
"FDUSD",
|
|
54
|
+
"BUSD",
|
|
55
|
+
"TUSD",
|
|
56
|
+
"USD",
|
|
57
|
+
"BTC",
|
|
58
|
+
"ETH",
|
|
59
|
+
"BNB"
|
|
60
|
+
];
|
|
61
|
+
function toBinanceSymbol(symbol) {
|
|
62
|
+
const [base, quote] = symbol.split("/");
|
|
63
|
+
if (!base || !quote) {
|
|
64
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
65
|
+
}
|
|
66
|
+
return `${base}${quote}`.toUpperCase();
|
|
67
|
+
}
|
|
68
|
+
function fromBinanceSymbol(s) {
|
|
69
|
+
const upper = s.toUpperCase();
|
|
70
|
+
for (const q of QUOTES) {
|
|
71
|
+
if (upper.endsWith(q) && upper.length > q.length) {
|
|
72
|
+
return `${upper.slice(0, -q.length)}/${q}`;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return upper;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/exchanges/binance/rest.ts
|
|
79
|
+
var BASE_SPOT = "https://api.binance.com";
|
|
80
|
+
var BASE_FAPI = "https://fapi.binance.com";
|
|
81
|
+
async function fetchBinanceOrderbook(opts) {
|
|
82
|
+
const symbol = toBinanceSymbol(opts.symbol);
|
|
83
|
+
const limit = opts.depth ?? 1e3;
|
|
84
|
+
const url = opts.market === "spot" ? `${BASE_SPOT}/api/v3/depth?symbol=${symbol}&limit=${limit}` : `${BASE_FAPI}/fapi/v1/depth?symbol=${symbol}&limit=${limit}`;
|
|
85
|
+
const data = await httpJson({
|
|
86
|
+
url,
|
|
87
|
+
timeoutMs: opts.timeoutMs,
|
|
88
|
+
transformUrl: opts.transformUrl
|
|
89
|
+
});
|
|
90
|
+
return {
|
|
91
|
+
exchange: "binance",
|
|
92
|
+
symbol: fromBinanceSymbol(symbol),
|
|
93
|
+
market: opts.market,
|
|
94
|
+
bids: data.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
95
|
+
asks: data.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
96
|
+
timestamp: data.E ?? data.T ?? Date.now(),
|
|
97
|
+
sequence: data.lastUpdateId
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/core/book-merger.ts
|
|
102
|
+
var BookMerger = class {
|
|
103
|
+
bids = /* @__PURE__ */ new Map();
|
|
104
|
+
// price -> size
|
|
105
|
+
asks = /* @__PURE__ */ new Map();
|
|
106
|
+
sequence = -1;
|
|
107
|
+
timestamp = 0;
|
|
108
|
+
hasSnapshot = false;
|
|
109
|
+
apply(event) {
|
|
110
|
+
if (event.kind === "snapshot") {
|
|
111
|
+
this.bids.clear();
|
|
112
|
+
this.asks.clear();
|
|
113
|
+
for (const { price, size } of event.bids) {
|
|
114
|
+
if (size > 0) this.bids.set(price, size);
|
|
115
|
+
}
|
|
116
|
+
for (const { price, size } of event.asks) {
|
|
117
|
+
if (size > 0) this.asks.set(price, size);
|
|
118
|
+
}
|
|
119
|
+
this.sequence = event.sequence;
|
|
120
|
+
this.timestamp = event.timestamp;
|
|
121
|
+
this.hasSnapshot = true;
|
|
122
|
+
return this.emit();
|
|
123
|
+
}
|
|
124
|
+
if (!this.hasSnapshot) {
|
|
125
|
+
return { ok: false, reason: "no-snapshot" };
|
|
126
|
+
}
|
|
127
|
+
if (event.sequence <= this.sequence) {
|
|
128
|
+
return this.emit();
|
|
129
|
+
}
|
|
130
|
+
if (event.prevSequence !== void 0) {
|
|
131
|
+
if (event.prevSequence !== this.sequence) {
|
|
132
|
+
return {
|
|
133
|
+
ok: false,
|
|
134
|
+
reason: "gap",
|
|
135
|
+
expected: this.sequence,
|
|
136
|
+
received: event.prevSequence
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
} else if (event.sequence !== this.sequence + 1) {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
reason: "gap",
|
|
143
|
+
expected: this.sequence + 1,
|
|
144
|
+
received: event.sequence
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
for (const { price, size } of event.bids) {
|
|
148
|
+
if (size === 0) this.bids.delete(price);
|
|
149
|
+
else this.bids.set(price, size);
|
|
150
|
+
}
|
|
151
|
+
for (const { price, size } of event.asks) {
|
|
152
|
+
if (size === 0) this.asks.delete(price);
|
|
153
|
+
else this.asks.set(price, size);
|
|
154
|
+
}
|
|
155
|
+
this.sequence = event.sequence;
|
|
156
|
+
this.timestamp = event.timestamp;
|
|
157
|
+
return this.emit();
|
|
158
|
+
}
|
|
159
|
+
reset() {
|
|
160
|
+
this.bids.clear();
|
|
161
|
+
this.asks.clear();
|
|
162
|
+
this.sequence = -1;
|
|
163
|
+
this.timestamp = 0;
|
|
164
|
+
this.hasSnapshot = false;
|
|
165
|
+
}
|
|
166
|
+
/** Returns true once the merger has a usable book. */
|
|
167
|
+
isReady() {
|
|
168
|
+
return this.hasSnapshot;
|
|
169
|
+
}
|
|
170
|
+
emit() {
|
|
171
|
+
const bids = [];
|
|
172
|
+
for (const [price, size] of this.bids) bids.push({ price, size });
|
|
173
|
+
bids.sort((a, b) => b.price - a.price);
|
|
174
|
+
const asks = [];
|
|
175
|
+
for (const [price, size] of this.asks) asks.push({ price, size });
|
|
176
|
+
asks.sort((a, b) => a.price - b.price);
|
|
177
|
+
return {
|
|
178
|
+
ok: true,
|
|
179
|
+
bids,
|
|
180
|
+
asks,
|
|
181
|
+
sequence: this.sequence,
|
|
182
|
+
timestamp: this.timestamp
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// src/core/event-emitter.ts
|
|
188
|
+
var TypedEmitter = class {
|
|
189
|
+
listeners = /* @__PURE__ */ new Map();
|
|
190
|
+
on(event, fn) {
|
|
191
|
+
let set = this.listeners.get(event);
|
|
192
|
+
if (!set) {
|
|
193
|
+
set = /* @__PURE__ */ new Set();
|
|
194
|
+
this.listeners.set(event, set);
|
|
195
|
+
}
|
|
196
|
+
set.add(fn);
|
|
197
|
+
return this;
|
|
198
|
+
}
|
|
199
|
+
off(event, fn) {
|
|
200
|
+
this.listeners.get(event)?.delete(fn);
|
|
201
|
+
return this;
|
|
202
|
+
}
|
|
203
|
+
emit(event, ...args) {
|
|
204
|
+
const set = this.listeners.get(event);
|
|
205
|
+
if (!set || set.size === 0) return false;
|
|
206
|
+
for (const fn of set) fn(...args);
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
removeAllListeners() {
|
|
210
|
+
this.listeners.clear();
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
// src/core/stream.ts
|
|
215
|
+
var OrderbookStream = class extends TypedEmitter {
|
|
216
|
+
constructor(onClose) {
|
|
217
|
+
super();
|
|
218
|
+
this.onClose = onClose;
|
|
219
|
+
}
|
|
220
|
+
onClose;
|
|
221
|
+
closed = false;
|
|
222
|
+
close() {
|
|
223
|
+
if (this.closed) return;
|
|
224
|
+
this.closed = true;
|
|
225
|
+
this.onClose();
|
|
226
|
+
this.removeAllListeners();
|
|
227
|
+
}
|
|
228
|
+
/** Yields each maintained book as it becomes available. */
|
|
229
|
+
async *iter() {
|
|
230
|
+
const queue = [];
|
|
231
|
+
let resolveNext = null;
|
|
232
|
+
let pendingError = null;
|
|
233
|
+
let ended = false;
|
|
234
|
+
const onUpdate = (b) => {
|
|
235
|
+
queue.push(b);
|
|
236
|
+
resolveNext?.();
|
|
237
|
+
};
|
|
238
|
+
const onError = (e) => {
|
|
239
|
+
pendingError = e;
|
|
240
|
+
resolveNext?.();
|
|
241
|
+
};
|
|
242
|
+
const onClose = () => {
|
|
243
|
+
ended = true;
|
|
244
|
+
resolveNext?.();
|
|
245
|
+
};
|
|
246
|
+
this.on("update", onUpdate);
|
|
247
|
+
this.on("error", onError);
|
|
248
|
+
this.on("disconnected", onClose);
|
|
249
|
+
try {
|
|
250
|
+
while (true) {
|
|
251
|
+
if (pendingError) throw pendingError;
|
|
252
|
+
const next = queue.shift();
|
|
253
|
+
if (next) {
|
|
254
|
+
yield next;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (ended || this.closed) return;
|
|
258
|
+
await new Promise((r) => {
|
|
259
|
+
resolveNext = r;
|
|
260
|
+
});
|
|
261
|
+
resolveNext = null;
|
|
262
|
+
}
|
|
263
|
+
} finally {
|
|
264
|
+
this.off("update", onUpdate);
|
|
265
|
+
this.off("error", onError);
|
|
266
|
+
this.off("disconnected", onClose);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// src/core/reconnect.ts
|
|
272
|
+
var Backoff = class _Backoff {
|
|
273
|
+
attempt = 0;
|
|
274
|
+
opts;
|
|
275
|
+
constructor(opts) {
|
|
276
|
+
this.opts = opts;
|
|
277
|
+
}
|
|
278
|
+
static withDefaults(opts = {}) {
|
|
279
|
+
return new _Backoff({
|
|
280
|
+
initialMs: opts.initialMs ?? 500,
|
|
281
|
+
maxMs: opts.maxMs ?? 3e4,
|
|
282
|
+
factor: opts.factor ?? 2,
|
|
283
|
+
jitter: opts.jitter ?? 0.3,
|
|
284
|
+
maxAttempts: opts.maxAttempts ?? 0
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
next() {
|
|
288
|
+
if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
this.attempt += 1;
|
|
292
|
+
const base = Math.min(
|
|
293
|
+
this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
|
|
294
|
+
this.opts.maxMs
|
|
295
|
+
);
|
|
296
|
+
const jitterRange = base * this.opts.jitter;
|
|
297
|
+
const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
|
|
298
|
+
return { wait, attempt: this.attempt };
|
|
299
|
+
}
|
|
300
|
+
reset() {
|
|
301
|
+
this.attempt = 0;
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
|
|
305
|
+
|
|
306
|
+
// src/transport/ws.ts
|
|
307
|
+
var cachedCtor = null;
|
|
308
|
+
async function getWebSocketCtor() {
|
|
309
|
+
if (cachedCtor) return cachedCtor;
|
|
310
|
+
if (hasNativeWebSocket) {
|
|
311
|
+
cachedCtor = globalThis.WebSocket;
|
|
312
|
+
return cachedCtor;
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
const mod = await import('ws');
|
|
316
|
+
const ctor = mod.default ?? mod.WebSocket;
|
|
317
|
+
if (!ctor) throw new Error("missing default export");
|
|
318
|
+
cachedCtor = ctor;
|
|
319
|
+
return cachedCtor;
|
|
320
|
+
} catch (err) {
|
|
321
|
+
throw new Error(
|
|
322
|
+
"WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
var WSClient = class extends TypedEmitter {
|
|
327
|
+
constructor(cfg) {
|
|
328
|
+
super();
|
|
329
|
+
this.cfg = cfg;
|
|
330
|
+
this.backoff = Backoff.withDefaults(cfg.reconnect);
|
|
331
|
+
}
|
|
332
|
+
cfg;
|
|
333
|
+
ws = null;
|
|
334
|
+
backoff;
|
|
335
|
+
closed = false;
|
|
336
|
+
pingTimer = null;
|
|
337
|
+
async connect() {
|
|
338
|
+
if (this.closed) return;
|
|
339
|
+
const WS = await getWebSocketCtor();
|
|
340
|
+
const url = typeof this.cfg.url === "function" ? await this.cfg.url() : this.cfg.url;
|
|
341
|
+
const ws = new WS(url);
|
|
342
|
+
ws.binaryType = "arraybuffer";
|
|
343
|
+
this.ws = ws;
|
|
344
|
+
ws.onopen = async () => {
|
|
345
|
+
this.backoff.reset();
|
|
346
|
+
this.startPing();
|
|
347
|
+
this.emit("open");
|
|
348
|
+
try {
|
|
349
|
+
await this.cfg.onOpen?.({
|
|
350
|
+
send: (d) => ws.send(d),
|
|
351
|
+
close: () => this.close()
|
|
352
|
+
});
|
|
353
|
+
} catch (err) {
|
|
354
|
+
this.emit("error", err);
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
ws.onmessage = (e) => {
|
|
358
|
+
let result;
|
|
359
|
+
try {
|
|
360
|
+
result = this.cfg.onMessage(e.data);
|
|
361
|
+
} catch (err) {
|
|
362
|
+
this.emit("error", err);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
if (result && typeof result.catch === "function") {
|
|
366
|
+
result.catch(
|
|
367
|
+
(err) => this.emit("error", err)
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
ws.onerror = (e) => {
|
|
372
|
+
this.emit("error", new Error(e?.message ?? "WebSocket error"));
|
|
373
|
+
};
|
|
374
|
+
ws.onclose = (e) => {
|
|
375
|
+
this.stopPing();
|
|
376
|
+
const reason = e?.reason ?? "closed";
|
|
377
|
+
this.emit("close", reason);
|
|
378
|
+
if (!this.closed) this.scheduleReconnect();
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
send(data) {
|
|
382
|
+
this.ws?.send(data);
|
|
383
|
+
}
|
|
384
|
+
close() {
|
|
385
|
+
this.closed = true;
|
|
386
|
+
this.stopPing();
|
|
387
|
+
try {
|
|
388
|
+
this.ws?.close();
|
|
389
|
+
} catch {
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
startPing() {
|
|
393
|
+
if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
|
|
394
|
+
this.stopPing();
|
|
395
|
+
this.pingTimer = setInterval(() => {
|
|
396
|
+
try {
|
|
397
|
+
this.ws?.send(this.cfg.pingPayload());
|
|
398
|
+
} catch {
|
|
399
|
+
}
|
|
400
|
+
}, this.cfg.pingIntervalMs);
|
|
401
|
+
}
|
|
402
|
+
stopPing() {
|
|
403
|
+
if (this.pingTimer) {
|
|
404
|
+
clearInterval(this.pingTimer);
|
|
405
|
+
this.pingTimer = null;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
scheduleReconnect() {
|
|
409
|
+
const next = this.backoff.next();
|
|
410
|
+
if (!next) {
|
|
411
|
+
this.emit("error", new Error("max reconnect attempts exceeded"));
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
this.emit("reconnecting", next.attempt, next.wait);
|
|
415
|
+
setTimeout(() => {
|
|
416
|
+
this.connect().catch((e) => this.emit("error", e));
|
|
417
|
+
}, next.wait);
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// src/exchanges/binance/ws.ts
|
|
422
|
+
var WS_SPOT = "wss://stream.binance.com:9443/ws";
|
|
423
|
+
var WS_FUTURES = "wss://fstream.binance.com/ws";
|
|
424
|
+
function streamBinanceOrderbook(opts) {
|
|
425
|
+
const symbol = toBinanceSymbol(opts.symbol);
|
|
426
|
+
const isSpot = opts.market === "spot";
|
|
427
|
+
const interval = opts.interval ?? "100ms";
|
|
428
|
+
const wsBase = isSpot ? WS_SPOT : WS_FUTURES;
|
|
429
|
+
const wsUrl = `${wsBase}/${symbol.toLowerCase()}@depth@${interval}`;
|
|
430
|
+
const merger = new BookMerger();
|
|
431
|
+
let snapshotId = -1;
|
|
432
|
+
let lastU = -1;
|
|
433
|
+
let snapshotInFlight = false;
|
|
434
|
+
let snapshotDone = false;
|
|
435
|
+
let buffered = [];
|
|
436
|
+
let recovering = false;
|
|
437
|
+
let ws = null;
|
|
438
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
439
|
+
const emit = (r) => {
|
|
440
|
+
const book = {
|
|
441
|
+
exchange: "binance",
|
|
442
|
+
symbol: fromBinanceSymbol(symbol),
|
|
443
|
+
market: opts.market,
|
|
444
|
+
bids: r.bids,
|
|
445
|
+
asks: r.asks,
|
|
446
|
+
timestamp: r.timestamp,
|
|
447
|
+
sequence: r.sequence
|
|
448
|
+
};
|
|
449
|
+
stream.emit("update", book);
|
|
450
|
+
};
|
|
451
|
+
const triggerSnapshot = () => {
|
|
452
|
+
if (snapshotInFlight) return;
|
|
453
|
+
snapshotInFlight = true;
|
|
454
|
+
fetchBinanceOrderbook({
|
|
455
|
+
symbol: opts.symbol,
|
|
456
|
+
market: opts.market,
|
|
457
|
+
depth: opts.depth ?? 1e3,
|
|
458
|
+
timeoutMs: opts.timeoutMs,
|
|
459
|
+
transformUrl: opts.transformUrl
|
|
460
|
+
}).then((snap) => {
|
|
461
|
+
snapshotId = snap.sequence;
|
|
462
|
+
const r = merger.apply({
|
|
463
|
+
kind: "snapshot",
|
|
464
|
+
bids: snap.bids,
|
|
465
|
+
asks: snap.asks,
|
|
466
|
+
sequence: snap.sequence,
|
|
467
|
+
timestamp: snap.timestamp
|
|
468
|
+
});
|
|
469
|
+
if (r.ok) emit(r);
|
|
470
|
+
snapshotDone = true;
|
|
471
|
+
lastU = -1;
|
|
472
|
+
const pending = buffered;
|
|
473
|
+
buffered = [];
|
|
474
|
+
for (const ev of pending) processDelta(ev);
|
|
475
|
+
}).catch((err) => stream.emit("error", err)).finally(() => {
|
|
476
|
+
snapshotInFlight = false;
|
|
477
|
+
});
|
|
478
|
+
};
|
|
479
|
+
const resync = () => {
|
|
480
|
+
if (recovering) return;
|
|
481
|
+
recovering = true;
|
|
482
|
+
merger.reset();
|
|
483
|
+
snapshotId = -1;
|
|
484
|
+
snapshotDone = false;
|
|
485
|
+
lastU = -1;
|
|
486
|
+
buffered = [];
|
|
487
|
+
setTimeout(() => {
|
|
488
|
+
recovering = false;
|
|
489
|
+
triggerSnapshot();
|
|
490
|
+
}, 100);
|
|
491
|
+
};
|
|
492
|
+
const processDelta = (ev) => {
|
|
493
|
+
if (ev.u < snapshotId + 1) return;
|
|
494
|
+
const bids = ev.b.map(([p, s]) => ({
|
|
495
|
+
price: Number(p),
|
|
496
|
+
size: Number(s)
|
|
497
|
+
}));
|
|
498
|
+
const asks = ev.a.map(([p, s]) => ({
|
|
499
|
+
price: Number(p),
|
|
500
|
+
size: Number(s)
|
|
501
|
+
}));
|
|
502
|
+
let prevSequence;
|
|
503
|
+
if (lastU < 0) {
|
|
504
|
+
const overlap = isSpot ? ev.U <= snapshotId + 1 : ev.U <= snapshotId;
|
|
505
|
+
if (!overlap) {
|
|
506
|
+
resync();
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
prevSequence = snapshotId;
|
|
510
|
+
} else if (isSpot) {
|
|
511
|
+
prevSequence = ev.U - 1;
|
|
512
|
+
} else {
|
|
513
|
+
if (ev.pu === void 0) {
|
|
514
|
+
resync();
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
prevSequence = ev.pu;
|
|
518
|
+
}
|
|
519
|
+
const r = merger.apply({
|
|
520
|
+
kind: "delta",
|
|
521
|
+
bids,
|
|
522
|
+
asks,
|
|
523
|
+
sequence: ev.u,
|
|
524
|
+
prevSequence,
|
|
525
|
+
timestamp: ev.E
|
|
526
|
+
});
|
|
527
|
+
if (r.ok) {
|
|
528
|
+
lastU = ev.u;
|
|
529
|
+
emit(r);
|
|
530
|
+
} else if (r.reason === "gap" || r.reason === "no-snapshot") {
|
|
531
|
+
resync();
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
const onMessage = (raw) => {
|
|
535
|
+
if (typeof raw !== "string") return;
|
|
536
|
+
let msg;
|
|
537
|
+
try {
|
|
538
|
+
msg = JSON.parse(raw);
|
|
539
|
+
} catch {
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
if (msg.e !== "depthUpdate") return;
|
|
543
|
+
if (!snapshotDone) {
|
|
544
|
+
buffered.push(msg);
|
|
545
|
+
if (!snapshotInFlight) triggerSnapshot();
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
processDelta(msg);
|
|
549
|
+
};
|
|
550
|
+
ws = new WSClient({
|
|
551
|
+
url: wsUrl,
|
|
552
|
+
onOpen: () => {
|
|
553
|
+
merger.reset();
|
|
554
|
+
snapshotId = -1;
|
|
555
|
+
snapshotDone = false;
|
|
556
|
+
lastU = -1;
|
|
557
|
+
buffered = [];
|
|
558
|
+
},
|
|
559
|
+
onMessage
|
|
560
|
+
// Binance server-initiated WS-level ping; auto-handled by the WS impl.
|
|
561
|
+
});
|
|
562
|
+
ws.on("open", () => stream.emit("connected"));
|
|
563
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
564
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
565
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
566
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
567
|
+
return stream;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// src/exchanges/binance/index.ts
|
|
571
|
+
var BinanceClient = class {
|
|
572
|
+
exchange = "binance";
|
|
573
|
+
transformUrl;
|
|
574
|
+
timeoutMs;
|
|
575
|
+
constructor(opts = {}) {
|
|
576
|
+
this.transformUrl = opts.transformUrl;
|
|
577
|
+
this.timeoutMs = opts.timeoutMs;
|
|
578
|
+
}
|
|
579
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
580
|
+
const { pair, market } = parseSymbol(symbol);
|
|
581
|
+
return fetchBinanceOrderbook({
|
|
582
|
+
symbol: pair,
|
|
583
|
+
market,
|
|
584
|
+
depth: opts.depth,
|
|
585
|
+
timeoutMs: this.timeoutMs,
|
|
586
|
+
transformUrl: this.transformUrl
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
streamOrderbook(symbol, opts = {}) {
|
|
590
|
+
const { pair, market } = parseSymbol(symbol);
|
|
591
|
+
return streamBinanceOrderbook({
|
|
592
|
+
symbol: pair,
|
|
593
|
+
market,
|
|
594
|
+
depth: opts.depth,
|
|
595
|
+
transformUrl: this.transformUrl,
|
|
596
|
+
timeoutMs: this.timeoutMs
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
exports.BinanceClient = BinanceClient;
|
|
602
|
+
exports.fetchBinanceOrderbook = fetchBinanceOrderbook;
|
|
603
|
+
exports.streamBinanceOrderbook = streamBinanceOrderbook;
|
|
604
|
+
//# sourceMappingURL=index.cjs.map
|
|
605
|
+
//# sourceMappingURL=index.cjs.map
|