GMXTrading

Documentation for eth_defi.gmx.trading.GMXTrading Python class.

class GMXTrading

Bases: object

Comprehensive trading execution system for GMX protocol operations.

This class implements the core trading capabilities needed for professional trading operations on the GMX protocol, providing sophisticated abstractions over complex protocol mechanics while maintaining the precision and control required for advanced trading strategies.

Trading System Philosophy:

The design follows professional trading system principles where execution quality is paramount. Every method provides comprehensive parameter control, extensive validation, and safety features. The architecture supports both manual trading workflows and algorithmic strategy implementation.

Leveraged Trading Architecture:

GMX’s leveraged trading system allows traders to open positions larger than their collateral by borrowing capital from liquidity providers. This creates sophisticated risk/reward dynamics where successful trades can generate amplified returns, but unsuccessful trades can result in rapid capital loss through liquidation.

Risk Control Philosophy:

Every trading operation includes multiple layers of risk control including slippage protection, collateral adequacy validation, leverage limits, and execution parameter verification. The system prevents common trading errors while providing the flexibility needed for sophisticated strategies.

Variables

config (GMXConfig) – GMX configuration object containing network and wallet settings

Initialize the trading system with GMX configuration and validation.

This constructor establishes the trading system with comprehensive configuration validation to ensure all necessary components are available for safe trading operations. Since trading involves financial transactions with potential for significant losses, the configuration must include transaction signing capabilities.

Parameters
  • config (GMXConfig) – Complete GMX configuration object containing network settings and wallet credentials. Must have write capability enabled as all trading operations require transaction signing and execution

  • gas_monitor_config (GasMonitorConfig | None) – Optional configuration for gas monitoring. If None, defaults are used. Set enabled=False in the config to disable gas monitoring entirely.

Raises

ValueError – When the configuration lacks transaction signing capabilities required for trading operations and position management

Attributes summary

gas_monitor

Lazy-initialise and return the gas monitor instance.

gas_monitor_config

Return the gas monitor configuration.

Methods summary

__init__(config[, gas_monitor_config])

Initialize the trading system with GMX configuration and validation.

close_position(market_symbol, ...[, ...])

Execute strategic position closure with precise size and collateral control.

create_stop_loss(market_symbol, ...[, ...])

Create a standalone Stop Loss order for an existing position.

create_take_profit(market_symbol, ...[, ...])

Create a standalone Take Profit order for an existing position.

execute_order(order_result, wallet[, check_gas])

Execute an order with gas monitoring and graceful failure handling.

open_limit_position(market_symbol, ...[, ...])

Open a limit position that triggers at specified price.

open_position(market_symbol, ...[, ...])

Execute sophisticated position opening with comprehensive risk and execution control.

open_position_with_sltp(market_symbol, ...)

Open a position with bundled Stop Loss and Take Profit orders.

swap_tokens(in_token_symbol, ...[, ...])

Execute sophisticated token swaps for portfolio management and strategy implementation.

__init__(config, gas_monitor_config=None)

Initialize the trading system with GMX configuration and validation.

This constructor establishes the trading system with comprehensive configuration validation to ensure all necessary components are available for safe trading operations. Since trading involves financial transactions with potential for significant losses, the configuration must include transaction signing capabilities.

Parameters
  • config (GMXConfig) – Complete GMX configuration object containing network settings and wallet credentials. Must have write capability enabled as all trading operations require transaction signing and execution

  • gas_monitor_config (GasMonitorConfig | None) – Optional configuration for gas monitoring. If None, defaults are used. Set enabled=False in the config to disable gas monitoring entirely.

Raises

ValueError – When the configuration lacks transaction signing capabilities required for trading operations and position management

property gas_monitor: eth_defi.gmx.gas_monitor.GMXGasMonitor

Lazy-initialise and return the gas monitor instance.

Returns

GMXGasMonitor instance for this trading session

property gas_monitor_config: eth_defi.gmx.gas_monitor.GasMonitorConfig

Return the gas monitor configuration.

Returns

