Integration guide
Use this page when you want exact integration steps. The hand-written API pages explain which surfaces exist and how they behave operationally. The GMX API OpenAPI reference is generated and is best used for endpoint schemas and response fields, not for workflow guidance. Use Troubleshooting when reads do not match expected state.
Choose the right integration surface
Start by choosing the narrowest surface that solves your problem.
| Need | Recommended surface | Notes |
|---|---|---|
| Live oracle prices, market snapshots, liquidity, and APY | Oracle API pages | Stable public HTTP endpoints on gmxinfra.io |
| Read markets, tickers, tokens, pairs, rates, APY, performance, positions, orders, OHLCV, wallet balances, allowances, buyback stats, or staking power over HTTP from TypeScript | SDK v2 or the generated GMX API reference | HTTP-backed and expanding |
| Historical trade and order activity | GraphQL | Indexed data, not write-path state |
| Submit, edit, cancel, or track orders | SDK v2, SDK v1, or direct contract calls | SDK v2 posts signed order intents to the GMX API, which relays express orders via Gelato. SDK v1 and direct contracts remain available for RPC-owned flows |
| Exchange or aggregator pair listings | Integration pair feed | Public GET endpoints at https://gmx-integration-cg.vercel.app/api/arbitrum/pairs and https://gmx-integration-cg.vercel.app/api/avalanche/pairs |
| Delegated, gasless, or one-click order flows on behalf of a user | Delegated trading integration | Subaccount and relay pattern using SubaccountGelatoRelayRouter and MultichainSubaccountRouter |
| GM or GLV token prices | Getting GM and GLV token prices | Explains when to use Chainlink Data Feeds, Reader calls, or API/SDK data for GM/GLV valuation |
What is available now
The current hand-written docs and checked-out code support the following split:
| Surface | Read | Write | Description |
|---|---|---|---|
| GMX API OpenAPI Reference | ✅ | ✅ | Generated schema reference for the GMX API. Covers markets, tokens, positions, orders, rates, APY, performance, JIT liquidity, wallet balances, allowances, staking power, buyback stats, subaccount approval/status, and order transaction prepare/submit/status/edit/cancel/collateral flows. Deployed per chain across two independent peer base URLs: https://{chain}.gmxapi.io/v1 and https://{chain}.gmxapi.ai/v1. |
Oracle API (gmxinfra.io) | ✅ | ❌ | Public market, price, liquidity, APY, and performance reads. Manual docs cover the stable public HTTP endpoints. |
| GraphQL | ✅ | ❌ | Historical indexed activity. Best for history, not write-path confirmation. |
SDK v1 (GmxSdk) | ✅ | ✅ | Full TypeScript integration with reads and writes. Uses RPC, oracle, and Subsquid connections directly. |
SDK v2 (GmxApiSdk) | ✅ | ✅ | TypeScript integration over HTTP against the GMX API. Reads, wallet helpers, subaccount helpers, and order-submission methods are available. |
| Direct contracts | ✅ | ✅ | Lowest-level integration and custom transaction flows. Highest control and highest implementation burden. |
Use the generated GMX API reference for endpoint-level request and response schemas. Use the SDK v2 docs for typed client method names, bigint parsing, signing helpers, and complete TypeScript workflows.
Build a live market overview
Use the Oracle API when you need public market snapshots and fallback URLs. Use /markets for a slower-changing market list, and /markets/info for a near-live market state snapshot.
const endpoints = [
"https://arbitrum-api.gmxinfra.io/markets/info",
"https://arbitrum-api-fallback.gmxinfra.io/markets/info",
"https://arbitrum-api-fallback.gmxinfra2.io/markets/info",
];
async function fetchMarketsInfo() {
let lastError: Error | undefined;
for (const endpoint of endpoints) {
try {
const response = await fetch(endpoint, {
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
lastError = error as Error;
}
}
throw lastError ?? new Error("All market endpoints failed");
}
const markets = await fetchMarketsInfo();
console.log("Loaded markets:", markets.length);
Use this refresh strategy:
- Call
/marketswhen you need the market catalog and can tolerate a60second cache window. - Call
/markets/infowhen you need liquidity, open interest, funding, borrowing, token amounts, andisDisabled. This is also the correct endpoint for near-live funding rates. - Treat
/markets/infoas a snapshot, not a guarantee of the latest block. The current implementation caches the route for1second and refreshes market values on a5000ms pull interval, so build for near-live rather than same-block state. - Use
/ratesfor historical funding and borrowing rate data. This endpoint returns hourly snapshots from the Squid indexer, not realtime values. Use it for rate averages, trends, and historical analysis.
Read positions and related orders for one account
Use SDK v2 if you are already in TypeScript and want bigint-aware responses. Use the generated GMX API reference if you need raw HTTP schemas.
Install @gmx-io/sdk, then import GmxApiSdk from @gmx-io/sdk/v2. The v2 path is a subpath export, not a separate package.
import { GmxApiSdk } from "@gmx-io/sdk/v2";
const apiSdk = new GmxApiSdk({ chainId: 42161 });
const positions = await apiSdk.fetchPositionsInfo({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
includeRelatedOrders: true,
});
const orders = await apiSdk.fetchOrders({
address: "0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33",
});
console.log({
positions,
orders,
});
Use this flow when you render account state:
- Fetch positions with
includeRelatedOrders: trueif your page shows open positions and their linked orders together. - Fetch standalone orders only if you also need an account-wide orders view.
- After submitting a write through SDK v1 or direct contracts, poll these read endpoints until the expected state appears instead of assuming immediate consistency.
Read historical trade activity
Use GraphQL for historical, indexed activity. Do not try to reconstruct history from live HTTP snapshots.
query RecentTrades($account: String!) {
tradeActions(where: { account_eq: $account }, limit: 50, orderBy: timestamp_DESC) {
eventName
account
timestamp
transactionHash
sizeDeltaUsd
collateralDeltaAmount
}
}
The current GraphQL schema exposes transactionHash and top-level timestamp. See GraphQL for schema usage notes and migration context.
For referral analytics, the GraphQL schema also exposes the affiliateStats and traderReferralStats resolvers, plus per-hour stats entities (AffiliateReferralTradeStatsByHour, TraderReferralTradeStatsByHour, AffiliateTraderStatsByHour). Use these instead of stitching tradeActions for affiliate dashboards or trader rebate views — both resolvers accept from/to time windows and return pre-aggregated volume, rebate, discount, and trader-flow figures. See GraphQL — Referral analytics for the full schema and example queries.
Operational notes
Freshness and caching
GET /marketsuses a60second HTTP cache in the current implementation.GET /markets/infouses a1second HTTP cache in the current implementation.- The backend currently caches
prices,tokensData, andmarketsInfofor1second,userReferralInfofor5seconds, andonchainSettingsfor60seconds. - Avoid joining data from unrelated polls when you need one coherent snapshot. Prefer composite endpoints such as
/markets/infoorfetchPositionsInfo({ includeRelatedOrders: true }).
Retries, timeouts, and fallback URLs
- The current API server timeout is
60000ms. - SDK v2 uses
HttpClientWithFallbackby default and tries the configured peer hosts for server or network errors. You still own request retry timing, backoff, and user-facing recovery behavior. - Use the Fallback URLs page for Oracle API market and oracle reads.
- If you receive a timeout, network error,
429, or5xx, retry with backoff and fail over where you have fallback endpoints.
Surface-specific operational model
- The Oracle API is deployed per chain on
https://{chain}-api.gmxinfra.ioprimary hosts, uses endpoint-specific cache windows, and documents fallback URLs for some public reads. - The GMX API is deployed per chain across two independent peer base URLs (
https://{chain}.gmxapi.io/v1andhttps://{chain}.gmxapi.ai/v1). Both are equal; there is no primary/secondary. Clients that hit the API directly can use either base URL or rotate across both. The generated reference does not define your retry policy. - GraphQL is indexed data. Expect lag relative to live chain state.
- SDK v1 mixes live RPC, oracle, and indexed reads. Default SDK-created HTTP transports disable retries.
- SDK v2 is an HTTP client for reads and API-relayed order workflows. Its default HTTP client fails over between GMX API peer hosts for server and network errors, but it does not define your application-level retry policy.
- Direct contracts give you the most control, but your app owns retry, nonce, gas, and receipt strategy.
- Delegated trading flows run through
SubaccountGelatoRelayRouterorMultichainSubaccountRouterand have their own session lifecycle — your integration owns subaccount authorization, expiry, action-count tracking, and relay-nonce handling. See Delegated trading integration.
Idempotency and race conditions
- For SDK v2 and API-relayed order workflows, persist the
requestIdreturned by prepare or submit calls and poll order status instead of resubmitting blindly. - After a write, do not assume your first follow-up read will reflect final state. Submission, relay processing, keeper execution, and indexing can land at different times.
- If you need "position plus linked orders" on one screen, prefer a single positions call with
includeRelatedOrders: trueover stitching data from independent polls.
Next steps
- Use API Overview to decide between the GMX API, Oracle API, GraphQL, contracts, and the SDK.
- Use Getting GM and GLV token prices when you need to choose between Chainlink Data Feeds, direct Reader calls, and API or SDK data for GM/GLV valuation.
- Use the Oracle API for public market, price, and liquidity endpoints.
- Use the generated GMX API OpenAPI Reference for endpoint-level request and response schemas.
- Use Troubleshooting if your reads look stale, a query fails validation, or a write does not show up yet.
- Use SDK v2 when your application needs API-relayed order flows.
- Use SDK v1 when your application needs direct RPC-backed write flows such as creating or canceling orders.
- Use Delegated trading integration when you need subaccount-based, gasless, or one-click order flows on behalf of a user.