@drift-labs/common 1.0.10 → 1.0.11

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.
@@ -12,8 +12,16 @@ const calculatePnlPctFromPosition = (pnl, position, marginUsed) => {
12
12
  }
13
13
  else {
14
14
  const leverage = (_a = convertMarginRatioToLeverage(position.maxMarginRatio)) !== null && _a !== void 0 ? _a : 1;
15
- marginUsedNum =
16
- sdk_1.BigNum.from(position.quoteEntryAmount.abs(), sdk_1.QUOTE_PRECISION_EXP).toNum() / leverage;
15
+ const quoteEntryAmountNum = sdk_1.BigNum.from(position.quoteEntryAmount.abs(), sdk_1.QUOTE_PRECISION_EXP).toNum();
16
+ if (leverage <= 0 || quoteEntryAmountNum <= 0) {
17
+ marginUsedNum = 0;
18
+ }
19
+ else {
20
+ marginUsedNum = quoteEntryAmountNum / leverage;
21
+ }
22
+ }
23
+ if (marginUsedNum <= 0) {
24
+ return 0;
17
25
  }
18
26
  return (sdk_1.BigNum.from(pnl, sdk_1.QUOTE_PRECISION_EXP)
19
27
  .shift(5)
@@ -1 +1 @@
1
- {"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/common-ui-utils/trading.ts"],"names":[],"mappings":";;;AAAA,yCAiByB;AAGzB,MAAM,2BAA2B,GAAG,CACnC,GAAO,EACP,QAAsB,EACtB,UAAe,EACN,EAAE;;IACX,IAAI,CAAC,CAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAA,KAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,gBAAgB,CAAC,EAAE,CAAC,UAAI,CAAC,CAAA;QACrE,OAAO,CAAC,CAAC;IAEV,IAAI,aAAqB,CAAC;IAE1B,IAAI,UAAU,EAAE,CAAC;QAChB,aAAa,GAAG,YAAM,CAAC,IAAI,CAAC,UAAU,EAAE,yBAAmB,CAAC,CAAC,KAAK,EAAE,CAAC;IACtE,CAAC;SAAM,CAAC;QACP,MAA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Account,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tmarginUsedNum =\n\t\t\tBigNum.from(\n\t\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\t\tQUOTE_PRECISION_EXP\n\t\t\t).toNum() / leverage;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\treturn Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n};\n"]}
1
+ {"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/common-ui-utils/trading.ts"],"names":[],"mappings":";;;AAAA,yCAiByB;AAGzB,MAAM,2BAA2B,GAAG,CACnC,GAAO,EACP,QAAsB,EACtB,UAAe,EACN,EAAE;;IACX,IAAI,CAAC,CAAA,QAAQ,aAA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AuB,EACvB,WAAW,CAAC,SAAS,CACrB,CAAC;IACF,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;AAC/D,CAAC,CAAC;AANW,QAAA,qBAAqB,yBAMhC;AAEW,QAAA,aAAa,GAAG;IAC5B,2BAA2B;IAC3B,wBAAwB;IACxB,uCAAuC;IACvC,sBAAsB;IACtB,4BAA4B;IAC5B,4BAA4B;IAC5B,iBAAiB;IACjB,yBAAyB;IACzB,iBAAiB;IACjB,yBAAyB;IACzB,qBAAqB,EAArB,6BAAqB;CACrB,CAAC","sourcesContent":["import {\n\tAMM_RESERVE_PRECISION,\n\tBN,\n\tBigNum,\n\tDriftClient,\n\tMARGIN_PRECISION,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tONE,\n\tPRICE_PRECISION,\n\tPRICE_PRECISION_EXP,\n\tPerpMarketAccount,\n\tPositionDirection,\n\tQUOTE_PRECISION_EXP,\n\tSpotMarketAccount,\n\tUser,\n\tZERO,\n\tisVariant,\n} from '@drift-labs/sdk';\nimport { MarketId, OpenPosition, UIOrderType } from 'src/types';\n\nconst calculatePnlPctFromPosition = (\n\tpnl: BN,\n\tposition: OpenPosition,\n\tmarginUsed?: BN\n): number => {\n\tif (!position?.quoteEntryAmount || position?.quoteEntryAmount.eq(ZERO))\n\t\treturn 0;\n\n\tlet marginUsedNum: number;\n\n\tif (marginUsed) {\n\t\tmarginUsedNum = BigNum.from(marginUsed, QUOTE_PRECISION_EXP).toNum();\n\t} else {\n\t\tconst leverage = convertMarginRatioToLeverage(position.maxMarginRatio) ?? 1;\n\t\tconst quoteEntryAmountNum = BigNum.from(\n\t\t\tposition.quoteEntryAmount.abs(),\n\t\t\tQUOTE_PRECISION_EXP\n\t\t).toNum();\n\n\t\tif (leverage <= 0 || quoteEntryAmountNum <= 0) {\n\t\t\tmarginUsedNum = 0;\n\t\t} else {\n\t\t\tmarginUsedNum = quoteEntryAmountNum / leverage;\n\t\t}\n\t}\n\n\tif (marginUsedNum <= 0) {\n\t\treturn 0;\n\t}\n\n\treturn (\n\t\tBigNum.from(pnl, QUOTE_PRECISION_EXP)\n\t\t\t.shift(5)\n\t\t\t.div(BigNum.fromPrint(`${marginUsedNum}`, QUOTE_PRECISION_EXP))\n\t\t\t.toNum() * 100\n\t);\n};\n\nconst POTENTIAL_PROFIT_DEFAULT_STATE = {\n\testimatedProfit: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedProfitBeforeFees: BigNum.zero(PRICE_PRECISION_EXP),\n\testimatedTakerFee: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtEntry: BigNum.zero(PRICE_PRECISION_EXP),\n\tnotionalSizeAtExit: BigNum.zero(PRICE_PRECISION_EXP),\n};\n\nconst calculatePotentialProfit = (props: {\n\tcurrentPositionSize: BigNum;\n\tcurrentPositionDirection: PositionDirection;\n\tcurrentPositionEntryPrice: BigNum;\n\ttradeDirection: PositionDirection;\n\t/**\n\t * Amount of position being closed in base asset size\n\t */\n\texitBaseSize: BigNum;\n\t/**\n\t * Either the user's limit price (for limit orders) or the estimated exit price (for market orders)\n\t */\n\texitPrice: BigNum;\n\ttakerFeeBps: number;\n\tslippageTolerance?: number;\n\tisMarketOrder?: boolean;\n}): {\n\testimatedProfit: BigNum;\n\testimatedProfitBeforeFees: BigNum;\n\testimatedTakerFee: BigNum;\n\tnotionalSizeAtEntry: BigNum;\n\tnotionalSizeAtExit: BigNum;\n} => {\n\tlet estimatedProfit = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedProfitBeforeFees = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet estimatedTakerFee = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtEntry = BigNum.zero(PRICE_PRECISION_EXP);\n\tlet notionalSizeAtExit = BigNum.zero(PRICE_PRECISION_EXP);\n\n\tconst isClosingLong =\n\t\tisVariant(props.currentPositionDirection, 'long') &&\n\t\tisVariant(props.tradeDirection, 'short');\n\tconst isClosingShort =\n\t\tisVariant(props.currentPositionDirection, 'short') &&\n\t\tisVariant(props.tradeDirection, 'long');\n\n\tif (!isClosingLong && !isClosingShort) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\tif (!props.exitBaseSize) return POTENTIAL_PROFIT_DEFAULT_STATE;\n\n\tif (\n\t\tprops.exitBaseSize.eqZero() ||\n\t\tprops.currentPositionSize.lt(props.exitBaseSize)\n\t) {\n\t\treturn POTENTIAL_PROFIT_DEFAULT_STATE;\n\t}\n\n\tconst baseSizeBeingClosed = props.exitBaseSize.lte(props.currentPositionSize)\n\t\t? props.exitBaseSize\n\t\t: props.currentPositionSize;\n\n\t// Notional size of amount being closed at entry and exit\n\tnotionalSizeAtEntry = baseSizeBeingClosed.mul(\n\t\tprops.currentPositionEntryPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\tnotionalSizeAtExit = baseSizeBeingClosed.mul(\n\t\tprops.exitPrice.shiftTo(baseSizeBeingClosed.precision)\n\t);\n\n\tif (isClosingLong) {\n\t\testimatedProfitBeforeFees = notionalSizeAtExit.sub(notionalSizeAtEntry);\n\t} else if (isClosingShort) {\n\t\testimatedProfitBeforeFees = notionalSizeAtEntry.sub(notionalSizeAtExit);\n\t}\n\n\t// subtract takerFee if applicable\n\tif (props.takerFeeBps > 0) {\n\t\tconst takerFeeDenominator = Math.floor(100 / (props.takerFeeBps * 0.01));\n\t\testimatedTakerFee = notionalSizeAtExit.scale(1, takerFeeDenominator);\n\t\testimatedProfit = estimatedProfitBeforeFees.sub(\n\t\t\testimatedTakerFee.shiftTo(estimatedProfitBeforeFees.precision)\n\t\t);\n\t} else {\n\t\testimatedProfit = estimatedProfitBeforeFees;\n\t}\n\n\treturn {\n\t\testimatedProfit,\n\t\testimatedProfitBeforeFees,\n\t\testimatedTakerFee,\n\t\tnotionalSizeAtEntry,\n\t\tnotionalSizeAtExit,\n\t};\n};\n\n/**\n * Check if the order type is a market order or oracle market order\n */\nconst checkIsMarketOrderType = (orderType: UIOrderType) => {\n\treturn orderType === 'market' || orderType === 'oracle';\n};\n\n/**\n * Calculate the liquidation price of a position after a trade. Requires DriftClient to be subscribed.\n * If the order type is limit order, a limit price must be provided.\n */\nconst calculateLiquidationPriceAfterPerpTrade = ({\n\testEntryPrice,\n\torderType,\n\tperpMarketIndex,\n\ttradeBaseSize,\n\tisLong,\n\tuserClient,\n\toraclePrice,\n\tlimitPrice,\n\toffsetCollateral,\n\tprecision = 2,\n\tisEnteringHighLeverageMode,\n\tcapLiqPrice,\n}: {\n\testEntryPrice: BN;\n\torderType: UIOrderType;\n\tperpMarketIndex: number;\n\ttradeBaseSize: BN;\n\tisLong: boolean;\n\tuserClient: User;\n\toraclePrice: BN;\n\tlimitPrice?: BN;\n\toffsetCollateral?: BN;\n\tprecision?: number;\n\tisEnteringHighLeverageMode?: boolean;\n\tcapLiqPrice?: boolean;\n}) => {\n\tconst ALLOWED_ORDER_TYPES: UIOrderType[] = [\n\t\t'limit',\n\t\t'market',\n\t\t'oracle',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t];\n\n\tif (!ALLOWED_ORDER_TYPES.includes(orderType)) {\n\t\tconsole.error(\n\t\t\t'Invalid order type for perp trade liquidation price calculation',\n\t\t\torderType\n\t\t);\n\t\treturn 0;\n\t}\n\n\tif (orderType === 'limit' && !limitPrice) {\n\t\tconsole.error(\n\t\t\t'Limit order must have a limit price for perp trade liquidation price calculation'\n\t\t);\n\t\treturn 0;\n\t}\n\n\tconst signedBaseSize = isLong ? tradeBaseSize : tradeBaseSize.neg();\n\tconst priceToUse = [\n\t\t'limit',\n\t\t'stopMarket',\n\t\t'stopLimit',\n\t\t'oracleLimit',\n\t].includes(orderType)\n\t\t? limitPrice\n\t\t: estEntryPrice;\n\n\tconst liqPriceBn = userClient.liquidationPrice(\n\t\tperpMarketIndex,\n\t\tsignedBaseSize,\n\t\tpriceToUse,\n\t\tundefined,\n\t\tundefined, // we can exclude open orders since open orders will be cancelled first (which results in reducing account leverage) before actual liquidation\n\t\toffsetCollateral,\n\t\tisEnteringHighLeverageMode\n\t);\n\n\tif (liqPriceBn.isNeg()) {\n\t\t// means no liquidation price\n\t\treturn 0;\n\t}\n\n\t// Check if user has a spot position using the same oracle as the perp market\n\t// If so, force capLiqPrice to be false to avoid incorrect price capping\n\t// Technically in this case, liq price could be lower for a short or higher for a long\n\tconst perpMarketOracle =\n\t\tuserClient.driftClient.getPerpMarketAccount(perpMarketIndex)?.amm?.oracle;\n\n\tconst spotMarketWithSameOracle = userClient.driftClient\n\t\t.getSpotMarketAccounts()\n\t\t.find((market) => market.oracle.equals(perpMarketOracle));\n\n\tlet hasSpotPositionWithSameOracle = false;\n\tif (spotMarketWithSameOracle) {\n\t\tconst spotPosition = userClient.getSpotPosition(\n\t\t\tspotMarketWithSameOracle.marketIndex\n\t\t);\n\t\thasSpotPositionWithSameOracle = !!spotPosition;\n\t}\n\n\tconst effectiveCapLiqPrice = hasSpotPositionWithSameOracle\n\t\t? false\n\t\t: capLiqPrice;\n\n\tconst cappedLiqPriceBn = effectiveCapLiqPrice\n\t\t? isLong\n\t\t\t? BN.min(liqPriceBn, oraclePrice)\n\t\t\t: BN.max(liqPriceBn, oraclePrice)\n\t\t: liqPriceBn;\n\n\tconst liqPriceBigNum = BigNum.from(cappedLiqPriceBn, PRICE_PRECISION_EXP);\n\n\tconst liqPriceNum =\n\t\tMath.round(liqPriceBigNum.toNum() * 10 ** precision) / 10 ** precision;\n\n\treturn liqPriceNum;\n};\n\nconst convertLeverageToMarginRatio = (leverage: number): number | undefined => {\n\tif (!leverage) return undefined;\n\treturn Math.round((1 / leverage) * MARGIN_PRECISION.toNumber());\n};\n\nconst convertMarginRatioToLeverage = (\n\tmarginRatio: number,\n\tdecimals?: number\n): number | undefined => {\n\tif (!marginRatio) return undefined;\n\n\tconst leverage = 1 / (marginRatio / MARGIN_PRECISION.toNumber());\n\n\treturn decimals\n\t\t? parseFloat(leverage.toFixed(decimals))\n\t\t: Math.round(leverage);\n};\n\nconst getMarketTickSize = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n): BN => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderTickSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderTickSize;\n\t}\n};\n\nconst getMarketTickSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst tickSize = getMarketTickSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tPRICE_PRECISION.div(tickSize.eq(ZERO) ? ONE : tickSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\nconst getMarketStepSize = (driftClient: DriftClient, marketId: MarketId) => {\n\tconst marketAccount = marketId.isPerp\n\t\t? driftClient.getPerpMarketAccount(marketId.marketIndex)\n\t\t: driftClient.getSpotMarketAccount(marketId.marketIndex);\n\tif (!marketAccount) return ZERO;\n\n\tif (marketId.isPerp) {\n\t\treturn (marketAccount as PerpMarketAccount).amm.orderStepSize;\n\t} else {\n\t\treturn (marketAccount as SpotMarketAccount).orderStepSize;\n\t}\n};\n\nconst getMarketStepSizeDecimals = (\n\tdriftClient: DriftClient,\n\tmarketId: MarketId\n) => {\n\tconst stepSize = getMarketStepSize(driftClient, marketId);\n\n\tconst decimalPlaces = Math.max(\n\t\t0,\n\t\tMath.floor(\n\t\t\tMath.log10(\n\t\t\t\tAMM_RESERVE_PRECISION.div(stepSize.eq(ZERO) ? ONE : stepSize).toNumber()\n\t\t\t)\n\t\t)\n\t);\n\n\treturn decimalPlaces;\n};\n\n/**\n * Checks if a given order amount represents an entire position order\n * by comparing it with MAX_LEVERAGE_ORDER_SIZE\n * @param orderAmount - The BigNum order amount to check\n * @returns true if the order is for the entire position, false otherwise\n */\nexport const isEntirePositionOrder = (orderAmount: BigNum): boolean => {\n\tconst maxLeverageSize = new BigNum(\n\t\tMAX_LEVERAGE_ORDER_SIZE,\n\t\torderAmount.precision\n\t);\n\treturn Math.abs(maxLeverageSize.sub(orderAmount).toNum()) < 1;\n};\n\nexport const TRADING_UTILS = {\n\tcalculatePnlPctFromPosition,\n\tcalculatePotentialProfit,\n\tcalculateLiquidationPriceAfterPerpTrade,\n\tcheckIsMarketOrderType,\n\tconvertLeverageToMarginRatio,\n\tconvertMarginRatioToLeverage,\n\tgetMarketTickSize,\n\tgetMarketTickSizeDecimals,\n\tgetMarketStepSize,\n\tgetMarketStepSizeDecimals,\n\tisEntirePositionOrder,\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/common",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "description": "Common functions for Drift",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",