Skip to main content

markets

This module provides utilities for working with GMX markets, including market naming, pricing, liquidity calculations, and PnL computations. It handles market metadata, pool calculations, leverage limits, and various market-related operations.

Methods​

The markets utility module exports functions organized into six categories: display names, prices and PnL, liquidity and open interest, market classification, leverage, and data assembly.

Market display names​

getMarketFullName​

getMarketFullName(p: { longToken: Token; shortToken: Token; indexToken: Token; isSpotOnly: boolean }): string

Returns the full display name of a market combining the index name and pool name.

import { getMarketFullName } from "@gmx-io/sdk/utils/markets";

const fullName = getMarketFullName({
longToken: ethToken,
shortToken: usdcToken,
indexToken: ethToken,
isSpotOnly: false,
});
// "ETH/USD [ETH-USDC]"

getMarketIndexName​

getMarketIndexName(p: ({ indexToken: Token } | { glvToken: Token }) & { isSpotOnly: boolean }): string

Returns the index name portion of a market name (for example, "ETH/USD" or "SWAP-ONLY").

getMarketBaseName​

getMarketBaseName(p: ({ indexToken: Token } | { glvToken: Token }) & { isSpotOnly: boolean }): string

Returns the base token name from a market (for example, "ETH").

getMarketPoolName​

getMarketPoolName(p: { longToken: Token; shortToken: Token }, separator?: string): string

Returns the pool name combining long and short token symbols. Default separator is "-".

import { getMarketPoolName } from "@gmx-io/sdk/utils/markets";

getMarketPoolName({ longToken: ethToken, shortToken: usdcToken }); // "ETH-USDC"
getMarketPoolName({ longToken: ethToken, shortToken: usdcToken }, "/"); // "ETH/USDC"

getMarketAddressByName​

getMarketAddressByName(marketsInfoData: MarketsInfoData, name: string): string | undefined

Looks up a market token address by its full name string (for example, "ETH/USD [WETH-USDC]"). Returns undefined if not found.

Prices and PnL​

getContractMarketPrices​

getContractMarketPrices(tokensData: TokensData, market: Market): ContractMarketPrices | undefined

Returns contract-formatted prices for market tokens, or undefined if token price data is missing.

import { getContractMarketPrices } from "@gmx-io/sdk/utils/markets";

const contractPrices = getContractMarketPrices(tokensData, market);
if (contractPrices) {
console.log(contractPrices.indexTokenPrice);
}

getPriceForPnl​

getPriceForPnl(prices: TokenPrices, isLong: boolean, maximize: boolean): bigint

Returns the appropriate price (min or max) for PnL calculations based on position direction.

getMarketPnl​

getMarketPnl(marketInfo: MarketInfo, isLong: boolean, forMaxPoolValue: boolean): bigint

Returns the aggregate PnL for the long or short side of a market.

getPositiveMarketPnl​

getPositiveMarketPnl(marketInfo: MarketInfo, isLong: boolean, forMaxPoolValue: boolean): bigint

Returns the sum of positive PnL calculated separately for positions using the long and short collateral tokens. Losses in one collateral bucket don't offset profits in the other. If the collateral-split fields are unavailable, the helper falls back to getMarketPnl().

getMarket24Stats​

getMarket24Stats(dayPriceCandle: DayPriceCandle): { open24h, high24h, low24h, close24h, priceChange24h, priceChangePercent24hBps }

Computes 24-hour OHLC stats and price change in basis points from a day price candle.

getMarketTicker​

getMarketTicker(marketInfo: MarketInfo, dayPriceCandle: DayPriceCandle): MarketTicker

Returns a comprehensive market ticker including prices, open interest, liquidity, funding rates, and borrowing rates.

Liquidity and open interest​

getPoolUsdWithoutPnl​

getPoolUsdWithoutPnl(marketInfo: MarketInfo, isLong: boolean, priceType: "minPrice" | "maxPrice" | "midPrice"): bigint

Returns the USD value of the long or short pool excluding PnL.

getCappedPoolPnl​

getCappedPoolPnl(p: { marketInfo: MarketInfo; poolUsd: bigint; poolPnl: bigint; isLong: boolean }): bigint

Returns the pool PnL capped at the market's maximum allowed PnL ratio.

getAvailableUsdLiquidityForCollateral​

