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