gmx.api
Documentation for eth_defi.gmx.api Python module.
GMX API Module
This module provides functionality for interacting with GMX APIs.
Functions
Clear the APY cache. |
|
Clear the markets cache. |
|
Clear the markets info cache. |
|
Clear the ticker prices cache. |
Classes
API interaction functionality for GMX protocol. |
- clear_ticker_prices_cache()
Clear the ticker prices cache.
This function clears the module-level cache that stores ticker price data. Useful for testing or when fresh data is explicitly required.
- Return type
None
- clear_markets_cache()
Clear the markets cache.
This function clears the module-level cache that stores markets list data. Useful for testing or when fresh data is explicitly required.
- Return type
None
- clear_markets_info_cache()
Clear the markets info cache.
This function clears the module-level cache that stores detailed markets info data. Useful for testing or when fresh data is explicitly required.
- Return type
None
- clear_apy_cache()
Clear the APY cache.
This function clears the module-level cache that stores APY data. Useful for testing or when fresh data is explicitly required.
- Return type
None
- class GMXAPI
Bases:
objectAPI interaction functionality for GMX protocol.
This class provides a unified interface to interact with GMX protocol APIs, supporting both Arbitrum and Avalanche networks. It handles automatic failover to backup URLs and provides both raw dictionary responses and pandas DataFrame conversions for price data.
Example:
# Initialize GMX API client config = GMXConfig(chain="arbitrum") gmx_api = GMXAPI(config) # Get current token prices tickers = gmx_api.get_tickers() # Get historical candlestick data as DataFrame df = gmx_api.get_candlesticks_dataframe("ETH", period="1h")
Initialise the GMX API client with the provided configuration.
- Parameters
config (Optional[GMXConfig]) – GMX configuration object containing chain and other settings (optional if chain is provided)
chain (Optional[str]) – Chain name (arbitrum or avalanche) as an alternative to config (optional if config is provided)
retry_config – Retry behaviour for API requests. Defaults to production settings when
None.
- Raises
ValueError – If neither config nor chain is provided
- __init__(config=None, chain=None, retry_config=None)
Initialise the GMX API client with the provided configuration.
- Parameters
config (Optional[GMXConfig]) – GMX configuration object containing chain and other settings (optional if chain is provided)
chain (Optional[str]) – Chain name (arbitrum or avalanche) as an alternative to config (optional if config is provided)
retry_config (eth_defi.gmx.retry.GMXRetryConfig | None) – Retry behaviour for API requests. Defaults to production settings when
None.
- Raises
ValueError – If neither config nor chain is provided
- property base_url: str
Get the primary API URL for the configured chain.
- Returns
Primary GMX API URL for the current chain
- Return type
- property backup_url: str
Get the backup API URL for the configured chain.
- Returns
Backup GMX API URL for the current chain
- Return type
- property base_v2_url: str
Get the REST API v2 URL for the configured chain.
- Returns
GMX REST API v2 base URL for the current chain, or empty string if no v2 endpoint is configured for this chain.
- get_tickers(use_cache=True)
Get current price information for all supported tokens.
This endpoint provides real-time pricing data for all tokens supported by the GMX protocol on the configured network. Results are cached for 10 seconds to reduce API calls.
- get_signed_prices()
Get cryptographically signed prices for use in on-chain transactions.
These signed prices are required for certain GMX protocol interactions that need price verification on-chain. The signatures ensure price authenticity and prevent manipulation.
- get_tokens()
Get comprehensive information about all supported tokens.
This endpoint provides detailed metadata about each token supported by the GMX protocol, including contract addresses, decimals, and other relevant token properties.
- get_candlesticks(token_symbol, period='1h', limit=10000)
Get historical price data in candlestick format for a specific token.
This method retrieves OHLCV (Open, High, Low, Close, Volume) data for the specified token and time period.
- Parameters
- Returns
Dictionary containing candlestick data with timestamps and OHLCV values
- Return type
- get_candlesticks_dataframe(token_symbol, period='1h', limit=10000)
Get historical price data as a pandas DataFrame for easy analysis.
This is a convenience method that fetches candlestick data and converts it into a pandas DataFrame with properly formatted timestamps and standardized column names.
Example:
# Get hourly ETH price data df = gmx_api.get_candlesticks_dataframe("ETH", period="1h") # DataFrame will have columns: timestamp, open, high, low, close print(df.head()) # Calculate simple moving average df["sma_20"] = df["close"].rolling(window=20).mean()
- Parameters
- Returns
pandas DataFrame with columns: timestamp (datetime), open (float), high (float), low (float), close (float)
- Return type
pd.DataFrame
- get_markets(use_cache=True)
Get list of all GMX trading markets.
Fetches market metadata from /markets endpoint including market tokens, index tokens, collateral tokens, and listing status/dates.
Uses existing retry logic with automatic backup failover via make_gmx_api_request from eth_defi.gmx.retry module.
- Parameters
use_cache (bool) – Whether to use module-level cache (10 minute TTL)
- Returns
Dictionary with ‘markets’ key containing list of market objects
- Raises
RuntimeError – If all API endpoints fail after retries
- Return type
- get_markets_info(market_tokens_data=True, use_cache=True)
Get comprehensive market information including liquidity and rates.
Fetches detailed market data from /markets/info endpoint including: - Open interest (long/short) - Available liquidity - Pool amounts - Funding rates (long/short) - Borrowing rates (long/short) - Net rates (long/short) - isListed status (critical for filtering)
Uses existing retry logic with automatic backup failover via make_gmx_api_request from eth_defi.gmx.retry module.
- Parameters
- Returns
Dictionary with ‘markets’ key containing detailed market objects
- Raises
RuntimeError – If all API endpoints fail after retries
- Return type
- get_apy(period='30d', use_cache=True)
Get APY data for GMX and GLV positions by market.
Fetches annualised yield data from /apy endpoint for different time periods. Returns APY broken down by market token address including base APY and bonus APR.
Uses existing retry logic with automatic backup failover via make_gmx_api_request from eth_defi.gmx.retry module.
- Parameters
- Returns
Dictionary with ‘markets’ key mapping market token addresses to APY data: {‘markets’: {‘0x…’: {‘apy’: 0.215, ‘baseApy’: 0.215, ‘bonusApr’: 0}}}
- Raises
ValueError – If period is invalid
RuntimeError – If all API endpoints fail after retries
- Return type
Example:
api = GMXAPI(config) apy_data = api.get_apy(period="30d") # Get APY for specific market market_token = "0xd62068697bCc92AF253225676D618B0C9f17C663" if market_token in apy_data.get("markets", {}): market_apy = apy_data["markets"][market_token]["apy"] print(f"30-day APY: {market_apy * 100:.2f}%")
- get_market_depth(market_symbol=None, use_cache=True)
Get market depth information for all listed GMX markets.
Parses the
/markets/infoREST response into structuredMarketDepthInfodataclasses, giving a real-time view of:Current long / short open interest (USD)
Remaining pool capacity before the reserve cap is hit
Funding and borrowing rates
The response is cached for 60 seconds by default (
use_cache=True), so calling this method repeatedly in a tight loop is safe.Example:
api = GMXAPI(chain="arbitrum") eth_markets = api.get_market_depth(market_symbol="ETH") for m in eth_markets: print(f"{m.market_symbol}: longOI=${m.long_open_interest_usd:,.0f}") print(f" Available long cap: ${m.available_long_oi_usd:,.0f}") print(f" Available short cap: ${m.available_short_oi_usd:,.0f}")
- Parameters
market_symbol (str | None) – Optional case-insensitive substring filter applied to the market name. For example
"ETH"matches"ETH/USD [WETH-USDC]"but not"BTC/USD". IfNone, all listed markets are returned.use_cache (bool) – Whether to use the module-level 60-second cache for
/markets/info. Set toFalseto force a fresh API call.
- Returns
List of
MarketDepthInfofor all active (isListed=True) markets, optionally filtered by market_symbol.- Raises
RuntimeError – If all API endpoints fail after retries
- Return type
- get_positions(address, include_related_orders=False, use_cache=True)
Fetch open positions for a wallet address via the v2 API.
Returns position data including unrealised PnL, fees, leverage, collateral amount, and liquidation price. This endpoint is only available on the v2 REST API and is not present in v1.
Example:
api = GMXAPI(chain="arbitrum") positions = api.get_positions("0xAbC...") for pos in positions: print(pos["market"], pos["leverage"])- Parameters
address (eth_typing.evm.HexAddress) – Wallet address to query positions for (checksummed hex).
include_related_orders (bool) – Include related SL/TP orders attached to each position.
use_cache (bool) – Use the module-level 15-second cache.
- Returns
Parsed API response — typically a list of position objects.
- Raises
ValueError – When no v2 API URL is configured for the current chain.
RuntimeError – When all retry attempts fail.
- Return type
- get_orders(address)
Fetch open orders for a wallet address via the v2 API.
Returns all pending/open orders including limit orders, stop-loss, and take-profit orders. Not available in v1.
Example:
api = GMXAPI(chain="arbitrum") orders = api.get_orders("0xAbC...")- Parameters
address (eth_typing.evm.HexAddress) – Wallet address to query orders for (checksummed hex).
- Returns
Parsed API response — typically a list of order objects.
- Raises
ValueError – When no v2 API URL is configured for the current chain.
RuntimeError – When all retry attempts fail.
- Return type
- get_rates(address=None, use_cache=True)
Fetch funding and borrowing rate snapshots via the v2 API.
Returns the latest rate snapshots for all markets (or a single market when
addressis supplied). Not available in v1.Note
The
/ratesendpoint does not accept aperiodoraverage_byparameter — passing them results in a 400 error.Example:
api = GMXAPI(chain="arbitrum") rates = api.get_rates()
- Parameters
- Returns
Parsed API response containing rate snapshots per market.
- Raises
ValueError – When no v2 API URL is configured for the current chain.
RuntimeError – When all retry attempts fail.
- Return type
- get_ohlcv(symbol, timeframe='1h', limit=100, since=None)
Fetch OHLCV candle data via the v2 API.
Similar to
get_candlesticks()but uses the v2 endpoint which supports asinceparameter (Unix milliseconds) for flexible historical data retrieval and pagination.Example:
api = GMXAPI(chain="arbitrum") candles = api.get_ohlcv("ETH", timeframe="4h", limit=500) # With since parameter for historical data import time one_week_ago_ms = int((time.time() - 7 * 86400) * 1000) candles = api.get_ohlcv("BTC", timeframe="1h", since=one_week_ago_ms)- Parameters
symbol (str) – Trading symbol (e.g.
"ETH","BTC").timeframe (str) – Candle timeframe:
"1m","5m","15m","1h","4h","1d". Default"1h".limit (int) – Maximum number of candles to return. Default
100.since (int | None) – Unix timestamp in milliseconds for the earliest candle.
Nonereturns the most recent candles.
- Returns
Parsed API response containing OHLCV candle data.
- Raises
ValueError – When no v2 API URL is configured for the current chain.
RuntimeError – When all retry attempts fail.
- Return type
- get_token_info(use_cache=True)
Fetch comprehensive token information via the v2 API.
Returns token metadata including current pricing and supply data. Richer than the v1
get_tokens()endpoint.Example:
api = GMXAPI(chain="arbitrum") tokens = api.get_token_info()
- Parameters
use_cache (bool) – Use the module-level 60-second cache.
- Returns
Parsed API response containing token info objects.
- Raises
ValueError – When no v2 API URL is configured for the current chain.
RuntimeError – When all retry attempts fail.
- Return type
- get_pairs(use_cache=True)
Fetch all trading pairs via the v2 API.
Returns the complete list of trading pairs available on the GMX protocol for the configured chain. Not available in v1.
Example:
api = GMXAPI(chain="arbitrum") pairs = api.get_pairs()
- Parameters
use_cache (bool) – Use the module-level 10-minute cache.
- Returns
Parsed API response containing trading pair objects.
- Raises
ValueError – When no v2 API URL is configured for the current chain.
RuntimeError – When all retry attempts fail.
- Return type