getAvailableUsdLiquidityForCollateral(marketInfo: MarketInfo, isLong: boolean): bigint

Returns available USD liquidity for collateral on the specified side.

getReservedUsd​

getReservedUsd(marketInfo: MarketInfo, isLong: boolean): bigint

Returns the reserved USD amount for the long or short side.

getOpenInterestUsd​

getOpenInterestUsd(marketInfo: MarketInfo, isLong: boolean): bigint

Returns the open interest in USD for the long or short side.

getOpenInterestInTokens​

getOpenInterestInTokens(marketInfo: MarketInfo, isLong: boolean): bigint

Returns the open interest in tokens for the long or short side.

getMarketInfoWithOpenInterestDelta​

getMarketInfoWithOpenInterestDelta(params: {
marketInfo: MarketInfo;
collateralToken: Token;
isLong: boolean;
sizeDeltaUsd: bigint;
sizeDeltaInTokens: bigint;
}): MarketInfo

Returns a copy of marketInfo with the long or short open interest, in USD and in tokens, moved by sizeDeltaUsd and sizeDeltaInTokens. It also moves the open interest for collateralToken when the per-collateral fields are present, and the virtual inventory for positions when the market has one. If both deltas are 0n, it returns marketInfo unchanged. Added in 1.9.1.

getMarketInfoWithSwapDelta​

getMarketInfoWithSwapDelta(marketInfo: MarketInfo, swapStep: SwapStats): MarketInfo

Returns the market a swap step leaves: the long and short pool amounts and the swap impact pool amounts move as the contracts move them, and so do the virtual pool amounts when the market has them. The exceptions are two fees that the swap step doesn't carry. The contracts add the pool's share of the swap fee to the input token's pool, and the helper doesn't. The contracts also take the UI fee out of the input amount before the swap, but getSwapPathStats doesn't, so amountInAfterFees and amountOut still include it. When the order's UI fee receiver has a UI fee factor above zero, the helper therefore adds more to the input token's pool than the contracts do, by the UI fee, and takes more from the output token's pool, by the UI fee's worth of the output token. Each virtual pool amount differs by the same amount as its pool. swapStep is one entry of swapSteps in the SwapPathStats that getSwapPathStats from @gmx-io/sdk/utils/swap returns. Added in 2.3.1.

getOpenInterestForBalance​

getOpenInterestForBalance(marketInfo: MarketInfo, isLong: boolean): bigint

Returns the open interest used for balance calculations. Uses token-denominated interest converted to USD when useOpenInterestInTokensForBalance is set.

getOiUsdFromRawValues​

getOiUsdFromRawValues(rawValues: { longInterestUsingLongToken, longInterestUsingShortToken, shortInterestUsingLongToken, shortInterestUsingShortToken }, marketDivisor: bigint): { longInterestUsd, shortInterestUsd }

Computes aggregate long/short USD open interest from raw on-chain split values, applying the market divisor.

getOiInTokensFromRawValues​

getOiInTokensFromRawValues(rawValues: {...}, marketDivisor: bigint): { longInterestInTokens, shortInterestInTokens }

Computes aggregate long/short token open interest from raw on-chain split values.

Market classification and config​

getTokenPoolType​

getTokenPoolType(marketInfo: { longToken: Token; shortToken: Token }, tokenAddress: string): "long" | "short" | undefined

Returns whether a token belongs to the "long" or "short" pool in a market.

getMarketDivisor​

getMarketDivisor({ longTokenAddress, shortTokenAddress }): bigint

Returns 2n for single-collateral markets (same long/short token) and 1n for two-token markets.

getOppositeCollateral​

getOppositeCollateral(marketInfo: MarketInfo, tokenAddress: string): Token | undefined

Returns the opposite collateral token for a given token in a market.

getOppositeCollateralFromConfig​

getOppositeCollateralFromConfig(marketConfig: ConfigMarketConfig, tokenAddress: string): string

Like getOppositeCollateral but works on the config object (addresses only, no hydrated token data).

getIsMarketAvailableForExpressSwaps​

getIsMarketAvailableForExpressSwaps(marketInfo: MarketInfo): boolean

Returns true if all three market tokens (index, long, short) have a price feed provider, enabling express swaps.

Leverage​

getMaxLeverageByMinCollateralFactor​

getMaxLeverageByMinCollateralFactor(minCollateralFactor: bigint | undefined): number

