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