Current gas monitor configuration

execute_order(order_result, wallet, check_gas=True)

Execute an order with gas monitoring and graceful failure handling.

This method provides comprehensive trade execution with: - Pre-trade gas balance checking (warning/critical thresholds) - Gas estimation with safety buffer - Logging of estimated and actual gas costs in native token and USD - Graceful handling of out-of-gas failures (returns status instead of crash)

Execution Flow:

  1. Check gas balance (if enabled) - Critical: return failed result OR raise (based on config) - Warning: log warning, continue

  2. Estimate gas with buffer, log estimate

  3. Sign and broadcast transaction

  4. On success: log actual gas usage, return success result

  5. On OutOfGas: return failed result (no crash)

  6. On other error: return failed result with error message

Example:

# Create order (existing flow)
order_result = trading.open_position(
    market_symbol="ETH",
    collateral_symbol="USDC",
    ...
)

# Execute with gas monitoring (new flow)
result = trading.execute_order(order_result, wallet)

if result.success:
    print(f"Trade executed: {result.tx_hash}")
    print(f"Gas cost: {result.gas_cost_native} ETH (~${result.gas_cost_usd})")
else:
    print(f"Trade failed: {result.reason}")
    # Handle gracefully - no crash, can retry or alert
Parameters
  • order_result (OrderResult) – OrderResult from open_position, close_position, swap_tokens, etc. Contains the unsigned transaction to execute.

  • wallet (HotWallet) – HotWallet instance for signing and broadcasting the transaction.

  • check_gas (bool) – Whether to perform gas balance check before execution. Set to False to skip balance checking (e.g., for testing).

Returns

TradeExecutionResult with comprehensive outcome information. Check result.success to determine if trade succeeded.

Return type

TradeExecutionResult

Raises

InsufficientGasError – Only if gas_monitor_config.raise_on_critical is True and balance is below critical threshold.

open_position(market_symbol, collateral_symbol, start_token_symbol, is_long, size_delta_usd, leverage, slippage_percent=0.003, **kwargs)

Execute sophisticated position opening with comprehensive risk and execution control.

This method creates leveraged trading positions on GMX with precise control over size, leverage, collateral composition, and execution parameters. It implements professional-grade position opening logic including collateral optimization, slippage protection, and execution cost management.

Leveraged Position Mechanics:

When you open a leveraged position, you’re essentially borrowing capital from GMX liquidity providers to control a position larger than your collateral. The leverage multiplier determines how much capital you control relative to your collateral. Higher leverage amplifies both potential gains and losses, requiring careful risk management.

Collateral Strategy:

The choice of collateral asset affects both your risk profile and trading costs. Using stable collateral (like USDC) provides predictable liquidation thresholds but may incur swap costs. Using the same asset as collateral and position (like ETH) minimizes swap costs but creates concentrated risk exposure.

Position Sizing and Risk Management:

Professional traders use position sizing as their primary risk management tool. The size_delta_usd parameter should be calculated based on your total portfolio size, risk tolerance, and the specific characteristics of the market you’re trading. Never risk more than you can afford to lose on any single position.

Example:

# Conservative long position with stable collateral
conservative_long = trader.open_position(
    market_symbol="ETH",
    collateral_symbol="USDC",  # Stable collateral
    start_token_symbol="USDC",  # Start with stable asset
    is_long=True,  # Bullish position
    size_delta_usd=1000,  # $1000 position
    leverage=2.0,  # Conservative 2x leverage
    slippage_percent=0.005,  # 0.5% slippage
    auto_cancel=True,  # Cancel if execution fails
)

