decrease
This module provides utilities for calculating decrease position amounts, fees, and next position values when closing or reducing trading positions. It handles complex calculations including PnL realization, fee deductions, collateral adjustments, and swap requirements.
Methods
getDecreasePositionAmounts
getDecreasePositionAmounts(params): DecreasePositionAmounts
Parameters
marketInfo: MarketInfo- Market information including tokens and feescollateralToken: TokenData- Token used as collateral for the positionisLong: boolean- Whether the position is long or shortposition: PositionInfoLoaded | undefined- Current position informationcloseSizeUsd: bigint- USD amount of position size to closekeepLeverage: boolean- Whether to maintain current leverage ratiotriggerPrice?: bigint- Price at which trigger order executesfixedAcceptablePriceImpactBps?: bigint- Fixed acceptable price impact in basis pointsacceptablePriceImpactBuffer?: number- Buffer for acceptable price impactuserReferralInfo: UserReferralInfo | undefined- User referral information for fee calculationsminCollateralUsd: bigint- Minimum required collateral in USDminPositionSizeUsd: bigint- Minimum position size in USDuiFeeFactor: bigint- UI fee factorisLimit?: boolean- Whether this is a limit orderlimitPrice?: bigint- Limit order pricetriggerOrderType?: DecreasePositionAmounts["triggerOrderType"]- Type of trigger orderisSetAcceptablePriceImpactEnabled: boolean- Whether acceptable price impact is enabledreceiveToken?: TokenData- Token to receive (defaults to collateral token)
Calculates comprehensive decrease position amounts including fees, PnL, collateral changes, and receive amounts.
import { getDecreasePositionAmounts } from "@gmx-ui/sdk/utils/trade/decrease";
const decreaseAmounts = getDecreasePositionAmounts({
marketInfo,
collateralToken: usdcToken,
isLong: true,
position: currentPosition,
closeSizeUsd: 1000000000000000000000n, // $1000
keepLeverage: false,
userReferralInfo: undefined,
minCollateralUsd: 5000000000000000000000n, // $5000
minPositionSizeUsd: 1000000000000000000000n, // $1000
uiFeeFactor: 5000000000000000n, // 0.05%
isSetAcceptablePriceImpactEnabled: true
});
console.log("Receive amount:", decreaseAmounts.receiveTokenAmount);
console.log("Total fees:", decreaseAmounts.positionFeeUsd);
getIsFullClose
getIsFullClose(params): boolean
Parameters
position: PositionInfoLoaded- Current position informationsizeDeltaUsd: bigint- USD amount of position size to closeindexPrice: bigint- Current index priceremainingCollateralUsd: bigint- Remaining collateral after decreaseminCollateralUsd: bigint- Minimum required collateralminPositionSizeUsd: bigint- Minimum position size
Determines whether a decrease operation should result in a full position close based on size and collateral requirements.
import { getIsFullClose } from "@gmx-ui/sdk/utils/trade/decrease";
const shouldFullClose = getIsFullClose({
position: currentPosition,
sizeDeltaUsd: 500000000000000000000n, // $500
indexPrice: 50000000000000000000000n, // $50,000
remainingCollateralUsd: 100000000000000000000n, // $100
minCollateralUsd: 5000000000000000000000n, // $5000
minPositionSizeUsd: 1000000000000000000000n // $1000
});
console.log("Should fully close position:", shouldFullClose);
getMinCollateralUsdForLeverage
getMinCollateralUsdForLeverage(position, openInterestDelta): bigint
Parameters
position: PositionInfoLoaded- Position informationopenInterestDelta: bigint- Change in open interest
Calculates the minimum collateral required to maintain leverage for a position.
import { getMinCollateralUsdForLeverage } from "@gmx-ui/sdk/utils/trade/decrease";
const minCollateral = getMinCollateralUsdForLeverage(
currentPosition,
-1000000000000000000000n // -$1000 decrease in OI
);
console.log("Minimum collateral required:", minCollateral);
payForCollateralCost
payForCollateralCost(params): object
Parameters
initialCostUsd: bigint- Initial cost in USD to be paidcollateralToken: TokenData- Collateral token informationcollateralPrice: bigint- Current collateral token priceoutputAmount: bigint- Available output amountremainingCollateralAmount: bigint- Remaining collateral amount
Calculates how costs are paid from available output and remaining collateral.
import { payForCollateralCost } from "@gmx-ui/sdk/utils/trade/decrease";
const paymentInfo = payForCollateralCost({
initialCostUsd: 100000000000000000000n, // $100
collateralToken: usdcToken,
collateralPrice: 1000000000000000000n, // $1
outputAmount: 50000000n, // 50 USDC
remainingCollateralAmount: 1000000000n // 1000 USDC
});
console.log("Paid from output:", paymentInfo.paidOutputAmount);
console.log("Paid from collateral:", paymentInfo.paidRemainingCollateralAmount);
estimateCollateralCost
estimateCollateralCost(baseUsd, collateralToken, collateralPrice): object
Parameters
baseUsd: bigint- Base cost in USDcollateralToken: TokenData- Collateral token informationcollateralPrice: bigint- Collateral token price
Estimates the collateral cost in both token amount and USD value.
import { estimateCollateralCost } from "@gmx-ui/sdk/utils/trade/decrease";
const costEstimate = estimateCollateralCost(
50000000000000000000n, // $50
usdcToken,
1000000000000000000n // $1
);
console.log("Cost in tokens:", costEstimate.amount);
console.log("Cost in USD:", costEstimate.usd);
getTotalFeesUsdForDecrease
getTotalFeesUsdForDecrease(params): bigint
Parameters
positionFeeUsd: bigint- Position fee in USDborrowingFeeUsd: bigint- Borrowing fee in USDfundingFeeUsd: bigint- Funding fee in USDswapProfitFeeUsd: bigint- Swap profit fee in USDswapUiFeeUsd: bigint- Swap UI fee in USDuiFeeUsd: bigint- UI fee in USDpnlUsd: bigint- PnL in USDtotalPendingImpactDeltaUsd: bigint- Total pending price impact delta in USD
Calculates the total fees in USD for a decrease position operation.
import { getTotalFeesUsdForDecrease } from "@gmx-ui/sdk/utils/trade/decrease";
const totalFees = getTotalFeesUsdForDecrease({
positionFeeUsd: 10000000000000000000n, // $10
borrowingFeeUsd: 5000000000000000000n, // $5
fundingFeeUsd: 2000000000000000000n, // $2
swapProfitFeeUsd: 1000000000000000000n, // $1
swapUiFeeUsd: 500000000000000000n, // $0.5
uiFeeUsd: 500000000000000000n, // $0.5
pnlUsd: -10000000000000000000n, // -$10 loss
totalPendingImpactDeltaUsd: -5000000000000000000n // -$5 negative impact
});
console.log("Total fees:", totalFees);
getNextPositionValuesForDecreaseTrade
getNextPositionValuesForDecreaseTrade(params): NextPositionValues
Parameters
existingPosition?: PositionInfo- Current position informationmarketInfo: MarketInfo- Market informationcollateralToken: TokenData- Collateral token informationsizeDeltaUsd: bigint- Size decrease in USDsizeDeltaInTokens: bigint- Size decrease in tokensrealizedPnl: bigint- Realized PnL from the decreaseestimatedPnl: bigint- Estimated total PnLcollateralDeltaUsd: bigint- Collateral change in USDcollateralDeltaAmount: bigint- Collateral change in token amountpayedRemainingCollateralUsd: bigint- Paid remaining collateral in USDpayedRemainingCollateralAmount: bigint- Paid remaining collateral amountproportionalPendingImpactDeltaUsd: bigint- Proportional pending impact deltashowPnlInLeverage: boolean- Whether to include PnL in leverage calculationisLong: boolean- Whether position is longminCollateralUsd: bigint- Minimum collateral requirementuserReferralInfo: UserReferralInfo | undefined- User referral information
Calculates the next position values after a decrease trade is executed.
import { getNextPositionValuesForDecreaseTrade } from "@gmx-ui/sdk/utils/trade/decrease";
const nextValues = getNextPositionValuesForDecreaseTrade({
existingPosition: currentPosition,
marketInfo,
collateralToken: usdcToken,
sizeDeltaUsd: 1000000000000000000000n, // $1000
sizeDeltaInTokens: 20000000000000000n, // 0.02 tokens
realizedPnl: 50000000000000000000n, // $50 profit
estimatedPnl: 100000000000000000000n, // $100 total PnL
collateralDeltaUsd: 100000000000000000000n, // $100
collateralDeltaAmount: 100000000n, // 100 USDC
payedRemainingCollateralUsd: 10000000000000000000n, // $10
payedRemainingCollateralAmount: 10000000n, // 10 USDC
proportionalPendingImpactDeltaUsd: 5000000000000000000n, // $5
showPnlInLeverage: true,
isLong: true,
minCollateralUsd: 5000000000000000000000n, // $5000
userReferralInfo: undefined
});
console.log("Next position size:", nextValues.nextSizeUsd);
console.log("Next leverage:", nextValues.nextLeverage);
console.log("Next liquidation price:", nextValues.nextLiqPrice);