GMX 백서

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 15쪽

lding decrease position order params --- ## positions This module provides utilities for working with trading positions in the GMX protocol. It includes functions for calculating position metrics, PnL, liquidation prices, leverage, and managing position keys. ## Methods The positions utility module exports functions organized into six groups: position key utilities, position value calculations, leverage and risk, price impact calculations, API data fetching, and position enrichment. Import any function directly from `@gmx-io/sdk/utils/positions`. ### Position key utilities These functions create and parse the string keys used to identify positions on-chain. #### getPositionKey ```typescript getPositionKey(account: string, marketAddress: string, collateralAddress: string, isLong: boolean): string ``` Generates a unique position key from position parameters. The key format is `account:marketAddress:collateralAddress:isLong`. ```typescript const positionKey = getPositionKey( "0x1234567890123456789012345678901234567890", "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", "0xfedcbafedcbafedcbafedcbafedcbafedcbafed", true ); // "0x1234...5678:0xabcd...abcd:0xfedc...afed:true" ``` #### parsePositionKey ```typescript parsePositionKey(positionKey: string): { account: string; marketAddress: string; collateralAddress: string; isLong: boolean; } ``` Parses a position key back into its component parts. The `isLong` field is parsed from the string `"true"` / `"false"`. ```typescript const parsed = parsePositionKey("0x1234567890123456789012345678901234567890:0xabcdef...:0xfedcba...:true"); // { account: "0x1234...", marketAddress: "0xabcdef...", collateralAddress: "0xfedcba...", isLong: true } ``` ### Position value calculations These functions compute USD-denominated metrics from raw position data. All values use 30-decimal fixed-point representation. #### getEntryPrice ```typescript getEntryPrice(p: { sizeInUsd: bigint; sizeInTokens: bigint; indexToken: Token }): bigint | undefined ``` Calculates the entry price of a position as `sizeInUsd × 10^indexToken.decimals / sizeInTokens`. Returns `undefined` when `sizeInTokens <= 0`. ```typescript const entryPrice = getEntryPrice({ sizeInUsd: 1800n * 10n ** 30n, // $1800 (30-decimal) sizeInTokens: 1n * 10n ** 18n, // 1 WETH (18-decimal) indexToken: wethToken, }); // 1800n * 10n ** 30n — price in 30-decimal format ``` #### getPositionValueUsd ```typescript getPositionValueUsd(p: { indexToken: Token; sizeInTokens: bigint; markPrice: bigint }): bigint ``` Calculates the current USD value of a position: `convertToUsd(sizeInTokens, indexToken.decimals, markPrice)`. ```typescript const valueUsd = getPositionValueUsd({ indexToken: wethToken, sizeInTokens: 1n * 10n ** 18n, // 1 WETH markPrice: 2100n * 10n ** 30n, // $2100 (30-decimal) }); // 2100n * 10n ** 30n ``` #### getPositionPnlUsd ```typescript getPositionPnlUsd(p: { marketInfo: MarketInfo; sizeInUsd: bigint; sizeInTokens: bigint; markPrice: bigint; isLong: boolean; }): bigint ``` Calculates the unrealized PnL of a position in USD (30-decimal). For profitable positions, the cap denominator is the sum of positive market PnL calculated separately for positions using the long and short collateral tokens, so a loss in one collateral bucket doesn't offset a profit in the other. If those split fields are unavailable, the helper falls back to aggregate market PnL. The result is scaled down proportionally when this PnL exceeds the market cap. - Long PnL: `positionValueUsd - sizeInUsd` - Short PnL: `sizeInUsd - positionValueUsd` ```typescript const pnl = getPositionPnlUsd({ marketInfo, sizeInUsd: 1800n * 10n ** 30n, // entry value sizeInTokens: 1n * 10n ** 18n, // 1 WETH markPrice: 2100n * 10n ** 30n, // current price isLong: true, }); // +300n * 10n ** 30n ($300 profit, before pool cap adjustment) ``` #### getPositionPendingFeesUsd ```typescript getPositionPendingFeesUsd(p: { pendingFundingFeesUsd: bigint; pendingBorrowingFeesUsd: bigint }): bigint ``` Returns `pendingBorrowingFeesUsd + pendingFundingFeesUsd`. ```typescript const pendingFees = getPositionPendingFeesUsd({ pendingFundingFeesUsd: 1n * 10n ** 30n, // $1 pendingBorrowingFeesUsd: 5n * 10n ** 29n, // $0.5 }); // 1_500_000n * 10n ** 24n ($1.5 in 30-decimal) ``` #### getPositionNetValue ```typescript getPositionNetValue(p: { collateralUsd: bigint; pendingFundingFeesUsd: bigint; pendingBorrowingFeesUsd: bigint; pnl: bigint; }): bigint ``` Returns the net value of a position: ``` collateralUsd - pendingBorrowingFeesUsd - pendingFundingFeesUsd + pnl ``` ```typescript const netValue = getPositionNetValue({ collateralUsd: 500n * 10n ** 30n, // $500 collateral pendingFundingFeesUsd: 1n * 10n ** 30n, pendingBorrowingFeesUsd: 5n * 10n ** 29n, pnl: 50n * 10n ** 30n, // $50 profit }); // $548.50 in 30-decimal ``` #### getPositionNetValueAfterAllFees ```typescript getPositionNetValueAfterAllFees(p: { collateralUsd: bigint; pnl: bigint; pendingBorrowingFeesUsd: bigint; pendingFundingFeesUsd: bigint; netPriceImpactDeltaUsd: bigint; closingFeeUsd: bigint; }): bigint ``` Returns the net value after borrowing fees, funding fees, close price impact, and the closing position fee: ``` collateralUsd + pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd + netPriceImpactDeltaUsd - closingFeeUsd ``` #### getPositionPnlAfterFees ```typescript getPositionPnlAfterFees(params: { pnl: bigint; pendingBorrowingFeesUsd: bigint; pendingFundingFeesUsd: bigint; }): bigint ``` Returns the position PnL after deducting pending borrowing and funding fees: ``` pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd ``` ```typescript const pnlAfterFees = getPositionPnlAfterFees({ pnl: 100n * 10n ** 30n, pendingBorrowingFeesUsd: 1n * 10n ** 30n, pendingFundingFeesUsd: 5n * 10n ** 29n, }); // $98.50 in 30-decimal ``` #### getPositionPnlAfterAllFees ```typescript getPositionPnlAfterAllFees(params: { pnl: bigint; pendingBorrowingFeesUsd: bigint; pendingFundingFeesUsd: bigint; netPriceImpactDeltaUsd: bigint; closingFeeUsd: bigint; }): bigint ``` Returns the position PnL after borrowing fees, funding fees, close price impact, and the closing position fee: ``` pnl - pendingBorrowingFeesUsd - pendingFundingFeesUsd + netPriceImpactDeltaUsd - closingFeeUsd ``` ### Leverage and risk These functions compute leverage and liquidation price for a position. #### getLeverage ```typescript getLeverage(p: { sizeInUsd: bigint; collateralUsd: bigint; pnl: bigint | undefined; pendingFundingFeesUsd: bigint; pendingBorrowingFeesUsd: bigint; }): bigint | undefined ``` Returns the current leverage in basis points (`sizeInUsd × BASIS_POINTS_DIVISOR / remainingCollateralUsd`), where `remainingCollateralUsd = collateralUsd + pnl - pendingFees`. Returns `undefined` when `remainingCollateralUsd <= 0`. `BASIS_POINTS_DIVISOR = 10000`, so a return value of `20000n` means 2× leverage. ```typescript const leverage = getLeverage({ sizeInUsd: 1000n * 10n ** 30n, collateralUsd: 100n * 10n ** 30n, pnl: 10n * 10n ** 30n, pendingFundingFeesUsd: 1n * 10n ** 30n, pendingBorrowingFeesUsd: 5n * 10n ** 29n, }); // ~92593n bps ≈ 9.26× ``` #### getLiquidationPrice ```typescript getLiquidationPrice(p: { sizeInUsd: bigint; sizeInTokens: bigint; collateralAmount: bigint; collateralUsd: bigint; collateralToken: TokenData; marketInfo: MarketInfo; pendingFundingFeesUsd: bigint; pendingBorrowingFeesUsd: bigint; pendingImpactAmount: bigint; minCollateralUsd: bigint; isLong: boolean; useMaxPriceImpact?: boolean; userReferralInfo: UserReferralInfo | undefined; }): bigint | undefined ``` Calculates the liquidation price for a position. Returns `undefined` when `sizeInUsd <= 0`, `sizeInTokens <= 0`, the denominator is zero, or when the computed price is `<= 0`. Two formulas are used depending on whether the collateral token is equivalent to the index token: - **Equivalent collateral** (for example, long ETH/USDC collateralized in ETH): combines token amounts directly with `sizeInTokens ± collateralAmount` as denominator. - **Non-equivalent collateral** (for example, long ETH/USDC collateralized in USDC): uses `remainingCollateralUsd` and `sizeInTokens` as denominator. When `useMaxPriceImpact` is `true`, uses `marketInfo.maxPositionImpactFactorForLiquidations` instead of computing the actual price impact. ```typescript const liquidationPrice = getLiquidationPrice({ sizeInUsd: 1800n * 10n ** 30n, sizeInTokens: 1n * 10n ** 18n, collateralAmount: 100n * 10n ** 6n, // 100 USDC (6-decimal collateral) collateralUsd: 100n * 10n ** 30n, collateralToken: usdcTokenData, marketInfo, pendingFundingFeesUsd: 1n * 10n ** 30n, pendingBorrowingFeesUsd: 5n * 10n ** 29n, pendingImpactAmount: 0n, minCollateralUsd: 10n * 10n ** 30n, isLong: true, useMaxPriceImpact: false, userReferralInfo: undefined, }); ``` ### Price impact calculations These functions compute the net price impact when decreasing a position, including contributions from the pending impact pool. #### getNetPriceImpactDeltaUsdForDecrease ```typescript getNetPriceImpactDeltaUsdForDecrease(params: { marketInfo: MarketInfo; sizeInUsd: bigint; pendingImpactAmount: bigint; priceImpactDeltaUsd: bigint; sizeDeltaUsd: bigint; }): { totalImpactDeltaUsd: bigint; proportionalPendingImpactDeltaUsd: bigint; priceImpactDiffUsd: bigint; } ``` Calculates the net price impact when decreasing a position by combining the current price impact with a proportional share of the pending impact pool. The positive total is capped by `maxPositionImpactFactor`; the negative total is floored by the max impact pool limit. ```typescript const impact = getNetPriceImpactDeltaUsdForDecrease({ marketInfo, sizeInUsd: 1800n * 10n ** 30n, pendingImpactAmount: 0n, priceImpactDeltaUsd: -5n * 10n ** 30n, // $5 adverse price impact sizeDeltaUsd: 900n * 10n ** 30n, // closing half the position }); // impact.totalImpactDeltaUsd — net impact after caps // impact.proportionalPendingImpactDeltaUsd — share of pending impact pool // impact.priceImpactDiffUsd — capped-off portion (goes to holding pool) ``` #### getPriceImpactDiffUsd ```typescript getPriceImpactDiffUsd(params: { totalImpactDeltaUsd: bigint; marketInfo: MarketInfo; sizeDeltaUsd: bigint; }): bigint ``` Returns the portion of a negative price impact that exceeds the market's maximum negative impact factor. Returns `0n` when `totalImpactDeltaUsd >= 0`. ```typescript const diff = getPriceImpactDiffUsd({ totalImpactDeltaUsd: -10n * 10n ** 30n, // $10 adverse impact marketInfo, sizeDeltaUsd: 500n * 10n ** 30n, }); // 0n if impact is within the max factor, otherwise the excess ``` ### API data fetching Use `fetchApiPositionsInfo` to retrieve position data from the GMX API as an alternative to on-chain multicalls. #### fetchApiPositionsInfo ```typescript fetchApiPositionsInfo(ctx: { api: IHttp }, params: { address: string; includeRelatedOrders?: boolean; }): Promise<ApiPositionInfo[]> ``` Fetches position data from the GMX API instead of on-chain multicalls. Available on chains where `isApiSupported(chainId)` returns `true` (Arbitrum, Avalanche, MegaETH, and Arbitrum Sepolia for active integrations). The response is deserialized with `deserializeBigIntsInObject`. ```typescript const apiSdk = new GmxApiSdk({ chainId: 42161 }); const positions = await fetchApiPositionsInfo( apiSdk.ctx, { address: "0x1234...5678", includeRelatedOrders: true } ); ``` ### Position enrichment These functions build fully computed position summaries from raw on-chain data and current market state. #### getPositionInfo ```typescript getPositionInfo(p: { position: Position; marketInfo: MarketInfo; minCollateralUsd: bigint; userReferralInfo?: UserReferralInfo; showPnlInLeverage?: boolean; uiFeeFactor?: bigint; }): PositionInfo ``` Computes a comprehensive position summary from a raw position and market data. Returns an object with entry price, mark price, PnL, PnL after pending fees, PnL after all close costs, leverage, liquidation price, net value, pending fees, and closing costs. This is the main function to use when you need a full picture of a position's current state. ```typescript const info = getPositionInfo({ position, marketInfo, minCollateralUsd: 10n * 10n ** 30n, userReferralInfo: undefined, }); console.log(info.entryPrice); // entry price in 30-decimal console.log(info.pnl); // unrealized PnL console.log(info.pnlAfterFees); // PnL minus pending borrowing and funding fees console.log(info.pnlAfterAllFees); // PnL after pending fees, close price impact, and closing fee console.log(info.leverage); // current leverage in basis points console.log(info.liquidationPrice); // liquidation price console.log(info.netValue); // net position value console.log(info.netValueAfterAllFees); // net value after all close costs ``` #### getContractPositionDynamicFees ```typescript getContractPositionDynamicFees(p: { position: { sizeInUsd: bigint; collateralTokenAddress: string; isLong: boolean; borrowingFactor: bigint; fundingFeeAmountPerSize: bigint; longTokenClaimableFundingAmountPerSize: bigint; shortTokenClaimableFundingAmountPerSize: bigint; }; marketInfo: MarketInfo; marketFeeState: { cumulativeBorrowingFactorLong: bigint; cumulativeBorrowingFactorShort: bigint; fundingFeeAmountPerSizeLongLong: bigint; fundingFeeAmountPerSizeLongShort: bigint; fundingFeeAmountPerSizeShortLong: bigint; fundingFeeAmountPerSizeShortShort: bigint; claimableFundingAmountPerSizeLongLong: bigint; claimableFundingAmountPerSizeLongShort: bigint; claimableFundingAmountPerSizeShortLong: bigint; claimableFundingAmountPerSizeShortShort: bigint; }; referralInfo?: UserReferralInfo; }): { pendingBorrowingFeesUsd: bigint; fundingFeeAmount: bigint; claimableLongTokenAmount: bigint; claimableShortTokenAmount: bigint; positionFeeAmount: bigint; traderDiscountAmount: bigint; uiFeeAmount: bigint; } ``` Calculates the dynamic fees for a position based on the current market fee state. Unlike the static fee fields on a position object, this function uses the latest cumulative borrowing and funding factors to compute up-to-date fee values. ```typescript const fees = getContractPositionDynamicFees({ position, marketInfo, marketFeeState, referralInfo: undefined, }); console.log(fees.pendingBorrowingFeesUsd); // current borrowing fees in USD console.log(fees.fundingFeeAmount); // funding fee in collateral token units ``` ### Collateral factor #### getMinCollateralFactorForPosition ```typescript getMinCollateralFactorForPosition(position: PositionInfoLoaded, openInterestDelta: bigint): bigint ``` Returns the minimum collateral factor (in PRECISION units) required for the position's market side, given the current open interest plus `openInterestDelta`. The result is the greater of the OI-based factor and the market's baseline `minCollateralFactor`. ```typescript const minFactor = getMinCollateralFactorForPosition( positionInfo, -1000n * 10n ** 30n // OI decreasing by $1000 ); ``` --- ## prices This module provides utilities for calculating prices, price impacts, and acceptable price ranges for GMX trading operations. This page also covers the related OHLCV read surface exposed through `GmxApiSdk`, because the candle types live in the same source area. ## Methods The `prices` module exports utilities for two tasks: determining which side of the bid-ask spread to use for a given operation, and computing acceptable prices that encode a user's slippage tolerance into an on-chain parameter. The OHLCV section below is included because the public `GmxApiSdk.fetchOhlcv()` method uses the same source area, but `@gmx-io/sdk/utils/prices` does not export the fetch helper directly. ### getMarkPrice ```typescript getMarkPrice(p: { prices: TokenPrices; isIncrease: boolean; isLong: boolean }): bigint ``` Returns the mark price for an operation. Long increases and short decreases use `maxPrice`; short increases and long decreases use `minPrice`. This matches the on-chain convention that the protocol uses the price least favorable to the trader. ```typescript const markPrice = getMarkPrice({ prices: { minPrice: 1800n * 10n ** 30n, maxPrice: 1802n * 10n ** 30n, }, isIncrease: true, isLong: true, }); // Returns prices.maxPrice (worst price for a long increase) ``` ### getShouldUseMaxPrice ```typescript getShouldUseMaxPrice(isIncrease: boolean, isLong: boolean): boolean ``` Returns `true` when the operation should use `maxPrice` and `false` when it should use `minPrice`. The rule is: `isIncrease ? isLong : !isLong`. ```typescript getShouldUseMaxPrice(true, true); // true — long increase uses maxPrice getShouldUseMaxPrice(true, false); // false — short increase uses minPrice getShouldUseMaxPrice(false, true); // false — long decrease uses minPrice getShouldUseMaxPrice(false, false); // true — short decrease uses maxPrice ``` ### getOrderThresholdType ```typescript getOrderThresholdType(orderType: OrderType, isLong: boolean): TriggerThresholdType | undefined ``` Returns the `TriggerThresholdType` (`Above` or `Below`) for a trigger order. Returns `undefined` for order types that don't use a trigger price (for example, Market Increase). | Order type | Long | Short | | -------------------------------- | ------- | ------- | | Limit Increase (`LimitIncrease`) | `Below` | `Above` | | Stop Market (`StopIncrease`) | `Above` | `Below` | | Take-Profit (`LimitDecrease`) | `Above` | `Below` | | Stop-Loss (`StopLossDecrease`) | `Below` | `Above` | ```typescript const thresholdType = getOrderThresholdType(OrderType.LimitIncrease, true); // TriggerThresholdType.Below — trigger when price drops to or below target ``` ### getAcceptablePriceInfo ```typescript getAcceptablePriceInfo(p: { marketInfo: MarketInfo; isIncrease: boolean; isLimit: boolean; isLong: boolean; indexPrice: bigint; sizeDeltaUsd: bigint; maxNegativePriceImpactBps?: bigint; }): { acceptablePrice: bigint; acceptablePriceDeltaBps: bigint; priceImpactDeltaAmount: bigint; priceImpactDeltaUsd: bigint; priceImpactDiffUsd: bigint; balanceWasImproved: boolean; } ``` Computes the acceptable price and price impact for an order. There are two code paths: - When `maxNegativePriceImpactBps` is provided (Limit and Trigger orders): the acceptable price is derived directly from the basis-points slippage tolerance, and price impact is back-calculated from that price. - When `maxNegativePriceImpactBps` is omitted (Market orders): the on-chain pool price impact is computed via `getCappedPositionImpactUsd` and used to derive the acceptable price. Returns zero values when `sizeDeltaUsd` is `0` or `indexPrice` is `0n`. ```typescript // Market order: derive acceptable price from live pool price impact const result = getAcceptablePriceInfo({ marketInfo, isIncrease: true, isLimit: false, isLong: true, indexPrice: 1800n * 10n ** 30n, sizeDeltaUsd: 10000n * 10n ** 30n, // $10,000 position }); console.log("Acceptable price:", result.acceptablePrice); console.log("Price impact USD:", result.priceImpactDeltaUsd); // Limit order: pass explicit slippage tolerance (50 bps = 0.5%) const limitResult = getAcceptablePriceInfo({ marketInfo, isIncrease: true, isLimit: true, isLong: true, indexPrice: 1800n * 10n ** 30n, sizeDeltaUsd: 10000n * 10n ** 30n, maxNegativePriceImpactBps: 50n, }); ``` ### getAcceptablePriceByPriceImpact ```typescript getAcceptablePriceByPriceImpact(p: { isIncrease: boolean; isLong: boolean; indexPrice: bigint; sizeDeltaUsd: bigint; priceImpactDeltaUsd: bigint; }): { acceptablePrice: bigint; acceptablePriceDeltaBps: bigint; priceDelta: bigint; } ``` Converts a USD price impact into an acceptable price. The formula is: ``` acceptablePrice = indexPrice × (sizeDeltaUsd + adjustedImpact) / sizeDeltaUsd ``` where `adjustedImpact` flips the sign for longs versus shor
프로젝트로 돌아가기