GMX 백서

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

t | | `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. ```typescript // 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 ```typescript 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` | ```typescript // 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 ```typescript 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 | ```typescript // 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 ```typescript 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. ```typescript // 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 ```typescript 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`. ```typescript 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](./decrease.md) — symmetric functions for closing or reducing positions - [Trade utilities](./trade.md) — shared helpers for both increase and decrease operations - [Fees module](../fees/fees.md) — position fee and price impact calculation functions --- ## trade This module provides utility functions for trade operations including slippage calculations, swap counting, and trade flag creation for the GMX protocol. ## Methods This module exports four utility functions used in trade calculations. ### applySlippageToPrice ```typescript applySlippageToPrice(allowedSlippage: number, price: bigint, isIncrease: boolean, isLong: boolean): bigint ``` Adjusts an acceptable price by the given slippage in basis points. For operations that use `maxPrice` (long increases and short decreases), slippage is added — resulting in a higher acceptable price. For operations that use `minPrice` (short increases and long decreases), slippage is subtracted. ```typescript // Long increase: acceptable price is 0.5% above mark price const acceptablePrice = applySlippageToPrice( 50, // 50 bps = 0.5% 1800n * 10n ** 30n, // mark price true, // isIncrease true // isLong ); // acceptablePrice ≈ 1800 × 1.005 = 1809 ``` ### applySlippageToMinOut ```typescript applySlippageToMinOut(allowedSlippage: number, minOutputAmount: bigint): bigint ``` Reduces `minOutputAmount` by the given slippage in basis points. Always reduces the minimum — use this to set the `minOut` parameter in swap orders. ```typescript const minOut = applySlippageToMinOut( 100, // 100 bps = 1% 1000n * 10n ** 6n // 1000 USDC (6 decimals) ); // minOut = 990 USDC — accept up to 1% slippage ``` ### getSwapCount ```typescript getSwapCount(params: { isSwap: boolean; isIncrease: boolean; swapAmounts?: SwapAmounts; increaseAmounts?: IncreasePositionAmounts; decreaseAmounts?: DecreasePositionAmounts; }): number | undefined ``` Returns the number of market swaps in the current trade. Returns `undefined` when the required amounts object is not provided. - For swaps: returns `swapAmounts.swapStrategy.swapPathStats?.swapPath.length ?? 0` - For increase orders: returns `increaseAmounts.swapStrategy.swapPathStats?.swapPath.length ?? 0` - For decrease orders: returns `1` when `decreaseSwapType !== NoSwap`, otherwise `0` ```typescript // 2-hop swap path const swapCount = getSwapCount({ isSwap: true, isIncrease: false, swapAmounts, }); // swapCount = swapAmounts.swapStrategy.swapPathStats?.swapPath.length ?? 0 ``` ### createTradeFlags ```typescript createTradeFlags(tradeType: TradeType, tradeMode: TradeMode): TradeFlags ``` Creates a `TradeFlags` object that derives all boolean flags from a `(TradeType, TradeMode)` pair. The derivation rules are: | Flag | Rule | | ------------ | ----------------------------------------------------------------------- | | `isLong` | `tradeType === TradeType.Long` | | `isShort` | `tradeType === TradeType.Short` | | `isSwap` | `tradeType === TradeType.Swap` | | `isPosition` | `isLong \|\| isShort` | | `isMarket` | `tradeMode === TradeMode.Market` | | `isLimit` | `tradeMode === TradeMode.Limit \|\| tradeMode === TradeMode.StopMarket` | | `isTrigger` | `tradeMode === TradeMode.Trigger` | | `isTwap` | `tradeMode === TradeMode.Twap` | | `isIncrease` | `isPosition && (isMarket \|\| isLimit \|\| isTwap)` | :::note Both `TradeMode.Limit` and `TradeMode.StopMarket` produce `isLimit: true`. A Trigger decrease (`TradeMode.Trigger`) produces `isIncrease: false`. ::: ```typescript const flags = createTradeFlags(TradeType.Long, TradeMode.Market); // { isLong: true, isShort: false, isSwap: false, isPosition: true, // isIncrease: true, isMarket: true, isLimit: false, isTrigger: false, isTwap: false } const triggerFlags = createTradeFlags(TradeType.Long, TradeMode.Trigger); // isIncrease: false — trigger decrease, not an increase ``` --- ## tradeHistory This module exports typed helpers for transforming Subsquid trade history records into SDK trade actions. ## Runtime exports - `createRawTradeActionTransformer` - `bigNumberify` ## Re-exported types - `TradeActionType` - `PositionTradeAction` - `SwapTradeAction` - `TradeAction` - `isPositionTradeAction` - `isSwapTradeAction` ```typescript ``` For swap records, `createRawTradeActionTransformer()` parses `swapFeeUsd` and `swapImpactUsd` into optional `bigint` fields on the returned `SwapTradeAction`. --- ## twap(Utils) This module exports helpers for validating and deriving TWAP order timing. ## Exports - `getIsValidTwapParams` - `getTwapDurationInSeconds` - `getTwapValidFromTime` - `changeTwapNumberOfPartsValue` - `getTwapOrderKey` - `makeTwapValidFromTimeGetter` - Re-exported types: `TwapDuration`, `TwapOrderParams`, `TwapPartParams` ```typescript ``` --- ## types This module exports small shared TypeScript utility types. ## Exports - `mustNeverExist` - `DeepPartial<T>` ```typescript ``` --- ## Integration guide(V1) Use this page when you want exact steps instead of a function-by-function reference. The [Getting Started](./readme.mdx) page explains the SDK surface area, and the [Exports](./exports/exports.md) pages document individual helpers. This page focuses on common workflows and the operational details that matter in production. ## What SDK v1 covers today SDK v1 (`GmxSdk`) is the full client. It reads markets, tokens, positions, orders, trades, and account delegates, and it submits or cancels orders through a connected wallet. | Workflow | Status | Notes | | -------- | ------ | ----- | | Read market, token, position, order, and trade data | ✅ | Available through `markets`, `tokens`, `positions`, `orders`, `trades`, and `accounts` | | Submit and cancel orders | ✅ | Available through `orders.long`, `orders.short`, `orders.swap`, `create*Order`, and `cancelOrders` | | Built-in transaction receipt polling | ❌ | Order methods return a transaction hash; your app must wait for receipts and refetch state | | Built-in idempotency keys or client order IDs | ❌ | Prevent duplicate submits in your app layer | | Automatic retry and backoff for RPC reads | ⚠️ | Default viem HTTP clients are created with `retryCount: 0` | SDK v1 does not expose GM or GLV token prices as first-class high-level methods. `sdk.markets.getMarketsInfo()` returns market state, token data, and pool values that can support off-chain displays, but use Chainlink Data Feeds where available or direct Reader / GlvReader contract calls for direct GMX valuation. See [Getting GM and GLV token prices](../../api/gm-glv-prices.md). If you are designing delegated trader, subaccount, or one-click trading flows, use [Delegated trading integration](../../api/contracts/delegated-trading.md) together with this SDK guide. The delegated trading architecture spans contracts, optional relay routers, and your own signer/session model. ## Read account state for one walle
프로젝트로 돌아가기