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.GetDataGMX 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
- 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
- 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
- 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.
- 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.GetDataGMX 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.
- 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.GetDataGMX 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
- get_per_market_claimable_fees()
Get detailed claimable fees data for each market.
- Returns
Dictionary of market symbol to fee details
- Return type
- generate_all_multicalls(markets)
Generate all multicall requests for all markets.
- Parameters
- 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.
- 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.GetDataGMX 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.
- 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.ABCBase 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
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.
- class GetGMPrices
Bases:
eth_defi.gmx.core.get_data.GetDataGM 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.
- 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.
- 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.
- 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.
- 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.
- 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.GetDataGMX 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
Initialize open interest data retrieval.
- Parameters
- __init__(config, filter_swap_markets=True)
Initialize open interest data retrieval.
- 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.
- 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.GetDataOpen 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.
- get_chain_tokens()
Get chain token information - for backward compatibility with tests.
- Returns
Dictionary mapping token addresses to their information
- Return type
- 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.GetDataGMX 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.
- 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.
- 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.GetDataGMX 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.
- 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.
- 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.
- create_balance_of_call(glv_address, market_address)
Create multicall for ERC20 balanceOf.
- Parameters
- 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
- 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.
- extract_glv_price(results)
Extract GLV price from multicall results.
- extract_balance(results, market_address)
Extract balance from multicall results.
- extract_gm_price(results, market_address)
Extract GM price from multicall 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.
- 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:
objectLiquidity information for a specific GMX market.
- market_address: eth_typing.evm.HexAddress
GMX market contract address
- 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
market_address (eth_typing.evm.HexAddress) –
market_symbol (str) –
long_liquidity (float) –
short_liquidity (float) –
total_liquidity (float) –
long_token_address (eth_typing.evm.HexAddress) –
short_token_address (eth_typing.evm.HexAddress) –
- Return type
None
- class MarketDepthInfo
Bases:
objectMarket depth snapshot for a single GMX v2 perpetual market.
Populated from the
/markets/infoREST endpoint (cached 60 s). All USD values are already divided by10^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)
- 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)
- 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_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.
- __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
market_token_address (eth_typing.evm.HexAddress) –
market_symbol (str) –
index_token_address (eth_typing.evm.HexAddress) –
long_token_address (eth_typing.evm.HexAddress) –
short_token_address (eth_typing.evm.HexAddress) –
long_open_interest_usd (float) –
short_open_interest_usd (float) –
max_long_open_interest_usd (float) –
max_short_open_interest_usd (float) –
available_long_oi_usd (float) –
available_short_oi_usd (float) –
long_pool_amount (float) –
short_pool_amount (float) –
long_funding_rate (float) –
short_funding_rate (float) –
long_borrowing_rate (float) –
short_borrowing_rate (float) –
is_listed (bool) –
- Return type
None
- class Markets
Bases:
objectGMX 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
- 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.
- get_decimal_factor(market_key, long=False, short=False)
Get decimal factor for a market token.
- is_synthetic(market_key)
Check if a market is synthetic.
- 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]
- class OpenInterestInfo
Bases:
objectOpen interest information for a specific GMX market.
- market_address: eth_typing.evm.HexAddress
GMX market contract address
- 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
market_address (eth_typing.evm.HexAddress) –
market_symbol (str) –
long_open_interest (float) –
short_open_interest (float) –
total_open_interest (float) –
long_token_address (eth_typing.evm.HexAddress) –
short_token_address (eth_typing.evm.HexAddress) –
- Return type
None
- class OraclePrices
Bases:
objectGMX 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
- 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.
- 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
token_address (eth_typing.evm.HexAddress) – Token address (testnet or mainnet)
use_cache (bool) – Whether to use cached oracle prices
- Returns
Price data dict or None if not found
- Return type
dict | None
- class PriceImpactParams
Bases:
objectPer-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().- max_positive_factor: int
Maximum position impact factor cap for positive impact (30-decimal int).
0means no explicit cap applies.
- max_negative_factor: int
Maximum position impact factor cap for negative impact (30-decimal int).
0means no explicit cap applies.
- __init__(positive_factor, negative_factor, positive_exponent, negative_exponent, max_positive_factor, max_negative_factor)
- 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
market_info (dict) –
market_address (str) –
index_token_address (str) –
size_in_usd (decimal.Decimal) –
size_in_tokens (decimal.Decimal) –
collateral_amount (decimal.Decimal) –
collateral_usd (decimal.Decimal) –
collateral_token_address (str) –
pending_funding_fees_usd (decimal.Decimal) –
pending_borrowing_fees_usd (decimal.Decimal) –
min_collateral_usd (decimal.Decimal) –
is_long (bool) –
chain (str) –
use_max_price_impact (bool) –
user_referral_info (dict) –
- Return type
- 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
PriceImpactParamsobtained viafetch_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
initialDiffandnextDiffare 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_impacthelper ineth_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) –
Truefor a long position,Falsefor shortparams (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
- 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 individualgetUintcalls on the DataStore contract.- Parameters
config (eth_defi.gmx.config.GMXConfig) – Initialised GMX configuration with web3 connection
market_address (eth_typing.evm.HexAddress) – GMX market token address (
MarketDepthInfo.market_token_address)
- Returns
Populated
PriceImpactParams- Return type
- 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) –
Truefor a long position,Falsefor shortmax_price_impact_bps (float) – Maximum acceptable price impact expressed in basis points (1 bps = 0.01 %). E.g.
5.0means 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 toGMX_DEFAULT_SEARCH_MAX_USD($100 M), which covers typical GMX market sizes. UseMarketDepthInfo.available_long_oi_usdorMarketDepthInfo.available_short_oi_usdhere 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_bpsbasis points. Returns0.0if even the smallest position exceeds the threshold.- Return type
- 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}”)
- parse_market_depth(market_data)
Parse a single market entry from the
/markets/infoREST response.- Parameters
market_data (dict[str, Any]) – Raw market dictionary as returned inside
response["markets"].- Returns
Structured
MarketDepthInfofor this market.- Return type
Modules
|
GMX Available Liquidity Data Retrieval Module. |
|
GMX Borrow APR Data Retrieval Module. |
|
GMX Claimable Fees Data Retrieval Module. |
|
GMX Funding APR Data Retrieval Module. |
|
GMX Data Retrieval Base Class. |
|
GMX GLV Stats Data Retrieval Module. |
|
GMX GM Prices Data Module. |
|
GMX V2 Liquidation Price Calculation. |
|
GMX Markets Data Module |
|
GMX Open Interest Data Retrieval Module |
|
GMX Open Positions Data Module. |
|
GMX Oracle Price Data Module. |
|
GMX Pool TVL Data Retrieval Module |