@paradex/sdk 0.11.0 → 0.12.1
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 +132 -2
- package/dist/api-errors.d.ts +76 -0
- package/dist/api-errors.js +249 -0
- package/dist/builder-app.d.ts +329 -0
- package/dist/builder-app.js +527 -0
- package/dist/builder-codes.d.ts +4 -1
- package/dist/builder-codes.js +4 -2
- package/dist/evm-owner-client.d.ts +101 -0
- package/dist/evm-owner-client.js +191 -0
- package/dist/evm-owner-signer.d.ts +81 -0
- package/dist/evm-owner-signer.js +165 -0
- package/dist/index.d.ts +48 -1
- package/dist/index.js +40 -1
- package/dist/owner-auth.d.ts +68 -0
- package/dist/owner-auth.js +184 -0
- package/dist/paraclear.d.ts +6 -1
- package/dist/paraclear.js +15 -8
- package/dist/rfq.d.ts +54 -0
- package/dist/rfq.js +64 -0
- package/dist/sbe.d.ts +47 -0
- package/dist/sbe.js +744 -0
- package/dist/session-accounts.d.ts +33 -1
- package/dist/session-accounts.js +148 -40
- package/dist/session-auth.d.ts +3 -0
- package/dist/session-auth.js +12 -0
- package/dist/session-transport.d.ts +8 -1
- package/dist/session-transport.js +4 -0
- package/dist/siwe.d.ts +35 -0
- package/dist/siwe.js +94 -0
- package/dist/trading.d.ts +98 -0
- package/dist/trading.js +39 -0
- package/dist/wallet.d.ts +78 -0
- package/dist/wallet.js +157 -0
- package/package.json +4 -2
package/dist/sbe.js
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads the binary (SBE) messages the websocket sends and turns each into
|
|
3
|
+
* the object the JSON feed sends for it: the API's snake_case names,
|
|
4
|
+
* decimals as strings, times in milliseconds.
|
|
5
|
+
*
|
|
6
|
+
* A message's header gives the length of its fixed part, and the reader
|
|
7
|
+
* goes by that, so fields a newer server adds at the end are skipped and
|
|
8
|
+
* fields an older one lacks read as missing.
|
|
9
|
+
*/
|
|
10
|
+
const SCHEMA_ID = 1;
|
|
11
|
+
/** The newest schema version the decoder reads and the server offers. */
|
|
12
|
+
const SCHEMA_VERSION = 3;
|
|
13
|
+
const HEADER_LENGTH = 8;
|
|
14
|
+
const NULL_INT64 = -(2n ** 63n);
|
|
15
|
+
/** A message that could not be read. */
|
|
16
|
+
export class SbeDecodeError extends Error {
|
|
17
|
+
constructor(message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'SbeDecodeError';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** `url` asking the server for messages this decoder reads. */
|
|
23
|
+
export function withSbeParams(url) {
|
|
24
|
+
if (/[?&]sbeSchemaId=/.test(url))
|
|
25
|
+
return url;
|
|
26
|
+
const [address = '', fragment] = url.split('#');
|
|
27
|
+
const join = address.includes('?') ? '&' : '?';
|
|
28
|
+
const params = `sbeSchemaId=${SCHEMA_ID}&sbeSchemaVersion=${SCHEMA_VERSION}`;
|
|
29
|
+
// A websocket URL has no use for a fragment, but a custom factory may.
|
|
30
|
+
return `${address}${join}${params}${fragment != null ? `#${fragment}` : ''}`;
|
|
31
|
+
}
|
|
32
|
+
/** The bytes of a websocket message, or `undefined` for a text message. */
|
|
33
|
+
export function binaryFrame(data) {
|
|
34
|
+
if (data instanceof ArrayBuffer)
|
|
35
|
+
return new Uint8Array(data);
|
|
36
|
+
if (ArrayBuffer.isView(data)) {
|
|
37
|
+
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
38
|
+
}
|
|
39
|
+
// An ArrayBuffer from another realm (a frame, a worker, a test sandbox).
|
|
40
|
+
if (Object.prototype.toString.call(data) === '[object ArrayBuffer]') {
|
|
41
|
+
return new Uint8Array(data);
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const SIDE = { 1: 'BUY', 2: 'SELL' };
|
|
46
|
+
const FILL_TYPE = {
|
|
47
|
+
1: 'FILL',
|
|
48
|
+
2: 'LIQUIDATION',
|
|
49
|
+
3: 'UNWIND_TRANSFER',
|
|
50
|
+
4: 'SETTLE_MARKET',
|
|
51
|
+
5: 'RPI',
|
|
52
|
+
6: 'BLOCK_TRADE',
|
|
53
|
+
};
|
|
54
|
+
const ORDER_TYPE = {
|
|
55
|
+
1: 'LIMIT',
|
|
56
|
+
2: 'MARKET',
|
|
57
|
+
3: 'STOP_LIMIT',
|
|
58
|
+
4: 'STOP_MARKET',
|
|
59
|
+
5: 'TAKE_PROFIT_LIMIT',
|
|
60
|
+
6: 'TAKE_PROFIT_MARKET',
|
|
61
|
+
7: 'STOP_LOSS_LIMIT',
|
|
62
|
+
8: 'STOP_LOSS_MARKET',
|
|
63
|
+
};
|
|
64
|
+
const ORDER_STATUS = { 1: 'NEW', 2: 'UNTRIGGERED', 3: 'OPEN', 4: 'CLOSED' };
|
|
65
|
+
const INSTRUCTION = { 1: 'GTC', 2: 'IOC', 3: 'POST_ONLY', 4: 'RPI' };
|
|
66
|
+
const STP = {
|
|
67
|
+
0: '',
|
|
68
|
+
1: 'EXPIRE_MAKER',
|
|
69
|
+
2: 'EXPIRE_TAKER',
|
|
70
|
+
3: 'EXPIRE_BOTH',
|
|
71
|
+
};
|
|
72
|
+
const LIQUIDITY = { 1: 'MAKER', 2: 'TAKER' };
|
|
73
|
+
const POSITION_SIDE = { 1: 'LONG', 2: 'SHORT' };
|
|
74
|
+
const POSITION_STATUS = { 1: 'OPEN', 2: 'CLOSED', 3: 'UNSPECIFIED' };
|
|
75
|
+
const ACCOUNT_STATUS = { 1: 'ACTIVE', 2: 'LIQUIDATION' };
|
|
76
|
+
const REQUEST_STATUS = {
|
|
77
|
+
0: 'UNSPECIFIED',
|
|
78
|
+
1: 'PENDING',
|
|
79
|
+
2: 'PROCESSED',
|
|
80
|
+
3: 'REJECTED',
|
|
81
|
+
4: 'SUCCESS',
|
|
82
|
+
};
|
|
83
|
+
const REQUEST_TYPE = { 0: 'UNSPECIFIED', 1: 'MODIFY_ORDER' };
|
|
84
|
+
const ASSET_KIND = {
|
|
85
|
+
0: 'UNSPECIFIED',
|
|
86
|
+
1: 'PERPETUAL_FUTURE',
|
|
87
|
+
2: 'OPTION',
|
|
88
|
+
3: 'SPOT',
|
|
89
|
+
};
|
|
90
|
+
const FUNDING_SOURCE = {
|
|
91
|
+
0: 'UNSPECIFIED',
|
|
92
|
+
1: 'PARADEX',
|
|
93
|
+
2: 'BINANCE',
|
|
94
|
+
3: 'BYBIT',
|
|
95
|
+
4: 'OKX',
|
|
96
|
+
5: 'DERIBIT',
|
|
97
|
+
6: 'DERIVE',
|
|
98
|
+
7: 'HYPERLIQUID',
|
|
99
|
+
8: 'LIGHTER',
|
|
100
|
+
9: 'DATABENTO',
|
|
101
|
+
10: 'PUBLISHER',
|
|
102
|
+
11: 'PYTH',
|
|
103
|
+
12: 'STORK',
|
|
104
|
+
};
|
|
105
|
+
const ORDER_FLAGS = [
|
|
106
|
+
'REDUCE_ONLY',
|
|
107
|
+
'STOP_CONDITION_BELOW_TRIGGER',
|
|
108
|
+
'STOP_CONDITION_ABOVE_TRIGGER',
|
|
109
|
+
'INTERACTIVE',
|
|
110
|
+
'TARGET_STRATEGY_VWAP',
|
|
111
|
+
'MMP',
|
|
112
|
+
];
|
|
113
|
+
/** By bit. Bit 7 is set for a flag the schema has no bit for. */
|
|
114
|
+
const FILL_FLAGS = [
|
|
115
|
+
'interactive',
|
|
116
|
+
'rpi',
|
|
117
|
+
'fastfill',
|
|
118
|
+
undefined,
|
|
119
|
+
undefined,
|
|
120
|
+
undefined,
|
|
121
|
+
undefined,
|
|
122
|
+
'UNKNOWN',
|
|
123
|
+
];
|
|
124
|
+
/** Reads fields in order, never past the part it was told to stop at. */
|
|
125
|
+
class Reader {
|
|
126
|
+
constructor(bytes, blockLength) {
|
|
127
|
+
this.bytes = bytes;
|
|
128
|
+
this.offset = HEADER_LENGTH;
|
|
129
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
130
|
+
this.end = HEADER_LENGTH + blockLength;
|
|
131
|
+
if (this.end > bytes.byteLength) {
|
|
132
|
+
throw new SbeDecodeError('message is shorter than its header says');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
take(size) {
|
|
136
|
+
const at = this.offset;
|
|
137
|
+
if (at + size > this.end)
|
|
138
|
+
throw new SbeDecodeError('message is too short');
|
|
139
|
+
this.offset += size;
|
|
140
|
+
return at;
|
|
141
|
+
}
|
|
142
|
+
/** Whether the fixed part holds another `size` bytes. */
|
|
143
|
+
has(size) {
|
|
144
|
+
return this.offset + size <= this.end;
|
|
145
|
+
}
|
|
146
|
+
u8() {
|
|
147
|
+
return this.view.getUint8(this.take(1));
|
|
148
|
+
}
|
|
149
|
+
u16() {
|
|
150
|
+
return this.view.getUint16(this.take(2), true);
|
|
151
|
+
}
|
|
152
|
+
i16() {
|
|
153
|
+
return this.view.getInt16(this.take(2), true);
|
|
154
|
+
}
|
|
155
|
+
u64() {
|
|
156
|
+
return this.view.getBigUint64(this.take(8), true);
|
|
157
|
+
}
|
|
158
|
+
i64() {
|
|
159
|
+
return this.view.getBigInt64(this.take(8), true);
|
|
160
|
+
}
|
|
161
|
+
/** A decimal as a string; `''` for none. */
|
|
162
|
+
decimal(places = 8) {
|
|
163
|
+
const mantissa = this.i64();
|
|
164
|
+
return mantissa === NULL_INT64 ? '' : decimalString(mantissa, places);
|
|
165
|
+
}
|
|
166
|
+
/** A decimal added in a later schema version. */
|
|
167
|
+
addedDecimal(places = 8) {
|
|
168
|
+
return this.has(8) ? this.decimal(places) : '';
|
|
169
|
+
}
|
|
170
|
+
/** A time in microseconds, as milliseconds. */
|
|
171
|
+
ms() {
|
|
172
|
+
return Number(this.i64() / 1000n);
|
|
173
|
+
}
|
|
174
|
+
oneOf(names) {
|
|
175
|
+
return names[this.u8()] ?? 'UNKNOWN';
|
|
176
|
+
}
|
|
177
|
+
flags(names) {
|
|
178
|
+
const bits = this.u8();
|
|
179
|
+
return names.filter((name, i) => name != null && (bits & (1 << i)) !== 0);
|
|
180
|
+
}
|
|
181
|
+
address() {
|
|
182
|
+
const at = this.take(32);
|
|
183
|
+
const hex = Array.from(this.bytes.subarray(at, at + 32), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
184
|
+
return `0x${hex.replace(/^0+(?=.)/, '')}`;
|
|
185
|
+
}
|
|
186
|
+
/** Moves past the fixed part, to the groups and texts after it. */
|
|
187
|
+
endBlock() {
|
|
188
|
+
this.offset = this.end;
|
|
189
|
+
this.end = this.bytes.byteLength;
|
|
190
|
+
}
|
|
191
|
+
/** A repeating group. Must be called after {@link endBlock}. */
|
|
192
|
+
group(read) {
|
|
193
|
+
const length = this.u16();
|
|
194
|
+
const count = this.u16();
|
|
195
|
+
const out = [];
|
|
196
|
+
for (let i = 0; i < count; i++) {
|
|
197
|
+
const start = this.take(length);
|
|
198
|
+
const entry = new Reader(this.bytes, 0);
|
|
199
|
+
entry.offset = start;
|
|
200
|
+
entry.end = start + length;
|
|
201
|
+
out.push(read(entry));
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/** A text; `''` if the message ends before it (an older server). */
|
|
206
|
+
text() {
|
|
207
|
+
if (this.offset === this.end)
|
|
208
|
+
return '';
|
|
209
|
+
const length = this.u8();
|
|
210
|
+
const at = this.take(length);
|
|
211
|
+
return new TextDecoder().decode(this.bytes.subarray(at, at + length));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function decimalString(mantissa, places) {
|
|
215
|
+
const negative = mantissa < 0n;
|
|
216
|
+
const digits = (negative ? -mantissa : mantissa)
|
|
217
|
+
.toString()
|
|
218
|
+
.padStart(places + 1, '0');
|
|
219
|
+
const fraction = digits.slice(-places).replace(/0+$/, '');
|
|
220
|
+
const whole = digits.slice(0, -places);
|
|
221
|
+
return `${negative ? '-' : ''}${whole}${fraction === '' ? '' : `.${fraction}`}`;
|
|
222
|
+
}
|
|
223
|
+
/** Drops the fields that are `''`, which the JSON feed leaves out. */
|
|
224
|
+
function present(fields) {
|
|
225
|
+
return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== ''));
|
|
226
|
+
}
|
|
227
|
+
function trade(r) {
|
|
228
|
+
r.i64(); // ts, the same as created_at
|
|
229
|
+
r.i64(); // seq, not in the JSON feed
|
|
230
|
+
const numericId = r.i64();
|
|
231
|
+
const side = r.oneOf(SIDE);
|
|
232
|
+
const price = r.decimal();
|
|
233
|
+
const size = r.decimal();
|
|
234
|
+
const createdAt = r.ms();
|
|
235
|
+
const tradeType = r.oneOf(FILL_TYPE);
|
|
236
|
+
r.endBlock();
|
|
237
|
+
const market = r.text();
|
|
238
|
+
const id = r.text();
|
|
239
|
+
return {
|
|
240
|
+
base: 'trades',
|
|
241
|
+
market,
|
|
242
|
+
data: {
|
|
243
|
+
// The numeric id is too small for a trade id and wraps.
|
|
244
|
+
id: id === '' ? numericId.toString() : id,
|
|
245
|
+
market,
|
|
246
|
+
side,
|
|
247
|
+
size,
|
|
248
|
+
price,
|
|
249
|
+
created_at: createdAt,
|
|
250
|
+
trade_type: tradeType,
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
function bbo(r) {
|
|
255
|
+
const lastUpdatedAt = r.ms();
|
|
256
|
+
const seqNo = Number(r.i64());
|
|
257
|
+
const bid = r.decimal();
|
|
258
|
+
const bidSize = r.decimal();
|
|
259
|
+
const ask = r.decimal();
|
|
260
|
+
const askSize = r.decimal();
|
|
261
|
+
r.endBlock();
|
|
262
|
+
const market = r.text();
|
|
263
|
+
return {
|
|
264
|
+
base: 'bbo',
|
|
265
|
+
market,
|
|
266
|
+
data: {
|
|
267
|
+
market,
|
|
268
|
+
seq_no: seqNo,
|
|
269
|
+
ask,
|
|
270
|
+
ask_size: askSize,
|
|
271
|
+
bid,
|
|
272
|
+
bid_size: bidSize,
|
|
273
|
+
last_updated_at: lastUpdatedAt,
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
function book(r) {
|
|
278
|
+
const lastUpdatedAt = r.ms();
|
|
279
|
+
const seqNo = Number(r.i64());
|
|
280
|
+
const snapshot = r.u8() === 0;
|
|
281
|
+
const best = (name, side) => {
|
|
282
|
+
const price = r.decimal();
|
|
283
|
+
const size = r.decimal();
|
|
284
|
+
return price === '' ? {} : { [name]: { side, price, size } };
|
|
285
|
+
};
|
|
286
|
+
const interactive = {
|
|
287
|
+
...best('best_bid_interactive', 'BUY'),
|
|
288
|
+
...best('best_ask_interactive', 'SELL'),
|
|
289
|
+
};
|
|
290
|
+
const relativeSpread = r.decimal();
|
|
291
|
+
const api = {
|
|
292
|
+
...best('best_bid_api', 'BUY'),
|
|
293
|
+
...best('best_ask_api', 'SELL'),
|
|
294
|
+
};
|
|
295
|
+
r.endBlock();
|
|
296
|
+
const level = (side) => (entry) => ({
|
|
297
|
+
side,
|
|
298
|
+
price: entry.decimal(),
|
|
299
|
+
size: entry.decimal(),
|
|
300
|
+
});
|
|
301
|
+
const levels = [...r.group(level('BUY')), ...r.group(level('SELL'))];
|
|
302
|
+
const market = r.text();
|
|
303
|
+
return {
|
|
304
|
+
base: 'order_book',
|
|
305
|
+
market,
|
|
306
|
+
data: {
|
|
307
|
+
seq_no: seqNo,
|
|
308
|
+
market,
|
|
309
|
+
last_updated_at: lastUpdatedAt,
|
|
310
|
+
update_type: snapshot ? 's' : 'd',
|
|
311
|
+
inserts: snapshot ? levels : [],
|
|
312
|
+
// A removed level has size 0. A new level and a changed one look the
|
|
313
|
+
// same, so both are updates.
|
|
314
|
+
updates: snapshot ? [] : levels.filter((l) => l.size !== '0'),
|
|
315
|
+
deletes: snapshot ? [] : levels.filter((l) => l.size === '0'),
|
|
316
|
+
...interactive,
|
|
317
|
+
...api,
|
|
318
|
+
...present({ relative_spread: relativeSpread }),
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function marketSummary(r) {
|
|
323
|
+
const createdAt = r.ms();
|
|
324
|
+
r.i64(); // seq, always 0
|
|
325
|
+
const markPrice = r.decimal();
|
|
326
|
+
const underlyingPrice = r.decimal();
|
|
327
|
+
const lastTradedPrice = r.decimal();
|
|
328
|
+
const volume24h = r.decimal();
|
|
329
|
+
const openInterest = r.decimal();
|
|
330
|
+
const roundedFundingRate = r.decimal();
|
|
331
|
+
const bid = r.decimal();
|
|
332
|
+
const ask = r.decimal();
|
|
333
|
+
const totalVolume = r.decimal();
|
|
334
|
+
const priceChangeRate24h = r.decimal();
|
|
335
|
+
const ivs = {
|
|
336
|
+
mark_iv: r.decimal(),
|
|
337
|
+
bid_iv: r.decimal(),
|
|
338
|
+
ask_iv: r.decimal(),
|
|
339
|
+
last_iv: r.decimal(),
|
|
340
|
+
};
|
|
341
|
+
const greeks = present({
|
|
342
|
+
delta: r.decimal(),
|
|
343
|
+
gamma: r.decimal(),
|
|
344
|
+
vega: r.decimal(),
|
|
345
|
+
theta: r.decimal(),
|
|
346
|
+
rho: r.decimal(),
|
|
347
|
+
volga: r.decimal(),
|
|
348
|
+
vanna: r.decimal(),
|
|
349
|
+
});
|
|
350
|
+
const futureFundingRate = r.decimal();
|
|
351
|
+
const externalFairPrice = r.decimal();
|
|
352
|
+
const bidSize = r.decimal();
|
|
353
|
+
const askSize = r.decimal();
|
|
354
|
+
const forwardRate = r.addedDecimal();
|
|
355
|
+
const riskFreeRate = r.addedDecimal();
|
|
356
|
+
const fundingRate = r.addedDecimal(12);
|
|
357
|
+
const settlementTwapEstimate = r.addedDecimal();
|
|
358
|
+
r.endBlock();
|
|
359
|
+
const market = r.text();
|
|
360
|
+
return {
|
|
361
|
+
base: 'markets_summary',
|
|
362
|
+
market,
|
|
363
|
+
data: {
|
|
364
|
+
symbol: market,
|
|
365
|
+
mark_price: markPrice,
|
|
366
|
+
last_traded_price: lastTradedPrice,
|
|
367
|
+
bid,
|
|
368
|
+
bid_size: bidSize,
|
|
369
|
+
ask,
|
|
370
|
+
ask_size: askSize,
|
|
371
|
+
volume_24h: volume24h,
|
|
372
|
+
total_volume: totalVolume,
|
|
373
|
+
created_at: createdAt,
|
|
374
|
+
underlying_price: underlyingPrice,
|
|
375
|
+
open_interest: openInterest,
|
|
376
|
+
funding_rate: fundingRate === '' ? roundedFundingRate : fundingRate,
|
|
377
|
+
price_change_rate_24h: priceChangeRate24h,
|
|
378
|
+
...present({
|
|
379
|
+
...ivs,
|
|
380
|
+
future_funding_rate: futureFundingRate,
|
|
381
|
+
external_fair_price: externalFairPrice,
|
|
382
|
+
forward_rate: forwardRate,
|
|
383
|
+
risk_free_rate: riskFreeRate,
|
|
384
|
+
settlement_twap_estimate: settlementTwapEstimate,
|
|
385
|
+
}),
|
|
386
|
+
...(Object.keys(greeks).length > 0 ? { greeks } : {}),
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function fundingData(r) {
|
|
391
|
+
r.i64(); // ts, the same as created_at
|
|
392
|
+
r.i64(); // seq, always 0
|
|
393
|
+
const fundingRate = r.decimal();
|
|
394
|
+
const fundingIndex = r.decimal();
|
|
395
|
+
const createdAt = r.ms();
|
|
396
|
+
const fundingPremium = r.decimal();
|
|
397
|
+
const fundingRate8h = r.decimal();
|
|
398
|
+
const fundingPeriodHours = r.i16();
|
|
399
|
+
const impactPremiumRate = r.addedDecimal();
|
|
400
|
+
r.endBlock();
|
|
401
|
+
const market = r.text();
|
|
402
|
+
return {
|
|
403
|
+
base: 'funding_data',
|
|
404
|
+
market,
|
|
405
|
+
data: {
|
|
406
|
+
market,
|
|
407
|
+
funding_index: fundingIndex,
|
|
408
|
+
funding_premium: fundingPremium,
|
|
409
|
+
funding_rate: fundingRate,
|
|
410
|
+
funding_rate_8h: fundingRate8h,
|
|
411
|
+
funding_period_hours: fundingPeriodHours,
|
|
412
|
+
created_at: createdAt,
|
|
413
|
+
...present({ impact_premium_rate: impactPremiumRate }),
|
|
414
|
+
},
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
function fundingRateComparison(r) {
|
|
418
|
+
r.i64(); // ts, the same as last_updated_at
|
|
419
|
+
const lastUpdatedAt = r.ms();
|
|
420
|
+
const hourlyFundingRate = r.decimal(12);
|
|
421
|
+
const assetKind = r.oneOf(ASSET_KIND);
|
|
422
|
+
const source = r.oneOf(FUNDING_SOURCE);
|
|
423
|
+
r.endBlock();
|
|
424
|
+
const market = r.text();
|
|
425
|
+
return {
|
|
426
|
+
base: 'funding_rate_comparison',
|
|
427
|
+
market,
|
|
428
|
+
data: {
|
|
429
|
+
asset_kind: `ASSET_KIND_${assetKind}`,
|
|
430
|
+
symbol: market,
|
|
431
|
+
source: `SOURCE_${source}`,
|
|
432
|
+
last_updated_at: lastUpdatedAt,
|
|
433
|
+
hourly_funding_rate: hourlyFundingRate,
|
|
434
|
+
},
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
function order(r) {
|
|
438
|
+
r.i64(); // ts, the same as last_updated_at
|
|
439
|
+
const seqNo = Number(r.i64());
|
|
440
|
+
const status = r.oneOf(ORDER_STATUS);
|
|
441
|
+
const side = r.oneOf(SIDE);
|
|
442
|
+
const type = r.oneOf(ORDER_TYPE);
|
|
443
|
+
const instruction = r.oneOf(INSTRUCTION);
|
|
444
|
+
const price = r.decimal();
|
|
445
|
+
const triggerPrice = r.decimal();
|
|
446
|
+
const size = r.decimal();
|
|
447
|
+
const remainingSize = r.decimal();
|
|
448
|
+
const avgFillPrice = r.decimal();
|
|
449
|
+
const createdAt = r.ms();
|
|
450
|
+
const lastUpdatedAt = r.ms();
|
|
451
|
+
const account = r.address();
|
|
452
|
+
const receivedAt = r.ms();
|
|
453
|
+
const publishedAt = r.ms();
|
|
454
|
+
const stp = r.oneOf(STP);
|
|
455
|
+
const flags = r.flags(ORDER_FLAGS);
|
|
456
|
+
const request = r.has(2)
|
|
457
|
+
? {
|
|
458
|
+
status: r.oneOf(REQUEST_STATUS),
|
|
459
|
+
request_type: r.oneOf(REQUEST_TYPE),
|
|
460
|
+
}
|
|
461
|
+
: undefined;
|
|
462
|
+
r.endBlock();
|
|
463
|
+
const id = r.text();
|
|
464
|
+
const clientId = r.text();
|
|
465
|
+
const market = r.text();
|
|
466
|
+
const cancelReason = r.text();
|
|
467
|
+
const requestId = r.text();
|
|
468
|
+
const requestMessage = r.text();
|
|
469
|
+
return {
|
|
470
|
+
base: 'orders',
|
|
471
|
+
market,
|
|
472
|
+
data: {
|
|
473
|
+
id,
|
|
474
|
+
account,
|
|
475
|
+
market,
|
|
476
|
+
side,
|
|
477
|
+
type,
|
|
478
|
+
size,
|
|
479
|
+
remaining_size: remainingSize,
|
|
480
|
+
price,
|
|
481
|
+
status,
|
|
482
|
+
created_at: createdAt,
|
|
483
|
+
last_updated_at: lastUpdatedAt,
|
|
484
|
+
cancel_reason: cancelReason,
|
|
485
|
+
client_id: clientId,
|
|
486
|
+
seq_no: seqNo,
|
|
487
|
+
instruction,
|
|
488
|
+
avg_fill_price: avgFillPrice,
|
|
489
|
+
stp,
|
|
490
|
+
received_at: receivedAt,
|
|
491
|
+
published_at: publishedAt,
|
|
492
|
+
flags,
|
|
493
|
+
trigger_price: triggerPrice,
|
|
494
|
+
// Absent only when both are UNSPECIFIED: the server sets them apart.
|
|
495
|
+
...(request != null &&
|
|
496
|
+
(request.status !== 'UNSPECIFIED' ||
|
|
497
|
+
request.request_type !== 'UNSPECIFIED')
|
|
498
|
+
? {
|
|
499
|
+
request_info: {
|
|
500
|
+
id: requestId,
|
|
501
|
+
message: requestMessage,
|
|
502
|
+
...request,
|
|
503
|
+
},
|
|
504
|
+
}
|
|
505
|
+
: {}),
|
|
506
|
+
},
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function fill(r) {
|
|
510
|
+
r.i64(); // ts, the same as created_at
|
|
511
|
+
r.i64(); // seq, the same as orderbook_seq_no
|
|
512
|
+
const fillType = r.oneOf(FILL_TYPE);
|
|
513
|
+
const side = r.oneOf(SIDE);
|
|
514
|
+
const liquidity = r.oneOf(LIQUIDITY);
|
|
515
|
+
const price = r.decimal();
|
|
516
|
+
const size = r.decimal();
|
|
517
|
+
const fee = r.decimal();
|
|
518
|
+
const realizedPnl = r.decimal();
|
|
519
|
+
const createdAt = r.ms();
|
|
520
|
+
const account = r.address();
|
|
521
|
+
const underlyingPrice = r.decimal();
|
|
522
|
+
const realizedFunding = r.decimal();
|
|
523
|
+
const flags = r.has(1) ? r.flags(FILL_FLAGS) : [];
|
|
524
|
+
const orderbookSeqNo = r.has(8) ? Number(r.u64()) : 0;
|
|
525
|
+
r.endBlock();
|
|
526
|
+
const id = r.text();
|
|
527
|
+
const orderId = r.text();
|
|
528
|
+
const clientId = r.text();
|
|
529
|
+
r.text(); // trade id, always empty
|
|
530
|
+
const market = r.text();
|
|
531
|
+
const feeCurrency = r.text();
|
|
532
|
+
return {
|
|
533
|
+
base: 'fills',
|
|
534
|
+
market,
|
|
535
|
+
data: {
|
|
536
|
+
id,
|
|
537
|
+
side,
|
|
538
|
+
liquidity,
|
|
539
|
+
market,
|
|
540
|
+
order_id: orderId,
|
|
541
|
+
price,
|
|
542
|
+
size,
|
|
543
|
+
fee,
|
|
544
|
+
fee_currency: feeCurrency,
|
|
545
|
+
created_at: createdAt,
|
|
546
|
+
client_id: clientId,
|
|
547
|
+
fill_type: fillType,
|
|
548
|
+
realized_pnl: realizedPnl,
|
|
549
|
+
realized_funding: realizedFunding,
|
|
550
|
+
account,
|
|
551
|
+
underlying_price: underlyingPrice,
|
|
552
|
+
flags,
|
|
553
|
+
...(orderbookSeqNo !== 0 ? { orderbook_seq_no: orderbookSeqNo } : {}),
|
|
554
|
+
},
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
function position(r) {
|
|
558
|
+
r.i64(); // ts, the same as last_updated_at
|
|
559
|
+
const seqNo = Number(r.i64());
|
|
560
|
+
const side = r.oneOf(POSITION_SIDE);
|
|
561
|
+
const size = r.decimal();
|
|
562
|
+
const averageEntryPrice = r.decimal();
|
|
563
|
+
const unrealizedPnl = r.decimal();
|
|
564
|
+
const realizedPnl = r.decimal();
|
|
565
|
+
r.i64(); // mark price, always empty
|
|
566
|
+
const liquidationPrice = r.decimal();
|
|
567
|
+
const leverage = r.decimal();
|
|
568
|
+
const lastUpdatedAt = r.ms();
|
|
569
|
+
const account = r.address();
|
|
570
|
+
const averageEntryPriceUsd = r.decimal();
|
|
571
|
+
const cost = r.decimal();
|
|
572
|
+
const costUsd = r.decimal();
|
|
573
|
+
const cachedFundingIndex = r.decimal();
|
|
574
|
+
const unrealizedFundingPnl = r.decimal();
|
|
575
|
+
const status = r.oneOf(POSITION_STATUS);
|
|
576
|
+
r.endBlock();
|
|
577
|
+
const market = r.text();
|
|
578
|
+
const lastFillId = r.text();
|
|
579
|
+
return {
|
|
580
|
+
base: 'positions',
|
|
581
|
+
market,
|
|
582
|
+
data: {
|
|
583
|
+
account,
|
|
584
|
+
market,
|
|
585
|
+
status,
|
|
586
|
+
side,
|
|
587
|
+
// The message has the size without its sign; the JSON feed signs it.
|
|
588
|
+
size: side === 'SHORT' && size !== '0' ? `-${size}` : size,
|
|
589
|
+
average_entry_price: averageEntryPrice,
|
|
590
|
+
average_entry_price_usd: averageEntryPriceUsd,
|
|
591
|
+
unrealized_pnl: unrealizedPnl,
|
|
592
|
+
unrealized_funding_pnl: unrealizedFundingPnl,
|
|
593
|
+
cost,
|
|
594
|
+
cost_usd: costUsd,
|
|
595
|
+
cached_funding_index: cachedFundingIndex,
|
|
596
|
+
last_updated_at: lastUpdatedAt,
|
|
597
|
+
last_fill_id: lastFillId,
|
|
598
|
+
seq_no: seqNo,
|
|
599
|
+
liquidation_price: liquidationPrice,
|
|
600
|
+
leverage,
|
|
601
|
+
realized_positional_pnl: realizedPnl,
|
|
602
|
+
},
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
function account(r) {
|
|
606
|
+
r.i64(); // ts, the same as updated_at
|
|
607
|
+
const seqNo = Number(r.i64());
|
|
608
|
+
const totalCollateral = r.decimal();
|
|
609
|
+
const freeCollateral = r.decimal();
|
|
610
|
+
const initialMargin = r.decimal();
|
|
611
|
+
const maintenanceMargin = r.decimal();
|
|
612
|
+
const accountValue = r.decimal();
|
|
613
|
+
r.i64(); // unrealized PnL, always empty
|
|
614
|
+
const updatedAt = r.ms();
|
|
615
|
+
const address = r.address();
|
|
616
|
+
const marginCushion = r.decimal();
|
|
617
|
+
const status = r.oneOf(ACCOUNT_STATUS);
|
|
618
|
+
const lastSeenNotification = r.has(8) ? r.ms() : 0;
|
|
619
|
+
r.endBlock();
|
|
620
|
+
const settlementAsset = r.text();
|
|
621
|
+
return {
|
|
622
|
+
base: 'account',
|
|
623
|
+
market: undefined,
|
|
624
|
+
data: {
|
|
625
|
+
account: address,
|
|
626
|
+
initial_margin_requirement: initialMargin,
|
|
627
|
+
maintenance_margin_requirement: maintenanceMargin,
|
|
628
|
+
account_value: accountValue,
|
|
629
|
+
total_collateral: totalCollateral,
|
|
630
|
+
free_collateral: freeCollateral,
|
|
631
|
+
margin_cushion: marginCushion,
|
|
632
|
+
settlement_asset: settlementAsset,
|
|
633
|
+
updated_at: updatedAt,
|
|
634
|
+
status,
|
|
635
|
+
seq_no: seqNo,
|
|
636
|
+
last_seen_notification: lastSeenNotification,
|
|
637
|
+
},
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
const MESSAGES = {
|
|
641
|
+
1: trade,
|
|
642
|
+
2: bbo,
|
|
643
|
+
3: book,
|
|
644
|
+
4: marketSummary,
|
|
645
|
+
5: fundingData,
|
|
646
|
+
6: fundingRateComparison,
|
|
647
|
+
20: order,
|
|
648
|
+
21: fill,
|
|
649
|
+
22: position,
|
|
650
|
+
23: account,
|
|
651
|
+
};
|
|
652
|
+
/** Heartbeat and subscribed: nothing to hand to a subscriber. */
|
|
653
|
+
const CONTROL_MESSAGES = new Set([40, 41]);
|
|
654
|
+
/** Channels whose messages are binary, so carry no channel name. */
|
|
655
|
+
const BINARY_BASES = new Set([
|
|
656
|
+
'trades',
|
|
657
|
+
'bbo',
|
|
658
|
+
'order_book',
|
|
659
|
+
'markets_summary',
|
|
660
|
+
'funding_data',
|
|
661
|
+
'funding_rate_comparison',
|
|
662
|
+
'orders',
|
|
663
|
+
'fills',
|
|
664
|
+
'positions',
|
|
665
|
+
'account',
|
|
666
|
+
]);
|
|
667
|
+
/** Whether `bytes` is a binary message rather than text sent as bytes. */
|
|
668
|
+
export function isSbeFrame(bytes) {
|
|
669
|
+
// The schema id. A zero byte never occurs in JSON text.
|
|
670
|
+
return (bytes.byteLength >= HEADER_LENGTH &&
|
|
671
|
+
(bytes[4] ?? 0) + (bytes[5] ?? 0) * 256 === SCHEMA_ID);
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Reads one message; `undefined` for a control message.
|
|
675
|
+
*
|
|
676
|
+
* @throws SbeDecodeError if it is malformed or of a type not known here.
|
|
677
|
+
*/
|
|
678
|
+
export function decodeSbe(bytes) {
|
|
679
|
+
if (!isSbeFrame(bytes)) {
|
|
680
|
+
throw new SbeDecodeError('not a Paradex binary message');
|
|
681
|
+
}
|
|
682
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
683
|
+
const blockLength = view.getUint16(0, true);
|
|
684
|
+
const templateId = view.getUint16(2, true);
|
|
685
|
+
if (CONTROL_MESSAGES.has(templateId))
|
|
686
|
+
return undefined;
|
|
687
|
+
const read = MESSAGES[templateId];
|
|
688
|
+
if (read == null) {
|
|
689
|
+
throw new SbeDecodeError(`unknown message type ${templateId}`);
|
|
690
|
+
}
|
|
691
|
+
return read(new Reader(bytes, blockLength));
|
|
692
|
+
}
|
|
693
|
+
/** The market a channel of binary messages covers; `undefined` for all. */
|
|
694
|
+
function channelMarket(channel) {
|
|
695
|
+
const name = channel.split('.')[1]?.split('@')[0];
|
|
696
|
+
return name == null || name === 'ALL' ? undefined : name;
|
|
697
|
+
}
|
|
698
|
+
function channelBase(channel) {
|
|
699
|
+
return channel.split('.')[0]?.split('@')[0] ?? channel;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Account channels that take a market. The SDK subscribes to their `.ALL`
|
|
703
|
+
* channel once and filters by market itself, so `orders.ALL` and
|
|
704
|
+
* `orders.BTC-USD-PERP` can be open together.
|
|
705
|
+
*/
|
|
706
|
+
const SHARED_BASES = new Set(['orders', 'fills']);
|
|
707
|
+
/** The channel the server is asked for to serve `channel`. */
|
|
708
|
+
export function subscriptionChannel(channel) {
|
|
709
|
+
const base = channelBase(channel);
|
|
710
|
+
return SHARED_BASES.has(base) ? `${base}.ALL` : channel;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Whether a text message the server sent on `sent` is one that `channel`
|
|
714
|
+
* delivers: the same channel, or the shared `.ALL` channel serving it with
|
|
715
|
+
* a matching market.
|
|
716
|
+
*/
|
|
717
|
+
export function channelDeliversText(channel, sent, data) {
|
|
718
|
+
if (channel === sent)
|
|
719
|
+
return true;
|
|
720
|
+
if (subscriptionChannel(channel) !== sent)
|
|
721
|
+
return false;
|
|
722
|
+
const market = channelMarket(channel);
|
|
723
|
+
return (market == null ||
|
|
724
|
+
data?.market === market);
|
|
725
|
+
}
|
|
726
|
+
/** Whether `message` is one that `channel` delivers. */
|
|
727
|
+
export function channelDelivers(channel, message) {
|
|
728
|
+
if (channelBase(channel) !== message.base)
|
|
729
|
+
return false;
|
|
730
|
+
const market = channelMarket(channel);
|
|
731
|
+
return market == null || message.market == null || market === message.market;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Whether the messages of two channels can't be told apart on one
|
|
735
|
+
* connection: binary ones that share a market.
|
|
736
|
+
*/
|
|
737
|
+
export function channelsOverlap(a, b) {
|
|
738
|
+
const base = channelBase(a);
|
|
739
|
+
if (a === b || base !== channelBase(b) || !BINARY_BASES.has(base)) {
|
|
740
|
+
return false;
|
|
741
|
+
}
|
|
742
|
+
const [marketA, marketB] = [channelMarket(a), channelMarket(b)];
|
|
743
|
+
return marketA == null || marketB == null || marketA === marketB;
|
|
744
|
+
}
|