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

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

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 or undefined, defaults to 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);
// triggerRatio is undefined when triggerRatioValue is 0n or 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;
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).

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;
}): 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.

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

Returns: NextPositionValuesnextSizeUsd, 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,
});

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