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