# Aggressive position with asset collateral
aggressive_long = trader.open_position(
    market_symbol="ETH",
    collateral_symbol="ETH",  # Same asset collateral
    start_token_symbol="ETH",  # Start with ETH
    is_long=True,
    size_delta_usd=5000,  # $5000 position
    leverage=5.0,  # Aggressive 5x leverage
    slippage_percent=0.01,  # 1% slippage for speed
    execution_buffer=2.0,  # Higher execution buffer
)
Parameters
  • market_symbol (str) – Symbol identifying the market to trade (e.g., “ETH”, “BTC”). Determines which asset you’re taking directional exposure to

  • collateral_symbol (str) – Symbol of the asset to use as collateral (e.g., “USDC”, “ETH”). Affects liquidation thresholds, swap costs, and risk concentration

  • start_token_symbol (str) – Symbol of the asset you currently hold to fund the position. May require swapping to reach the desired collateral asset

  • is_long (bool) – Whether to open a long (bullish) or short (bearish) position. Long positions profit when prices rise, short positions profit when prices fall

  • size_delta_usd (float) – Total position size in USD terms. Combined with leverage, determines the actual capital exposure and potential profit/loss

  • leverage (float) – Leverage multiplier determining how much capital you control relative to your collateral. Higher leverage increases both potential returns and liquidation risk

  • slippage_percent (Optional[float]) – Maximum acceptable slippage as decimal (0.003 = 0.3%). Higher values enable faster execution in volatile markets at the cost of potentially worse prices

  • kwargs (Any) – Additional advanced parameters for execution control including auto_cancel, execution_buffer, max_fee_per_gas, and other order-specific settings

Returns

Configured increase order object ready for execution with all specified parameters and risk controls applied

Return type

IncreaseOrder

Raises

ValueError – When parameters are invalid, insufficient collateral, or leverage exceeds protocol limits for the specified market

close_position(market_symbol, collateral_symbol, start_token_symbol, is_long, size_delta_usd, initial_collateral_delta, slippage_percent=0.003, **kwargs)

Execute strategic position closure with precise size and collateral control.

This method provides sophisticated position closure capabilities with independent control over position size reduction and collateral withdrawal. It supports both full position closure and partial closure strategies that are essential for advanced risk management and profit optimization.

Position Closure Strategy:

Professional traders rarely close entire positions at once. Instead, they use partial closures to lock in profits while maintaining market exposure, reduce risk during uncertain periods, or free up collateral for new opportunities. This method provides the precision needed for these sophisticated strategies.

Collateral Management:

The independent control over collateral withdrawal allows for advanced capital management strategies. You might close 50% of a position size while withdrawing 75% of collateral to maximize capital efficiency, or close 100% of position size while leaving collateral for rapid re-entry.

Timing and Market Conditions:

Position closure timing can significantly impact profitability. The method provides slippage controls that allow traders to balance execution speed against price protection based on current market volatility and urgency of the closure requirement.

Example:

# Profit-taking strategy: Partial closure with stable output
profit_taking = trader.close_position(
    market_symbol="ETH",
    collateral_symbol="USDC",
    start_token_symbol="USDC",
    is_long=True,
    size_delta_usd=2000,  # Close $2000 of position
    initial_collateral_delta=500,  # Remove $500 collateral
    slippage_percent=0.003,  # Tight slippage for profits
    auto_cancel=True,
)

# Emergency closure: Full exit with speed priority
emergency_close = trader.close_position(
    market_symbol="BTC",
    collateral_symbol="BTC",
    start_token_symbol="BTC",
    is_long=False,
    size_delta_usd=10000,  # Close entire $10k position
    initial_collateral_delta=2000,  # Withdraw all collateral
    slippage_percent=0.02,  # Higher slippage for speed
    execution_buffer=3.0,  # Higher execution buffer
)
Parameters
  • market_symbol (str) – Symbol identifying the market containing the position to close. Must match the market where you currently have an open position

  • collateral_symbol (str) – Symbol of the collateral asset in the existing position. Must match the collateral type of the position being closed

  • start_token_symbol (str) – Symbol of the asset to receive upon position closure. May trigger asset conversion affecting final proceeds and exposure

  • is_long (bool) – Whether the existing position is long (True) or short (False). Must match the direction of the position being closed

  • size_delta_usd (float) – USD value of position size to close. Can be partial (less than total position size) or full closure. Determines exposure reduction

  • initial_collateral_delta (float) – Amount of collateral to withdraw upon closure. Independent of position size, allowing flexible capital management strategies

  • slippage_percent (Optional[float]) – Maximum acceptable slippage as decimal. Lower values provide better price protection, higher values enable faster execution in volatile conditions

  • kwargs (Any) – Additional advanced parameters for execution control including auto_cancel, execution_buffer, max_fee_per_gas, and other closure-specific settings