Returns the theoretical maximum leverage (as a basis-point integer) from the minimum collateral factor.

getMaxAllowedLeverage​

getMaxAllowedLeverage(params: {
minCollateralFactor: bigint | undefined;
minCollateralFactorForLiquidation: bigint | undefined;
positionFeeFactorForBalanceWasNotImproved: bigint | undefined;
}): number

Returns the maximum allowed leverage as a basis-point integer. The helper uses the market's opening collateral factor, liquidation collateral factor, and position fee factor, then rounds down to the nearest 5x leverage step.

If any required value is missing or zero, the helper returns 100x (100 * BASIS_POINTS_DIVISOR) as the fallback cap.

getMarketWithTiers​

getMarketWithTiers(marketInfo: MarketInfo, constants: { minCollateralUsd, minPositionSizeUsd }): MarketWithTiers

Returns a MarketWithTiers object including leverage tiers and size limits, used for market listing displays.

Market data assembly​

These functions assemble market data from raw on-chain responses. Typically used internally by the SDK client rather than called directly.

composeRawMarketInfo​

composeRawMarketInfo({ market, marketValues, marketConfig, marketsConstants }): RawMarketInfo

Merges on-chain market values, config, and constants into a RawMarketInfo record.

composeRawMarketsInfoData​

composeRawMarketsInfoData({ marketsAddresses, marketValues, marketConfigs, marketsConstants }): RawMarketsInfoData

Composes a full RawMarketsInfoData map for multiple markets.

hydrateMarketInfo​

hydrateMarketInfo({ chainId, rawMarketInfo, tokensData, claimableFundingData? }): MarketInfo | undefined

Hydrates a RawMarketInfo into a full MarketInfo by resolving token addresses to Token objects. Returns undefined if any token is missing from tokensData.

composeFullMarketsInfoData​

composeFullMarketsInfoData({ chainId, marketsAddresses, rawMarketsInfoData, tokensData, claimableFundingData? }): MarketsInfoData

Hydrates a full RawMarketsInfoData map into MarketsInfoData.

API data fetching​

fetchApiMarketsTickers​

fetchApiMarketsTickers(ctx: { api: IHttp }, params?: { addresses?: string[]; symbols?: string[] }): Promise<MarketTickerWithCapacity[]>

Fetches filterable market tickers. Each row may include parsed capacityLong and capacityShort values.

parseTradingCapacity​

parseTradingCapacity(raw: unknown): TradingCapacity | undefined

Parses and validates a trading-capacity response. Numeric capacity fields are returned as bigint; invalid shapes return undefined.

fetchApiTradingCapacity​

fetchApiTradingCapacity(ctx: { api: IHttp }, params: GetTradingCapacityParams): Promise<TradingCapacity>

Fetches validated capacity for params.symbol and params.direction from /v1/markets/trading-capacity. It throws if the response doesn't match TradingCapacity.

fetchApiMarketsInfo​

fetchApiMarketsInfo(ctx: { api: IHttp }): Promise<RawMarketInfo[]>

Fetches raw market info records from the GMX API.

fetchApiTokensData​

fetchApiTokensData(ctx: { api: IHttp }): Promise<TokenData[]>

Fetches token data from the GMX API.

Multicall helpers​

These functions build and parse multicall requests for on-chain market data. They are used internally by the SDK.

buildClaimableFundingDataRequest​

Builds a multicall request for claimable funding data for a given account and set of markets.

buildMarketsValuesRequest​

Builds a multicall request for market values (pool amounts, open interest, PnL, and borrowing fees) for a set of markets.

parseMarketsValuesResponse​

Parses the multicall response from buildMarketsValuesRequest into MarketsValuesData.

buildMarketsConfigsRequest​

Builds a multicall request for market configurations (fees, impact factors, and borrowing rate parameters) for a set of markets.

parseMarketsConfigsResponse​

Parses the multicall response from buildMarketsConfigsRequest into MarketsConfigsData.

Hash key helpers (from hashKeys.ts)​

Used internally for building multicall key hashes.

hashMarketConfigKeys​

hashMarketConfigKeys(market: MarketConfigInput): MarketConfigKeysHash

hashMarketValuesKeys​

hashMarketValuesKeys(market: MarketConfigInput): MarketValuesKeysHash

hashKinkModelKeys​

hashKinkModelKeys(marketAddress: string): KinkModelKeysHash