gmx.core

Documentation for eth_defi.gmx.core Python module.

GMX Core Package

This package contains core implementations for GMX protocol data retrieval, replacing the gmx_python_sdk functionality with a more robust and maintainable implementation based on eth_defi patterns.

class GetAvailableLiquidity

Bases: eth_defi.gmx.core.get_data.GetData

GMX available liquidity data retrieval using efficient multicall batching.

Retrieves available liquidity information for all GMX markets with efficient multicall batching for better performance and reduced RPC usage.

Initialize available liquidity data retrieval.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

  • use_original_approach – Whether to use original individual calls instead of multicall

__init__(config, filter_swap_markets=True, use_original_approach=False)

Initialize available liquidity data retrieval.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

  • use_original_approach (bool) – Whether to use original individual calls instead of multicall

generate_multicall_requests(market_key, long_token, short_token)

Generate multicall requests for liquidity data.

For each market we need to query: - pool_amount for long token - pool_amount for short token - reserve_factor for long - reserve_factor for short - open_interest_reserve_factor for long - open_interest_reserve_factor for short

Parameters
  • market_key (str) – Market address

  • long_token (str) – Long token address

  • short_token (str) – Short token address

Returns

Iterable of EncodedCall objects

Return type

Iterable[eth_defi.event_reader.multicall_batcher.EncodedCall]

generate_all_multicalls()

Generate all multicall requests for all markets.

Returns

Iterable of all EncodedCall objects needed

Return type

Iterable[eth_defi.event_reader.multicall_batcher.EncodedCall]

get_max_reserved_usd(market, token, is_long)

For a given market, long/short token and pool direction get the uncalled web3 functions to calculate pool size, pool reserve factor and open interest reserve factor.

Parameters
  • market (str) – contract address of GMX market

  • token (str) – contract address of long or short token

  • is_long (bool) – pass True for long pool or False for short

Returns

tuple containing: - pool_amount: uncalled web3 contract object for pool amount - reserve_factor: uncalled web3 contract object for pool reserve factor - open_interest_reserve_factor: uncalled web3 contract object for open interest reserve factor

Return type

tuple

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetBorrowAPR

Bases: eth_defi.gmx.core.get_data.GetData

GMX borrow APR data retrieval class.

Retrieves borrow APR information for all available GMX markets, replacing the gmx_python_sdk GetBorrowAPR functionality.

Initialize borrow APR data retrieval.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

__init__(config, filter_swap_markets=True)

Initialize borrow APR data retrieval.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetClaimableFees

Bases: eth_defi.gmx.core.get_data.GetData

GMX claimable fees data retrieval with multicall optimization.

Retrieves claimable fees information for all available GMX markets using multicall batching for better performance.

Initialize claimable fees data retrieval.

Parameters

config – GMXConfig instance containing chain and network info

__init__(config)

Initialize claimable fees data retrieval.

Parameters

config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

get_claimable_fees()

Get claimable fees data using multicall optimization.

Uses multicall batching to query all claimable fee amounts in a single RPC call, significantly improving performance compared to sequential calls.

Returns

Dictionary containing total claimable fees

Return type

dict

get_per_market_claimable_fees()

Get detailed claimable fees data for each market.

Returns

Dictionary of market symbol to fee details

Return type

dict

generate_all_multicalls(markets)

Generate all multicall requests for all markets.

Parameters

markets (dict[str, Any]) – Dictionary of available markets

Returns

Iterable of all EncodedCall objects needed

Return type

Iterable[eth_defi.event_reader.multicall_batcher.EncodedCall]

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetFundingFee

Bases: eth_defi.gmx.core.get_data.GetData

GMX funding fee data retrieval class.

Retrieves funding fee information for all available GMX markets, replacing the gmx_python_sdk GetFundingFee functionality.

Initialize funding fee data retrieval.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

__init__(config, filter_swap_markets=True)

Initialize funding fee data retrieval.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetData

Bases: abc.ABC

Base class for GMX data retrieval operations.

This class provides common functionality for retrieving and processing GMX protocol data, including market filtering, oracle price integration, and data export capabilities.