Returns

Configured decrease order object ready for execution with all specified closure parameters and risk controls applied

Return type

DecreaseOrder

Raises

ValueError – When parameters don’t match existing position, insufficient position size, or invalid collateral withdrawal amounts

swap_tokens(in_token_symbol, out_token_symbol, amount, position_usd=0, slippage_percent=0.02, execution_buffer=2.2, **kwargs)

Execute sophisticated token swaps for portfolio management and strategy implementation.

This method provides advanced token swapping capabilities that go beyond simple asset conversion. It supports both basic swaps for portfolio rebalancing and position-based swaps that integrate with broader trading strategies. The implementation includes sophisticated slippage management and execution optimization.

Strategic Swap Applications:

Token swaps serve multiple strategic purposes in professional trading: converting profits to stable assets, rebalancing portfolio compositions, preparing assets for new position openings, and implementing arbitrage strategies across different markets or protocols.

Slippage and Execution Management:

Swap execution quality depends heavily on market conditions and swap size relative to available liquidity. The method provides dynamic slippage controls and execution buffers that can be adjusted based on market volatility, urgency, and the specific assets being swapped.

Integration with Trading Strategies:

Swaps often form part of larger trading strategies rather than standalone operations. The method supports integration with position management workflows, enabling complex strategies that combine position adjustments with asset rebalancing in coordinated sequences.

Example:

# Portfolio rebalancing: Convert profits to stable assets
profit_conversion = trader.swap_tokens(
    in_token_symbol="ETH",
    out_token_symbol="USDC",
    amount=2.5,  # Swap 2.5 ETH
    slippage_percent=0.01,  # 1% slippage tolerance
    execution_buffer=2.0,  # Standard execution buffer
    auto_cancel=True,
)

# Strategy preparation: Convert stable assets for position opening
position_prep = trader.swap_tokens(
    in_token_symbol="USDC",
    out_token_symbol="BTC",
    amount=5000,  # Swap $5000 USDC
    slippage_percent=0.015,  # 1.5% slippage for large swap
    execution_buffer=3.0,  # Higher buffer for complex swap
    max_fee_per_gas=50000000000,  # Custom gas price
)
Parameters
  • in_token_symbol (str) – Symbol of the token to swap from (e.g., “ETH”, “USDC”). Must be an asset you currently hold in sufficient quantity for the intended swap amount

  • out_token_symbol (str) – Symbol of the token to receive from the swap (e.g., “USDC”, “BTC”). Determines your final asset exposure and liquidity characteristics after the swap completion

  • amount (float) – Quantity of the input token to swap. Must not exceed your current balance of the input token and should consider any held collateral requirements

  • position_usd (Optional[float]) – Optional USD value for position-based swaps that integrate with broader trading strategies. Set to 0 for simple asset conversion

  • slippage_percent (Optional[float]) – Maximum acceptable slippage as decimal (0.02 = 2%). Higher values enable execution in volatile conditions but may result in worse prices than expected

  • execution_buffer (float) – Multiplier for execution fee estimation to ensure successful transaction processing. Higher values reduce execution failure risk but increase transaction costs

  • kwargs (Any) – Additional advanced parameters for swap control including auto_cancel, max_fee_per_gas, and other swap-specific settings

Returns

Configured swap order object ready for execution with all specified parameters and slippage controls applied

Return type

SwapOrder

Raises

ValueError – When insufficient balance, invalid token pairs, or swap amount exceeds available liquidity in the target market

open_limit_position(market_symbol, collateral_symbol, start_token_symbol, is_long, size_delta_usd, leverage, trigger_price, slippage_percent=0.003, auto_cancel=True, **kwargs)

