The Web3 Paradigm: Why Is There No Order Book Here?
Unlike centralized exchanges (CEX) or ZK-Rollup DEXs (like ApeX or dYdX), GMX is an oracle-based pool AMM. GMX has no order book and no order-matching engine. You trade directly against liquidity pools (GM tokens in V2 or GLP in V1).
Security: Your Keys, Your Orders
On GMX there is no such thing as an "API key" for trading. All trading operations are on-chain transactions. Your API key is the private key of your EVM wallet.
Key security practices:
- Wallet separation: Create a dedicated EVM address with the minimum necessary balance for your bot's operation. Do not use your main wallet.
- Private key protection: Store `PRIVATE_KEY` exclusively in `.env` files. Never hard-code keys into scripts.
- Approval control: Grant ERC-20 spending approvals only to the official Router smart contract of the GMX platform. For more on contract security, see the security audit reports.
GMX V2 Architecture: Two-Step Execution
To protect against front-running (MEV attacks) and ensure precise pricing, GMX V2 uses an architecture involving Keepers and Chainlink Data Streams. Order placement happens in two stages:
- Create Order: Your bot calls the
ExchangeRouter.createOrder()smart-contract function. The transaction is recorded on-chain, reserving collateral, but the position is not yet open. - Execution: Decentralized Keeper bots (run by GMX or independent ones) pick up your request. They fetch an ultra-fast price from Chainlink Data Streams and execute your order (or cancel it if slippage thresholds were hit).
Implication for developers: You do not receive confirmation of the opened position in the same transaction. You need to listen to the on-chain Events of the EventEmitter contract for confirmation.
Use Cases: Algo Trading on GMX Pools
The absence of size-dependent price impact mitigations makes GMX popular among quants. Current open interest (OI) and pool volume metrics are available on the GMX statistics dashboard:
- Delta-Neutral Hedging: Buying GM tokens (the fee-earning liquidity pool) while simultaneously opening a short position on GMX or a CEX to hedge the price risk of the underlying asset.
- Running Your Own Keeper Bot: Developers can earn execution fees by running their own node that processes user orders and liquidations.
- On-Chain Arbitrage: Using Flash Loans on Arbitrum to arbitrage between GMX, Uniswap V3 and Camelot DEX.
Where to Get Data? (REST, GraphQL, RPC)
Since smart contracts are not suited for bulk historical data queries, GMX infrastructure is split into three layers:
1. Trading and Balances (RPC Nodes)
Use Ethers.js, Web3.py or Viem to connect to Arbitrum / Avalanche nodes (Alchemy, Infura, QuickNode). This is where you read balances and send transactions.
2. Historical Data (The Graph / Subgraphs)
The entire history of positions, liquidations, volumes and fees is aggregated by the The Graph protocol. You send GraphQL queries to the official GMX V2 subgraphs.
3. GMX Stats API (REST)
The official public API for fetching current pool APRs, marker prices and open interest. Requires no authentication.
- Arbitrum:
https://arbitrum-api.gmxinfra.io - Avalanche:
https://avalanche-api.gmxinfra.io
Error Handling (Smart Contract Reverts)
Errors when trading on GMX are transaction reverts on the blockchain. The main causes:
| Revert Reason / Event Error | Cause | Solution |
|---|---|---|
| MaxPriceImpactExceeded | Your trade causes too large a pool imbalance (Price Impact). | Reduce the position size or wait until arbitrageurs rebalance the long/short pool balance. |
| InsufficientCollateral | Not enough margin to maintain the position after fees (Execution Fee, Borrow Fee). | Increase initialCollateralAmount when calling the order creation function. |
| Cancellation by Keeper (Slippage) | The order was accepted into the mempool, but by the time the keeper executed it, the oracle price had moved beyond your slippage limit. | Widen the allowed slippage parameter in your bot logic, especially in volatile markets. |
Code Examples: Integrating with GMX Data
Example 1: Fetching Market Prices (REST API)
A quick way to get prices for all tradable assets without connecting a Web3 provider:
const fetch = require('node-fetch');
async function getGmxPrices() {
try {
const response = await fetch('https://arbitrum-api.gmxinfra.io/prices/tickers');
const data = await response.json();
// Ищем токен (например, WETH)
const wethData = data.find(item => item.tokenSymbol === 'WETH');
console.log("Текущая цена WETH на GMX:", wethData.maxPrice);
} catch (error) {
console.error("Ошибка:", error);
}
}
getGmxPrices();
Example 2: Querying The Graph (GraphQL)
Retrieving information about the last 5 open positions on Arbitrum:
const fetch = require('node-fetch');
const query = `
{
positions(first: 5, orderBy: createdAt, orderDirection: desc) {
id
account
marketAddress
sizeInUsd
isLong
}
}`;
async function fetchRecentPositions() {
// Обратитесь к актуальному GMX V2 Subgraph URL в документации GMX
const subgraphUrl = 'https://subgraph.satsuma-prod.com/gmx/gmx-v2-arbitrum/api';
const response = await fetch(subgraphUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
});
const result = await response.json();
console.log(result.data.positions);
}
fetchRecentPositions();
Frequently Asked Questions (FAQ) about the GMX API
Where do I get an API key for trading on GMX?
In AMM-based DeFi (such as GMX or Uniswap), there are no centralized servers issuing API keys for trading. You build transactions locally with Ethers.js/Web3.py libraries, sign them with your wallet's private key and submit them to Arbitrum or Avalanche through RPC nodes (Infura, Alchemy).
How do I get GMX order book data?
GMX has no order book. It is a pooled system. Your trades are executed against pool liquidity (GM tokens), and prices come from ultra-fast oracles (Chainlink Data Streams). You can query the pool's available liquidity, but not order book depth.