nodejs-order-book 8.0.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.
@@ -0,0 +1,847 @@
1
+ var __assign = (this && this.__assign) || function () {
2
+ __assign = Object.assign || function(t) {
3
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
4
+ s = arguments[i];
5
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6
+ t[p] = s[p];
7
+ }
8
+ return t;
9
+ };
10
+ return __assign.apply(this, arguments);
11
+ };
12
+ /* node:coverage ignore next - Don't know why first and last line of each file count as uncovered */
13
+ import { CustomError, ERROR } from "./errors";
14
+ import { OrderFactory, } from "./order";
15
+ import { OrderSide } from "./orderside";
16
+ import { StopBook } from "./stopbook";
17
+ import { OrderType, Side, TimeInForce, } from "./types";
18
+ var validTimeInForce = Object.values(TimeInForce);
19
+ var OrderBook = /** @class */ (function () {
20
+ /**
21
+ * Creates an instance of OrderBook.
22
+ * @param {OrderBookOptions} [options={}] - Options for configuring the order book.
23
+ * @param {JournalLog} [options.snapshot] - The orderbook snapshot will be restored before processing any journal logs, if any.
24
+ * @param {JournalLog} [options.journal] - Array of journal logs (optional).
25
+ * @param {boolean} [options.enableJournaling=false] - Flag to enable journaling. Default to false
26
+ * @param {boolean} [options.experimentalConditionalOrders=false] - Flag to enable experimental Conditional Order (Stop Market, Stop Limit and OCO orders). Default to false
27
+ */
28
+ function OrderBook(_a) {
29
+ var _b = _a === void 0 ? {} : _a, snapshot = _b.snapshot, journal = _b.journal, _c = _b.enableJournaling, enableJournaling = _c === void 0 ? false : _c, _d = _b.experimentalConditionalOrders, experimentalConditionalOrders = _d === void 0 ? false : _d;
30
+ var _this = this;
31
+ this.orders = {};
32
+ this._lastOp = 0;
33
+ this._marketPrice = 0;
34
+ /**
35
+ * Create a stop market order. See {@link StopMarketOrderOptions} for details.
36
+ *
37
+ * @param options
38
+ * @param options.side - `sell` or `buy`
39
+ * @param options.size - How much of currency you want to trade in units of base currency
40
+ * @param options.stopPrice - The price at which the order will be triggered.
41
+ * @returns An object with the result of the processed order or an error. See {@link IProcessOrder} for the returned data structure
42
+ */
43
+ this.stopMarket = function (options) {
44
+ /* node:coverage ignore next 4 - We don't need test for this */
45
+ if (!_this.experimentalConditionalOrders)
46
+ throw new Error("In order to use conditional orders you need to instantiate the order book with the `experimentalConditionalOrders` option set to true");
47
+ return _this._stopMarket(options);
48
+ };
49
+ /**
50
+ * Create a stop limit order. See {@link StopLimitOrderOptions} for details.
51
+ *
52
+ * @param options
53
+ * @param options.side - `sell` or `buy`
54
+ * @param options.id - Unique order ID
55
+ * @param options.size - How much of currency you want to trade in units of base currency
56
+ * @param options.price - The price at which the order is to be fullfilled, in units of the quote currency
57
+ * @param options.stopPrice - The price at which the order will be triggered.
58
+ * @param options.timeInForce - Time-in-force type supported are: GTC, FOK, IOC. Default is GTC
59
+ * @returns An object with the result of the processed order or an error. See {@link IProcessOrder} for the returned data structure
60
+ */
61
+ this.stopLimit = function (options) {
62
+ /* node:coverage ignore next 4 - We don't need test for this */
63
+ if (!_this.experimentalConditionalOrders)
64
+ throw new Error("In order to use conditional orders you need to instantiate the order book with the `experimentalConditionalOrders` option set to true");
65
+ return _this._stopLimit(options);
66
+ };
67
+ /**
68
+ * Create an OCO (One-Cancels-the-Other) order.
69
+ * OCO order combines a `stop_limit` order and a `limit` order, where if stop price
70
+ * is triggered or limit order is fully or partially fulfilled, the other is canceled.
71
+ * Both orders have the same `side` and `size`. If you cancel one of the orders, the
72
+ * entire OCO order pair will be canceled.
73
+ *
74
+ * For BUY orders the `stopPrice` must be above the current price and the `price` below the current price
75
+ * For SELL orders the `stopPrice` must be below the current price and the `price` above the current price
76
+ *
77
+ * See {@link OCOOrderOptions} for details.
78
+ *
79
+ * @param options
80
+ * @param options.side - `sell` or `buy`
81
+ * @param options.id - Unique order ID
82
+ * @param options.size - How much of currency you want to trade in units of base currency
83
+ * @param options.price - The price of the `limit` order at which the order is to be fullfilled, in units of the quote currency
84
+ * @param options.stopPrice - The price at which the `stop_limit` order will be triggered.
85
+ * @param options.stopLimitPrice - The price of the `stop_limit` order at which the order is to be fullfilled, in units of the quote currency.
86
+ * @param options.timeInForce - Time-in-force of the `limit` order. Type supported are: GTC, FOK, IOC. Default is GTC
87
+ * @param options.stopLimitTimeInForce - Time-in-force of the `stop_limit` order. Type supported are: GTC, FOK, IOC. Default is GTC
88
+ * @returns An object with the result of the processed order or an error. See {@link IProcessOrder} for the returned data structure
89
+ */
90
+ this.oco = function (options) {
91
+ /* node:coverage ignore next 4 - We don't need test for this */
92
+ if (!_this.experimentalConditionalOrders)
93
+ throw new Error("In order to use conditional orders you need to instantiate the order book with the `experimentalConditionalOrders` option set to true");
94
+ return _this._oco(options);
95
+ };
96
+ /**
97
+ * Modify an existing order with given ID. When an order is modified by price or quantity,
98
+ * it will be deemed as a new entry. Under the price-time-priority algorithm, orders are
99
+ * prioritized according to their order price and order time. Hence, the latest orders
100
+ * will be placed at the back of the matching order queue.
101
+ *
102
+ * @param orderID - The ID of the order to be modified
103
+ * @param orderUpdate - An object with the modified size and/or price of an order. The shape of the object is `{size, price}`.
104
+ * @returns An object with the result of the processed order or an error
105
+ */
106
+ this.modify = function (orderID, orderUpdate) {
107
+ var _a, _b, _c;
108
+ var order = _this.orders[orderID];
109
+ if (order === undefined) {
110
+ return {
111
+ done: [],
112
+ activated: [],
113
+ partial: null,
114
+ partialQuantityProcessed: 0,
115
+ quantityLeft: 0,
116
+ err: CustomError(ERROR.ORDER_NOT_FOUND),
117
+ };
118
+ }
119
+ if ((orderUpdate === null || orderUpdate === void 0 ? void 0 : orderUpdate.price) !== undefined || (orderUpdate === null || orderUpdate === void 0 ? void 0 : orderUpdate.size) !== undefined) {
120
+ var newPrice = (_a = orderUpdate.price) !== null && _a !== void 0 ? _a : order.price;
121
+ var newSize = (_b = orderUpdate.size) !== null && _b !== void 0 ? _b : order.size;
122
+ if (newPrice > 0 && newSize > 0) {
123
+ var response = _this.getProcessOrderResponse(newSize);
124
+ _this._cancelOrder(order.id, true);
125
+ _this.createLimitOrder(response, order.side, order.id, newSize, newPrice, order.postOnly, TimeInForce.GTC);
126
+ if (_this.enableJournaling) {
127
+ response.log = {
128
+ opId: ++_this._lastOp,
129
+ ts: Date.now(),
130
+ op: "u",
131
+ o: { orderID: orderID, orderUpdate: orderUpdate },
132
+ };
133
+ }
134
+ return response;
135
+ }
136
+ }
137
+ // Missing one of price and/or size, or the provided ones are not greater than zero
138
+ return {
139
+ done: [],
140
+ activated: [],
141
+ partial: null,
142
+ partialQuantityProcessed: 0,
143
+ quantityLeft: (_c = orderUpdate === null || orderUpdate === void 0 ? void 0 : orderUpdate.size) !== null && _c !== void 0 ? _c : 0,
144
+ err: CustomError(ERROR.INVALID_PRICE_OR_QUANTITY),
145
+ };
146
+ };
147
+ /**
148
+ * Remove an existing order with given ID from the order book
149
+ *
150
+ * @param orderID - The ID of the order to be removed
151
+ * @returns The removed order if exists or `undefined`
152
+ */
153
+ this.cancel = function (orderID) {
154
+ return _this._cancelOrder(orderID);
155
+ };
156
+ /**
157
+ * Get an existing order with the given ID
158
+ *
159
+ * @param orderID - The ID of the order to be returned
160
+ * @returns The order if exists or `undefined`
161
+ */
162
+ this.order = function (orderID) {
163
+ return _this.orders[orderID];
164
+ };
165
+ // Returns price levels and volume at price level
166
+ this.depth = function () {
167
+ var asks = [];
168
+ var bids = [];
169
+ _this.asks.priceTree().forEach(function (levelPrice, level) {
170
+ asks.push([levelPrice, level.volume()]);
171
+ });
172
+ _this.bids.priceTree().forEach(function (levelPrice, level) {
173
+ bids.push([levelPrice, level.volume()]);
174
+ });
175
+ return [asks, bids];
176
+ };
177
+ this.toString = function () {
178
+ /* node:coverage ignore next - Don't know what is the uncovered branch here */
179
+ return "".concat(_this.asks.toString(), "\r\n------------------------------------").concat(_this.bids.toString());
180
+ };
181
+ // Returns total market price for requested quantity
182
+ // if err is not null price returns total price of all levels in side
183
+ this.calculateMarketPrice = function (side, size) {
184
+ var price = 0;
185
+ var err = null;
186
+ var level;
187
+ var iter;
188
+ var quantity = size;
189
+ if (side === Side.BUY) {
190
+ level = _this.asks.minPriceQueue();
191
+ iter = _this.asks.greaterThan;
192
+ }
193
+ else {
194
+ level = _this.bids.maxPriceQueue();
195
+ iter = _this.bids.lowerThan;
196
+ }
197
+ while (quantity > 0 && level !== undefined) {
198
+ var levelVolume = level.volume();
199
+ var levelPrice = level.price();
200
+ if (_this.greaterThanOrEqual(quantity, levelVolume)) {
201
+ price += levelPrice * levelVolume;
202
+ quantity -= levelVolume;
203
+ level = iter(levelPrice);
204
+ }
205
+ else {
206
+ price += levelPrice * quantity;
207
+ quantity = 0;
208
+ }
209
+ }
210
+ if (quantity > 0) {
211
+ err = CustomError(ERROR.INSUFFICIENT_QUANTITY);
212
+ }
213
+ return { price: price, err: err };
214
+ };
215
+ this.snapshot = function () {
216
+ var bids = [];
217
+ var asks = [];
218
+ _this.bids.priceTree().forEach(function (price, orders) {
219
+ bids.push({ price: price, orders: orders.toArray() });
220
+ });
221
+ _this.asks.priceTree().forEach(function (price, orders) {
222
+ asks.push({ price: price, orders: orders.toArray() });
223
+ });
224
+ return { bids: bids, asks: asks, ts: Date.now(), lastOp: _this._lastOp };
225
+ };
226
+ this._market = function (options, incomingResponse) {
227
+ var response = incomingResponse !== null && incomingResponse !== void 0 ? incomingResponse : _this.validateMarketOrder(options);
228
+ if (response.err != null)
229
+ return response;
230
+ var quantityToTrade = options.size;
231
+ var iter;
232
+ var sideToProcess;
233
+ if (options.side === Side.BUY) {
234
+ iter = _this.asks.minPriceQueue;
235
+ sideToProcess = _this.asks;
236
+ }
237
+ else {
238
+ iter = _this.bids.maxPriceQueue;
239
+ sideToProcess = _this.bids;
240
+ }
241
+ var priceBefore = _this._marketPrice;
242
+ while (quantityToTrade > 0 && sideToProcess.len() > 0) {
243
+ // if sideToProcess.len > 0 it is not necessary to verify that bestPrice exists
244
+ var bestPrice = iter();
245
+ var _a = _this.processQueue(bestPrice, quantityToTrade), done = _a.done, partial = _a.partial, partialQuantityProcessed = _a.partialQuantityProcessed, quantityLeft = _a.quantityLeft;
246
+ response.done = response.done.concat(done);
247
+ response.partial = partial;
248
+ response.partialQuantityProcessed = partialQuantityProcessed;
249
+ quantityToTrade = quantityLeft;
250
+ }
251
+ response.quantityLeft = quantityToTrade;
252
+ _this.executeConditionalOrder(options.side, priceBefore, response);
253
+ if (_this.enableJournaling) {
254
+ response.log = {
255
+ opId: ++_this._lastOp,
256
+ ts: Date.now(),
257
+ op: "m",
258
+ o: { side: options.side, size: options.size },
259
+ };
260
+ }
261
+ return response;
262
+ };
263
+ this._limit = function (options, incomingResponse) {
264
+ var _a, _b;
265
+ var response = incomingResponse !== null && incomingResponse !== void 0 ? incomingResponse : _this.validateLimitOrder(options);
266
+ if (response.err != null)
267
+ return response;
268
+ var order = _this.createLimitOrder(response, options.side, options.id, options.size, options.price, (_a = options.postOnly) !== null && _a !== void 0 ? _a : false, (_b = options.timeInForce) !== null && _b !== void 0 ? _b : TimeInForce.GTC, options.ocoStopPrice);
269
+ if (_this.enableJournaling && order != null) {
270
+ response.log = {
271
+ opId: ++_this._lastOp,
272
+ ts: Date.now(),
273
+ op: "l",
274
+ o: {
275
+ side: order.side,
276
+ id: order.id,
277
+ size: order.size,
278
+ price: order.price,
279
+ timeInForce: order.timeInForce,
280
+ },
281
+ };
282
+ }
283
+ return response;
284
+ };
285
+ this._stopMarket = function (options) {
286
+ var response = _this.validateMarketOrder(options);
287
+ if (response.err != null)
288
+ return response;
289
+ var stopMarket = OrderFactory.createOrder(__assign(__assign({}, options), { type: OrderType.STOP_MARKET }));
290
+ return _this._stopOrder(stopMarket, response);
291
+ };
292
+ this._stopLimit = function (options) {
293
+ var _a;
294
+ var response = _this.validateLimitOrder(options);
295
+ if (response.err != null)
296
+ return response;
297
+ var stopLimit = OrderFactory.createOrder(__assign(__assign({}, options), { type: OrderType.STOP_LIMIT, timeInForce: (_a = options.timeInForce) !== null && _a !== void 0 ? _a : TimeInForce.GTC }));
298
+ return _this._stopOrder(stopLimit, response);
299
+ };
300
+ this._oco = function (options) {
301
+ var _a;
302
+ var response = _this.validateLimitOrder(options);
303
+ /* node:coverage ignore next - Already validated with limit test */
304
+ if (response.err != null)
305
+ return response;
306
+ if (_this.validateOCOOrder(options)) {
307
+ // We use the same ID for Stop Limit and Limit Order, since
308
+ // we check only on limit order for duplicated ids
309
+ _this._limit({
310
+ id: options.id,
311
+ side: options.side,
312
+ size: options.size,
313
+ price: options.price,
314
+ timeInForce: options.timeInForce,
315
+ ocoStopPrice: options.stopPrice,
316
+ }, response);
317
+ /* node:coverage ignore next - Already validated with limit test */
318
+ if (response.err != null)
319
+ return response;
320
+ var stopLimit = OrderFactory.createOrder({
321
+ type: OrderType.STOP_LIMIT,
322
+ id: options.id,
323
+ side: options.side,
324
+ size: options.size,
325
+ price: options.stopLimitPrice,
326
+ stopPrice: options.stopPrice,
327
+ timeInForce: (_a = options.stopLimitTimeInForce) !== null && _a !== void 0 ? _a : TimeInForce.GTC,
328
+ isOCO: true,
329
+ });
330
+ _this.stopBook.add(stopLimit);
331
+ response.done.push(stopLimit);
332
+ }
333
+ else {
334
+ response.err = CustomError(ERROR.INVALID_CONDITIONAL_ORDER);
335
+ }
336
+ return response;
337
+ };
338
+ this._stopOrder = function (stopOrder, response) {
339
+ if (_this.stopBook.validConditionalOrder(_this._marketPrice, stopOrder)) {
340
+ _this.stopBook.add(stopOrder);
341
+ response.done.push(stopOrder);
342
+ }
343
+ else {
344
+ response.err = CustomError(ERROR.INVALID_CONDITIONAL_ORDER);
345
+ }
346
+ return response;
347
+ };
348
+ this.restoreSnapshot = function (snapshot) {
349
+ _this._lastOp = snapshot.lastOp;
350
+ for (var _i = 0, _a = snapshot.bids; _i < _a.length; _i++) {
351
+ var level = _a[_i];
352
+ for (var _b = 0, _c = level.orders; _b < _c.length; _b++) {
353
+ var order = _c[_b];
354
+ _this.orders[order.id] = order;
355
+ _this.bids.append(order);
356
+ }
357
+ }
358
+ for (var _d = 0, _e = snapshot.asks; _d < _e.length; _d++) {
359
+ var level = _e[_d];
360
+ for (var _f = 0, _g = level.orders; _f < _g.length; _f++) {
361
+ var order = _g[_f];
362
+ _this.orders[order.id] = order;
363
+ _this.asks.append(order);
364
+ }
365
+ }
366
+ };
367
+ /**
368
+ * Remove an existing order with given ID from the order book
369
+ * @param orderID The id of the order to be deleted
370
+ * @param internalDeletion Set to true when the delete comes from internal operations
371
+ * @returns The removed order if exists or `undefined`
372
+ */
373
+ this._cancelOrder = function (orderID, internalDeletion) {
374
+ if (internalDeletion === void 0) { internalDeletion = false; }
375
+ var order = _this.orders[orderID];
376
+ if (order === undefined)
377
+ return;
378
+ delete _this.orders[orderID];
379
+ var side = order.side === Side.BUY ? _this.bids : _this.asks;
380
+ var response = {
381
+ order: side.remove(order),
382
+ };
383
+ // Delete OCO Order only when the delete request comes from user
384
+ if (!internalDeletion && order.ocoStopPrice !== undefined) {
385
+ response.stopOrder = _this.stopBook.remove(order.side, orderID, order.ocoStopPrice);
386
+ }
387
+ if (_this.enableJournaling) {
388
+ response.log = {
389
+ opId: internalDeletion ? _this._lastOp : ++_this._lastOp,
390
+ ts: Date.now(),
391
+ op: "d",
392
+ o: { orderID: orderID },
393
+ };
394
+ }
395
+ return response;
396
+ };
397
+ this.getProcessOrderResponse = function (size) {
398
+ return {
399
+ done: [],
400
+ activated: [],
401
+ partial: null,
402
+ partialQuantityProcessed: 0,
403
+ quantityLeft: size,
404
+ err: null,
405
+ };
406
+ };
407
+ this.createLimitOrder = function (response, side, orderID, size, price, postOnly, timeInForce, ocoStopPrice) {
408
+ var quantityToTrade = size;
409
+ var sideToProcess;
410
+ var sideToAdd;
411
+ var comparator;
412
+ var iter;
413
+ if (side === Side.BUY) {
414
+ sideToAdd = _this.bids;
415
+ sideToProcess = _this.asks;
416
+ comparator = _this.greaterThanOrEqual;
417
+ iter = _this.asks.minPriceQueue;
418
+ }
419
+ else {
420
+ sideToAdd = _this.asks;
421
+ sideToProcess = _this.bids;
422
+ comparator = _this.lowerThanOrEqual;
423
+ iter = _this.bids.maxPriceQueue;
424
+ }
425
+ if (timeInForce === TimeInForce.FOK) {
426
+ var fillable = _this.canFillOrder(sideToProcess, side, size, price);
427
+ if (!fillable) {
428
+ response.err = CustomError(ERROR.LIMIT_ORDER_FOK_NOT_FILLABLE);
429
+ return;
430
+ }
431
+ }
432
+ var bestPrice = iter();
433
+ var priceBefore = _this._marketPrice;
434
+ while (quantityToTrade > 0 &&
435
+ sideToProcess.len() > 0 &&
436
+ bestPrice !== undefined &&
437
+ comparator(price, bestPrice.price())) {
438
+ if (postOnly) {
439
+ response.err = CustomError(ERROR.LIMIT_ORDER_POST_ONLY);
440
+ return;
441
+ }
442
+ var _a = _this.processQueue(bestPrice, quantityToTrade), done = _a.done, partial = _a.partial, partialQuantityProcessed = _a.partialQuantityProcessed, quantityLeft = _a.quantityLeft;
443
+ response.done = response.done.concat(done);
444
+ response.partial = partial;
445
+ response.partialQuantityProcessed = partialQuantityProcessed;
446
+ quantityToTrade = quantityLeft;
447
+ response.quantityLeft = quantityToTrade;
448
+ bestPrice = iter();
449
+ }
450
+ _this.executeConditionalOrder(side, priceBefore, response);
451
+ var order;
452
+ var takerQty = size - quantityToTrade;
453
+ var makerQty = quantityToTrade;
454
+ if (quantityToTrade > 0) {
455
+ order = OrderFactory.createOrder(__assign({ type: OrderType.LIMIT, id: orderID, side: side, size: quantityToTrade, origSize: size, price: price, time: Date.now(), timeInForce: timeInForce, postOnly: postOnly, takerQty: takerQty, makerQty: makerQty }, (ocoStopPrice !== undefined ? { ocoStopPrice: ocoStopPrice } : {})));
456
+ if (response.done.length > 0) {
457
+ response.partialQuantityProcessed = size - quantityToTrade;
458
+ response.partial = order;
459
+ }
460
+ _this.orders[orderID] = sideToAdd.append(order);
461
+ }
462
+ else {
463
+ var totalQuantity_1 = 0;
464
+ var totalPrice_1 = 0;
465
+ response.done.forEach(function (order) {
466
+ totalQuantity_1 += order.size;
467
+ totalPrice_1 += order.price * order.size;
468
+ });
469
+ if (response.partialQuantityProcessed > 0 && response.partial !== null) {
470
+ totalQuantity_1 += response.partialQuantityProcessed;
471
+ totalPrice_1 +=
472
+ response.partial.price * response.partialQuantityProcessed;
473
+ }
474
+ order = OrderFactory.createOrder({
475
+ id: orderID,
476
+ type: OrderType.LIMIT,
477
+ side: side,
478
+ size: size,
479
+ origSize: size,
480
+ price: totalPrice_1 / totalQuantity_1,
481
+ time: Date.now(),
482
+ timeInForce: timeInForce,
483
+ postOnly: postOnly,
484
+ takerQty: takerQty,
485
+ makerQty: makerQty,
486
+ });
487
+ response.done.push(order);
488
+ }
489
+ // If IOC order was not matched completely remove from the order book
490
+ if (timeInForce === TimeInForce.IOC && response.quantityLeft > 0) {
491
+ _this._cancelOrder(orderID, true);
492
+ }
493
+ return order;
494
+ };
495
+ this.executeConditionalOrder = function (side, priceBefore, response) {
496
+ if (!_this.experimentalConditionalOrders)
497
+ return;
498
+ var pendingOrders = _this.stopBook.getConditionalOrders(side, priceBefore, _this._marketPrice);
499
+ if (pendingOrders.length > 0) {
500
+ var toBeExecuted_1 = [];
501
+ // Before get all orders to be executed and clean up the stop queue
502
+ // in order to avoid that an executed limit/market order run against
503
+ // the same stop order queue
504
+ pendingOrders.forEach(function (queue) {
505
+ while (queue.len() > 0) {
506
+ var headOrder = queue.removeFromHead();
507
+ if (headOrder !== undefined)
508
+ toBeExecuted_1.push(headOrder);
509
+ }
510
+ // Queue is empty now so remove the priceLevel
511
+ _this.stopBook.removePriceLevel(side, queue.price);
512
+ });
513
+ toBeExecuted_1.forEach(function (stopOrder) {
514
+ if (stopOrder.type === OrderType.STOP_MARKET) {
515
+ _this._market({
516
+ id: stopOrder.id,
517
+ side: stopOrder.side,
518
+ size: stopOrder.size,
519
+ }, response);
520
+ }
521
+ else {
522
+ if (stopOrder.isOCO) {
523
+ _this._cancelOrder(stopOrder.id, true);
524
+ }
525
+ _this._limit({
526
+ id: stopOrder.id,
527
+ side: stopOrder.side,
528
+ size: stopOrder.size,
529
+ price: stopOrder.price,
530
+ timeInForce: stopOrder.timeInForce,
531
+ }, response);
532
+ }
533
+ response.activated.push(stopOrder);
534
+ });
535
+ }
536
+ };
537
+ this.replayJournal = function (journal) {
538
+ for (var _i = 0, journal_1 = journal; _i < journal_1.length; _i++) {
539
+ var log = journal_1[_i];
540
+ switch (log.op) {
541
+ case "m": {
542
+ var _a = log.o, side = _a.side, size = _a.size;
543
+ if (side == null || size == null) {
544
+ throw CustomError(ERROR.INVALID_JOURNAL_LOG);
545
+ }
546
+ _this.market({ side: side, size: size });
547
+ break;
548
+ }
549
+ case "l": {
550
+ var _b = log.o, side = _b.side, id = _b.id, size = _b.size, price = _b.price, timeInForce = _b.timeInForce;
551
+ if (side == null || id == null || size == null || price == null) {
552
+ throw CustomError(ERROR.INVALID_JOURNAL_LOG);
553
+ }
554
+ _this.limit({
555
+ side: side,
556
+ id: id,
557
+ size: size,
558
+ price: price,
559
+ timeInForce: timeInForce,
560
+ });
561
+ break;
562
+ }
563
+ case "d":
564
+ if (log.o.orderID == null)
565
+ throw CustomError(ERROR.INVALID_JOURNAL_LOG);
566
+ _this.cancel(log.o.orderID);
567
+ break;
568
+ case "u":
569
+ if (log.o.orderID == null || log.o.orderUpdate == null) {
570
+ throw CustomError(ERROR.INVALID_JOURNAL_LOG);
571
+ }
572
+ _this.modify(log.o.orderID, log.o.orderUpdate);
573
+ break;
574
+ default:
575
+ throw CustomError(ERROR.INVALID_JOURNAL_LOG);
576
+ }
577
+ }
578
+ };
579
+ /**
580
+ * OCO Order:
581
+ * Buy: price < marketPrice < stopPrice
582
+ * Sell: price > marketPrice > stopPrice
583
+ */
584
+ this.validateOCOOrder = function (options) {
585
+ var response = false;
586
+ if (options.side === Side.BUY &&
587
+ options.price < _this._marketPrice &&
588
+ _this._marketPrice < options.stopPrice) {
589
+ response = true;
590
+ }
591
+ if (options.side === Side.SELL &&
592
+ options.price > _this._marketPrice &&
593
+ _this._marketPrice > options.stopPrice) {
594
+ response = true;
595
+ }
596
+ return response;
597
+ };
598
+ this.greaterThanOrEqual = function (a, b) {
599
+ return a >= b;
600
+ };
601
+ this.lowerThanOrEqual = function (a, b) {
602
+ return a <= b;
603
+ };
604
+ this.processQueue = function (orderQueue, quantityToTrade) {
605
+ var response = {
606
+ done: [],
607
+ activated: [],
608
+ partial: null,
609
+ partialQuantityProcessed: 0,
610
+ quantityLeft: quantityToTrade,
611
+ err: null,
612
+ };
613
+ if (response.quantityLeft > 0) {
614
+ while (orderQueue.len() > 0 && response.quantityLeft > 0) {
615
+ var headOrder = orderQueue.head();
616
+ if (headOrder !== undefined) {
617
+ if (response.quantityLeft < headOrder.size) {
618
+ response.partial = OrderFactory.createOrder(__assign(__assign({}, headOrder.toObject()), { size: headOrder.size - response.quantityLeft }));
619
+ _this.orders[headOrder.id] = response.partial;
620
+ response.partialQuantityProcessed = response.quantityLeft;
621
+ orderQueue.update(headOrder, response.partial);
622
+ response.quantityLeft = 0;
623
+ }
624
+ else {
625
+ response.quantityLeft = response.quantityLeft - headOrder.size;
626
+ var canceledOrder = _this._cancelOrder(headOrder.id, true);
627
+ /* node:coverage ignore next - Unable to test when order is undefined */
628
+ if ((canceledOrder === null || canceledOrder === void 0 ? void 0 : canceledOrder.order) !== undefined) {
629
+ response.done.push(canceledOrder.order);
630
+ }
631
+ }
632
+ // Remove linked OCO Stop Order if any
633
+ if (_this.experimentalConditionalOrders &&
634
+ headOrder.ocoStopPrice !== undefined) {
635
+ _this.stopBook.remove(headOrder.side, headOrder.id, headOrder.ocoStopPrice);
636
+ }
637
+ _this._marketPrice = headOrder.price;
638
+ }
639
+ }
640
+ }
641
+ return response;
642
+ };
643
+ this.canFillOrder = function (orderSide, side, size, price) {
644
+ return side === Side.BUY
645
+ ? _this.buyOrderCanBeFilled(orderSide, size, price)
646
+ : _this.sellOrderCanBeFilled(orderSide, size, price);
647
+ };
648
+ this.buyOrderCanBeFilled = function (orderSide, size, price) {
649
+ if (orderSide.volume() < size) {
650
+ return false;
651
+ }
652
+ var cumulativeSize = 0;
653
+ orderSide.priceTree().forEach(function (_, level) {
654
+ if (price >= level.price() && cumulativeSize < size) {
655
+ cumulativeSize += level.volume();
656
+ }
657
+ else {
658
+ return true; // break the loop
659
+ }
660
+ });
661
+ return cumulativeSize >= size;
662
+ };
663
+ this.sellOrderCanBeFilled = function (orderSide, size, price) {
664
+ if (orderSide.volume() < size) {
665
+ return false;
666
+ }
667
+ var cumulativeSize = 0;
668
+ orderSide.priceTree().forEach(function (_, level) {
669
+ if (price <= level.price() && cumulativeSize < size) {
670
+ cumulativeSize += level.volume();
671
+ }
672
+ else {
673
+ return true; // break the loop
674
+ }
675
+ });
676
+ return cumulativeSize >= size;
677
+ };
678
+ this.validateMarketOrder = function (order) {
679
+ var response = _this.getProcessOrderResponse(order.size);
680
+ if (![Side.SELL, Side.BUY].includes(order.side)) {
681
+ response.err = CustomError(ERROR.INVALID_SIDE);
682
+ return response;
683
+ }
684
+ if (typeof order.size !== "number" || order.size <= 0) {
685
+ response.err = CustomError(ERROR.INSUFFICIENT_QUANTITY);
686
+ return response;
687
+ }
688
+ return response;
689
+ };
690
+ this.validateLimitOrder = function (options) {
691
+ var response = _this.getProcessOrderResponse(options.size);
692
+ if (![Side.SELL, Side.BUY].includes(options.side)) {
693
+ response.err = CustomError(ERROR.INVALID_SIDE);
694
+ return response;
695
+ }
696
+ if (_this.orders[options.id] !== undefined) {
697
+ response.err = CustomError(ERROR.ORDER_ALREDY_EXISTS);
698
+ return response;
699
+ }
700
+ if (typeof options.size !== "number" || options.size <= 0) {
701
+ response.err = CustomError(ERROR.INVALID_QUANTITY);
702
+ return response;
703
+ }
704
+ if (typeof options.price !== "number" || options.price <= 0) {
705
+ response.err = CustomError(ERROR.INVALID_PRICE);
706
+ return response;
707
+ }
708
+ if (options.timeInForce &&
709
+ !validTimeInForce.includes(options.timeInForce)) {
710
+ response.err = CustomError(ERROR.INVALID_TIF);
711
+ return response;
712
+ }
713
+ return response;
714
+ };
715
+ this.bids = new OrderSide(Side.BUY);
716
+ this.asks = new OrderSide(Side.SELL);
717
+ this.enableJournaling = enableJournaling;
718
+ this.stopBook = new StopBook();
719
+ this.experimentalConditionalOrders = experimentalConditionalOrders;
720
+ // First restore from orderbook snapshot
721
+ if (snapshot != null) {
722
+ this.restoreSnapshot(snapshot);
723
+ }
724
+ // Than replay from journal log
725
+ if (journal != null) {
726
+ if (!Array.isArray(journal))
727
+ throw CustomError(ERROR.INVALID_JOURNAL_LOG);
728
+ // If a snapshot is available be sure to remove logs before the last restored operation
729
+ if (snapshot != null && snapshot.lastOp > 0) {
730
+ journal = journal.filter(function (log) { return log.opId > snapshot.lastOp; });
731
+ }
732
+ this.replayJournal(journal);
733
+ }
734
+ }
735
+ Object.defineProperty(OrderBook.prototype, "marketPrice", {
736
+ // Getter for the market price
737
+ get: function () {
738
+ return this._marketPrice;
739
+ },
740
+ enumerable: false,
741
+ configurable: true
742
+ });
743
+ Object.defineProperty(OrderBook.prototype, "lastOp", {
744
+ // Getter for the lastOp
745
+ get: function () {
746
+ return this._lastOp;
747
+ },
748
+ enumerable: false,
749
+ configurable: true
750
+ });
751
+ OrderBook.prototype.createOrder = function (typeOrOptions, side, size, price, orderID, timeInForce, stopPrice, stopLimitPrice, stopLimitTimeInForce, postOnly) {
752
+ if (timeInForce === void 0) { timeInForce = TimeInForce.GTC; }
753
+ if (stopLimitTimeInForce === void 0) { stopLimitTimeInForce = TimeInForce.GTC; }
754
+ var options;
755
+ // We don't want to test the deprecated signature.
756
+ /* node:coverage disable */
757
+ if (typeof typeOrOptions === "string" &&
758
+ side !== undefined &&
759
+ size !== undefined) {
760
+ options = {
761
+ type: typeOrOptions,
762
+ side: side,
763
+ size: size,
764
+ // @ts-expect-error
765
+ price: price,
766
+ id: orderID,
767
+ timeInForce: timeInForce,
768
+ // @ts-expect-error
769
+ stopPrice: stopPrice,
770
+ // @ts-expect-error
771
+ stopLimitPrice: stopLimitPrice,
772
+ stopLimitTimeInForce: stopLimitTimeInForce,
773
+ postOnly: postOnly,
774
+ };
775
+ /* node:coverage enable */
776
+ }
777
+ else if (typeof typeOrOptions === "object") {
778
+ options = typeOrOptions;
779
+ /* node:coverage disable */
780
+ }
781
+ else {
782
+ throw new Error("Invalid arguments.");
783
+ }
784
+ /* node:coverage enable */
785
+ switch (options.type) {
786
+ case OrderType.MARKET:
787
+ return this.market(options);
788
+ case OrderType.LIMIT:
789
+ return this.limit(options);
790
+ case OrderType.STOP_MARKET:
791
+ return this.stopMarket(options);
792
+ case OrderType.STOP_LIMIT:
793
+ return this.stopLimit(options);
794
+ case OrderType.OCO:
795
+ return this.oco(options);
796
+ default:
797
+ return {
798
+ done: [],
799
+ activated: [],
800
+ partial: null,
801
+ partialQuantityProcessed: 0,
802
+ quantityLeft: 0,
803
+ err: CustomError(ERROR.INVALID_ORDER_TYPE),
804
+ };
805
+ }
806
+ };
807
+ OrderBook.prototype.market = function (sideOrOptions, size) {
808
+ // We don't want to test the deprecated signature.
809
+ /* node:coverage disable */
810
+ if (typeof sideOrOptions === "string" && size !== undefined) {
811
+ return this._market({ side: sideOrOptions, size: size });
812
+ /* node:coverage enable */
813
+ }
814
+ if (typeof sideOrOptions === "object") {
815
+ return this._market(sideOrOptions);
816
+ /* node:coverage disable */
817
+ }
818
+ throw new Error("Invalid arguments.");
819
+ /* node:coverage enable */
820
+ };
821
+ OrderBook.prototype.limit = function (sideOrOptions, orderID, size, price, timeInForce) {
822
+ if (timeInForce === void 0) { timeInForce = TimeInForce.GTC; }
823
+ // We don't want to test the deprecated signature.
824
+ /* node:coverage disable */
825
+ if (typeof sideOrOptions === "string" &&
826
+ orderID !== undefined &&
827
+ size !== undefined &&
828
+ price !== undefined) {
829
+ return this._limit({
830
+ id: orderID,
831
+ side: sideOrOptions,
832
+ size: size,
833
+ price: price,
834
+ timeInForce: timeInForce,
835
+ });
836
+ /* node:coverage enable */
837
+ }
838
+ if (typeof sideOrOptions === "object") {
839
+ return this._limit(sideOrOptions);
840
+ /* node:coverage disable */
841
+ }
842
+ throw new Error("Invalid arguments.");
843
+ /* node:coverage enable */
844
+ };
845
+ return OrderBook;
846
+ }());
847
+ export { OrderBook };