Open a limit position that triggers at specified price.

Creates a limit order that opens a position when the market price reaches the trigger price. Unlike market orders which execute immediately, limit orders remain pending until price conditions are met.

When to Use Limit Orders:

Limit orders are useful when you want to enter a position at a specific price level rather than the current market price. Common use cases include:

  • Buying dips: Set a trigger price below current market to buy if price drops

  • Selling rallies: Set a trigger price above current market to short if price rises

  • Range trading: Enter positions at predetermined support/resistance levels

Trigger Price Logic:

For long positions, the order triggers when the market price falls to or below the trigger price. For short positions, the order triggers when the market price rises to or above the trigger price.

Example:

# Limit long order - buy ETH if price drops to $3000
limit_long = trader.open_limit_position(
    market_symbol="ETH",
    collateral_symbol="ETH",
    start_token_symbol="ETH",
    is_long=True,
    size_delta_usd=1000,
    leverage=2.5,
    trigger_price=3000.0,  # Buy at $3000 or better
    slippage_percent=0.005,
)

# Limit short order - short ETH if price rises to $4000
limit_short = trader.open_limit_position(
    market_symbol="ETH",
    collateral_symbol="USDC",
    start_token_symbol="USDC",
    is_long=False,
    size_delta_usd=1000,
    leverage=2.0,
    trigger_price=4000.0,  # Short at $4000 or better
)
Parameters
  • market_symbol (str) – Symbol identifying the market to trade (e.g., “ETH”, “BTC”)

  • collateral_symbol (str) – Symbol of the asset to use as collateral (e.g., “USDC”, “ETH”)

  • start_token_symbol (str) – Symbol of the asset you currently hold to fund the position

  • is_long (bool) – Whether to open a long (bullish) or short (bearish) position

  • size_delta_usd (float) – Total position size in USD terms

  • leverage (float) – Leverage multiplier (e.g., 2.5 for 2.5x leverage)

  • trigger_price (float) – USD price at which the order triggers and executes

  • slippage_percent (Optional[float]) – Maximum acceptable slippage as decimal (0.003 = 0.3%)

  • auto_cancel (bool) – Whether to auto-cancel the order if it can’t execute (default True)

  • kwargs (Any) – Additional parameters including execution_buffer, max_fee_per_gas, etc.

Returns

OrderResult containing unsigned transaction ready for signing

Return type

OrderResult

Raises

ValueError – When parameters are invalid or trigger_price is not positive

open_position_with_sltp(market_symbol, collateral_symbol, start_token_symbol, is_long, size_delta_usd, leverage, stop_loss_percent=None, take_profit_percent=None, stop_loss_price=None, take_profit_price=None, slippage_percent=0.003, execution_buffer=2.5, **kwargs)

Open a position with bundled Stop Loss and Take Profit orders.

Creates a single atomic transaction that opens a position and attaches SL/TP orders. All three orders are submitted together, ensuring the protective orders are in place from the moment the position is opened.

Example:

# Open long with 5% stop loss and 10% take profit
result = trader.open_position_with_sltp(
    market_symbol="ETH",
    collateral_symbol="ETH",
    start_token_symbol="ETH",
    is_long=True,
    size_delta_usd=1000,
    leverage=2.5,
    stop_loss_percent=0.05,  # 5% below entry
    take_profit_percent=0.10,  # 10% above entry
)

# Or use absolute prices
result = trader.open_position_with_sltp(
    market_symbol="ETH",
    collateral_symbol="ETH",
    start_token_symbol="ETH",
    is_long=True,
    size_delta_usd=1000,
    leverage=2.5,
    stop_loss_price=2850.0,  # SL at $2850
    take_profit_price=3300.0,  # TP at $3300
)
Parameters
  • market_symbol (str) – Market to trade (e.g., “ETH”, “BTC”)

  • collateral_symbol (str) – Collateral asset (e.g., “ETH”, “USDC”)

  • start_token_symbol (str) – Asset you’re starting with

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

  • size_delta_usd (float) – Position size in USD

  • leverage (float) – Leverage multiplier (e.g., 2.5 for 2.5x)

  • stop_loss_percent (float | None) – SL trigger as percentage (0.05 = 5%)

  • take_profit_percent (float | None) – TP trigger as percentage (0.10 = 10%)

  • stop_loss_price (float | None) – Absolute SL trigger price in USD

  • take_profit_price (float | None) – Absolute TP trigger price in USD

  • slippage_percent (float) – Maximum slippage (default 0.3%)

  • execution_buffer (float) – Fee buffer multiplier (default 2.5)

