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).
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.
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 |
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 |
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 or undefined, defaults to 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);
// 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.
| 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;
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).
| 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;
}): 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.
| 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 |
Returns: NextPositionValues — nextSizeUsd, 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);
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