Skip to main content

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).

note

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:

StrategyInput requiredDescription
"leverageByCollateral"initialCollateralAmount + leverageUser specifies how much collateral to deposit; size is derived from the leverage target
"leverageBySize"indexTokenAmount + leverageUser specifies position size in tokens; collateral is derived from the leverage target
"independent"indexTokenAmount and/or initialCollateralAmountSize 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:

ParameterTypeRequiredDescription
marketInfoMarketInfoYesTarget market
indexTokenTokenDataYesIndex token for the position
initialCollateralTokenTokenDataYesToken the user deposits (may differ from collateralToken if a swap is needed)
collateralTokenTokenDataYesFinal collateral token used by the position after any swap
isLongbooleanYestrue for long, false for short
strategy"leverageBySize" | "leverageByCollateral" | "independent"YesSize calculation strategy
findSwapPathFindSwapPathYesFunction for resolving collateral swap paths
uiFeeFactorbigintYesUI fee factor (30-decimal fraction)
chainIdnumberYesChain ID (for example, 42161 for Arbitrum)
isSetAcceptablePriceImpactEnabledbooleanYesWhen false, acceptable price is set to maxUint256 (longs) or 0 (shorts) for limit orders
initialCollateralAmountbigint | undefinedConditionalRequired for "leverageByCollateral" and "independent"
indexTokenAmountbigint | undefinedConditionalRequired for "leverageBySize" and "independent"
leveragebigint | undefinedConditionalRequired for "leverageBySize" and "leverageByCollateral" (basis points: 200000n = 20x)
positionPositionInfo | undefinedNoExisting position — used to pull pending borrow and funding fees
triggerPricebigint | undefinedNoTrigger price for limit orders (30-decimal precision)
limitOrderTypeOrderType.LimitIncrease | OrderType.StopIncrease | undefinedNoSet for limit and stop-market orders
fixedAcceptablePriceImpactBpsbigint | undefinedNoOverride the recommended acceptable price impact buffer
acceptablePriceImpactBuffernumber | undefinedNoAdditional buffer on top of estimated impact (default: 30 bps = 0.3%)
userReferralInfoUserReferralInfo | undefinedNoReferral data for position fee discount
proDiscountFactorbigint | undefinedNoPro-tier position fee discount factor; the larger of this and the referral discount applies
marketsInfoDataMarketsInfoData | undefinedNoAll markets data, used for finding swap paths
externalSwapQuoteExternalSwapQuote | undefinedNoPre-computed quote from an external aggregator; skips internal swap path finding
externalSwapQuoteParamsExternalSwapQuoteParams | undefinedNoParameters for external swap quotes
disabledMarketsstring[] | undefinedNoMarket addresses to leave out of the swap path; applies only with externalSwapQuoteParams
manualPathstring[] | undefinedNoFixed 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).

ParameterTypeDescription
fromTokenTokenDataSource token (for example, ETH for an ETH/USDC pair)
toTokenTokenDataTarget token (for example, USDC)
triggerRatioValuebigintUser-specified trigger ratio; if 0n, triggerRatio uses the mark ratio
markPricebigintCurrent 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.

ParameterTypeDescription
collateralTokenTokenDataCollateral token for token-amount conversion
leveragebigintTarget leverage in basis points (200000n = 20x)
sizeDeltaUsdbigintDesired position size increase in USD (30-decimal precision)
collateralPricebigintCollateral token price in USD (30-decimal precision)
uiFeeFactorbigintUI fee factor (present in the type; not used in calculation)
positionFeeUsdbigintPosition fee in USD
borrowingFeeUsdbigintPending borrow fee in USD
uiFeeUsdbigintUI fee in USD
swapUiFeeUsdbigintSwap UI fee in USD
fundingFeeUsdbigintPending 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.

ParameterTypeDescription
triggerPricebigint | undefinedUser-set trigger price (30-decimal precision); required for limit orders
indexTokenTokenDataIndex token with live price data
initialCollateralTokenTokenDataToken the user deposits
collateralTokenTokenDataFinal position collateral token
isLongbooleantrue for long, false for short
limitOrderTypeOrderType.LimitIncrease | OrderType.StopIncrease | undefinedSet 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.

