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