Parameters
  • config (GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

Initialize data retrieval base class.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

__init__(config, filter_swap_markets=True)

Initialize data retrieval base class.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

class GetGMPrices

Bases: eth_defi.gmx.core.get_data.GetData

GM token prices data provider for GMX protocol.

Retrieves current prices and valuation data for GM (liquidity provider) tokens. GM tokens represent shares in GMX liquidity pools and their prices reflect the underlying value of the pooled assets plus accumulated fees.

Supports three different pricing scenarios:

  • Traders: Prices for trading scenarios (most commonly used)

  • Deposits: Prices optimized for deposit operations

  • Withdrawals: Prices optimized for withdrawal operations

Each pricing scenario uses different PNL factor configurations to account for the specific risk and fee structures associated with different operation types.

Initialize GM prices data provider.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

__init__(config, filter_swap_markets=True)

Initialize GM prices data provider.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

get_price_traders()

Get GM token prices for traders.

Retrieves GM token prices optimized for trading scenarios, using the MAX_PNL_FACTOR_FOR_TRADERS configuration. This is the most commonly used price type for general trading operations.

Returns

Dictionary containing GM prices for traders

Return type

dict[str, float]

get_price_deposit()

Get GM token prices for deposits.

This method retrieves GM token prices optimized for deposit scenarios, using the MAX_PNL_FACTOR_FOR_DEPOSITS configuration. These prices account for the specific risks associated with adding liquidity to pools.

Returns

Dictionary containing GM prices for deposits

Return type

dict[str, float]

get_price_withdraw()

Get GM token prices for withdrawals.

This method retrieves GM token prices optimized for withdrawal scenarios, using the MAX_PNL_FACTOR_FOR_WITHDRAWALS configuration. These prices account for the specific risks associated with removing liquidity from pools.

Returns

Dictionary containing GM prices for withdrawals

Return type

dict[str, float]

get_prices(price_type='traders')

Get GM token prices with specified price type.

This is a unified method that calls the appropriate specific price method based on the price_type parameter. This provides a convenient interface when the price type needs to be determined dynamically.

Parameters

price_type (str) – Type of price to retrieve (“traders”, “deposits”, “withdrawals”)

Returns

Dictionary containing GM prices data

Return type

dict[str, float]

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetOpenInterest

Bases: eth_defi.gmx.core.get_data.GetData

GMX open interest data retrieval class.

This class retrieves open interest information for all available GMX markets, including position PnL calculations. It inherits from the GetData base class and provides specific implementation for open interest data processing.

Parameters
  • config (GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

Initialize open interest data retrieval.

Parameters
  • config (GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

__init__(config, filter_swap_markets=True)

Initialize open interest data retrieval.

Parameters
  • config (GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetOpenPositions

Bases: eth_defi.gmx.core.get_data.GetData

Open positions data provider for GMX protocol.

Retrieves all open trading positions for a specific user address. Provides detailed information about current trading positions, including position sizes, entry prices, current profit/loss, margin requirements, and liquidation thresholds.

Initialize open positions data provider.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

  • use_graphql – Whether to use GraphQL (faster) instead of RPC calls (default: False - uses contract calls)

__init__(config, filter_swap_markets=True, use_graphql=False)

Initialize open positions data provider.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

  • use_graphql (bool) – Whether to use GraphQL (faster) instead of RPC calls (default: False - uses contract calls)

get_data(address)

Get all open positions for a given address on the configured chain.

Tries data sources in order: REST API v2 → Subsquid GraphQL → RPC Reader contract. Each fallback is attempted only when the previous source fails or returns an empty result.

Non-empty results from the REST API are returned immediately (fast path). An empty REST API response is treated as inconclusive — the API indexes live-chain state only, so it may lag by a few blocks or be blind to Anvil fork positions.

GraphQL results are only trusted when the REST API also succeeded but was empty (e.g. Anvil fork scenario). When the REST API explicitly returned no positions, a non-empty GraphQL result is treated as suspect because the Subsquid indexer lags by several blocks and may still show positions that have already been closed on-chain (“ghost positions”). In that case the query falls through to the authoritative RPC source.

The on-chain RPC Reader is always the authoritative final word when earlier tiers return no positions or when REST-vs-GraphQL disagree.

Parameters

address (str) – User wallet address to query positions for

Returns

A dictionary containing the open positions, where asset and direction are the keys

Return type

dict

get_chain_tokens()

Get chain token information - for backward compatibility with tests.

Returns

Dictionary mapping token addresses to their information

Return type

dict

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GetPoolTVL

Bases: eth_defi.gmx.core.get_data.GetData

GMX pool TVL data retrieval using multicall optimization.

Retrieves pool TVL information for all available GMX markets using multicall batching for better performance while maintaining identical results to the original gmx-python-sdk implementation.

Initialize pool TVL data retrieval.

Parameters

config – GMXConfig instance containing chain and network info

__init__(config)

Initialize pool TVL data retrieval.

Parameters

config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

get_pool_balances()

Get pool balances using DataStore contract with multicall optimization.

This method uses multicall batching to query all pool amounts in a single RPC call, significantly improving performance compared to sequential calls.

Returns

Dictionary of total USD value per pool with structure: {

”MARKET_SYMBOL”: {

“total_tvl”: float, “long_token”: str (address), “short_token”: str (address)

}

}

Return type

Optional[dict[str, float]]

generate_all_multicalls(markets)

Generate all multicall requests for all markets.

Parameters

markets (dict) – Dictionary of available markets

Returns

Iterable of all EncodedCall objects needed

Return type

Iterable[eth_defi.event_reader.multicall_batcher.EncodedCall]

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class GlvStats

Bases: eth_defi.gmx.core.get_data.GetData

GMX GLV statistics data retrieval with multicall optimization.

Retrieves GLV information including prices and composition using multicall batching for better performance.

Initialize GLV stats data retrieval.

Parameters
  • config – GMXConfig instance containing chain and network info

  • filter_swap_markets – Whether to filter out swap markets from results

__init__(config, filter_swap_markets=True)

Initialize GLV stats data retrieval.

Parameters
  • config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

  • filter_swap_markets (bool) – Whether to filter out swap markets from results

property glv_reader_contract

GLV Reader contract instance for GLV data queries.

get_glv_stats()

Get GLV statistics using multicall optimization.

Returns

Dictionary containing GLV statistics

Return type

dict[str, float]

get_glv_stats_multicall()

Get GLV statistics data using multicall optimization.

This method uses multicall batching to query all GLV data in fewer RPC calls, significantly improving performance.

Returns

Dictionary containing GLV statistics

Return type

dict[str, Any]

generate_all_multicalls(glv_info_dict)

Generate all multicall requests for GLV statistics.

For each GLV, we need: - getGlvTokenPrice() call - balanceOf() calls for each market composition - getMarketTokenPrice() calls for each market (GM prices)

Parameters

glv_info_dict (dict) – Dictionary of GLV information

Returns

Tuple of (encoded_calls, call_metadata)

Return type

tuple[list[eth_defi.event_reader.multicall_batcher.EncodedCall], dict]

create_glv_token_price_call(glv_address, market_addresses, index_token_prices, long_token_price, short_token_price)

Create multicall for GLV token price.

Parameters
  • glv_address (str) –

  • market_addresses (list) –

  • index_token_prices (list) –

  • long_token_price (tuple) –

  • short_token_price (tuple) –

Return type

Optional[eth_defi.event_reader.multicall_batcher.EncodedCall]

create_balance_of_call(glv_address, market_address)

Create multicall for ERC20 balanceOf.

Parameters
  • glv_address (str) –

  • market_address (str) –

Return type

Optional[eth_defi.event_reader.multicall_batcher.EncodedCall]

create_gm_price_call(glv_address, market_address)

Create multicall for GM token price.

Parameters
  • glv_address (str) –

  • market_address (str) –

Return type

Optional[eth_defi.event_reader.multicall_batcher.EncodedCall]

process_multicall_results(glv_info_dict, multicall_results, call_metadata)

Process multicall results and build final GLV statistics.

Parameters
  • glv_info_dict (dict) – Original GLV information

  • multicall_results (dict) – Results from multicall execution

  • call_metadata (dict) – Metadata for processing calls

Returns

Complete GLV statistics dictionary

Return type

dict[str, Any]

extract_glv_price(results)

Extract GLV price from multicall results.

Parameters

results (dict) –

Return type

float

extract_balance(results, market_address)

Extract balance from multicall results.

Parameters
  • results (dict) –

  • market_address (str) –

Return type

float

extract_gm_price(results, market_address)

Extract GM price from multicall results.

Parameters
  • results (dict) –

  • market_address (str) –

Return type

float

property datastore_contract

DataStore contract instance for blockchain data access.

property datastore_contract_address: eth_typing.evm.HexAddress

DataStore contract address.

get_data(to_json=False, to_csv=False)

Get data using the specific implementation and optionally export it.

Parameters
  • to_json (bool) – Whether to save data to JSON file

  • to_csv (bool) – Whether to save data to CSV file

Returns

Dictionary containing processed data

Return type

dict[str, Any]

property markets: eth_defi.gmx.core.markets.Markets

Markets instance for retrieving market information.

property reader_contract

Reader contract instance for data queries.

class LiquidityInfo

Bases: object

Liquidity information for a specific GMX market.

market_address: eth_typing.evm.HexAddress

GMX market contract address

market_symbol: str

Market symbol identifier

long_liquidity: float

Available liquidity for long positions in USD

short_liquidity: float

Available liquidity for short positions in USD

total_liquidity: float

Total available liquidity in USD

long_token_address: eth_typing.evm.HexAddress

Address of the long token

short_token_address: eth_typing.evm.HexAddress

Address of the short token

__init__(market_address, market_symbol, long_liquidity, short_liquidity, total_liquidity, long_token_address, short_token_address)
Parameters
Return type

None

class MarketDepthInfo

Bases: object

Market depth snapshot for a single GMX v2 perpetual market.

Populated from the /markets/info REST endpoint (cached 60 s). All USD values are already divided by 10^30 (the GMX fixed-point precision) and expressed as plain floats.

Pool amounts (long_pool_amount, short_pool_amount) are kept in raw token units as returned by the API, because the conversion to USD requires per-token decimal information.

market_token_address: eth_typing.evm.HexAddress

GMX market token address (identifies the GM liquidity pool)

market_symbol: str

Human-readable market name, e.g. "ETH/USD [WETH-USDC]"

index_token_address: eth_typing.evm.HexAddress

Address of the index token (the asset being traded)

long_token_address: eth_typing.evm.HexAddress

Address of the long collateral token

short_token_address: eth_typing.evm.HexAddress

Address of the short collateral token (usually USDC)

long_open_interest_usd: float

Current long open interest in USD

short_open_interest_usd: float

Current short open interest in USD

max_long_open_interest_usd: float

Maximum long OI the pool can accept before hitting the reserve cap (USD). Computed as long_open_interest_usd + available_long_oi_usd.

max_short_open_interest_usd: float

Maximum short OI the pool can accept before hitting the reserve cap (USD). Computed as short_open_interest_usd + available_short_oi_usd.

available_long_oi_usd: float

Remaining long OI capacity in USD. This is the USD amount of new long positions the pool can absorb.

available_short_oi_usd: float

Remaining short OI capacity in USD. This is the USD amount of new short positions the pool can absorb.

long_pool_amount: float

Long pool token amount (raw token units as returned by the API)

short_pool_amount: float

Short pool token amount (raw token units as returned by the API)

long_funding_rate: float

Long funding rate, annualised (REST fundingRateLong / 10^30). Positive means longs receive funding; negative means longs pay. Multiply by 100 for annual percentage.

short_funding_rate: float

Short funding rate, annualised (REST fundingRateShort / 10^30). Positive means shorts receive funding; negative means shorts pay. Multiply by 100 for annual percentage.

long_borrowing_rate: float

Long borrowing rate, annualised (REST borrowingRateLong / 10^30). Always non-negative. Multiply by 100 for annual percentage.

short_borrowing_rate: float

Short borrowing rate, annualised (REST borrowingRateShort / 10^30). Always non-negative. Multiply by 100 for annual percentage.

is_listed: bool

Whether this market is currently listed for trading

__init__(market_token_address, market_symbol, index_token_address, long_token_address, short_token_address, long_open_interest_usd, short_open_interest_usd, max_long_open_interest_usd, max_short_open_interest_usd, available_long_oi_usd, available_short_oi_usd, long_pool_amount, short_pool_amount, long_funding_rate, short_funding_rate, long_borrowing_rate, short_borrowing_rate, is_listed)
Parameters
Return type

None

class Markets

Bases: object

GMX markets data provider.

This class retrieves information about all trading markets available on GMX, replacing the gmx_python_sdk Markets class functionality.

Initialise markets data provider.

Parameters

config – GMXConfig instance containing chain and network info

__init__(config)

Initialise markets data provider.

Parameters

config (eth_defi.gmx.config.GMXConfig) – GMXConfig instance containing chain and network info

get_available_markets()

Get the available markets on a given chain.

Returns

Dictionary of the available markets

Return type

dict

get_index_token_address(market_key)

Get index token address for a market.

Parameters

market_key (str) – Market contract address

Returns

Index token address

Return type

HexAddress

get_long_token_address(market_key)

Get long token address for a market.

Parameters

market_key (str) – Market contract address

Returns

Long token address

Return type

HexAddress

get_short_token_address(market_key)

Get short token address for a market.

Parameters

market_key (str) – Market contract address

Returns

Short token address

Return type

HexAddress

get_market_symbol(market_key)

Get market symbol for a market.

Parameters

market_key (str) – Market contract address

Returns

Market symbol

Return type

str

get_decimal_factor(market_key, long=False, short=False)

Get decimal factor for a market token.

Parameters
  • market_key (str) – Market contract address

  • long (bool) – Get decimals for long token

  • short (bool) – Get decimals for short token

Returns

Token decimal factor

Return type

int

is_synthetic(market_key)

Check if a market is synthetic.

Parameters

market_key (str) – Market contract address

Returns

True if market is synthetic, False otherwise

Return type

bool

get_market_info(market_address)

Get detailed information for a specific market.

Parameters

market_address (HexAddress) – Market contract address

Returns

Market information or None if not found

Return type

Optional[MarketInfo]

is_market_disabled(market_address)

Check if a market is disabled.

Parameters

market_address (HexAddress) – Market contract address

Returns

True if market is disabled, False otherwise

Return type

bool

class OpenInterestInfo

Bases: object

Open interest information for a specific GMX market.

market_address: eth_typing.evm.HexAddress

GMX market contract address

market_symbol: str

Market symbol identifier

long_open_interest: float

Long open interest in USD

short_open_interest: float

Short open interest in USD

total_open_interest: float

Total open interest in USD

long_token_address: eth_typing.evm.HexAddress

Address of the long token

short_token_address: eth_typing.evm.HexAddress

Address of the short token

__init__(market_address, market_symbol, long_open_interest, short_open_interest, total_open_interest, long_token_address, short_token_address)
Parameters
Return type

None

class OraclePrices

Bases: object

GMX Oracle Prices API client.

Provides access to GMX protocol oracle price feeds across supported networks. Handles API requests with retry logic and exponential backoff.

Parameters

chain – Blockchain network name (e.g., ‘arbitrum’, ‘avalanche’)

Raises

ValueError – If unsupported chain is provided

__init__(chain)
Parameters

chain (str) –

Return type

None

get_recent_prices(use_cache=True, cache_ttl=None)

Get raw output of the GMX rest v2 api for signed prices.

Uses module-level caching with TTL to avoid repeated API calls. Oracle prices change frequently but not every second, so short-term caching (10s default) provides significant performance improvement.

Parameters
  • use_cache (bool) – Whether to use cached values. Default is True.

  • cache_ttl (float) – Cache TTL in seconds. If None, uses module default (10s).

Returns

Dictionary containing raw output for each token as its keys

Return type

dict[str, float]

get_price_for_token(token_address, use_cache=True)

Get oracle price for a specific token, handling testnet address translation.

This is the recommended method for getting token prices as it automatically handles testnet-to-mainnet address mapping.

Parameters
Returns

Price data dict or None if not found

Return type

dict | None

class PriceImpactParams

Bases: object

Per-market price impact parameters read from the GMX DataStore contract.

All factor and exponent values use GMX’s 30-decimal fixed-point format (integers). Pass them directly to estimate_position_price_impact().

positive_factor: int

Impact factor for positive (balance-improving) trades (30-decimal int)

negative_factor: int

Impact factor for negative (balance-worsening) trades (30-decimal int)

positive_exponent: int

Exponent factor for positive impact (30-decimal int)

negative_exponent: int

Exponent factor for negative impact (30-decimal int)

max_positive_factor: int

Maximum position impact factor cap for positive impact (30-decimal int). 0 means no explicit cap applies.

max_negative_factor: int

Maximum position impact factor cap for negative impact (30-decimal int). 0 means no explicit cap applies.

__init__(positive_factor, negative_factor, positive_exponent, negative_exponent, max_positive_factor, max_negative_factor)
Parameters
  • positive_factor (int) –

  • negative_factor (int) –

  • positive_exponent (int) –

  • negative_exponent (int) –

  • max_positive_factor (int) –

  • max_negative_factor (int) –

Return type

None

calculate_liquidation_price(datastore_obj, market_info, market_address, index_token_address, size_in_usd, size_in_tokens, collateral_amount, collateral_usd, collateral_token_address, pending_funding_fees_usd, pending_borrowing_fees_usd, min_collateral_usd, is_long, chain='arbitrum', use_max_price_impact=True, user_referral_info=None)

Calculate liquidation price for a GMX V2 position.

This implementation matches the official GMX TypeScript SDK logic, including all fees, price impacts, and edge cases.

Args:

datastore_obj: GMX datastore contract instance market_info: Market information dictionary from Markets.get_available_markets() market_address: Market contract address index_token_address: Index token address (e.g., WETH for ETH/USD market) size_in_usd: Position size in USD (30 decimals) size_in_tokens: Position size in tokens (token decimals) collateral_amount: Collateral amount in token units collateral_usd: Collateral value in USD (30 decimals) collateral_token_address: Collateral token address pending_funding_fees_usd: Pending funding fees in USD (30 decimals) pending_borrowing_fees_usd: Pending borrowing fees in USD (30 decimals) min_collateral_usd: Minimum collateral requirement in USD (30 decimals) is_long: True for long position, False for short chain: Chain name (arbitrum, avalanche, etc.) use_max_price_impact: If True, use maximum negative price impact user_referral_info: Optional referral information

Returns:

Liquidation price in token’s native decimals, or None if calculation impossible

Parameters
Return type

Optional[decimal.Decimal]

estimate_position_price_impact(long_open_interest_usd, short_open_interest_usd, size_delta_usd, is_long, params)

Estimate price impact for a position using the GMX v2 formula.

This is a pure-Python implementation – no RPC calls are needed. Pass PriceImpactParams obtained via fetch_price_impact_params().

The GMX price impact formula from PricingUtils.sol (called by PositionPricingUtils.sol):

applyImpactFactor(diffUsd) = diffUsd ^ exponent * factor
impact = applyImpactFactor(initialDiff) - applyImpactFactor(nextDiff)

where initialDiff and nextDiff are the absolute OI imbalances before and after the trade respectively.

Note

Virtual inventory (cross-market impact) is not modelled here, matching the behaviour of the existing _estimate_price_impact helper in eth_defi.gmx.order.base_order.

Parameters
  • long_open_interest_usd (float) – Current long open interest in USD

  • short_open_interest_usd (float) – Current short open interest in USD

  • size_delta_usd (float) – Position size to open in USD (must be positive)

  • is_long (bool) – True for a long position, False for short

  • params (eth_defi.gmx.market_depth.PriceImpactParams) – Price impact parameters fetched from the DataStore contract

Returns

Price impact in USD. Negative values are a cost to the trader (execution price worsens). Positive values are a rebate.

Return type

float

fetch_price_impact_params(config, market_address)

Fetch price impact parameters from the GMX DataStore contract.

Reads the six per-market parameters needed by estimate_position_price_impact() via individual getUint calls on the DataStore contract.

Parameters
Returns

Populated PriceImpactParams

Return type

eth_defi.gmx.market_depth.PriceImpactParams

find_max_position_size(long_open_interest_usd, short_open_interest_usd, is_long, max_price_impact_bps, params, max_oi_available_usd=0.0, search_precision_usd=100.0)

Find the maximum position size that keeps price impact within a threshold.

Uses binary search over the price impact curve, which is monotonically increasing with position size for balance-worsening trades.

Parameters
  • long_open_interest_usd (float) – Current long open interest in USD

  • short_open_interest_usd (float) – Current short open interest in USD

  • is_long (bool) – True for a long position, False for short

  • max_price_impact_bps (float) – Maximum acceptable price impact expressed in basis points (1 bps = 0.01 %). E.g. 5.0 means 5 bps = 0.05 %.

  • params (eth_defi.gmx.market_depth.PriceImpactParams) – Price impact parameters from fetch_price_impact_params()

  • max_oi_available_usd (float) – Upper bound for the search in USD. If 0 (the default), falls back to GMX_DEFAULT_SEARCH_MAX_USD ($100 M), which covers typical GMX market sizes. Use MarketDepthInfo.available_long_oi_usd or MarketDepthInfo.available_short_oi_usd here for accuracy.

  • search_precision_usd (float) – The binary search halts when the range is narrower than this value (USD). Default 100.0 (i.e., $100 precision).

Returns

Maximum position size in USD at which the absolute price impact stays at or below max_price_impact_bps basis points. Returns 0.0 if even the smallest position exceeds the threshold.

Return type

float

get_liquidation_price(config, position_dict, wallet_address=None)

Get liquidation price for a GMX position.

High-level convenience function that fetches all required data and calculates the liquidation price for a position.

Args:

config: GMXConfig instance position_dict: Position dictionary from get_positions() wallet_address: Wallet address (optional, uses config if not provided)

Returns:

Liquidation price as float, or None if calculation not possible

Example:

from eth_defi.gmx.config import GMXConfig from eth_defi.gmx.utils import get_positions from eth_defi.gmx.core.liquidation import get_liquidation_price

config = GMXConfig(web3, user_wallet_address=”0x…”) positions = get_positions(config)

if “ETH_long” in positions:

liq_price = get_liquidation_price(config, positions[“ETH_long”]) print(f”ETH long liquidation price: ${liq_price:.2f}”)

Parameters
Return type

Optional[float]

parse_market_depth(market_data)

Parse a single market entry from the /markets/info REST response.

Parameters

market_data (dict[str, Any]) – Raw market dictionary as returned inside response["markets"].

Returns

Structured MarketDepthInfo for this market.

Return type

eth_defi.gmx.market_depth.MarketDepthInfo

Modules

eth_defi.gmx.core.available_liquidity

GMX Available Liquidity Data Retrieval Module.

eth_defi.gmx.core.borrow_apr

GMX Borrow APR Data Retrieval Module.

eth_defi.gmx.core.claimable_fees

GMX Claimable Fees Data Retrieval Module.

eth_defi.gmx.core.funding_fee

GMX Funding APR Data Retrieval Module.

eth_defi.gmx.core.get_data

GMX Data Retrieval Base Class.

eth_defi.gmx.core.glv_stats

GMX GLV Stats Data Retrieval Module.

eth_defi.gmx.core.gm_prices

GMX GM Prices Data Module.

eth_defi.gmx.core.liquidation

GMX V2 Liquidation Price Calculation.

eth_defi.gmx.core.markets

GMX Markets Data Module

eth_defi.gmx.core.open_interest

GMX Open Interest Data Retrieval Module

eth_defi.gmx.core.open_positions

GMX Open Positions Data Module.

eth_defi.gmx.core.oracle

GMX Oracle Price Data Module.

eth_defi.gmx.core.pool_tvl

GMX Pool TVL Data Retrieval Module