Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@
"@cosmjs/stargate": "^0.32.1",
"@cosmjs/tendermint-rpc": "^0.32.1",
"@datadog/browser-logs": "^5.23.3",
"@dydxprotocol/v4-client-js": "3.1.1",
"@dydxprotocol/v4-localization": "1.1.358",
"@dydxprotocol/v4-client-js": "3.2.0",
"@dydxprotocol/v4-localization": "1.1.361",
"@dydxprotocol/v4-proto": "^7.0.0-dev.0",
"@emotion/is-prop-valid": "^1.3.0",
"@hugocxl/react-to-image": "^0.0.9",
Expand Down
16 changes: 8 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 45 additions & 1 deletion src/bonsai/calculators/markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
getDisplayableTickerFromMarket,
} from '@/lib/assetUtils';
import { isTruthy } from '@/lib/isTruthy';
import { MaybeBigNumber, MustBigNumber, MustNumber } from '@/lib/numbers';
import { BIG_NUMBERS, MaybeBigNumber, MustBigNumber, MustNumber } from '@/lib/numbers';
import { objectFromEntries } from '@/lib/objectHelpers';

import { MarketsData } from '../types/rawTypes';
Expand All @@ -36,6 +36,7 @@ export function calculateAllMarkets(markets: MarketsData | undefined): MarketsIn
if (markets == null) {
return markets;
}

return mapValues(markets, calculateMarket);
}

Expand Down Expand Up @@ -175,6 +176,49 @@ export function createMarketSummary(
);
}

/**
* Calculate the effective selected leverage for a market.
* Returns user-selected leverage if set, otherwise calculates max leverage from IMF only (ignoring OIMF).
*/
export function calculateEffectiveSelectedLeverage({
userSelectedLeverage,
initialMarginFraction,
}: {
userSelectedLeverage: number | undefined;
initialMarginFraction: string | number | BigNumber | null | undefined;
}): number {
return calculateEffectiveSelectedLeverageBigNumber({
userSelectedLeverage,
initialMarginFraction,
}).toNumber();
}

/**
* Calculate the effective selected leverage for a market, returning BigNumber.
* Returns user-selected leverage if set, otherwise calculates max leverage from IMF only (ignoring OIMF).
*/
export function calculateEffectiveSelectedLeverageBigNumber({
userSelectedLeverage,
initialMarginFraction,
}: {
userSelectedLeverage: number | undefined;
initialMarginFraction: string | number | BigNumber | null | undefined;
}): BigNumber {
// Return user-selected leverage if it exists
if (userSelectedLeverage != null) {
return MaybeBigNumber(userSelectedLeverage) ?? BIG_NUMBERS.ONE;
}

// Otherwise calculate from IMF only (ignoring OIMF as requested)
const imf = MaybeBigNumber(initialMarginFraction);
if (imf != null && !imf.isZero()) {
return BIG_NUMBERS.ONE.div(imf);
}

// Fallback
return BIG_NUMBERS.ONE;
}

