gmx.api

Documentation for eth_defi.gmx.api Python module.

GMX API Module

This module provides functionality for interacting with GMX APIs.

Functions

clear_apy_cache()

Clear the APY cache.

clear_markets_cache()

Clear the markets cache.

clear_markets_info_cache()

Clear the markets info cache.

clear_ticker_prices_cache()

Clear the ticker prices cache.

Classes

GMXAPI

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: object

API 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)

Raises

ValueError – If neither config nor chain is provided

__init__(config=None, chain=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)

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

str

property backup_url: str

Get the backup API URL for the configured chain.

Returns

Backup GMX API URL for the current chain

Return type

str

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.

Parameters

use_cache (bool) – Whether to use cached data if available (default True)

Returns

Dictionary containing current price information for all tokens, typically including bid/ask prices, last price, and volume data

Return type

dict[str, Any]

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.

Returns

Dictionary containing signed price data that can be submitted to smart contracts for price verification

Return type

dict[str, Any]

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.

Returns

Dictionary containing detailed information about all supported tokens, including addresses, symbols, decimals, and other metadata

Return type

dict[str, Any]

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
  • token_symbol (str) – Symbol of the token to retrieve data for (e.g., “ETH”, “BTC”)

  • period (str) – Time period for each candlestick. Supported values are: ‘1m’, ‘5m’, ‘15m’, ‘1h’, ‘4h’, ‘1d’. Default is ‘1h’

  • limit (int) – Maximum number of candles to retrieve. Default is 10000

Returns

Dictionary containing candlestick data with timestamps and OHLCV values

Return type

dict[str, Any]

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
  • token_symbol (str) – Symbol of the token to retrieve data for (e.g., “ETH”, “BTC”)

  • period (str) – Time period for each candlestick. Supported values are: ‘1m’, ‘5m’, ‘15m’, ‘1h’, ‘4h’, ‘1d’. Default is ‘1h’

  • limit (int) – Maximum number of candles to retrieve. Default is 10000

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

dict[str, Any]

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
  • market_tokens_data (bool) – Include detailed market token data in response

  • use_cache (bool) – Whether to use module-level cache (60 second TTL)

Returns

Dictionary with ‘markets’ key containing detailed market objects

Raises

RuntimeError – If all API endpoints fail after retries

Return type

dict[str, Any]

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
  • period (str) – Time period for APY calculation. Valid values: ‘1d’, ‘7d’, ‘30d’, ‘90d’, ‘180d’, ‘1y’, ‘total’ Default: ‘30d’

  • use_cache (bool) – Whether to use module-level cache (300 second TTL)

Returns

Dictionary with ‘markets’ key mapping market token addresses to APY data: {‘markets’: {‘0x…’: {‘apy’: 0.215, ‘baseApy’: 0.215, ‘bonusApr’: 0}}}

Raises
Return type

dict[str, Any]

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}%")