Getting Started
Use SDK v2 when you want HTTP-backed GMX data or API-relayed order workflows without wiring RPC, oracle, or Subsquid connections yourself.
Install the shared SDK package first:
npm install @gmx-io/sdk
Then import the client from the v2 subpath:
import { GmxApiSdk } from "@gmx-io/sdk/v2";
const apiSdk = new GmxApiSdk({ chainId: 42161 }); // Arbitrum
const markets = await apiSdk.fetchMarkets();
const marketsInfo = await apiSdk.fetchMarketsInfo();
const marketsConfig = await apiSdk.fetchMarketsConfig();
const marketsValues = await apiSdk.fetchMarketsValues();
const tickers = await apiSdk.fetchMarketsTickers({
symbols: ["BTC/USD"],
});
const tokens = await apiSdk.fetchTokens();
const tokensData = await apiSdk.fetchTokensData();
const pairs = await apiSdk.fetchPairs();
const rates = await apiSdk.fetchRates({ period: "7d" });
const apy = await apiSdk.fetchApy({ period: "7d" });
const annualized = await apiSdk.fetchPerformanceAnnualized({
period: "30d",
});
const snapshots = await apiSdk.fetchPerformanceSnapshots({
period: "30d",
});
const positions = await apiSdk.fetchPositionsInfo({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
includeRelatedOrders: true,
});
const orders = await apiSdk.fetchOrders({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
});
const trades = await apiSdk.fetchTrades({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
limit: 20,
});
const jitLiquidity = await apiSdk.fetchJitLiquidityInfo({ apiVersion: "v2" });
const candles = await apiSdk.fetchOhlcv({
symbol: "BTC/USD",
timeframe: "1h",
limit: 100,
});
GmxApiSdk calls the GMX API directly — no RPC endpoint, oracle URL, or Subsquid URL required. It supports active mainnet integrations on Arbitrum, Avalanche, and MegaETH, plus Arbitrum Sepolia for testing. The constructor throws for unsupported chains.
If your app switches chains dynamically, prefer isApiSupported(chainId), getApiUrl(chainId), and getApiFallbackUrls(chainId) from @gmx-io/sdk/configs/api instead of hardcoding API hosts.
GMX API deployment
The GMX API deployment exposes independent peer base URLs such as https://{chain}.gmxapi.io/v1 and https://{chain}.gmxapi.ai/v1. GmxApiSdk builds an HttpClientWithFallback from the primary URL returned by getApiUrl(chainId) and any peers configured by getApiFallbackUrls(chainId).
Fallback lists are configuration, not a fixed SDK guarantee. In the current published latest, 1.8.0, the packaged list is empty for every chain, so HttpClientWithFallback runs against a single host unless you supply the peer. If your integration requires peer failover, pass the second host explicitly and monitor both in your own HTTP layer.
Arbitrum Sepolia uses a separate test host returned by getApiUrl(421614). Test hosts can change, so use the exported helper instead of hardcoding the URL.
@gmx-io/sdk/v2 is an import path inside the @gmx-io/sdk package, not a separate npm package.
If you're using CommonJS, require the v2 client from the v2 subpath:
const { GmxApiSdk } = require("@gmx-io/sdk/v2");
const apiSdk = new GmxApiSdk({ chainId: 42161 });
TypeScript subpath resolution is supported for @gmx-io/sdk/v2 and the SDK's utility, config, ABI, and type-only entrypoints.
What SDK v2 covers today
| Workflow | Status | Notes |
|---|---|---|
| Read market catalogs, configuration, values, tickers, trading capacity, and token data over HTTP | ✅ | Available through fetchMarkets(), fetchMarketsInfo(), fetchMarketsConfig(), fetchMarketsValues(), fetchMarketsTickers(), getTradingCapacity(), fetchTokens(), and fetchTokensData() |
| Read pairs, rates, APY, performance, and GM pool yield/PnL analytics over HTTP | ✅ | Available through fetchPairs(), fetchRates(), fetchApy(), fetchPerformanceAnnualized(), fetchPerformanceSnapshots(), and fetchGmPoolYieldPnl() |
| Read one account's positions and orders over HTTP | ✅ | Available through fetchPositionsInfo() and fetchOrders() |
| Read trade history over HTTP | ✅ | Available through fetchTrades() and searchTrades() |
| Read OHLCV candles over HTTP | ✅ | Available through fetchOhlcv() |
| Read protocol buyback stats over HTTP | ✅ | Available through fetchBuybackWeeklyStats() |
| Read JIT liquidity over HTTP | ✅ | Available through fetchJitLiquidityInfo() |
| Read staking power over HTTP | ✅ | Available through fetchStakingPower() |
| Read wallet balances and allowances over HTTP | ✅ | Available through fetchWalletBalances() and fetchAllowances() |
| Build approval transaction calldata | ✅ | Available through buildApproveTransaction(), buildErc20ApproveTxn(), and executeErc20Approve() |
| GMX Account deposits and withdrawals | ✅ | Available through same-chain deposit/withdraw helpers and cross-chain deposit/withdraw helpers |
| Submit, edit, cancel, or track orders | ✅ | Signed order intents are posted to the GMX API, which submits express orders through GMX Relay. SDK v1 and direct contracts remain available for integrations that prefer RPC. |
| One-click-trading subaccount helpers | ✅ | Available through generateSubaccount(), activateSubaccount(), refreshSubaccountState(), clearSubaccount(), fetchSubaccountStatus(), prepareSubaccountApproval(), and signSubaccountApproval() |
See Order Examples for runnable code showing how to open, close, edit, cancel, and track orders, including TP/SL, TWAP, classic mode, and one-click trading flows.
Use SDK Overview if you want a quick capability comparison before wiring an integration.
Methods
GmxApiSdk exposes the following methods. All of them call the GMX API directly -- no RPC, oracle, or Subsquid connection is required.
| Method | Parameters | Returns | Notes |
|---|---|---|---|
fetchMarkets() | -- | MarketWithTiers[] | Market catalog data from /markets |
fetchMarketsInfo() | -- | RawMarketInfo[] | Market definitions and pricing from /markets/info |
fetchMarketsConfig() | -- | RawMarketConfig[] | Slower-changing market configuration from /markets/config |
fetchMarketsValues() | -- | RawMarketValues[] | Frequently changing market state from /markets/values; each row includes its least-recent component timestamp in updatedAt |
fetchMarketsTickers(params?) | addresses?: string[], symbols?: string[] | MarketTickerWithCapacity[] | Filterable market tickers from /markets/tickers, each optionally carrying JIT-aware capacityLong/capacityShort |
getTradingCapacity(params) | symbol: string, direction: "long" | "short" | TradingCapacity | Validated capacity for one market side from /markets/trading-capacity |
fetchTokens() | -- | Token[] | Static token catalog from /tokens |
fetchTokensData() | -- | TokenData[] | Token metadata and current prices from /tokens/info |
fetchPairs() | -- | Pair[] | Pair-level summary data from /pairs |
fetchRates(params?) | period?: ApiParameterPeriod, averageBy?: "1d" | "7d" | "30d", address?: string | MarketRates[] | Hourly funding and borrowing rate snapshots from /rates. For near-live rates, use /markets/info or fetchMarketsInfo() instead |
fetchApy(params?) | period?: ApiParameterPeriod | ApyResponse | Market and GLV APY data from /apy |
fetchPerformanceAnnualized(params?) | period?: ApiParameterPeriod, address?: string | PerformanceAnnualized[] | Annualized performance summaries from /performance/annualized |
fetchPerformanceSnapshots(params?) | period?: ApiParameterPeriod, address?: string | PerformanceSnapshots[] | Historical performance snapshot series from /performance/snapshots |
fetchGmPoolYieldPnl(params?) | pools?: string[], period?: ApiParameterPeriod, includeComponents?: boolean | GmPoolsYieldPnlResponse | Fee-only APY plus trader-perspective PnL per GM pool from /yield/gm-pools |
fetchPositionsInfo(params) | address: string, includeRelatedOrders?: boolean | ApiPositionInfo[] | Position objects for an address; optionally includes related orders |
fetchOrders(params) | address: string | ApiOrderInfo[] | Active order objects for an address |
fetchTrades(params) | address: string, symbol?: string, marketAddress?: string, since?: number, until?: number, actions?: TradeEventName[], limit?: number, cursor?: string | TradesListResponse | Account trade history from /trades |
searchTrades(params) | address?: string, forAllAccounts?: boolean, fromTimestamp?: number, toTimestamp?: number, marketsDirections?: MarketDirectionFilter[], orderEventCombinations?: OrderEventCombination[], showDebugValues?: boolean, limit?: number, cursor?: string | TradesListResponse | Advanced trade-history search from /trades/search |
fetchOhlcv(params) | symbol: string, timeframe: string, limit?: number, since?: number | OhlcvCandle[] | OHLCV candle data from /prices/ohlcv |
fetchBuybackWeeklyStats() | -- | BuybackWeeklyStatsResponse | Weekly buyback accrual data and cumulative summary from /buyback/weekly-stats |
fetchJitLiquidityInfo(params?) | apiVersion?: "v1" | "v2" | JitLiquidityMap | JIT liquidity map from /v2/jit/liquidity_info. Pass apiVersion: "v2": the legacy /v1/jit/liquidity_info route is no longer served. To size an increase, use getTradingCapacity() instead |
fetchStakingPower(params) | address: string | StakingPowerResponse | Staking power, loyalty ratio, and reward share data for an address from /staking/power |