Skip to main content

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 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 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 Arbitrum, Avalanche, Botanix, and MegaETH on mainnet, 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

Mainnet chains are each served by two independent peer base URLs — https://{chain}.gmxapi.io/v1 and https://{chain}.gmxapi.ai/v1. Both receive the same data and accept the same requests. By default, GmxApiSdk builds an HttpClientWithFallback from getApiUrl(chainId) and getApiFallbackUrls(chainId), starts from a randomized peer, and tries the other peer for server or network errors.

Arbitrum Sepolia uses a separate test host returned by getApiUrl(421614). Test hosts can change between alpha releases, 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

WorkflowStatusNotes
Read market catalogs, tickers, and token data over HTTPAvailable through fetchMarkets(), fetchMarketsInfo(), fetchMarketsTickers(), fetchTokens(), and fetchTokensData()
Read pairs, rates, APY, and performance analytics over HTTPAvailable through fetchPairs(), fetchRates(), fetchApy(), fetchPerformanceAnnualized(), and fetchPerformanceSnapshots()
Read one account's positions and orders over HTTPAvailable through fetchPositionsInfo() and fetchOrders()
Read OHLCV candles over HTTPAvailable through fetchOhlcv()
Read protocol buyback stats over HTTPAvailable through fetchBuybackWeeklyStats()
Read staking power over HTTPAvailable through fetchStakingPower()
Read wallet balances and allowances over HTTPAvailable through fetchWalletBalances() and fetchAllowances()
Build approval transaction calldataAvailable through buildApproveTransaction()
Submit, edit, cancel, or track ordersSigned order intents are posted to the GMX API, which relays express orders via Gelato. SDK v1 and direct contracts remain available for integrations that prefer RPC.
One-click-trading subaccount helpersAvailable through generateSubaccount(), activateSubaccount(), clearSubaccount(), fetchSubaccountStatus(), prepareSubaccountApproval(), and signSubaccountApproval()
Trade history readsUse SDK v1 or GraphQL

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.

MethodParametersReturnsNotes
fetchMarkets()--MarketWithTiers[]Market catalog data from /markets
fetchMarketsInfo()--RawMarketInfo[]Market definitions and pricing from /markets/info
fetchMarketsTickers(params?)addresses?: string[], symbols?: string[]MarketTicker[]Filterable market tickers from /markets/tickers
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`
fetchApy(params?)period?: ApiParameterPeriodApyResponseMarket and GLV APY data from /apy
fetchPerformanceAnnualized(params?)period?: ApiParameterPeriod, address?: stringPerformanceAnnualized[]Annualized performance summaries from /performance/annualized
fetchPerformanceSnapshots(params?)period?: ApiParameterPeriod, address?: stringPerformanceSnapshots[]Historical performance snapshot series from /performance/snapshots
fetchPositionsInfo(params)address: string, includeRelatedOrders?: booleanApiPositionInfo[]Position objects for an address; optionally includes related orders
fetchOrders(params)address: stringApiOrderInfo[]Active order objects for an address
fetchOhlcv(params)symbol: string, timeframe: string, limit?: number, since?: numberOhlcvCandle[]OHLCV candle data from /prices/ohlcv
fetchBuybackWeeklyStats()--BuybackWeeklyStatsResponseWeekly buyback accrual data and cumulative summary from /buyback/weekly-stats
fetchStakingPower(params)address: stringStakingPowerResponseStaking power, loyalty ratio, and reward share data for an address from /staking/power

Account and order methods

These methods cover wallet data, approval calldata, API-relayed order workflows, and one-click-trading subaccounts.

  • fetchWalletBalances({ address }) returns wallet balances from /balances/wallet.
  • fetchAllowances({ address, spender }) returns token allowances from /allowances. spender is "router" or "glv".
  • buildApproveTransaction(params) builds ERC-20 approval calldata for the selected chain.
  • prepareOrder(request) prepares a swap, increase, or decrease order and returns either typed data for express mode or transaction calldata for classic mode. See Order Examples for full usage.
  • signOrder(prepared, signer) signs a prepared express order with an IAbstractSigner.
  • submitOrder(request) submits a signed express order intent to /orders/txns/submit.
  • executeExpressOrder(request, signer) runs the common prepare, sign, and submit flow in one call.
  • fetchOrderStatus({ requestId }) returns relay, creation, execution, cancellation, and error state for an API-relayed order request.
  • prepareEditOrder(request), prepareCancelOrder(request), and prepareCollateral(request) prepare edit, cancel, collateral deposit, or collateral withdrawal order intents.
  • fetchSubaccountStatus(request), prepareSubaccountApproval(request), and signSubaccountApproval(prepared, signer) support one-click-trading authorization flows.
  • generateSubaccount(mainSigner), activateSubaccount(mainSigner, options?), and clearSubaccount() manage the SDK's local subaccount state. When an active subaccount exists, executeExpressOrder() signs with the subaccount automatically.

PrivateKeySigner and the IAbstractSigner type are exported from @gmx-io/sdk/v2. Lower-level signer helpers are also available from @gmx-io/sdk/utils/signer.

Staking power timestamps

StakingPowerResponse includes two protocol-level timestamps that are constant across all addresses:

FieldTypeDescription
powerAccrualStartunix secondsThe moment power began accumulating for staked GMX. Set to 1772582400 (March 4, 2026 00:00:00 UTC).
loyaltyTrackingStartunix secondsThe moment loyalty tracking became active. Before this time, unstaking did not affect the historical peak used for loyalty enforcement. Set to 1774396800 (March 25, 2026 00:00:00 UTC).

After loyaltyTrackingStart, if an account's staked balance drops below 80% of its historical peak, accumulated power resets to zero. See Rewards for the user-facing description of how the loyalty threshold works.

When to use SDK v2

Use GmxApiSdk for API integrations that need market, ticker, token, pair, rate, APY, performance, position, order, OHLCV, wallet-balance, allowance, buyback, or staking-power data, or API-relayed order submission, edit, cancellation, and subaccount flows. Use the full GmxSdk (SDK v1) when you need trade history or direct RPC-backed transaction ownership.

note

GmxApiSdk is under active development and covers an expanding share of the full SDK surface, replacing the need for direct RPC, oracle, and Subsquid connections. Order submission runs via the GMX API's Gelato relay. The GMX API OpenAPI Reference documents the underlying HTTP endpoints, while this page documents the typed SDK method names and signing helpers.