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 trades = await apiSdk.fetchTrades({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
limit: 20,
});
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 trade history over HTTPAvailable through fetchTrades() and searchTrades()
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(), 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.

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
fetchTrades(params)address: string, symbol?: string, marketAddress?: string, since?: number, until?: number, actions?: TradeEventName[], limit?: number, cursor?: stringTradesListResponseAccount trade history from /trades
searchTrades(params)address?: string, forAllAccounts?: boolean, fromTimestamp?: number, toTimestamp?: number, marketsDirections?: MarketDirectionFilter[], orderEventCombinations?: OrderEventCombination[], showDebugValues?: boolean, limit?: number, cursor?: stringTradesListResponseAdvanced trade-history search from /trades/search
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?), refreshSubaccountState(account), and clearSubaccount() manage the SDK's local subaccount state. subaccountAddress, subaccountStatus, hasActiveSubaccount, and subaccountApprovalMessage expose the current state.
  • When an active subaccount exists, prepareOrder(), prepareEditOrder(), prepareCancelOrder(), prepareCollateral(), and executeExpressOrder() attach the current subaccount approval automatically. signOrder() signs prepared subaccount orders with the generated subaccount key.

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.

One-click trading lifecycle

One-click trading uses three signing steps:

SignatureSignerWhen it is needed
Subaccount key derivationMain walletWhen generateSubaccount() or activateSubaccount() creates the local subaccount signer
Subaccount approvalMain walletOnly when the subaccount is not active on-chain, or when the requested expiry/action limit needs to be extended
Order signatureSubaccount signerFor each prepared subaccount order

activateSubaccount(mainSigner, options?) refreshes the current on-chain subaccount status, generates the local subaccount signer if needed, and signs a new approval only when the existing on-chain authorization is not enough for the requested expiry and maxAllowedCount. The signed approval is kept in SDK memory and submitted with the next subaccount order.

After an approval-bearing order is created or executed and the on-chain status is usable, refreshSubaccountState(account) updates subaccountStatus and subaccountApprovalMessage becomes an empty approval whose signature is "0x". The empty approval tells the relay to use the already-active on-chain authorization, so the main wallet does not sign every trade. Per-order signatures are produced by the generated subaccount key.

Use one GmxApiSdk instance per active wallet account, or call clearSubaccount() when the wallet account changes. The SDK rejects subaccount order preparation if the stored subaccount belongs to a different account.

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, trade-history, 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 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.