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