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
- Raises
ValueError – If neither config nor chain is provided
- __init__(config=None, chain=None)
Initialise the GMX API client with the provided configuration.
- Parameters
- 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
- 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}%")