export function calculateMarketsFeeDiscounts(
feeDiscounts: PerpetualMarketFeeDiscount | undefined
): AllPerpetualMarketsFeeDiscounts | undefined {
Expand Down
114 changes: 91 additions & 23 deletions src/bonsai/calculators/subaccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,32 @@ import {
SubaccountSummaryDerived,
} from '../types/summaryTypes';
import { getPositionUniqueId } from './helpers';
import { getMarketEffectiveInitialMarginForMarket } from './markets';
import {
calculateEffectiveSelectedLeverageBigNumber,
getMarketEffectiveInitialMarginForMarket,
} from './markets';

export function calculateParentSubaccountPositions(
parent: ParentSubaccountDataBase,
markets: MarketsData
markets: MarketsData,
rawSelectedMarketLeverages: { [marketId: string]: number }
): SubaccountPosition[] {
return Object.values(parent.childSubaccounts)
.filter(isPresent)
.flatMap((child) => {
const subaccount = calculateSubaccountSummary(child, markets);
const subaccount = calculateSubaccountSummary(child, markets, rawSelectedMarketLeverages);
return orderBy(
Object.values(child.openPerpetualPositions)
.filter(isPresent)
.filter((p) => p.status === IndexerPerpetualPositionStatus.OPEN)
.map((perp) => calculateSubaccountPosition(subaccount, perp, markets[perp.market])),
.map((perp) =>
calculateSubaccountPosition(
subaccount,
perp,
markets[perp.market],
rawSelectedMarketLeverages
)
),
[(f) => f.createdAt],
['desc']
);
Expand All @@ -58,10 +69,13 @@ export function calculateParentSubaccountPositions(

export function calculateParentSubaccountSummary(
parent: ParentSubaccountDataBase,
markets: MarketsData
markets: MarketsData,
rawSelectedMarketLeverages: { [marketId: string]: number }
): GroupedSubaccountSummary {
const summaries = mapValues(parent.childSubaccounts, (subaccount) =>
subaccount != null ? calculateSubaccountSummary(subaccount, markets) : subaccount
subaccount != null
? calculateSubaccountSummary(subaccount, markets, rawSelectedMarketLeverages)
: subaccount
);
const parentSummary = summaries[parent.parentSubaccount];
if (parentSummary == null) {
Expand All @@ -87,8 +101,16 @@ export function calculateMarketsNeededForSubaccount(parent: ParentSubaccountData
}

export const calculateSubaccountSummary = weakMapMemoize(
(subaccountData: ChildSubaccountData, markets: MarketsData): SubaccountSummary => {
const core = calculateSubaccountSummaryCore(subaccountData, markets);
(
subaccountData: ChildSubaccountData,
markets: MarketsData,
rawSelectedMarketLeverages: { [marketId: string]: number }
): SubaccountSummary => {
const core = calculateSubaccountSummaryCore(
subaccountData,
markets,
rawSelectedMarketLeverages
);
return {
...core,
...calculateSubaccountSummaryDerived(core),
Expand All @@ -99,7 +121,8 @@ export const calculateSubaccountSummary = weakMapMemoize(

function calculateSubaccountSummaryCore(
subaccountData: ChildSubaccountData,
markets: MarketsData
markets: MarketsData,
rawSelectedMarketLeverages: { [marketId: string]: number }
): SubaccountSummaryCore {
const quoteBalance = calc(() => {
const usdcPosition = subaccountData.assetPositions.USDC;
Expand All @@ -121,9 +144,9 @@ function calculateSubaccountSummaryCore(
const {
value: positionValue,
notional: positionNotional,
initialRisk: positionInitialRisk,
initialRiskFromSelectedLeverage: positionInitialRisk,
maintenanceRisk: positionMaintenanceRisk,
} = calculateDerivedPositionCore(getBnPosition(position), market);
} = calculateDerivedPositionCore(getBnPosition(position), market, rawSelectedMarketLeverages);
return {
valueTotal: acc.valueTotal.plus(positionValue),
notionalTotal: acc.notionalTotal.plus(positionNotional),
Expand Down Expand Up @@ -175,10 +198,11 @@ function calculateSubaccountSummaryDerived(core: SubaccountSummaryCore): Subacco
function calculateSubaccountPosition(
subaccountSummary: SubaccountSummary,
position: IndexerPerpetualPositionResponseObject,
market: IndexerWsBaseMarketObject | undefined
market: IndexerWsBaseMarketObject | undefined,
rawSelectedMarketLeverages?: { [marketId: string]: number }
): SubaccountPosition {
const bnPosition = getBnPosition(position);
const core = calculateDerivedPositionCore(bnPosition, market);
const core = calculateDerivedPositionCore(bnPosition, market, rawSelectedMarketLeverages);
return {
...bnPosition,
...core,
Expand All @@ -202,9 +226,31 @@ function getBnPosition(position: IndexerPerpetualPositionResponseObject): Subacc
};
}

export function calculateEffectiveMarketImfFromSelectedLeverage({
rawSelectedLeverage,
initialMarginFraction,
effectiveInitialMarginFraction,
}: {
rawSelectedLeverage: number | undefined;
initialMarginFraction: BigNumber | undefined;
effectiveInitialMarginFraction: BigNumber | undefined;
}) {
const effectiveSelectedLeverage = calculateEffectiveSelectedLeverageBigNumber({
userSelectedLeverage: rawSelectedLeverage,
initialMarginFraction,
});
const imfFromSelectedLeverage = BIG_NUMBERS.ONE.div(effectiveSelectedLeverage);
const adjustedImfFromSelectedLeverage = BigNumber.max(
imfFromSelectedLeverage,
effectiveInitialMarginFraction ?? 0
);
return { adjustedImfFromSelectedLeverage, effectiveSelectedLeverage };
}

function calculateDerivedPositionCore(
position: SubaccountPositionBase,
market: IndexerWsBaseMarketObject | undefined
market: IndexerWsBaseMarketObject | undefined,
rawSelectedMarketLeverages?: { [marketId: string]: number }
): SubaccountPositionDerivedCore {
const marginMode = isParentSubaccount(position.subaccountNumber) ? 'CROSS' : 'ISOLATED';
const effectiveImf =
Expand All @@ -222,6 +268,14 @@ function calculateDerivedPositionCore(
const notional = unsignedSize.times(oracle);
const value = signedSize.times(oracle);

const { adjustedImfFromSelectedLeverage, effectiveSelectedLeverage } =
calculateEffectiveMarketImfFromSelectedLeverage({
rawSelectedLeverage: rawSelectedMarketLeverages?.[position.market],
initialMarginFraction: MaybeBigNumber(market?.initialMarginFraction),
effectiveInitialMarginFraction: effectiveImf,
});
const initialRiskFromSelectedLeverage = notional.times(adjustedImfFromSelectedLeverage);

return {
uniqueId: getPositionUniqueId(position.market, position.subaccountNumber),
assetId: getAssetFromMarketId(position.market),
Expand All @@ -240,6 +294,9 @@ function calculateDerivedPositionCore(
}
return BIG_NUMBERS.ONE.div(effectiveImf);
}),
effectiveSelectedLeverage,
adjustedImfFromSelectedLeverage,
initialRiskFromSelectedLeverage,
baseEntryPrice: position.entryPrice,
baseNetFunding: position.netFunding,
};
Expand All @@ -250,13 +307,23 @@ function calculatePositionDerivedExtra(
subaccountSummary: SubaccountSummary
): SubaccountPositionDerivedExtra {
const { equity, maintenanceRiskTotal } = subaccountSummary;
const { signedSize, notional, value, marginMode, adjustedMmf, maintenanceRisk, initialRisk } =
position;
const {
signedSize,
notional,
value,
marginMode,
adjustedMmf,
maintenanceRisk,
initialRisk,
initialRiskFromSelectedLeverage,
} = position;

const leverage = equity.gt(0) ? notional.div(equity) : null;

const marginValueMaintenance = marginMode === 'ISOLATED' ? equity : maintenanceRisk;
const marginValueInitial = marginMode === 'ISOLATED' ? equity : initialRisk;
const marginValueInitialFromSelectedLeverage =
marginMode === 'ISOLATED' ? equity : initialRiskFromSelectedLeverage;

const liquidationPrice = calc(() => {
const otherPositionsRisk = maintenanceRiskTotal.minus(maintenanceRisk);
Expand All @@ -283,7 +350,7 @@ function calculatePositionDerivedExtra(
const entryValue = signedSize.multipliedBy(MustBigNumber(position.baseEntryPrice));
const unrealizedPnlInner = value.minus(entryValue);

const baseEquity = getPositionBaseEquity({ ...position, leverage });
const baseEquity = getPositionBaseEquity(position);

const unrealizedPnlPercentInner = baseEquity.isZero()
? null
Expand All @@ -296,6 +363,7 @@ function calculatePositionDerivedExtra(
leverage,
marginValueMaintenance,
marginValueInitial,
marginValueInitialFromSelectedLeverage,
liquidationPrice,
updatedUnrealizedPnl,
updatedUnrealizedPnlPercent,
Expand All @@ -304,12 +372,14 @@ function calculatePositionDerivedExtra(

export function calculateChildSubaccountSummaries(
parent: ParentSubaccountDataBase,
markets: MarketsData
markets: MarketsData,
selectedMarketLeverages: { [marketId: string]: number }
): ChildSubaccountSummaries {
return pickBy(
mapValues(
parent.childSubaccounts,
(subaccount) => subaccount && calculateSubaccountSummary(subaccount, markets)
(subaccount) =>
subaccount && calculateSubaccountSummary(subaccount, markets, selectedMarketLeverages)
),
isTruthy
);
Expand Down Expand Up @@ -356,13 +426,11 @@ export function calculateUnopenedIsolatedPositions(
}

export function getPositionBaseEquity(
position: Pick<SubaccountPosition, 'signedSize' | 'baseEntryPrice' | 'leverage'>
position: Pick<SubaccountPosition, 'signedSize' | 'baseEntryPrice' | 'effectiveSelectedLeverage'>
) {
const entryValue = position.signedSize.times(position.baseEntryPrice);

const scaledLeverage = position.leverage
? BigNumber.max(position.leverage.abs(), BIG_NUMBERS.ONE)
: BIG_NUMBERS.ONE;
const scaledLeverage = BigNumber.max(position.effectiveSelectedLeverage.abs(), BIG_NUMBERS.ONE);

return entryValue.abs().div(scaledLeverage);
}
Loading
Loading