Returns

SLTPOrderResult with bundled transaction

Return type

eth_defi.gmx.order.sltp_order.SLTPOrderResult

create_stop_loss(market_symbol, collateral_symbol, is_long, position_size_usd, entry_price, stop_loss_percent=None, stop_loss_price=None, close_percent=1.0, slippage_percent=0.003, execution_buffer=2.5, **kwargs)

Create a standalone Stop Loss order for an existing position.

The SL order will trigger when price moves against your position by the specified amount, limiting potential losses.

Example:

# Create SL 5% below entry for a long position
sl_result = trader.create_stop_loss(
    market_symbol="ETH",
    collateral_symbol="ETH",
    is_long=True,
    position_size_usd=1000,
    entry_price=3000.0,
    stop_loss_percent=0.05,  # Triggers at $2850
)

# Or use absolute price
sl_result = trader.create_stop_loss(
    market_symbol="ETH",
    collateral_symbol="ETH",
    is_long=True,
    position_size_usd=1000,
    entry_price=3000.0,
    stop_loss_price=2850.0,
)
Parameters
  • market_symbol (str) – Market of the position (e.g., “ETH”)

  • collateral_symbol (str) – Collateral asset of the position

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

  • position_size_usd (float) – Total position size in USD

  • entry_price (float) – Position entry price in USD

  • stop_loss_percent (float | None) – SL as percentage from entry (0.05 = 5%)

  • stop_loss_price (float | None) – Absolute SL price in USD

  • close_percent (float) – Fraction of position to close (1.0 = 100%)

  • slippage_percent (float) – Maximum slippage

  • execution_buffer (float) – Fee buffer multiplier

Returns

OrderResult with stop loss transaction

Return type

eth_defi.gmx.order.base_order.OrderResult

create_take_profit(market_symbol, collateral_symbol, is_long, position_size_usd, entry_price, take_profit_percent=None, take_profit_price=None, close_percent=1.0, slippage_percent=0.003, execution_buffer=2.5, **kwargs)

Create a standalone Take Profit order for an existing position.

The TP order will trigger when price moves in your favor by the specified amount, locking in profits.

Example:

# Create TP 10% above entry for a long position
tp_result = trader.create_take_profit(
    market_symbol="ETH",
    collateral_symbol="ETH",
    is_long=True,
    position_size_usd=1000,
    entry_price=3000.0,
    take_profit_percent=0.10,  # Triggers at $3300
)

# Scale out: close 50% at TP
tp_result = trader.create_take_profit(
    market_symbol="ETH",
    collateral_symbol="ETH",
    is_long=True,
    position_size_usd=1000,
    entry_price=3000.0,
    take_profit_price=3300.0,
    close_percent=0.5,  # Close 50% at TP
)
Parameters
  • market_symbol (str) – Market of the position (e.g., “ETH”)

  • collateral_symbol (str) – Collateral asset of the position

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

  • position_size_usd (float) – Total position size in USD

  • entry_price (float) – Position entry price in USD

  • take_profit_percent (float | None) – TP as percentage from entry (0.10 = 10%)

  • take_profit_price (float | None) – Absolute TP price in USD

  • close_percent (float) – Fraction of position to close (1.0 = 100%)

  • slippage_percent (float) – Maximum slippage

  • execution_buffer (float) – Fee buffer multiplier

Returns

OrderResult with take profit transaction

Return type

eth_defi.gmx.order.base_order.OrderResult