@fuzefinance/orderbook-bignumber
Version:
Node.js Lmit Order Book for high-frequency trading (HFT).
75 lines (74 loc) • 3.13 kB
JavaScript
/* node:coverage ignore next - Don't know why first and last line of each file count as uncovered */
import BigNumber from "bignumber.js";
import createRBTree from "functional-red-black-tree";
import { CustomError, ERROR } from "./errors";
import { StopQueue } from "./stopqueue";
import { Side } from "./types";
var StopSide = /** @class */ (function () {
function StopSide(side) {
var _this = this;
this._prices = {};
// appends order to definite price level
this.append = function (order) {
var price = order.stopPrice;
var strPrice = price.toString();
if (_this._prices[strPrice] === undefined) {
var priceQueue = new StopQueue(price);
_this._prices[strPrice] = priceQueue;
_this._priceTree = _this._priceTree.insert(price, priceQueue);
}
return _this._prices[strPrice].append(order);
};
// removes order from definite price level
this.remove = function (id, stopPrice) {
var strPrice = stopPrice.toString();
if (_this._prices[strPrice] === undefined) {
throw CustomError(ERROR.INVALID_PRICE_LEVEL);
}
var deletedOrder = _this._prices[strPrice].remove(id);
if (_this._prices[strPrice].len() === 0) {
delete _this._prices[strPrice];
_this._priceTree = _this._priceTree.remove(stopPrice);
}
return deletedOrder;
};
this.removePriceLevel = function (priceLevel) {
delete _this._prices[priceLevel.toString()];
_this._priceTree = _this._priceTree.remove(priceLevel);
};
// Get orders queue between two price levels
this.between = function (priceBefore, marketPrice) {
var queues = [];
var lowerBound = priceBefore;
var upperBound = marketPrice;
var highest = BigNumber.max(priceBefore, marketPrice);
var lowest = BigNumber.min(priceBefore, marketPrice);
if (_this._side === Side.BUY) {
lowerBound = highest;
upperBound = lowest.minus(1);
}
else {
lowerBound = lowest;
upperBound = highest.plus(1);
}
_this._priceTree.forEach(function (price, queue) {
if ((_this._side === Side.BUY && price.isGreaterThanOrEqualTo(lowest)) ||
(_this._side === Side.SELL && price.isLessThanOrEqualTo(highest))) {
queues.push(queue);
}
}, lowerBound, // Inclusive
upperBound);
return queues;
};
this.priceTree = function () {
return _this._priceTree;
};
var compare = side === Side.SELL
? function (a, b) { return a.minus(b).toNumber(); }
: function (a, b) { return b.minus(a).toNumber(); };
this._priceTree = createRBTree(compare);
this._side = side;
}
return StopSide;
}());
export { StopSide };