@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,30 @@
|
|
|
1
|
+
import { M as Market, a as Orderbook, c as OrderbookStream, C as ClientOptions, b as OrderbookOptions } from '../../stream-BKpWmRYN.cjs';
|
|
2
|
+
|
|
3
|
+
interface FetchBitgetOrderbookOptions {
|
|
4
|
+
symbol: string;
|
|
5
|
+
market: Market;
|
|
6
|
+
depth?: number;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
transformUrl?: (url: string) => string;
|
|
9
|
+
}
|
|
10
|
+
declare function fetchBitgetOrderbook(opts: FetchBitgetOrderbookOptions): Promise<Orderbook>;
|
|
11
|
+
|
|
12
|
+
interface StreamBitgetOrderbookOptions {
|
|
13
|
+
symbol: string;
|
|
14
|
+
market: Market;
|
|
15
|
+
depth?: number;
|
|
16
|
+
transformUrl?: (url: string) => string;
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
}
|
|
19
|
+
declare function streamBitgetOrderbook(opts: StreamBitgetOrderbookOptions): OrderbookStream;
|
|
20
|
+
|
|
21
|
+
declare class BitgetClient {
|
|
22
|
+
readonly exchange: "bitget";
|
|
23
|
+
private readonly transformUrl?;
|
|
24
|
+
private readonly timeoutMs?;
|
|
25
|
+
constructor(opts?: ClientOptions);
|
|
26
|
+
fetchOrderbook(symbol: string, opts?: OrderbookOptions): Promise<Orderbook>;
|
|
27
|
+
streamOrderbook(symbol: string, opts?: OrderbookOptions): OrderbookStream;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export { BitgetClient, fetchBitgetOrderbook, streamBitgetOrderbook };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { M as Market, a as Orderbook, c as OrderbookStream, C as ClientOptions, b as OrderbookOptions } from '../../stream-BKpWmRYN.js';
|
|
2
|
+
|
|
3
|
+
interface FetchBitgetOrderbookOptions {
|
|
4
|
+
symbol: string;
|
|
5
|
+
market: Market;
|
|
6
|
+
depth?: number;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
transformUrl?: (url: string) => string;
|
|
9
|
+
}
|
|
10
|
+
declare function fetchBitgetOrderbook(opts: FetchBitgetOrderbookOptions): Promise<Orderbook>;
|
|
11
|
+
|
|
12
|
+
interface StreamBitgetOrderbookOptions {
|
|
13
|
+
symbol: string;
|
|
14
|
+
market: Market;
|
|
15
|
+
depth?: number;
|
|
16
|
+
transformUrl?: (url: string) => string;
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
}
|
|
19
|
+
declare function streamBitgetOrderbook(opts: StreamBitgetOrderbookOptions): OrderbookStream;
|
|
20
|
+
|
|
21
|
+
declare class BitgetClient {
|
|
22
|
+
readonly exchange: "bitget";
|
|
23
|
+
private readonly transformUrl?;
|
|
24
|
+
private readonly timeoutMs?;
|
|
25
|
+
constructor(opts?: ClientOptions);
|
|
26
|
+
fetchOrderbook(symbol: string, opts?: OrderbookOptions): Promise<Orderbook>;
|
|
27
|
+
streamOrderbook(symbol: string, opts?: OrderbookOptions): OrderbookStream;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export { BitgetClient, fetchBitgetOrderbook, streamBitgetOrderbook };
|
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
// src/core/symbol.ts
|
|
2
|
+
function parseSymbol(symbol) {
|
|
3
|
+
const [pair, settle] = symbol.split(":");
|
|
4
|
+
const parts = (pair ?? "").split("/");
|
|
5
|
+
const base = parts[0]?.toUpperCase();
|
|
6
|
+
const quote = parts[1]?.toUpperCase();
|
|
7
|
+
if (!base || !quote) {
|
|
8
|
+
throw new Error(
|
|
9
|
+
`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
if (settle && settle.toUpperCase() !== quote) {
|
|
13
|
+
throw new Error(
|
|
14
|
+
`unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
base,
|
|
19
|
+
quote,
|
|
20
|
+
market: settle ? "perpetual" : "spot",
|
|
21
|
+
pair: `${base}/${quote}`
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/transport/http.ts
|
|
26
|
+
async function httpJson(req) {
|
|
27
|
+
const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
|
|
30
|
+
try {
|
|
31
|
+
const res = await fetch(url, {
|
|
32
|
+
method: req.method ?? "GET",
|
|
33
|
+
headers: req.headers,
|
|
34
|
+
body: req.body,
|
|
35
|
+
signal: controller.signal
|
|
36
|
+
});
|
|
37
|
+
if (!res.ok) {
|
|
38
|
+
const text = await res.text().catch(() => "");
|
|
39
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
|
|
40
|
+
}
|
|
41
|
+
return await res.json();
|
|
42
|
+
} finally {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/core/errors.ts
|
|
48
|
+
var ExchangeError = class extends Error {
|
|
49
|
+
constructor(exchange, message, cause) {
|
|
50
|
+
super(
|
|
51
|
+
`[${exchange}] ${message}`,
|
|
52
|
+
cause === void 0 ? void 0 : { cause }
|
|
53
|
+
);
|
|
54
|
+
this.exchange = exchange;
|
|
55
|
+
this.name = "ExchangeError";
|
|
56
|
+
}
|
|
57
|
+
exchange;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/exchanges/bitget/symbols.ts
|
|
61
|
+
var QUOTES = ["USDT", "USDC", "USD"];
|
|
62
|
+
function toBitgetSymbol(symbol) {
|
|
63
|
+
const [base, quote] = symbol.split("/");
|
|
64
|
+
if (!base || !quote) {
|
|
65
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
66
|
+
}
|
|
67
|
+
return `${base}${quote}`.toUpperCase();
|
|
68
|
+
}
|
|
69
|
+
function fromBitgetSymbol(s) {
|
|
70
|
+
const upper = s.toUpperCase();
|
|
71
|
+
for (const q of QUOTES) {
|
|
72
|
+
if (upper.endsWith(q)) {
|
|
73
|
+
return `${upper.slice(0, -q.length)}/${q}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return upper;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/exchanges/bitget/rest.ts
|
|
80
|
+
var BASE = "https://api.bitget.com";
|
|
81
|
+
async function fetchBitgetOrderbook(opts) {
|
|
82
|
+
const symbol = toBitgetSymbol(opts.symbol);
|
|
83
|
+
const limit = opts.depth ?? 50;
|
|
84
|
+
const url = opts.market === "spot" ? `${BASE}/api/v2/spot/market/orderbook?symbol=${symbol}&limit=${limit}` : `${BASE}/api/v2/mix/market/merge-depth?symbol=${symbol}&productType=USDT-FUTURES&limit=${limit}`;
|
|
85
|
+
const res = await httpJson({
|
|
86
|
+
url,
|
|
87
|
+
timeoutMs: opts.timeoutMs,
|
|
88
|
+
transformUrl: opts.transformUrl
|
|
89
|
+
});
|
|
90
|
+
if (res.code !== "00000") {
|
|
91
|
+
throw new ExchangeError("bitget", `${res.code}: ${res.msg}`);
|
|
92
|
+
}
|
|
93
|
+
const ts = Number(res.data.ts);
|
|
94
|
+
return {
|
|
95
|
+
exchange: "bitget",
|
|
96
|
+
symbol: fromBitgetSymbol(symbol),
|
|
97
|
+
market: opts.market,
|
|
98
|
+
bids: res.data.bids.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
99
|
+
asks: res.data.asks.map(([p, s]) => ({ price: Number(p), size: Number(s) })),
|
|
100
|
+
timestamp: ts,
|
|
101
|
+
sequence: ts
|
|
102
|
+
// REST endpoint doesn't expose a seq; ts is monotonic in practice
|
|
103
|
+
};
|
|
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/bitget/ws.ts
|
|
426
|
+
var WS_PUBLIC = "wss://ws.bitget.com/v2/ws/public";
|
|
427
|
+
function streamBitgetOrderbook(opts) {
|
|
428
|
+
const bitgetSymbol = toBitgetSymbol(opts.symbol);
|
|
429
|
+
const instType = opts.market === "spot" ? "SPOT" : "USDT-FUTURES";
|
|
430
|
+
const channel = "books";
|
|
431
|
+
const merger = new BookMerger();
|
|
432
|
+
let lastSeq = -1;
|
|
433
|
+
let recovering = false;
|
|
434
|
+
let ws = null;
|
|
435
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
436
|
+
const subscribePayload = JSON.stringify({
|
|
437
|
+
op: "subscribe",
|
|
438
|
+
args: [{ instType, channel, instId: bitgetSymbol }]
|
|
439
|
+
});
|
|
440
|
+
const handleEntry = (entry, isSnapshot) => {
|
|
441
|
+
const ts = Number(entry.ts);
|
|
442
|
+
const sequence = entry.seq ?? ts;
|
|
443
|
+
const event = isSnapshot ? {
|
|
444
|
+
kind: "snapshot",
|
|
445
|
+
bids: entry.bids.map(([p, s]) => ({
|
|
446
|
+
price: Number(p),
|
|
447
|
+
size: Number(s)
|
|
448
|
+
})),
|
|
449
|
+
asks: entry.asks.map(([p, s]) => ({
|
|
450
|
+
price: Number(p),
|
|
451
|
+
size: Number(s)
|
|
452
|
+
})),
|
|
453
|
+
sequence,
|
|
454
|
+
timestamp: ts
|
|
455
|
+
} : {
|
|
456
|
+
kind: "delta",
|
|
457
|
+
bids: entry.bids.map(([p, s]) => ({
|
|
458
|
+
price: Number(p),
|
|
459
|
+
size: Number(s)
|
|
460
|
+
})),
|
|
461
|
+
asks: entry.asks.map(([p, s]) => ({
|
|
462
|
+
price: Number(p),
|
|
463
|
+
size: Number(s)
|
|
464
|
+
})),
|
|
465
|
+
// bitget doesn't publish prevSeq; pass it ourselves so merger checks
|
|
466
|
+
// consecutive ordering without assuming the seq jumps by exactly 1.
|
|
467
|
+
prevSequence: lastSeq >= 0 ? lastSeq : void 0,
|
|
468
|
+
sequence,
|
|
469
|
+
timestamp: ts
|
|
470
|
+
};
|
|
471
|
+
const r = merger.apply(event);
|
|
472
|
+
if (r.ok) {
|
|
473
|
+
lastSeq = r.sequence;
|
|
474
|
+
stream.emit("update", {
|
|
475
|
+
exchange: "bitget",
|
|
476
|
+
symbol: fromBitgetSymbol(bitgetSymbol),
|
|
477
|
+
market: opts.market,
|
|
478
|
+
bids: r.bids,
|
|
479
|
+
asks: r.asks,
|
|
480
|
+
timestamp: r.timestamp,
|
|
481
|
+
sequence: r.sequence
|
|
482
|
+
});
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
if (r.reason === "no-snapshot" || r.reason === "gap") {
|
|
486
|
+
triggerResnapshot();
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
const triggerResnapshot = () => {
|
|
490
|
+
if (recovering) return;
|
|
491
|
+
recovering = true;
|
|
492
|
+
merger.reset();
|
|
493
|
+
lastSeq = -1;
|
|
494
|
+
fetchBitgetOrderbook({
|
|
495
|
+
symbol: opts.symbol,
|
|
496
|
+
market: opts.market,
|
|
497
|
+
depth: opts.depth,
|
|
498
|
+
timeoutMs: opts.timeoutMs,
|
|
499
|
+
transformUrl: opts.transformUrl
|
|
500
|
+
}).then((snap) => {
|
|
501
|
+
const r = merger.apply({
|
|
502
|
+
kind: "snapshot",
|
|
503
|
+
bids: snap.bids,
|
|
504
|
+
asks: snap.asks,
|
|
505
|
+
sequence: snap.sequence,
|
|
506
|
+
timestamp: snap.timestamp
|
|
507
|
+
});
|
|
508
|
+
if (r.ok) {
|
|
509
|
+
lastSeq = r.sequence;
|
|
510
|
+
stream.emit("update", { ...snap, bids: r.bids, asks: r.asks });
|
|
511
|
+
}
|
|
512
|
+
}).catch((err) => stream.emit("error", err)).finally(() => {
|
|
513
|
+
recovering = false;
|
|
514
|
+
});
|
|
515
|
+
};
|
|
516
|
+
const onMessage = (raw) => {
|
|
517
|
+
if (typeof raw !== "string") return;
|
|
518
|
+
if (raw === "pong") return;
|
|
519
|
+
let msg;
|
|
520
|
+
try {
|
|
521
|
+
msg = JSON.parse(raw);
|
|
522
|
+
} catch {
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
if (msg.event === "subscribe" || msg.event === "error") return;
|
|
526
|
+
if (!msg.action || !msg.data?.length) return;
|
|
527
|
+
if (msg.arg?.channel !== channel || msg.arg?.instId !== bitgetSymbol) return;
|
|
528
|
+
const isSnapshot = msg.action === "snapshot";
|
|
529
|
+
for (const entry of msg.data) {
|
|
530
|
+
handleEntry(entry, isSnapshot);
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
ws = new WSClient({
|
|
534
|
+
url: WS_PUBLIC,
|
|
535
|
+
onOpen: (sock) => {
|
|
536
|
+
merger.reset();
|
|
537
|
+
lastSeq = -1;
|
|
538
|
+
sock.send(subscribePayload);
|
|
539
|
+
},
|
|
540
|
+
onMessage,
|
|
541
|
+
pingIntervalMs: 25e3,
|
|
542
|
+
// bitget idle-closes at 30s
|
|
543
|
+
pingPayload: () => "ping"
|
|
544
|
+
});
|
|
545
|
+
ws.on("open", () => stream.emit("connected"));
|
|
546
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
547
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
548
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
549
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
550
|
+
return stream;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// src/exchanges/bitget/index.ts
|
|
554
|
+
var BitgetClient = class {
|
|
555
|
+
exchange = "bitget";
|
|
556
|
+
transformUrl;
|
|
557
|
+
timeoutMs;
|
|
558
|
+
constructor(opts = {}) {
|
|
559
|
+
this.transformUrl = opts.transformUrl;
|
|
560
|
+
this.timeoutMs = opts.timeoutMs;
|
|
561
|
+
}
|
|
562
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
563
|
+
const { pair, market } = parseSymbol(symbol);
|
|
564
|
+
return fetchBitgetOrderbook({
|
|
565
|
+
symbol: pair,
|
|
566
|
+
market,
|
|
567
|
+
depth: opts.depth,
|
|
568
|
+
timeoutMs: this.timeoutMs,
|
|
569
|
+
transformUrl: this.transformUrl
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
streamOrderbook(symbol, opts = {}) {
|
|
573
|
+
const { pair, market } = parseSymbol(symbol);
|
|
574
|
+
return streamBitgetOrderbook({
|
|
575
|
+
symbol: pair,
|
|
576
|
+
market,
|
|
577
|
+
depth: opts.depth,
|
|
578
|
+
transformUrl: this.transformUrl,
|
|
579
|
+
timeoutMs: this.timeoutMs
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
export { BitgetClient, fetchBitgetOrderbook, streamBitgetOrderbook };
|
|
585
|
+
//# sourceMappingURL=index.js.map
|
|
586
|
+
//# sourceMappingURL=index.js.map
|