bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 1쪽
# GMX Docs
> LLM-friendly documentation index and full-text bundle for GMX.
This file contains all documentation content in a single document following the llmstxt.org standard.
## GMX
GMX is a decentralized spot and perpetual exchange on Arbitrum, Avalanche, and MegaETH. It supports perpetual trades with up to 100x leverage and token swaps with low price impact. The [GMX Account](./trading/overview.md#gmx-account-multichain) lets you trade on GMX from any supported chain, including Ethereum, Base, and BNB. GMX uses Chainlink Data Stream oracles for accurate pricing, so liquidations occur only at fair market prices — not at momentary spread spikes.
GMX lists 100+ markets: crypto majors and altcoins, plus TradFi markets for gold, silver, oil, natural gas and US equities (SPCX, SPY, QQQ), all tradeable 24/7 with up to 100x leverage. See [TradFi markets](./trading/tradfi-markets.md).
Trading is powered by GM and GLV liquidity pools. GMX routes every order against these pools and quotes the oracle index price rather than relying on an order book or external market makers. Liquidity providers earn 63% of the fees generated from trading, liquidations, borrowing fees, and swaps on Arbitrum and Avalanche.
This documentation is structured for both humans and AI agents. Oracle-based pricing, deterministic execution, and comprehensive APIs support a range of use cases — whether you are a trader using the app, a developer building an integration, or an AI agent executing autonomous strategies.
## Get started
Choose your role to find the right starting point.
- **Traders:** [Trading on GMX](./trading/overview.md) — Open leveraged positions, place limit orders, and swap tokens.
- **Liquidity providers:** [Providing liquidity](./providing-liquidity.md) — Earn yield by depositing into GM or GLV pools.
- **Token holders:** [GMX token](./tokenomics/gmx-token.md) — Stake GMX to earn rewards. See also [Rewards](./tokenomics/rewards.md).
- **Governance:** [Voting power](./governance/voting-power.md) — Participate in protocol governance.
- **Developers:** [API](./api/overview.md) — Integrate with GMX contracts, the GMX API, the Oracle API, and the [TypeScript SDK](./sdk/overview.md).
- **AI agents:** [AI Agents](./ai-agents/overview.md) — Agent [plugins, skills](./ai-agents/plugins-and-skills.md), and LLM-optimized documentation for building on GMX.
---
## AI Agents
GMX is built for both humans and AI agents. The protocol's oracle-based pricing, deterministic execution, and comprehensive APIs make it the ideal venue for autonomous on-chain perpetual and spot trading.
## Why GMX for AI agents
Centralized exchanges require API keys, KYC approvals, and custodial trust. GMX combines self-custody with oracle-based pricing and purpose-built primitives for autonomous trading:
- **Non-custodial** — Agents hold their own keys. No exchange custody, no counterparty risk, no account freezes.
- **Permissionless** — No KYC, no API key provisioning, no rate limit negotiations. Any wallet can trade immediately.
- **Oracle-based pricing** — Execution happens at Chainlink oracle prices rather than against an internal pool curve. Price impact is determined by open interest imbalance and is predictable before submission.
- **Gasless execution** — [Express orders](../trading/order-types.md) use EIP-712 typed data signing for relay-router calls. Both the documented `/orders/txns` flow and the GMX interface submit through GMX Relay, GMX's self-hosted relay. GMX no longer uses Gelato Relay. Agents sign off-chain and pay relay fees in supported tokens such as USDC, WETH, or USDM instead of managing native gas tokens.
- **MEV protection** — Two-phase order execution (create then execute via keeper) prevents frontrunning and sandwich attacks. The user's intent is committed on-chain before oracle prices are included.
- **Subaccounts** — Agents operate with scoped on-chain permissions via subaccounts, never exposing the master private key.
- **Up to 100x leverage** — Trade perpetuals across major assets on Arbitrum, Avalanche, and MegaETH. Arbitrum has the deepest liquidity and most complete feature set.
- **Multichain trading** — Agents can trade from any chain by depositing into a GMX account, which routes funds to the destination chain without manual bridging. For direct non-custodial trading without account deposits, agents interact with active GMX markets on Arbitrum, Avalanche, and MegaETH.
- **Structured data APIs** — HTTP APIs, GraphQL, on-chain contract reads, and an [MCP server](#mcp-server) *(coming soon)* provide every data point an agent needs: prices, positions, orders, market conditions, fees, and trade history.
- **TypeScript SDK** — The [`@gmx-io/sdk`](../sdk/overview.md) package wraps all protocol operations into typed methods. Agents can fetch markets, calculate fees, open positions, and manage orders programmatically.
- **LLM-optimized docs** — This documentation site generates [`llms.txt`](https://docs.gmx.io/llms.txt) and [`llms-full.txt`](https://docs.gmx.io/llms-full.txt) bundles for direct model consumption.
## Integration paths
GMX offers multiple integration paths depending on the level of control your agent needs.
| Path | Best for | Capabilities |
|------|----------|-------------|
| **[Agent plugins and skills](./plugins-and-skills.md)** | AI coding agents (Claude Code, Codex, Cursor, Copilot, Windsurf, and others) | Pre-built trading skill with SDK and API references bundled |
| **[TypeScript SDK](../sdk/overview.md)** | Custom agents and bots | Full read + write access: markets, orders, positions, fees |
| **[GMX API and Oracle API](../api/overview.md)** | Lightweight data access | Oracle prices, markets, positions, orders, rates |
| **[MCP server](#mcp-server)** *(coming soon)* | Any MCP-compatible client (Claude, ChatGPT, Codex, Cursor, Copilot, Windsurf, and others) | Market data, positions, orders, pools; trade execution via prepare/confirm |
| **[Smart contracts](/docs/category/contracts)** | Direct on-chain interaction | Full protocol access via ExchangeRouter, Reader, GlvReader |
| **[GraphQL](../api/graphql.mdx)** | Historical data queries | Trade history, position events, indexed on-chain data |
### Agent plugins and skills
The [`gmx-io/gmx-ai`](https://github.com/gmx-io/gmx-ai) repository provides ready-to-use agent skills for AI frameworks. These skills bundle trading capabilities with SDK references, API endpoint documentation, contract addresses, and order type specifications so agents can trade on GMX without manual setup. See [Plugins and skills](./plugins-and-skills.md) for installation and usage.
### SDK for autonomous agents
The [SDK v1 (`GmxSdk`)](../sdk/v1/readme.mdx) is the recommended integration for agents that need full trading capabilities. It provides:
- Market discovery and price feeds
- Order creation (market, limit, stop-loss, take-profit)
- Position monitoring and management
- Fee estimation and execution cost calculation
- Automatic RPC batching for efficient data fetching
```typescript
const { GmxSdk } = require("@gmx-io/sdk");
const sdk = new GmxSdk({
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
account: walletAddress,
walletClient,
});
// Fetch markets and open a position
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
await sdk.orders.long({
marketAddress,
payTokenAddress: usdcAddress,
collateralTokenAddress: longToken,
payAmount: 100_000000n,
leverage: 50000n,
});
```
See the [SDK examples](../sdk/v1/examples.md) for complete agent workflows including position monitoring and closing.
### HTTP APIs for lightweight agents
For read-only agents or those that submit transactions separately, the [GMX API and Oracle API](../api/overview.md) provide oracle prices, market data, and position information over HTTP. No RPC connection or SDK installation needed.
### MCP server
:::note
The MCP server is under development and not yet available.
:::
An [MCP](https://modelcontextprotocol.io/) (Model Context Protocol) server is being added as a transport layer to the GMX API. MCP is an open standard supported by [70+ AI clients](https://modelcontextprotocol.io/clients) — including Claude, ChatGPT, OpenAI Codex, Cursor, GitHub Copilot, Windsurf, JetBrains, Gemini CLI, Amazon Q, and Cline. Any MCP-compatible client can query GMX data and execute trades directly through the protocol.
The server uses SSE transport mounted alongside the GMX API, sharing the same domain layer with no separate infrastructure required.
The MCP server ships in two phases:
- **Read-only tools** — Market data, positions, orders, pool information, and account summaries
- **Read-write tools** — Trade execution using a prepare/confirm pattern where the server returns human-readable previews and unsigned transactions, and all signing happens client-side
## Supported chains
| Chain | Chain ID | Native token | Status |
|-------|----------|--------------|--------|
| Arbitrum | 42161 | ETH | Active |
| Avalanche | 43114 | AVAX | Active |
| MegaETH | 4326 | ETH | Active |
---
## Plugins and Skills
The [`gmx-io/gmx-ai`](https://github.com/gmx-io/gmx-ai) repository provides pre-built agent skills that give AI coding agents the ability to trade perpetuals, provide liquidity, and swap tokens on GMX V2. Skills use a filesystem-based format compatible with a wide range of agents — see [Installation](#installation) for supported clients.
:::note
Skills currently use [SDK v1](../sdk/v1/readme.mdx) and direct contract calls for write operations, and the [GMX API and Oracle API](../api/overview.md) for data access. As the GMX API and SDK v2 mature, skills will migrate to fully leverage them — expanding capabilities to cover virtually any protocol action.
:::
## Available skills
The repository ships two skills that cover the main protocol operations.
### gmx-trading
Bundles everything an AI agent needs to trade on GMX:
- **Trading operations** — Open long/short positions with up to 100x leverage, swap tokens at oracle prices, and place market, limit, stop-loss, and take-profit orders.
- **Position management** — Query open positions, pending orders, and trade history.
- **Market data** — Fetch markets, token prices, pool sizes, and utilization rates.
- **Reference material** — SDK method signatures, GMX API, Oracle API, and GraphQL endpoint documentation, contract addresses for all supported chains, and order type behavior specifications.
### gmx-liquidity
Covers liquidity provision across GM pools and GLV vaults:
- **GM pool operations** — Deposit into single-market pools (balanced or single-sided), withdraw, and shift liquidity between pools atomically.
- **GLV vault operations** — Deposit raw tokens or existing GM tokens into multi-market auto-rebalancing vaults, and withdraw.
- **Pool data** — Query pool TVL, composition, utilization, capacity, and GM/GLV token balances.
- **Reference material** — Contract struct definitions, execution flows, gas estimation formulas, GLV vault addresses, and viem multicall examples.
### Supported chains
| Chain | Chain ID | Native token | Status |
|-------|----------|--------------|--------|
| Arbitrum | 42161 | ETH | Active |
| Avalanche | 43114 | AVAX | Active |
| MegaETH | 4326 | ETH | Active |
## Installation
### Claude Code
Install the GMX plugin from the Claude Code marketplace:
```
/plugin marketplace add gmx-io/gmx-ai
/plugin install gmx-io@gmx-ai
```
Once installed, Claude Code can execute trades, provide liquidity, query positions, and interact with GMX markets using natural language instructions.
### Skills CLI (Codex, Cursor, Copilot, Windsurf, and others)
Add the skill using the [Skills CLI](https://github.com/vercel-labs/skills):
```bash
npx skills add gmx-io/gmx-ai
```
This installs both the `gmx-trading` and `gmx-liquidity` skills as filesystem-based context files that any compatible coding agent can read. Supported agents include:
- OpenAI Codex
- Cursor
- GitHub Copilot
- Windsurf
- Gemini CLI
- Amp (Sourcegraph)
- Roo Code
- Goose
- Cline
- Continue
Any agent that reads project-level instruction files from the filesystem can use the skill.
## Reference files
Both skills expose capabilities through shared and skill-specific reference files:
| Reference | Skill | Contents |
|-----------|-------|----------|
| **SDK reference** | Shared | `GmxSdk` and `GmxApiSdk` class APIs, module methods, type definitions, and initialization patterns |
| **API endpoints** | Shared | Oracle API endpoints, GMX API OpenAPI endpoints, GraphQL queries, and fallback URLs per chain |
| **Contract addresses** | Shared | Deployed contract addresses for ExchangeRouter, Reader, GlvReader, vaults, and relay routers on every supported chain |
| **Order types** | Trading | Order type enum values, trigger conditions for longs and shorts, auto-cancel limits, and TWAP specifications |
| **Liquidity operations** | Liquidity | Contract struct definitions, execution flows, gas estimation formulas, GLV vault addresses, and viem multicall examples |
## How agents use the skills
When an AI agent has the skills installed, it can:
1. **Fetch market data** — Discover available markets, current prices, and pool conditions.
2. **Calculate fees** — Estimate execution fees, position fees, and price impact before placing orders.
3. **Open positions** — Create long or short positions with specified leverage and collateral.
4. **Set conditional orders** — Place limit entries, stop-losses, and take-profit orders.
5. **Monitor positions** — Check open positions, unrealized PnL, and pending orders.
6. **Close positions** — Compute decrease amounts and submit close orders.
7. **Swap tokens** — Execute token swaps at oracle-determined prices.
8. **Deposit liquidity** — Deposit into GM pools (balanced or single-sided) and GLV vaults.
9. **Withdraw liquidity** — Withdraw from GM pools and GLV vaults.
10. **Shift liquidity** — Move GM tokens between pools atomically without withdrawing first.
## Repository structure
```
gmx-io/gmx-ai/
.well-known/skills/ # Vercel Skills protocol
index.json # Skill registry
gmx-trading/
SKILL.md # Trading skill definition
references/
sdk-reference.md # SDK API reference (shared)
api-endpoints.md # GMX API, Oracle API, and GraphQL endpoints (shared)
contract-addresses.md # Deployed contracts per chain (shared)
order-types.md # Order type specifications
gmx-liquidity/
SKILL.md # Liquidity skill definition
references/
liquidity-operations.md # Contract structs, flows, gas formulas
plugins/gmx-io/ # Claude Code plugin
.claude-plugin/
plugin.json # Plugin manifest
skills/
gmx-trading/ # Trading skill files (mirrored)
gmx-liquidity/ # Liquidity skill files (mirrored)
```
## Links
- **Repository:** [github.com/gmx-io/gmx-ai](https://github.com/gmx-io/gmx-ai)
- **SDK package:** [`@gmx-io/sdk` on npm](https://www.npmjs.com/package/@gmx-io/sdk)
- **SDK documentation:** [SDK overview](../sdk/overview.md)
- **API documentation:** [API overview](../api/overview.md)
- **GMX app:** [app.gmx.io](https://app.gmx.io)
---
## Frontend Integration
The GMX protocol consists of smart contracts deployed on blockchains.
Users can interact directly with the smart contracts using blockchain explorers such as [Arbiscan](https://arbiscan.io/) and [SnowTrace](https://snowtrace.io/).
The [GMX frontend repository](https://github.com/gmx-io/gmx-interface) provides code to simplify contract interaction and to view protocol information and can be deployed by any community member.
A deployed instance of the GMX frontend is available at [https://app.gmx.io/](https://app.gmx.io/).
A backup instance of the GMX frontend is available at [https://gmxalt.io/](https://gmxalt.io/).
## Testnet frontend
A testnet GMX frontend is available at [https://test.gmx-interface.pages.dev/](https://test.gmx-interface.pages.dev/). Use it to test against testnet networks (Arbitrum Sepolia and Avalanche Fuji) and to access debug mode tooling.
## Running a frontend
Integrators can either deploy the [GMX frontend repository](https://github.com/gmx-io/gmx-interface) or build their own frontend, aggregator, or backend-driven trading flow.
The supported technical earning options are UI fees and referrals. UI fees pay a configured receiver on supported transactions. Referrals let a registered referral-code owner earn affiliate rewards on position fees when the referral code is applied to a trader.
One-Click Trading is not an earning option by itself. It is a delegated trading UX pattern that lets users approve a limited subaccount signer for faster order flow.
If your frontend reads orders from the GMX API, each order response includes `uiFeeFactor`. This is the 30-decimal factor snapshotted when the order was created, so use it for historical order attribution instead of looking up the receiver's current factor. Orders created before the snapshot field was introduced return `uiFeeFactor: null`; treat that as unavailable historical data, not as zero. The same rule applies to orders nested under a position response when you request `includeRelatedOrders: true`.
### If you use the GMX Interface repository
To run the GMX frontend locally, follow the instructions in the [GMX frontend repository](https://github.com/gmx-io/gmx-interface). You can also deploy it using a static hosting service such as Vercel, Netlify, or Cloudflare Pages.
#### UI fee receiver
To configure the UI fee receiver, add `VITE_APP_UI_FEE_RECEIVER` to your `.env` file. Set it to the wallet address that receives [UI fees](./contracts/fees.md#ui-fee).
```bash
VITE_APP_UI_FEE_RECEIVER=0xYourReceiverAddressHere
```
The current interface sets `uiFeeReceiver` for orders and for GM and GLV deposits, withdrawals, and shifts. The receiver account must configure its UI fee factor with `ExchangeRouter.setUiFeeFactor`. A configured receiver can claim accrued UI fees through `ExchangeRouter.claimUiFees`.
#### Referral codes
To apply a referral code from your frontend, link users to the interface with a `ref` query parameter.
```text
https://your-interface.example/#/?ref=YourReferralCode
```
The interface stores the encoded referral code in browser local storage as `GMX-referralCode`. When a user creates an order, the interface can pass the stored code to the contracts only if the trader does not already have an on-chain referral code, the local code has a registered owner, and the code is valid where `ReferralCodeValidator` is active. Existing pre-validator codes remain valid; new follower-chain codes may need to wait for leader-chain validation to propagate.
#### One-Click Trading storage
The GMX interface signs `SUBACCOUNT_MESSAGE`, derives the generated subaccount private key from the signature, encrypts that private key with the main account address, and stores One-Click Trading configuration in browser local storage under keys scoped by `chainId` and account.
The browser stores the One-Click Trading configuration under `[chainId, account, "one-click-trading-config"]` and the subaccount approval under `[chainId, account, "subaccount-approval"]`.
#### Custom RPC URLs
To override the default RPC endpoints for Arbitrum, Avalanche, or MegaETH, add the corresponding variable to your `.env` file. Each variable takes a JSON array of RPC URLs, which the interface uses as fallback endpoints. Replace the placeholder URLs with endpoints from your RPC provider.
```dotenv
VITE_APP_ARBITRUM_RPC_URLS=["https://your-arbitrum-rpc-provider.example/rpc"]
VITE_APP_AVALANCHE_RPC_URLS=["https://your-avalanche-rpc-provider.example/rpc"]
VITE_APP_MEGAETH_RPC_URLS=["https://your-megaeth-rpc-provider.example/rpc"]
```
### If you use your own frontend or aggregator
Custom integrations should not rely on GMX Interface environment variables or local storage keys. Build th프로젝트로 돌아가기