increase
This module provides utilities for calculating increase position amounts, prices, and next position values for GMX trading operations. It handles different trading strategies including leverage by size, leverage by collateral, and independent position management.
Methods
This module exports functions for computing the full set of amounts required to open or increase a leveraged position, and for checking whether the resulting position passes the contracts' margin checks. All USD values use 30-decimal precision (USD_DECIMALS = 30). Leverage values use basis-point encoding (10,000 = 1x, so 20x = 200000n).
All functions in this module are exported from @gmx-io/sdk/utils/trade. Import them individually as shown in each example.
getIncreasePositionAmounts
getIncreasePositionAmounts(params: IncreasePositionParams): IncreasePositionAmounts
Computes the complete set of amounts needed to open or increase a leveraged position. This is the primary function to call when constructing an increase order — it calculates size, collateral, fees (position fee, borrow fee, funding fee, UI fee), price impact, acceptable price, and any required collateral swap.
The function supports three strategies:
| Strategy | Input required | Description |
|---|---|---|
"leverageByCollateral" | initialCollateralAmount + leverage | User specifies how much collateral to deposit; size is derived from the leverage target |
"leverageBySize" | indexTokenAmount + leverage | User specifies position size in tokens; collateral is derived from the leverage target |
"independent" | indexTokenAmount and/or initialCollateralAmount | Size and collateral are set independently; leverage is computed from the result |
The acceptable price is computed automatically. For limit orders, the default acceptable price impact buffer is 30 bps (0.3%) unless overridden by fixedAcceptablePriceImpactBps or acceptablePriceImpactBuffer. Stop-increase orders (OrderType.StopIncrease) always get the widest acceptable price: maxUint256 for longs and 0 for shorts.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
marketInfo | MarketInfo | Yes | Target market |
indexToken | TokenData | Yes | Index token for the position |
initialCollateralToken | TokenData | Yes | Token the user deposits (may differ from collateralToken if a swap is needed) |
collateralToken | TokenData | Yes | Final collateral token used by the position after any swap |
isLong | boolean | Yes | true for long, false for short |
strategy | "leverageBySize" | "leverageByCollateral" | "independent" | Yes | Size calculation strategy |
findSwapPath | FindSwapPath | Yes | Function for resolving collateral swap paths |
uiFeeFactor | bigint | Yes | UI fee factor (30-decimal fraction) |
chainId | number | Yes | Chain ID (for example, 42161 for Arbitrum) |
isSetAcceptablePriceImpactEnabled | boolean | Yes | When false, acceptable price is set to maxUint256 (longs) or 0 (shorts) for limit orders |
initialCollateralAmount | bigint | undefined | Conditional | Required for "leverageByCollateral" and "independent" |
indexTokenAmount | bigint | undefined | Conditional | Required for "leverageBySize" and "independent" |
leverage | bigint | undefined | Conditional | Required for "leverageBySize" and "leverageByCollateral" (basis points: 200000n = 20x) |
position | PositionInfo | undefined | No | Existing position — used to pull pending borrow and funding fees |
triggerPrice | bigint | undefined | No | Trigger price for limit orders (30-decimal precision) |
limitOrderType | OrderType.LimitIncrease | OrderType.StopIncrease | undefined | No | Set for limit and stop-market orders |
fixedAcceptablePriceImpactBps | bigint | undefined | No | Override the recommended acceptable price impact buffer |
acceptablePriceImpactBuffer | number | undefined | No | Additional buffer on top of estimated impact (default: 30 bps = 0.3%) |
userReferralInfo | UserReferralInfo | undefined | No | Referral data for position fee discount |
proDiscountFactor | bigint | undefined | No | Pro-tier position fee discount factor; the larger of this and the referral discount applies |
marketsInfoData | MarketsInfoData | undefined | No | All markets data, used for finding swap paths |
externalSwapQuote | ExternalSwapQuote | undefined | No | Pre-computed quote from an external aggregator; skips internal swap path finding |
externalSwapQuoteParams | ExternalSwapQuoteParams | undefined | No | Parameters for external swap quotes |
disabledMarkets | string[] | undefined | No | Market addresses to leave out of the swap path; applies only with externalSwapQuoteParams |
manualPath | string[] | undefined | No | Fixed swap path (market addresses); applies only with externalSwapQuoteParams |
Returns: IncreasePositionAmounts — includes sizeDeltaUsd, collateralDeltaUsd, positionFeeUsd, borrowingFeeUsd, fundingFeeUsd, uiFeeUsd, acceptablePrice, positionPriceImpactDeltaUsd, and more.
import { getIncreasePositionAmounts } from "@gmx-io/sdk/utils/trade";
// Open a 20x long ETH position with 1 USDC collateral
const amounts = getIncreasePositionAmounts({
marketInfo,
indexToken: ethToken,
initialCollateralToken: usdcToken,
collateralToken: usdcToken,
isLong: true,
initialCollateralAmount: 1_000000n, // 1 USDC (6 decimals)
leverage: 200000n, // 20x (200000 / 10000)
strategy: "leverageByCollateral",
findSwapPath,
uiFeeFactor: 0n,
chainId: 42161,
marketsInfoData,
externalSwapQuote: undefined,
externalSwapQuoteParams: undefined,
position: undefined,
userReferralInfo: undefined,
isSetAcceptablePriceImpactEnabled: true,
});
console.log("Size (USD):", amounts.sizeDeltaUsd);
console.log("Collateral (USD):", amounts.collateralDeltaUsd);
console.log("Position fee (USD):", amounts.positionFeeUsd);
console.log("Acceptable price:", amounts.acceptablePrice);
console.log("Price impact (USD):", amounts.positionPriceImpactDeltaUsd);
getTokensRatio
getTokensRatio(params: {
fromToken: TokenData;
toToken: TokenData;
triggerRatioValue: bigint;
markPrice: bigint;
}): { markRatio: TokensRatio; triggerRatio?: TokensRatio }
Computes the mark ratio and (optionally) the trigger ratio between two tokens. Use this when displaying or computing trigger order prices expressed as a token-to-token ratio (for example, "sell ETH when it reaches 2000 USDC").
The fromToken price used is always fromToken.prices.minPrice. The markPrice parameter is the current mark price of toToken in terms of fromToken (for example, USDC per ETH).
| Parameter | Type | Description |
|---|---|---|
fromToken | TokenData | Source token (for example, ETH for an ETH/USDC pair) |
toToken | TokenData | Target token (for example, USDC) |
triggerRatioValue | bigint | User-specified trigger ratio; if 0n, triggerRatio uses the mark ratio |
markPrice | bigint | Current mark price of toToken per fromToken |
import { getTokensRatio } from "@gmx-io/sdk/utils/trade";
// Set a trigger to sell ETH when it reaches 2000 USDC; current mark is 1950 USDC
const ratios = getTokensRatio({
fromToken: ethToken,
toToken: usdcToken,
triggerRatioValue: 2_000000000000000000000n, // 2000 USDC per ETH (token-precision scaled)
markPrice: 1_950000000000000000000n, // 1950 USDC per ETH
});
console.log("Mark ratio:", ratios.markRatio.ratio);
console.log("Trigger ratio:", ratios.triggerRatio?.ratio);
// With triggerRatioValue 0n, triggerRatio.ratio equals markRatio.ratio; triggerRatio is undefined only when triggerRatioValue is undefined
leverageBySizeValues
leverageBySizeValues(params: {
collateralToken: TokenData;
leverage: bigint;
sizeDeltaUsd: bigint;
collateralPrice: bigint;
uiFeeFactor: bigint;
positionFeeUsd: bigint;
borrowingFeeUsd: bigint;
uiFeeUsd: bigint;
swapUiFeeUsd: bigint;
fundingFeeUsd: bigint;
}): {
collateralDeltaUsd: bigint;
collateralDeltaAmount: bigint;
baseCollateralUsd: bigint;
baseCollateralAmount: bigint;
}
Calculates the collateral requirements for the "leverageBySize" strategy, where the user specifies a position size and the required collateral is derived from the leverage target. The collateralDeltaUsd is sizeDeltaUsd / leverage, and baseCollateralUsd adds all fees on top.
This function is a building block used internally by getIncreasePositionAmounts. You may also call it directly when you need just the collateral breakdown without constructing a full order.
| Parameter | Type | Description |
|---|---|---|
collateralToken | TokenData | Collateral token for token-amount conversion |
leverage | bigint | Target leverage in basis points (200000n = 20x) |
sizeDeltaUsd | bigint | Desired position size increase in USD (30-decimal precision) |
collateralPrice | bigint | Collateral token price in USD (30-decimal precision) |
uiFeeFactor | bigint | UI fee factor (present in the type; not used in calculation) |
positionFeeUsd | bigint | Position fee in USD |
borrowingFeeUsd | bigint | Pending borrow fee in USD |
uiFeeUsd | bigint | UI fee in USD |
swapUiFeeUsd | bigint | Swap UI fee in USD |
fundingFeeUsd | bigint | Pending funding fee in USD |
import { leverageBySizeValues } from "@gmx-io/sdk/utils/trade";
// 20x long with $20 size (USD, 30-decimal): collateral should be ~$1
const values = leverageBySizeValues({
collateralToken: usdcToken,
leverage: 200000n, // 20x
sizeDeltaUsd: 20_000000000000000000000000000000n, // $20
collateralPrice: 1_000000000000000000000000000000n, // $1 per USDC
uiFeeFactor: 0n,
positionFeeUsd: 10000000000000000000000000000n, // $0.01 position fee
borrowingFeeUsd: 0n,
uiFeeUsd: 0n,
swapUiFeeUsd: 0n,
fundingFeeUsd: 0n,
});
console.log("Collateral delta (USD):", values.collateralDeltaUsd); // ~$1
console.log("Base collateral (USD):", values.baseCollateralUsd); // ~$1 + fees
console.log("Collateral amount (tokens):", values.collateralDeltaAmount);
getIncreasePositionPrices
getIncreasePositionPrices(params: {
triggerPrice?: bigint;
indexToken: TokenData;
initialCollateralToken: TokenData;
collateralToken: TokenData;
isLong: boolean;
limitOrderType?: OrderType.LimitIncrease | OrderType.StopIncrease;
}): {
indexPrice: bigint;
initialCollateralPrice: bigint;
collateralPrice: bigint;
evaluationPrice?: bigint;
triggerThresholdType?: TriggerThresholdType;
triggerPrice?: bigint;
}
Selects the correct prices to use for position calculations based on order type. For market orders, prices come from live token price feeds. For limit and stop-increase orders, the trigger price is used as the index price (and as the collateral price if the collateral token matches the index token). evaluationPrice is the trigger price for limit and stop-increase orders and undefined for market orders.
| Parameter | Type | Description |
|---|---|---|
triggerPrice | bigint | undefined | User-set trigger price (30-decimal precision); required for limit orders |
indexToken | TokenData | Index token with live price data |
initialCollateralToken | TokenData | Token the user deposits |
collateralToken | TokenData | Final position collateral token |
isLong | boolean | true for long, false for short |
limitOrderType | OrderType.LimitIncrease | OrderType.StopIncrease | undefined | Set for non-market orders; undefined means market order |
triggerThresholdType indicates the price crossing direction: ">" (Above) means the order executes when the price rises above the trigger; "<" (Below) means it executes when the price falls below.
import { getIncreasePositionPrices } from "@gmx-io/sdk/utils/trade";
import { OrderType } from "@gmx-io/sdk/utils/orders";
// Limit increase: buy ETH long when price drops to $1900
const prices = getIncreasePositionPrices({
triggerPrice: 1_900000000000000000000000000000n, // $1900 (30-decimal)
indexToken: ethToken,
initialCollateralToken: usdcToken,
collateralToken: usdcToken,
isLong: true,
limitOrderType: OrderType.LimitIncrease,
});
console.log("Index price:", prices.indexPrice); // 1_900000000000000000000000000000n
console.log("Threshold type:", prices.triggerThresholdType); // "<" (Below) — executes when price ≤ $1900
getNextPositionValuesForIncreaseTrade
getNextPositionValuesForIncreaseTrade(p: {
existingPosition?: PositionInfo;
marketInfo: MarketInfo;
collateralToken: TokenData;
positionPriceImpactDeltaUsd: bigint;
sizeDeltaUsd: bigint;
sizeDeltaInTokens: bigint;
collateralDeltaUsd: bigint;
collateralDeltaAmount: bigint;
indexPrice: bigint;
isLong: boolean;
showPnlInLeverage: boolean;
minCollateralUsd: bigint;
userReferralInfo: UserReferralInfo | undefined;
collateralPrice?: bigint;
}): NextPositionValues
Projects position values after an increase trade executes. Pass the outputs from getIncreasePositionAmounts along with the current position (if any) to show users their post-trade size, leverage, entry price, and liquidation price.
Pending borrow and funding fees are treated as zero because they are deducted at order execution time. The existing collateral is valued at collateralPrice; when you omit it, the function uses existingPosition.collateralUsd.
| Parameter | Type | Description |
|---|---|---|
existingPosition | PositionInfo | undefined | Current open position; pass undefined for a new position |
marketInfo | MarketInfo | Market info for liquidation price computation |
collateralToken | TokenData | Collateral token for the position |
positionPriceImpactDeltaUsd | bigint | Price impact from getIncreasePositionAmounts (may be negative) |
sizeDeltaUsd | bigint | Size increase in USD |
sizeDeltaInTokens | bigint | Size increase in index token units |
collateralDeltaUsd | bigint | Collateral added in USD |
collateralDeltaAmount | bigint | Collateral added in token units |
indexPrice | bigint | Current or trigger index price |
isLong | boolean | true for long positions |
showPnlInLeverage | boolean | When true, unrealized PnL is included in the leverage denominator |
minCollateralUsd | bigint | Minimum collateral threshold used for liquidation price calculation |
userReferralInfo | UserReferralInfo | undefined | Referral data for fee discount in liquidation price |
collateralPrice | bigint | undefined | Price for the existing collateral (pass amounts.collateralPrice) |
Returns: NextPositionValues — nextSizeUsd, nextSizeInTokens, nextCollateralUsd, nextEntryPrice, nextLeverage, nextLiqPrice, nextPendingImpactDeltaUsd, potentialPriceImpactDiffUsd.
import { getIncreasePositionAmounts, getNextPositionValuesForIncreaseTrade } from "@gmx-io/sdk/utils/trade";
const amounts = getIncreasePositionAmounts({
/* ... see above ... */
});
const nextValues = getNextPositionValuesForIncreaseTrade({
existingPosition: currentPosition, // undefined for new positions
marketInfo,
collateralToken: usdcToken,
positionPriceImpactDeltaUsd: amounts.positionPriceImpactDeltaUsd,
sizeDeltaUsd: amounts.sizeDeltaUsd,
sizeDeltaInTokens: amounts.sizeDeltaInTokens,
collateralDeltaUsd: amounts.collateralDeltaUsd,
collateralDeltaAmount: amounts.collateralDeltaAmount,
indexPrice: amounts.indexPrice,
isLong: true,
showPnlInLeverage: false,
minCollateralUsd: 1_000000000000000000000000000000n, // $1 minimum
userReferralInfo: undefined,
collateralPrice: amounts.collateralPrice,
});
console.log("Next size (USD):", nextValues.nextSizeUsd);
console.log("Next leverage:", nextValues.nextLeverage); // bigint, basis points (10000 = 1x)
console.log("Next liquidation price:", nextValues.nextLiqPrice);
console.log("Next entry price:", nextValues.nextEntryPrice);
getIncreaseResultingPositionMarginState
getIncreaseResultingPositionMarginState(p: {
marketInfo: MarketInfo;
collateralToken: TokenData;
isLong: boolean;
existingPosition: IncreasePositionState | undefined;
sizeDeltaUsd: bigint;
sizeDeltaInTokens: bigint;
collateralDeltaAmount: bigint;
minCollateralUsd: bigint;
userReferralInfo: UserReferralInfo | undefined;
proDiscountFactor?: bigint;
indexPriceForEvaluation?: bigint;
}): PositionMarginState | undefined
Checks whether the position an increase order leaves passes the margin checks the contracts run after an increase. Call it with the outputs of getIncreasePositionAmounts before you submit the order: if isLiquidatable is true, the order is expected to fail at execution at the prices you passed. The parameter type is exported as IncreaseResultingPositionMarginStateParams.
The function follows the contracts' post-increase validation:
- It adds the size, size in tokens, and collateral deltas to
existingPosition(or to an empty position), adds the price impact of the increase to the pending impact, and adds the size to the market's open interest. - It checks the collateral value against the resulting size times the greater of the market's
minCollateralFactorand its open-interest-based minimum collateral factor, as the contracts'PositionUtils.willPositionCollateralBeSufficientdoes. If the collateral falls short, it returnsisLiquidatable: truewith the reasonInsufficientCollateralUsd. - Otherwise, it runs
getResultingPositionMarginStateon the resulting position and the updated market, as the contracts'PositionUtils.validatePositiondoes.
It returns undefined when sizeDeltaUsd or sizeDeltaInTokens is 0n or less, so collateral-only deposits aren't checked, or when the index token price or the collateral token's minimum price is 0n or less. undefined means the check didn't run, not that the position passes.
The result is an estimate at the prices in marketInfo, collateralToken, and indexPriceForEvaluation. Prices, open interest, and fees can change before a keeper executes the order. The check doesn't cover the minimum position size or the market's liquidity and open interest limits.
| Parameter | Type | Description |
|---|---|---|
marketInfo | MarketInfo | Market of the position, with current prices and open interest |
collateralToken | TokenData | Position collateral token |
isLong | boolean | true for long positions |
existingPosition | IncreasePositionState | undefined | Current position (a PositionInfo works); pass undefined for a new position |
sizeDeltaUsd | bigint | Size increase in USD, from getIncreasePositionAmounts |
sizeDeltaInTokens | bigint | Size increase in index token units |
collateralDeltaAmount | bigint | Collateral added in token units |
minCollateralUsd | bigint | Minimum collateral in USD (for example, from sdk.positions.getPositionsConstants()) |
userReferralInfo | UserReferralInfo | undefined | Referral data for the closing fee discount |
proDiscountFactor | bigint | undefined | Pro-tier discount factor for the closing fee; the larger of this and the referral discount applies |
indexPriceForEvaluation | bigint | undefined | Price to evaluate the position at; the trigger price for limit and stop-increase orders |
For limit and stop-increase orders, pass the trigger price as indexPriceForEvaluation. getIncreaseEvaluationIndexPrice() from @gmx-io/sdk/utils/prices returns it, and undefined for market orders. The price replaces the price of the index token and of any market or collateral token equivalent to it.
Returns: PositionMarginState | undefined:
| Field | Type | Description |
|---|---|---|
isLiquidatable | boolean | true when the resulting position fails a check |
reason | PositionMarginFailureReason | undefined | The check that failed; undefined when isLiquidatable is false |
remainingCollateralUsd | bigint | Collateral value the check used: the collateral alone for InsufficientCollateralUsd, otherwise collateral plus PnL and negative price impact, minus the closing fee |
minCollateralUsd | bigint | The minCollateralUsd you passed |
minCollateralUsdForLeverage | bigint | Minimum collateral for the position size: the open-interest-based minimum for InsufficientCollateralUsd, otherwise sizeInUsd × the market's minCollateralFactor |
import { getIncreasePositionAmounts, getIncreaseResultingPositionMarginState } from "@gmx-io/sdk/utils/trade";
import { getIncreaseEvaluationIndexPrice } from "@gmx-io/sdk/utils/prices";
import { OrderType } from "@gmx-io/sdk/utils/orders";
const amounts = getIncreasePositionAmounts({
/* ... see above ... */
});
const marginState = getIncreaseResultingPositionMarginState({
marketInfo,
collateralToken: usdcToken,
isLong: true,
existingPosition: currentPosition, // undefined for new positions
sizeDeltaUsd: amounts.sizeDeltaUsd,
sizeDeltaInTokens: amounts.sizeDeltaInTokens,
collateralDeltaAmount: amounts.collateralDeltaAmount,
minCollateralUsd, // from sdk.positions.getPositionsConstants()
userReferralInfo: undefined,
// Trigger price for limit and stop-increase orders, undefined for market orders
indexPriceForEvaluation: getIncreaseEvaluationIndexPrice({
orderType: amounts.limitOrderType ?? OrderType.MarketIncrease,
triggerPrice: amounts.triggerPrice,
}),
});
if (marginState?.isLiquidatable) {
console.log("Order is expected to fail:", marginState.reason);
console.log("Remaining collateral (USD):", marginState.remainingCollateralUsd);
}
getIncreaseResultingPositionState
getIncreaseResultingPositionState(p: IncreaseResultingPositionMarginStateParams): IncreaseResultingPositionState | undefined
type IncreasePositionState = {
sizeInUsd: bigint;
sizeInTokens: bigint;
collateralAmount: bigint;
pendingImpactAmount: bigint;
};
type IncreaseResultingPositionState = {
marginState: PositionMarginState;
position: IncreasePositionState;
marketInfo: MarketInfo;
};
Runs the same checks as getIncreaseResultingPositionMarginState, with the same parameters, and also returns the resulting position and market. Use it when you need the projected position, for example to run your own checks on it. It returns undefined in the same cases. Available in @gmx-io/sdk 2.3.1 and later.
| Field | Description |
|---|---|
marginState | The PositionMarginState that getIncreaseResultingPositionMarginState returns |
position | Position after the increase: size in USD and in index token units, collateral amount, and pending price impact in index token units |
marketInfo | Market after the increase, with the size added to open interest and the indexPriceForEvaluation prices applied when you pass one |
import { getIncreaseResultingPositionState } from "@gmx-io/sdk/utils/trade";
const result = getIncreaseResultingPositionState({
/* same parameters as getIncreaseResultingPositionMarginState */
});
if (result) {
console.log("Resulting size (USD):", result.position.sizeInUsd);
console.log("Resulting collateral (tokens):", result.position.collateralAmount);
console.log("Liquidatable:", result.marginState.isLiquidatable);
}
getResultingPositionMarginState
getResultingPositionMarginState(p: {
marketInfo: MarketInfo;
collateralToken: TokenData;
sizeInUsd: bigint;
sizeInTokens: bigint;
collateralAmount: bigint;
pendingImpactAmount: bigint;
minCollateralUsd: bigint;
isLong: boolean;
userReferralInfo: UserReferralInfo | undefined;
proDiscountFactor?: bigint;
shouldValidateMinCollateralUsd?: boolean;
}): PositionMarginState
Checks whether a position is liquidatable right after its pending fees are settled, which is the state the contracts validate after an increase or a decrease. It ports the contracts' PositionUtils.isPositionLiquidatable check. getIncreaseResultingPositionMarginState calls it for you; call it directly when you already have the resulting position values. The parameter type is exported as PositionMarginStateParams.
The remaining collateral is the collateral value at the collateral token's minimum price, plus the position's PnL, plus the price impact of closing the whole position combined with pendingImpactAmount, minus the closing position fee after the larger of the referral and pro-tier discounts. A net positive price impact counts as zero, and a negative one is capped at sizeInUsd × the market's maxPositionImpactFactorForLiquidations. The function returns the first check that fails:
- Remaining collateral is below
minCollateralUsd: reasonMinCollateral. The function skips this check whenshouldValidateMinCollateralUsdisfalse. - Remaining collateral is
0or less: reasonNonPositiveRemainingMargin. - Remaining collateral is below
sizeInUsd× the market'sminCollateralFactor: reasonMinCollateralForLeverage.
If no check fails, it returns isLiquidatable: false and reason: undefined.
| Parameter | Type | Description |
|---|---|---|
marketInfo | MarketInfo | Market of the position |
collateralToken | TokenData | Position collateral token |
sizeInUsd | bigint | Position size in USD |
sizeInTokens | bigint | Position size in index token units |
collateralAmount | bigint | Collateral in token units |
pendingImpactAmount | bigint | Pending price impact in index token units (may be negative) |
minCollateralUsd | bigint | Minimum collateral in USD |
isLong | boolean | true for long positions |
userReferralInfo | UserReferralInfo | undefined | Referral data for the closing fee discount |
proDiscountFactor | bigint | undefined | Pro-tier discount factor for the closing fee |
shouldValidateMinCollateralUsd | boolean | undefined | Whether to run the MinCollateral check. Defaults to true. The decrease margin checks and getMaxWithdrawAmount pass false |
import { getIncreaseResultingPositionState, getResultingPositionMarginState } from "@gmx-io/sdk/utils/trade";
const result = getIncreaseResultingPositionState({
/* ... see above ... */
});
if (result) {
// Re-check the resulting position against a stricter minimum collateral of $5
const marginState = getResultingPositionMarginState({
marketInfo: result.marketInfo,
collateralToken: usdcToken,
...result.position,
minCollateralUsd: 5_000000000000000000000000000000n,
isLong: true,
userReferralInfo: undefined,
});
console.log("Liquidatable:", marginState.isLiquidatable, marginState.reason);
}
getMarketInfoAtIndexPrice
getMarketInfoAtIndexPrice(p: {
marketInfo: MarketInfo;
collateralToken: TokenData;
indexPrice: bigint | undefined;
}): { marketInfo: MarketInfo; collateralToken: TokenData }
Returns marketInfo and collateralToken with indexPrice as both the minimum and maximum price of the index token, and of the long, short, or collateral token when it's equivalent to the index token. Use it to evaluate a position at a trigger price. It returns the inputs unchanged when indexPrice is undefined, 0n, or less.
PositionMarginFailureReason
enum PositionMarginFailureReason {
MinCollateral = "min collateral",
NonPositiveRemainingMargin = "< 0",
MinCollateralForLeverage = "min collateral for leverage",
InsufficientCollateralUsd = "insufficient collateral usd",
UnableToWithdrawCollateral = "unable to withdraw collateral",
MaxAllowedLeverage = "max allowed leverage",
}
Lists the values of PositionMarginState.reason. The first three values are the reason strings the contracts return in a LiquidatablePosition error, and InsufficientCollateralUsd and UnableToWithdrawCollateral match the contracts' errors of the same names.
| Member | Set by | Meaning |
|---|---|---|
MinCollateral | getResultingPositionMarginState | Remaining collateral is below minCollateralUsd |
NonPositiveRemainingMargin | getResultingPositionMarginState | Remaining collateral is 0 or less |
MinCollateralForLeverage | getResultingPositionMarginState | Remaining collateral is below the minimum for the position size, so the leverage is too high |
InsufficientCollateralUsd | getIncreaseResultingPositionMarginState, getIncreaseResultingPositionState | Collateral is below the minimum for the market's open interest after the increase |
UnableToWithdrawCollateral | getDecreaseResultingPositionMarginState | A collateral withdrawal with no size change would leave too little collateral |
MaxAllowedLeverage | None of the functions on this page | Added in 2.3.1; getIsMaxLeverageMarginReason matches it |
getIncreaseResultingPositionMarginState and getIncreaseResultingPositionState also return the reasons that getResultingPositionMarginState sets. getDecreaseResultingPositionMarginState returns those reasons too, except MinCollateral.
getIsMaxLeverageMarginReason
getIsMaxLeverageMarginReason(reason: PositionMarginFailureReason | undefined): boolean
Returns true when a failure means the leverage is too high for the collateral: MinCollateralForLeverage, InsufficientCollateralUsd, or MaxAllowedLeverage. Returns false for MinCollateral, NonPositiveRemainingMargin, and undefined. Use it to tell leverage failures apart from minimum-collateral failures, for example to suggest lower leverage.
import { getIsMaxLeverageMarginReason, PositionMarginFailureReason } from "@gmx-io/sdk/utils/trade";
if (marginState?.isLiquidatable) {
if (getIsMaxLeverageMarginReason(marginState.reason)) {
console.log("Leverage is too high for this market. Lower the leverage or add collateral.");
} else if (marginState.reason === PositionMarginFailureReason.MinCollateral) {
console.log("Collateral after fees is below the minimum collateral.");
}
}
Related
- Decrease position utilities — symmetric functions for closing or reducing positions
- Trade utilities — shared helpers for both increase and decrease operations
- Fees module — position fee and price impact calculation functions