gmx.utils
Documentation for eth_defi.gmx.utils Python module.
GMX Utilities Module.
This module provides the essential utility functions and computational foundations that power the GMX integration system. It implements the mathematical calculations, data transformations, and helper operations that form the backbone of all higher-level trading, position management, and risk assessment functionality.
Utility Layer Architecture
Professional trading systems are built on layers of abstraction, where sophisticated user interfaces depend on robust utility layers that handle the complex mathematics and data processing behind the scenes. This module represents that crucial foundation layer, implementing the precise calculations and transformations needed for safe and accurate trading operations.
Key Computational Categories
Financial Mathematics: Precise liquidation price calculations and risk metrics
Data Transformation: Converting between different data formats and representations
Position Analysis: Extracting meaningful insights from complex position data
Parameter Validation: Ensuring data integrity and operational safety
Error Handling: Graceful handling of edge cases and exceptional conditions
Mathematical Precision Philosophy
Financial calculations require absolute precision because small errors can compound into significant financial losses. The utility functions implement robust mathematical operations using appropriate data types and validation to ensure accuracy across all supported market conditions and position sizes.
Integration with Trading Operations
These utilities serve as the computational engine for all higher-level operations. When you open a position through the trading interface, liquidation calculations happen here. When you analyze your portfolio through the market data interface, position formatting occurs here. Understanding these utilities helps you understand how the entire system works at its core.
Error Prevention and Validation
The utility layer implements comprehensive validation and error handling to prevent invalid operations from propagating through the system. This defensive programming approach ensures that errors are caught early and reported clearly, preventing costly mistakes during live trading operations.
Example:
# Mathematical risk analysis workflow
from eth_defi.gmx.config import GMXConfig
from eth_defi.gmx.utils import (
calculate_estimated_liquidation_price,
format_position_for_display,
get_positions,
)
# Set up configuration for analysis
config = GMXConfig.from_private_key(web3, "0x...", "arbitrum")
# Retrieve and analyze current positions
positions = get_positions(config.get_config())
for position_key, position_data in positions.items():
# Format position for human-readable analysis
display_info = format_position_for_display(position_data)
# Calculate liquidation risk
liq_price = calculate_estimated_liquidation_price(
entry_price=position_data["entry_price"],
collateral_usd=position_data["collateral_usd"],
size_usd=position_data["size_usd"],
is_long=position_data["is_long"],
maintenance_margin=0.01, # 1% maintenance margin
)
# Risk assessment analysis
current_price = position_data["mark_price"]
risk_distance = abs(current_price - liq_price) / current_price
print(f"Position: {display_info['market']} {display_info['direction']}")
print(f"Liquidation Price: ${liq_price:.2f}")
print(f"Risk Distance: {risk_distance:.1%}")
# Transform position for strategic closure if high risk
if risk_distance < 0.10: # Less than 10% safety margin
close_params = transform_open_position_to_order_parameters(
config=config.get_config(),
positions=positions,
market_symbol=display_info["market"],
is_long=position_data["is_long"],
slippage_percent=0.02, # Higher slippage for urgent closure
out_token="USDC", # Convert to stable asset
amount_of_position_to_close=0.5, # Reduce risk by 50%
amount_of_collateral_to_remove=0.2, # Free some capital
)
Design Philosophy
Functions
|
Calculate liquidation price matching GMX V2 SDK implementation. |
|
Convert GMX raw price to human-readable USD. |
|
Convert USD price to GMX raw format. |
|
Determine the optimal swap route through available GMX markets. |
|
Find a dictionary within a nested structure by key-value pair. |
|
Transform raw position data into human-readable format for analysis and display. |
|
Map testnet address to oracle address if on testnet |
|
Retrieve comprehensive position data with intelligent address resolution and error handling. |
Transform existing position data into precise order parameters for strategic position closure. |
- convert_raw_price_to_usd(raw_price, token_decimals)
Convert GMX raw price to human-readable USD.
- GMX stores prices in 30-decimal PRECISION format. The conversion formula is:
price_usd = raw_price / 10^(30 - token_decimals)
- Examples:
BTC (8 decimals): raw / 10^22
ETH (18 decimals): raw / 10^12
USDC (6 decimals): raw / 10^24
- convert_usd_to_raw_price(price_usd, token_decimals)
Convert USD price to GMX raw format.
Inverse of convert_raw_price_to_usd.
- format_position_for_display(position)
Transform raw position data into human-readable format for analysis and display.
This function serves as a crucial bridge between the complex internal data structures used by the GMX protocol and the simplified, meaningful information that traders need for decision-making. It extracts the essential metrics from technical position data and presents them in an intuitive format.
Data Transformation Philosophy:
Raw position data from blockchain protocols contains extensive technical information including contract addresses, encoded values, and implementation details that are necessary for system operation but overwhelming for human analysis. This function implements intelligent filtering and formatting to present only the information needed for trading decisions.
Essential Trading Metrics:
The formatted output focuses on the core metrics that professional traders use for position analysis: market identification, position direction, size measurements, leverage calculations, entry and current pricing, and profit/loss performance. These metrics enable quick assessment of position health and strategic planning.
Integration with Analysis Workflows:
The standardized output format integrates seamlessly with portfolio analysis tools, risk management systems, and reporting dashboards. By providing consistent data formatting, it enables reliable automation of position monitoring and strategic decision-making processes.
- Parameters
position (dict[str, Any]) – Raw position data dictionary containing all technical position information as returned from GMX protocol queries, including internal identifiers, encoded values, and comprehensive position state
- Returns
Formatted dictionary containing human-readable position information with standardized keys and simplified values optimized for analysis and display in trading interfaces
- Return type
- calculate_estimated_liquidation_price(entry_price, collateral_usd, size_usd, is_long, maintenance_margin=0.01, pending_funding_fees_usd=0.0, pending_borrowing_fees_usd=0.0, include_closing_fee=True, collateral_is_index_token=False, collateral_amount=None)
Calculate liquidation price matching GMX V2 SDK implementation.
This function implements the exact liquidation price calculation from the official GMX TypeScript SDK, accounting for fees, leverage, maintenance margin, and whether collateral token matches the index token.
How GMX Liquidation Works:
GMX liquidates positions when remaining collateral after fees falls below the minimum collateral requirement. The calculation must account for: - Pending funding fees (can be positive or negative) - Pending borrowing fees (always reduces collateral) - Position closing fees (~0.1% of position size) - Maintenance margin requirement (~0.5% of position size, min $5)
Accurate vs Approximate Mode:
If collateral_is_index_token and collateral_amount are provided: Uses EXACT formula matching GMX SDK (recommended)
If not provided: Uses APPROXIMATE formula (simpler but ±0.5% error)
Exact Calculation Formulas:
- Same token (e.g., ETH collateral for ETH/USD position):
Long: liq_price = (size + liq_collateral + fees) / (size_tokens + collateral_tokens) Short: liq_price = (size - liq_collateral - fees) / (size_tokens - collateral_tokens)
- Different tokens (e.g., USDC collateral for ETH/USD position):
Long: liq_price = (liq_collateral - remaining_collateral + size) / size_tokens Short: liq_price = (size - liq_collateral + remaining_collateral) / size_tokens
- Approximate Formula (fallback):
liq_price = entry_price * (1 ± max_loss_ratio)
This provides quick estimates when token details are unavailable.
Example:
# Approximate mode (quick estimate) liq_price = calculate_estimated_liquidation_price( entry_price=2000.0, collateral_usd=1000.0, size_usd=5000.0, # 5x leverage is_long=True, pending_funding_fees_usd=5.0, pending_borrowing_fees_usd=10.0, ) # Result: ~$1608 (approximate, ±0.5% error) # Exact mode (matches GMX SDK) liq_price = calculate_estimated_liquidation_price( entry_price=2000.0, collateral_usd=1000.0, collateral_amount=0.5, # 0.5 ETH collateral size_usd=5000.0, is_long=True, collateral_is_index_token=True, # ETH collateral for ETH position pending_funding_fees_usd=5.0, pending_borrowing_fees_usd=10.0, ) # Result: $1681.67 (exact, matches GMX TypeScript SDK)
- Parameters
entry_price (float) – Price at which the position was opened
collateral_usd (float) – Total collateral value in USD
size_usd (float) – Total position size in USD (collateral × leverage)
is_long (bool) – True for long position, False for short position
maintenance_margin (float) – Minimum margin requirement as decimal (default 0.01 = 1%) GMX typically uses 1% for most markets
pending_funding_fees_usd (float) – Accumulated funding fees in USD (can be negative for rebates)
pending_borrowing_fees_usd (float) – Accumulated borrowing fees in USD (always positive)
include_closing_fee (bool) – If True, includes 0.1% closing fee in calculation (default: True)
collateral_is_index_token (bool) – Whether collateral token matches index token (e.g., ETH collateral for ETH/USD). Required for exact calculation. If False, assumes different token like USDC.
collateral_amount (float | None) – Amount of collateral in tokens (e.g., 0.5 for 0.5 ETH). Required for exact calculation. If None, uses approximate formula.
- Returns
Liquidation price in USD
- Return type
- Note:
For maximum accuracy, provide collateral_is_index_token and collateral_amount. Without these, the function uses an approximate formula with ±0.5% error.
- get_positions(config, address=None)
Retrieve comprehensive position data with intelligent address resolution and error handling.
This function implements robust position retrieval logic that handles multiple address sources and provides clear error handling for common failure scenarios. It serves as a reliable foundation for all position-dependent operations throughout the trading system.
Address Resolution Strategy:
The function implements intelligent fallback logic for address determination. If an explicit address is provided, it takes precedence. If no address is provided, the function attempts to use the address from the configuration. This pattern provides flexibility for multi-wallet operations while ensuring safe defaults for single-wallet workflows.
Position Data Structure:
The returned data structure uses human-readable position keys (like “ETH_long”) that make position identification intuitive for both programmatic access and manual analysis. Each position entry contains comprehensive information about size, collateral, current performance, and risk metrics.
Error Handling Philosophy:
The function implements defensive programming principles by validating address availability before attempting position queries. Clear error messages help developers understand configuration requirements and debug common setup issues.
- Parameters
config (GMXConfigManager) – GMX configuration object containing network settings and optional wallet information for position queries
address (str, optional) – Specific Ethereum address to query positions for. If None, attempts to use the address from the provided configuration object
- Returns
Dictionary containing all open positions keyed by human-readable position identifiers (e.g., “ETH_long”, “BTC_short”) with comprehensive position data as values
- Return type
- Raises
Exception – When no address is available from either parameter or configuration, making position queries impossible
- transform_open_position_to_order_parameters(config, positions, market_symbol, is_long, slippage_percent, out_token, amount_of_position_to_close, amount_of_collateral_to_remove)
Transform existing position data into precise order parameters for strategic position closure.
This function implements sophisticated data transformation logic that bridges the gap between high-level trading intentions (“close 50% of my ETH position”) and the precise technical parameters required by the GMX protocol for order execution. It handles complex address resolution, swap path calculation, and mathematical precision for financial calculations.
Data Transformation Architecture:
The transformation process involves multiple complex steps: position identification using human-readable keys, address resolution for multiple token types, swap path determination for asset conversion, and precise mathematical calculations for partial position closure. Each step includes validation to ensure data integrity and prevent execution errors.
Mathematical Precision Requirements:
Financial calculations require absolute precision to prevent rounding errors that could cause transaction failures or unexpected results. The function uses Decimal arithmetic for position size calculations and properly scales values to match protocol requirements for order parameters.
Swap Path Intelligence:
When the desired output token differs from the position’s collateral token, the function automatically determines the optimal swap path through available markets. This enables strategic asset selection upon position closure without requiring manual path configuration.
Error Prevention and Validation:
Comprehensive validation ensures that all required position data is available and properly formatted before attempting transformation. Clear error messages help identify configuration issues or missing position data that would prevent successful order creation.
Example:
# Strategic position closure with precise control positions = get_positions(config) # Close 75% of ETH long position, convert to USDC close_params = transform_open_position_to_order_parameters( config=config, positions=positions, market_symbol="ETH", is_long=True, slippage_percent=0.005, # 0.5% slippage out_token="USDC", # Convert to stable asset amount_of_position_to_close=0.75, # Close 75% of position amount_of_collateral_to_remove=0.5, # Remove 50% of collateral ) # Parameters ready for order execution order = DecreaseOrder(**close_params)
- Parameters
config (GMXConfigManager) – GMX configuration object containing network settings and token information required for address resolution and market data access
positions (dict[str, Any]) – Dictionary containing all current open positions with human-readable keys and comprehensive position data for transformation
market_symbol (str) – Symbol identifying the market containing the position to close (e.g., “ETH”, “BTC”). Must match an existing position
is_long (bool) – Direction of the position to close - True for long positions, False for short positions. Must match existing position direction
slippage_percent (float) – Maximum acceptable slippage for the closure operation as decimal (0.005 = 0.5%). Higher values enable faster execution in volatile markets but may result in worse prices
out_token (str) – Symbol of the token to receive upon position closure. May differ from collateral token, triggering automatic swap path calculation
amount_of_position_to_close (float) – Fraction of total position size to close, expressed as decimal (0.5 = 50%). Enables precise partial position management strategies
amount_of_collateral_to_remove (float) – Fraction of position collateral to withdraw, expressed as decimal. Independent of position closure amount for flexible capital management
- Returns
Dictionary containing all parameters required for order execution, formatted according to GMX protocol requirements with proper address resolution and mathematical precision
- Return type
- Raises
Exception – When the specified position cannot be found in the positions dictionary, indicating invalid market/direction combination
- find_dictionary_by_key_value(outer_dict, key, value)
Find a dictionary within a nested structure by key-value pair.
- determine_swap_route(markets, in_token, out_token, chain='arbitrum')
Determine the optimal swap route through available GMX markets.
Using the available markets, find the list of GMX markets required to swap from token in to token out.
- Parameters
- Returns
Tuple of (list of GMX markets to swap through, requires_multi_swap)
- Return type