UNPKG

@drift-labs/common

Version:

Common functions for Drift

89 lines 2.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.COMMON_MATH = void 0; const sdk_1 = require("@drift-labs/sdk"); const calculateMarkPrice = (bestBidPrice, bestAskPrice, oraclePrice) => { const bid = bestBidPrice; const ask = bestAskPrice; let mid; // if bid/ask cross, force it to be the one closer to oracle, if oracle is in the middle, use oracle price if (bid && ask && bid.gt(ask) && oraclePrice) { if (bid.gt(oraclePrice) && ask.gt(oraclePrice)) { mid = sdk_1.BN.min(bid, ask); } else if (bid.lt(oraclePrice) && ask.lt(oraclePrice)) { mid = sdk_1.BN.max(bid, ask); } else { mid = oraclePrice; } } else { if (bid && ask) { mid = bid.add(ask).divn(2); } else if (oraclePrice) { mid = oraclePrice; } else { mid = undefined; } } return mid; }; const calculateBidAskAndmarkPrice = (l2, oraclePrice) => { const bestBidPrice = l2.bids.reduce((previousMax, currentBid) => { if (!previousMax) return currentBid.price; return sdk_1.BN.max(currentBid.price, previousMax); }, undefined); const bestAskPrice = l2.asks.reduce((previousMin, currentBid) => { if (!previousMin) return currentBid.price; return sdk_1.BN.min(currentBid.price, previousMin); }, undefined); const markPrice = calculateMarkPrice(bestBidPrice, bestAskPrice, oraclePrice); return { bestBidPrice, bestAskPrice, markPrice, }; }; const calculateSpreadQuote = (bestBidPrice, bestAskPrice) => { return bestBidPrice.sub(bestAskPrice).abs(); }; function calculateSpreadPct(markPricePrice, spreadQuote) { return spreadQuote.muln(100).mul(sdk_1.PERCENTAGE_PRECISION).div(markPricePrice); } const calculateSpread = (bestBidPrice, bestAskPrice, markPrice) => { const spreadQuote = calculateSpreadQuote(bestBidPrice, bestAskPrice); const spreadPct = calculateSpreadPct(markPrice, spreadQuote); return { spreadPct, spreadQuote, }; }; const calculateSpreadBidAskMark = (l2, oraclePrice) => { if (l2.asks.length === 0 || l2.bids.length === 0) { return { spreadQuote: undefined, spreadPct: undefined, markPrice: undefined, bestBidPrice: undefined, bestAskPrice: undefined, }; } const { bestBidPrice, bestAskPrice, markPrice } = calculateBidAskAndmarkPrice(l2, oraclePrice); const { spreadPct, spreadQuote } = calculateSpread(bestBidPrice, bestAskPrice, markPrice); return { bestBidPrice, bestAskPrice, markPrice, spreadPct, spreadQuote, }; }; exports.COMMON_MATH = { calculateSpreadBidAskMark, }; //# sourceMappingURL=math.js.map