ParameterTypeDescription
existingPositionPositionInfo | undefinedCurrent open position; pass undefined for a new position
marketInfoMarketInfoMarket info for liquidation price computation
collateralTokenTokenDataCollateral token for the position
positionPriceImpactDeltaUsdbigintPrice impact from getIncreasePositionAmounts (may be negative)
sizeDeltaUsdbigintSize increase in USD
sizeDeltaInTokensbigintSize increase in index token units
collateralDeltaUsdbigintCollateral added in USD
collateralDeltaAmountbigintCollateral added in token units
indexPricebigintCurrent or trigger index price
isLongbooleantrue for long positions
showPnlInLeveragebooleanWhen true, unrealized PnL is included in the leverage denominator
minCollateralUsdbigintMinimum collateral threshold used for liquidation price calculation
userReferralInfoUserReferralInfo | undefinedReferral data for fee discount in liquidation price
collateralPricebigint | undefinedPrice 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:

  1. 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.
  2. It checks the collateral value against the resulting size times the greater of the market's minCollateralFactor and its open-interest-based minimum collateral factor, as the contracts' PositionUtils.willPositionCollateralBeSufficient does. If the collateral falls short, it returns isLiquidatable: true with the reason InsufficientCollateralUsd.
  3. Otherwise, it runs getResultingPositionMarginState on the resulting position and the updated market, as the contracts' PositionUtils.validatePosition does.

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.

note

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.

ParameterTypeDescription
marketInfoMarketInfoMarket of the position, with current prices and open interest
collateralTokenTokenDataPosition collateral token
isLongbooleantrue for long positions
existingPositionIncreasePositionState | undefinedCurrent position (a PositionInfo works); pass undefined for a new position
sizeDeltaUsdbigintSize increase in USD, from getIncreasePositionAmounts
sizeDeltaInTokensbigintSize increase in index token units
collateralDeltaAmountbigintCollateral added in token units
minCollateralUsdbigintMinimum collateral in USD (for example, from sdk.positions.getPositionsConstants())
userReferralInfoUserReferralInfo | undefinedReferral data for the closing fee discount
proDiscountFactorbigint | undefinedPro-tier discount factor for the closing fee; the larger of this and the referral discount applies
indexPriceForEvaluationbigint | undefinedPrice 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:

FieldTypeDescription
isLiquidatablebooleantrue when the resulting position fails a check
reasonPositionMarginFailureReason | undefinedThe check that failed; undefined when isLiquidatable is false
remainingCollateralUsdbigintCollateral value the check used: the collateral alone for InsufficientCollateralUsd, otherwise collateral plus PnL and negative price impact, minus the closing fee
minCollateralUsdbigintThe minCollateralUsd you passed
minCollateralUsdForLeveragebigintMinimum 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.

FieldDescription
marginStateThe PositionMarginState that getIncreaseResultingPositionMarginState returns
positionPosition after the increase: size in USD and in index token units, collateral amount, and pending price impact in index token units
marketInfoMarket 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:

  1. Remaining collateral is below minCollateralUsd: reason MinCollateral. The function skips this check when shouldValidateMinCollateralUsd is false.
  2. Remaining collateral is 0 or less: reason NonPositiveRemainingMargin.
  3. Remaining collateral is below sizeInUsd × the market's minCollateralFactor: reason MinCollateralForLeverage.

If no check fails, it returns isLiquidatable: false and reason: undefined.

ParameterTypeDescription
marketInfoMarketInfoMarket of the position
collateralTokenTokenDataPosition collateral token
sizeInUsdbigintPosition size in USD
sizeInTokensbigintPosition size in index token units
collateralAmountbigintCollateral in token units
pendingImpactAmountbigintPending price impact in index token units (may be negative)
minCollateralUsdbigintMinimum collateral in USD
isLongbooleantrue for long positions
userReferralInfoUserReferralInfo | undefinedReferral data for the closing fee discount
proDiscountFactorbigint | undefinedPro-tier discount factor for the closing fee
shouldValidateMinCollateralUsdboolean | undefinedWhether 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.

MemberSet byMeaning
MinCollateralgetResultingPositionMarginStateRemaining collateral is below minCollateralUsd
NonPositiveRemainingMargingetResultingPositionMarginStateRemaining collateral is 0 or less
MinCollateralForLeveragegetResultingPositionMarginStateRemaining collateral is below the minimum for the position size, so the leverage is too high
InsufficientCollateralUsdgetIncreaseResultingPositionMarginState, getIncreaseResultingPositionStateCollateral is below the minimum for the market's open interest after the increase
UnableToWithdrawCollateralgetDecreaseResultingPositionMarginStateA collateral withdrawal with no size change would leave too little collateral
MaxAllowedLeverageNone of the functions on this pageAdded 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.");
}
}