gmx.ccxt

Documentation for eth_defi.gmx.ccxt Python module.

CCXT-compatible exchange adapter for GMX protocol.

class GMX

Bases: eth_defi.ccxt.exchange_compatible.ExchangeCompatible

CCXT-compatible wrapper for GMX protocol market data and trading.

This class provides a familiar CCXT-style interface for interacting with GMX protocol, implementing synchronous methods and data structures that match CCXT conventions. This allows traders to use GMX with minimal changes to existing CCXT-based trading systems.

Market Data Methods:

  • load_markets() / fetch_markets() - Get all available markets

  • fetch_ticker(symbol) - Get current price and 24h stats for one market

  • fetch_tickers(symbols) - Get ticker data for multiple markets

  • fetch_ohlcv(symbol, timeframe) - Get candlestick/OHLCV data

  • fetch_trades(symbol, since, limit) - Get recent public trades

  • fetch_currencies() - Get token metadata (decimals, addresses)

  • fetch_time() - Get blockchain time

  • fetch_status() - Check API operational status

Open Interest & Funding:

  • fetch_open_interest(symbol) - Current open interest

  • fetch_open_interest_history(symbol, timeframe, since, limit) - Historical OI

  • fetch_open_interests(symbols) - Batch OI fetch

  • fetch_funding_rate(symbol) - Current funding rate

  • fetch_funding_rate_history(symbol, since, limit) - Historical funding

Trading Methods:

  • fetch_balance() - Get account token balances

  • fetch_open_orders(symbol) - List open positions as orders

  • fetch_my_trades(symbol, since, limit) - User trade history

  • create_order(symbol, type, side, amount, price, params) - Create and execute order (requires wallet)

  • create_market_buy_order(symbol, amount, params) - Open long position

  • create_market_sell_order(symbol, amount, params) - Open short position

  • create_limit_order(symbol, side, amount, price, params) - Create limit order (behaves as market)

Position Management:

  • fetch_positions(symbols) - Get detailed position information with metrics

  • set_leverage(leverage, symbol) - Configure leverage settings

  • fetch_leverage(symbol) - Query leverage configuration

GMX Limitations:

  • No fetch_order_book() - GMX uses liquidity pools, not order books

  • No cancel_order() - GMX orders execute immediately or revert

  • No fetch_order() - Orders execute immediately via keeper system

  • Volume data not available in OHLCV

  • 24h high/low calculated from recent OHLCV data

  • Trades derived from position change events

  • Balance “used” amount not calculated (shown as 0.0)

  • Order creation requires wallet parameter during initialization

Variables
  • config (GMXConfig) – GMX configuration object

  • api (GMXAPI) – GMX API client for market data

  • web3 (Web3) – Web3 instance for blockchain queries

  • subsquid (GMXSubsquidClient) – Subsquid GraphQL client for historical data

  • markets (Dict[str, Any]) – Dictionary of available markets (populated by load_markets)

  • timeframes (Dict[str, str]) – Supported timeframe intervals

  • markets_loaded (bool) – Flag indicating if markets have been loaded

Initialize the CCXT wrapper with GMX configuration.

Supports two initialization styles:

  1. CCXT-style (recommended):

    gmx = GMX(
        params={
            "rpcUrl": "https://arb1.arbitrum.io/rpc",
            "privateKey": "0x...",  # Optional - for trading
            "chainId": 42161,  # Optional - auto-detected from RPC
            "subsquidEndpoint": "...",  # Optional
            "wallet": wallet_object,  # Optional - alternative to privateKey
            "verbose": True,  # Optional - enable debug logging
            "requireMultipleProviders": True,  # Optional - enforce fallback support
        }
    )
    
  2. Legacy-style (backward compatible):

    gmx = GMX(config=config, wallet=wallet, subsquid_endpoint="...")
    
Parameters
  • config (GMXConfig | dict | None) – GMXConfig object (legacy) or parameters dict (if passed as first arg)

  • params (dict | None) – CCXT-style parameters dictionary

  • subsquid_endpoint (str | None) – Optional Subsquid GraphQL endpoint URL (legacy only)

  • wallet (HotWallet | None) – HotWallet for transaction signing (legacy only)

  • price_sanity_config (PriceSanityCheckConfig | None) – Configuration for price sanity checks (optional)

__init__(config=None, params=None, subsquid_endpoint=None, wallet=None, price_sanity_config=None, **kwargs)

Initialize the CCXT wrapper with GMX configuration.

Supports two initialization styles:

  1. CCXT-style (recommended):

    gmx = GMX(
        params={
            "rpcUrl": "https://arb1.arbitrum.io/rpc",
            "privateKey": "0x...",  # Optional - for trading
            "chainId": 42161,  # Optional - auto-detected from RPC
            "subsquidEndpoint": "...",  # Optional
            "wallet": wallet_object,  # Optional - alternative to privateKey
            "verbose": True,  # Optional - enable debug logging
            "requireMultipleProviders": True,  # Optional - enforce fallback support
        }
    )
    
  2. Legacy-style (backward compatible):

    gmx = GMX(config=config, wallet=wallet, subsquid_endpoint="...")
    
Parameters
  • config (GMXConfig | dict | None) – GMXConfig object (legacy) or parameters dict (if passed as first arg)

  • params (dict | None) – CCXT-style parameters dictionary

  • subsquid_endpoint (str | None) – Optional Subsquid GraphQL endpoint URL (legacy only)

  • wallet (HotWallet | None) – HotWallet for transaction signing (legacy only)

  • price_sanity_config (PriceSanityCheckConfig | None) – Configuration for price sanity checks (optional)

property oracle_prices: eth_defi.gmx.core.oracle.OraclePrices

Oracle prices instance for retrieving current prices.

Uses lazy initialization pattern for efficiency. Only creates the OraclePrices instance when first accessed.

Returns

OraclePrices instance for this exchange’s chain

Return type

OraclePrices

Raises

ValueError – If accessed before config is set

property gas_monitor: eth_defi.gmx.gas_monitor.GMXGasMonitor | None

Gas monitor instance for checking balance and estimating gas costs.

Uses lazy initialisation pattern for efficiency. Only creates the GMXGasMonitor instance when first accessed.

Returns

GMXGasMonitor instance for this exchange’s chain, or None during initialisation

Return type

GMXGasMonitor | None

calculate_fee(symbol, type, side, amount, price, takerOrMaker='taker', params=None)

Calculate trading fee for GMX positions.

GMX uses dynamic fees based on pool balancing: - Position open/close: 0.04% (balanced) or 0.06% (imbalanced) - Normal swaps: 0.05% (balanced) or 0.07% (imbalanced) - Stablecoin swaps: 0.005% (balanced) or 0.02% (imbalanced)

For backtesting, we use a fixed 0.06% (0.0006) which represents a realistic middle ground for position trading.

Parameters
  • symbol (str) – Trading pair symbol (e.g., “ETH/USD”)

  • type (str) – Order type (e.g., “market”, “limit”)

  • side (str) – Order side (“buy” or “sell”)

  • amount (float) – Order amount in base currency

  • price (float) – Order price

  • takerOrMaker (str) – “taker” or “maker” (not used for GMX)

  • params (dict) – Additional parameters

Returns

Fee dictionary with rate and cost

Return type

dict

describe()

Get CCXT exchange description.

load_markets(reload=False, params=None)

Load available markets from GMX protocol (synchronous version).

This is the synchronous implementation for the sync GMX class. For async support, use the GMX class from eth_defi.gmx.ccxt.async_support.

Loading modes (in priority order): 1. REST API (DEFAULT) - Fast (1-2s), official GMX endpoint, comprehensive data 2. GraphQL - Fast (1-2s), requires subsquid 3. RPC - Slow (87-217s), most comprehensive on-chain data

Use options or params to control loading mode: - options={‘rest_api_mode’: False} - Disable REST API mode - options={‘graphql_only’: True} - Force GraphQL mode - params={‘graphql_only’: True} - Force GraphQL mode (CCXT style)

Parameters
  • reload (bool) – If True, force reload markets even if already loaded

  • params (dict | None) – Additional parameters (for CCXT compatibility)

Returns

dictionary mapping unified symbols (e.g. “ETH/USDC”) to market info

Return type

dict[str, Any]

fetch_markets(params=None)

Fetch all available markets from GMX protocol.

This method fetches market data from GMX and returns it as a list of market structures. Unlike load_markets(), this method does not cache the results and always fetches fresh data.

Parameters

params (Dict[str, Any | None]) – Additional parameters (not used currently)

Returns

List of market structures

Return type

List[Dict[str, Any]]

Example:

markets = gmx.fetch_markets()
for market in markets:
    print(f"{market['symbol']}: {market['base']}/{market['quote']}")
market(symbol)

Get market information for a specific trading pair.

Parameters

symbol (str) – Unified symbol (e.g., “ETH/USD” or “ETH/USDC:USDC”)

Returns

Market information dictionary

Return type

dict[str, Any]

Raises

ValueError – If markets haven’t been loaded or symbol not found

fetch_market_leverage_tiers(symbol, params=None)

Fetch leverage tiers for a specific market.

GMX uses a dynamic leverage system where minimum collateral requirements increase with open interest. This method returns discrete tiers approximating the continuous leverage model.

Parameters
  • symbol (str) – Unified symbol (e.g., “ETH/USD”, “BTC/USD”)

  • params (dict[str, Any] | None) –

    Optional parameters:

    • side: “long” or “short” (default: “long”)

    • num_tiers: Number of tiers to generate (default: 5)

Returns

List of leverage tier dictionaries with fields:

  • tier: Tier number

  • minNotional: Minimum position size in USD

  • maxNotional: Maximum position size in USD

  • maxLeverage: Maximum leverage for this tier

  • minCollateralFactor: Required collateral factor

Return type

list[dict[str, Any]]

Example:

# Get leverage tiers for ETH/USD longs
tiers = gmx.fetch_market_leverage_tiers("ETH/USD")

# Get tiers for shorts
tiers = gmx.fetch_market_leverage_tiers("ETH/USD", {"side": "short"})
fetch_leverage_tiers(symbols=None, params=None)

Fetch leverage tiers for multiple markets.

Parameters
  • symbols (list[str] | None) – List of symbols (e.g., [“ETH/USD”, “BTC/USD”]). If None, fetches for all markets.

  • params (dict[str, Any] | None) – Optional parameters (passed to fetch_market_leverage_tiers)

Returns

Dictionary mapping symbols to their leverage tiers

Return type

dict[str, list[dict[str, Any]]]

Example:

# Get leverage tiers for all markets
all_tiers = gmx.fetch_leverage_tiers()

# Get tiers for specific markets
tiers = gmx.fetch_leverage_tiers(["ETH/USD", "BTC/USD"])
fetch_ohlcv(symbol, timeframe='1m', since=None, limit=None, params=None)

Fetch historical OHLCV (Open, High, Low, Close, Volume) candlestick data.

This method follows CCXT conventions for fetching historical market data. It returns a list of OHLCV candles where each candle is a list of [timestamp, open, high, low, close, volume].

Parameters
  • symbol (str) – Unified symbol (e.g., “ETH/USD”, “BTC/USD”)

  • timeframe (str) – Candlestick interval - “1m”, “5m”, “15m”, “1h”, “4h”, “1d”

  • since (int | None) – Unix timestamp in milliseconds for the earliest candle to fetch (GMX API returns recent candles, filtering is done client-side)

  • limit (int | None) – Maximum number of candles to return

  • params (dict[str, Any] | None) – Additional parameters (e.g., {“until”: timestamp_ms, “skip_validation”: True})

Returns

list of OHLCV candles, each as [timestamp_ms, open, high, low, close, volume]

Return type

list[list]

Raises

Note

Volume is always 0 as GMX API doesn’t provide volume data

Example:

# Fetch last 100 hourly candles for ETH
candles = gmx.fetch_ohlcv("ETH/USD", "1h", limit=100)

# Fetch candles since specific time
since = int(time.time() * 1000) - 86400000
candles = gmx.fetch_ohlcv("ETH/USD", "1h", since=since)

# Each candle: [timestamp, open, high, low, close, volume]
for candle in candles:
    timestamp, o, h, l, c, v = candle
    print(f"{timestamp}: O:{o} H:{h} L:{l} C:{c} V:{v}")
parse_ohlcvs(ohlcvs, market=None, timeframe='1m', since=None, limit=None, use_tail=True)

Parse multiple OHLCV candles from GMX format to CCXT format.

Converts GMX candlestick data (5 fields) to CCXT format (6 fields with volume). Applies filtering based on ‘since’ timestamp and ‘limit’ parameters.

Parameters
  • ohlcvs (list[list]) – list of raw OHLCV data from GMX API (V will be always 0 for GMX)

  • market (dict[str, Any] | None) – Market information dictionary (optional)

  • timeframe (str) – Candlestick interval

  • since (int | None) – Filter candles after this timestamp (ms)

  • limit (int | None) – Maximum number of candles to return

  • use_tail (bool) – If True, return the most recent candles when limiting

Returns

list of parsed OHLCV candles in CCXT format

Return type

list[list]

parse_ticker(ticker, market=None)

Parse GMX ticker data to CCXT format.

Parameters
  • ticker (dict) – Raw ticker data from GMX API

  • market (dict) – Market structure from load_markets()

Returns

CCXT-formatted ticker:

{

”symbol”: “ETH/USD”, “timestamp”: 1234567890000, “datetime”: “2021-01-01T00:00:00.000Z”, “high”: None, # Calculated separately from OHLCV “low”: None, # Calculated separately from OHLCV “bid”: last_price, # GMX doesn’t have order books “bidVolume”: None, “ask”: last_price, “askVolume”: None, “vwap”: None, “open”: None, # Calculated separately from OHLCV “close”: 3350.0, # Current price “last”: 3350.0, # Current price “previousClose”: None, “change”: None, “percentage”: None, “average”: None, “baseVolume”: None, # GMX doesn’t provide volume “quoteVolume”: None, “info”: {…}, # Raw GMX ticker data

}

Return type

dict

fetch_open_interest(symbol, params=None)

Fetch current open interest for a symbol.

This method returns the current open interest data for both long and short positions on GMX protocol using the fast Subsquid GraphQL endpoint.

Follows CCXT standard by aggregating long + short into openInterestValue, while preserving granular long/short breakdown in info field.

Parameters
  • symbol (str) – Unified symbol (e.g., “ETH/USD”, “BTC/USD”)

  • params (dict[str, Any] | None) – Additional parameters - can include “market_address” to query specific market

Returns

dictionary with open interest information:

{

”symbol”: “ETH/USD”, “baseVolume”: None, “quoteVolume”: None, “openInterestAmount”: 12345.67, # Total OI in tokens (ETH) “openInterestValue”: 37615898.78, # Aggregated long + short OI in USD “timestamp”: 1234567890000, “datetime”: “2021-01-01T00:00:00.000Z”, “info”: {

”longOpenInterest”: 18807949.39, # Long OI in USD (parsed) “shortOpenInterest”: 18807949.39, # Short OI in USD (parsed) “longOpenInterestTokens”: 6172.835, # Long OI in ETH (parsed) “shortOpenInterestTokens”: 6172.835, # Short OI in ETH (parsed) … # Raw Subsquid data + raw USD/token values

}

}

Return type

dict[str, Any]

Raises

ValueError – If invalid symbol or markets not loaded

Example:

# Get current open interest for ETH
oi = gmx.fetch_open_interest("ETH/USD")
print(f"Total OI: {oi['openInterestAmount']:.2f} ETH")
print(f"Total OI: ${oi['openInterestValue']:,.0f}")

# Access long/short breakdown from info field
print(f"Long: {oi['info']['longOpenInterestTokens']:.2f} ETH")
print(f"Short: {oi['info']['shortOpenInterestTokens']:.2f} ETH")
print(f"Long: ${oi['info']['longOpenInterest']:,.0f}")
print(f"Short: ${oi['info']['shortOpenInterest']:,.0f}")

Note

Data is fetched from Subsquid GraphQL endpoint for fast access. Long/short breakdown is available in the info field.

fetch_open_interest_history(symbol, timeframe='1h', since=None, limit=None, params=None)

Fetch historical open interest data from Subsquid.

Retrieves historical open interest snapshots from the GMX Subsquid GraphQL endpoint. Data includes long and short open interest values over time.

Parameters
  • symbol (str) – Unified symbol (e.g., “ETH/USD”)

  • timeframe (str) – Time interval (note: data is snapshot-based, not aggregated)

  • since (int | None) – Start timestamp in milliseconds

  • limit (int | None) – Maximum number of records (default: 100)

  • params (dict[str, Any] | None) – Additional parameters (e.g., {“market_address”: “0x…”})

Returns

list of historical open interest snapshots

Return type

list[dict[str, Any]]

Raises

ValueError – If invalid symbol or markets not loaded

Example:

# Get historical OI for ETH
history = exchange.fetch_open_interest_history("ETH/USD", limit=50)
for snapshot in history:
    print(f"{snapshot['datetime']}: ${snapshot['openInterestValue']:,.0f}")

Note

Data is fetched from Subsquid GraphQL endpoint. Returns snapshots, not time-aggregated data.

fetch_open_interests(symbols=None, params=None)

Fetch open interest for multiple symbols at once.

Parameters
  • symbols (list[str] | None) – List of symbols (e.g., [“ETH/USD”, “BTC/USD”]). If None, fetch all markets.

  • params (dict[str, Any] | None) – Additional parameters

Returns

Dictionary mapping symbols to open interest data

Return type

dict[str, dict[str, Any]]

Example:

# Fetch OI for multiple markets
ois = gmx.fetch_open_interests(["ETH/USD", "BTC/USD", "ARB/USD"])
for symbol, oi in ois.items():
    print(f"{symbol}: ${oi['openInterestValue']:,.0f}")

# Fetch OI for all markets
all_ois = gmx.fetch_open_interests()
parse_open_interest(interest, market=None)

Parse raw open interest data to CCXT format.

Follows CCXT pattern: aggregates long + short into standard fields, preserves granular breakdown in info field.

Parameters
  • interest (dict[str, Any]) – Raw market info from Subsquid with fields: - longOpenInterestUsd: Long OI in USD (30 decimals) - shortOpenInterestUsd: Short OI in USD (30 decimals) - longOpenInterestInTokens: Long OI in tokens (token decimals) - shortOpenInterestInTokens: Short OI in tokens (token decimals)

  • market (dict[str, Any] | None) – Market information (CCXT market structure)

Returns

Parsed open interest in CCXT format with structure:

{

”symbol”: “ETH/USD”, “openInterestAmount”: 12345.67, # Total OI in tokens (ETH) “openInterestValue”: 37615898.78, # Total OI in USD “timestamp”: 1234567890000, “datetime”: “2021-01-01T00:00:00.000Z”, “info”: {

”longOpenInterest”: 18807949.39, # Long OI in USD (parsed) “shortOpenInterest”: 18807949.39, # Short OI in USD (parsed) “longOpenInterestUsd”: “…”, # Long OI in USD (raw 30 decimals) “shortOpenInterestUsd”: “…”, # Short OI in USD (raw 30 decimals) “longOpenInterestTokens”: 6172.835, # Long OI in ETH (parsed) “shortOpenInterestTokens”: 6172.835, # Short OI in ETH (parsed) “longOpenInterestInTokens”: “…”, # Long OI (raw with decimals) “shortOpenInterestInTokens”: “…”, # Short OI (raw with decimals) … # Additional Subsquid fields

}

}

Return type

dict[str, Any]

Example:

raw_data = subsquid.get_market_infos(market_address, limit=1)[0]
market_info = gmx.market("ETH/USD")
parsed = gmx.parse_open_interest(raw_data, market_info)

# Access aggregated values
print(f"Total OI: {parsed['openInterestAmount']:.2f} ETH")
print(f"Total OI: ${parsed['openInterestValue']:,.2f} USD")

# Access long/short breakdown
print(f"Long: {parsed['info']['longOpenInterestTokens']:.2f} ETH")
print(f"Short: {parsed['info']['shortOpenInterestTokens']:.2f} ETH")
fetch_funding_rate(symbol, params=None)

Fetch current funding rate for a symbol.

This method returns the current funding rate for both long and short positions on GMX protocol using the fast Subsquid GraphQL endpoint.

Parameters
  • symbol (str) – Unified symbol (e.g., “ETH/USD”, “BTC/USD”)

  • params (dict[str, Any] | None) – Additional parameters - can include “market_address” to query specific market

Returns

dictionary with funding rate information:

{

”symbol”: “ETH/USD”, “fundingRate”: 0.0001, # Per-second rate (as decimal) “longFundingRate”: 0.0001, # Long position rate (per-second) “shortFundingRate”: -0.0001, # Short position rate (per-second) “fundingTimestamp”: 1234567890000, “fundingDatetime”: “2021-01-01T00:00:00.000Z”, “timestamp”: 1234567890000, “datetime”: “2021-01-01T00:00:00.000Z”, “info”: {…}, # Raw Subsquid data

}

Return type

dict[str, Any]

Raises

ValueError – If invalid symbol or markets not loaded

Example:

# Get current funding rate for BTC
fr = exchange.fetch_funding_rate("BTC/USD")
# Convert per-second to hourly
hourly_rate = fr["fundingRate"] * 3600
print(f"Hourly funding: {hourly_rate:.6f}")

# Positive rate = longs pay shorts
# Negative rate = shorts pay longs

Note

Data is fetched from Subsquid GraphQL endpoint for fast access. Rates are per-second values. Multiply by 3600 for hourly rate.

fetch_funding_rate_history(symbol, since=None, limit=None, params=None)

Fetch historical funding rate data from Subsquid.

Retrieves historical funding rate snapshots from the GMX Subsquid GraphQL endpoint. Data includes funding rates per second and direction (longs pay shorts or vice versa).

Parameters
  • symbol (str) – Unified symbol (e.g., “ETH/USD”)

  • since (int | None) – Start timestamp in milliseconds

  • limit (int | None) – Maximum number of records (default: 100)

  • params (dict | None) – Additional parameters (e.g., {“market_address”: “0x…”})

Returns

list of historical funding rate snapshots

Return type

list[dict[str, Any]]

Raises

ValueError – If invalid symbol or markets not loaded

Example:

# Get historical funding rates for BTC
history = exchange.fetch_funding_rate_history("BTC/USD", limit=50)
for snapshot in history:
    rate = snapshot["fundingRate"]
    print(f"{snapshot['datetime']}: {rate * 100:.6f}% per hour")

Note

Data is fetched from Subsquid GraphQL endpoint. Funding rates are per-second values, multiply by 3600 for hourly rate.

fetch_funding_history(symbol=None, since=None, limit=None, params=None)

Fetch funding fee payment history for positions.

GMX V2 does not track historical funding fee payments per position. This method returns an empty list to indicate no funding history is available. Freqtrade will calculate funding fees as 0.0 when summing the empty list.

Parameters
  • symbol (str | None) – Unified symbol (e.g., “ETH/USD”, “BTC/USD”) - not used

  • since (int | None) – Timestamp in milliseconds - not used

  • limit (int | None) – Maximum number of records - not used

  • params (dict[str, Any] | None) – Additional parameters - not used

Returns

Empty list (GMX doesn’t provide funding history)

Return type

list[dict[str, Any]]

Note

GMX V2 does not track historical funding fee payments. Funding fees are continuously accrued and settled, but the protocol does not maintain a queryable history of past payments.

If you need funding rate history (not payment history), use fetch_funding_rate_history() instead.

fetch_ticker(symbol, params=None)

Fetch ticker data for a single market.

Gets current price and 24h statistics for the specified market. Note: GMX doesn’t provide 24h high/low, so these are calculated from recent OHLCV.

Parameters
  • symbol (str) – CCXT symbol (e.g., “ETH/USD”)

  • params (dict) – Optional parameters (not used currently)

Returns

CCXT-formatted ticker (see parse_ticker for structure)

Return type

dict

Example:

ticker = gmx.fetch_ticker("ETH/USD")
print(f"Current price: ${ticker['last']}")
print(f"24h high: ${ticker['high']}")
fetch_tickers(symbols=None, params=None)

Fetch ticker data for multiple markets at once.

Parameters
  • symbols (list[str]) – List of CCXT symbols to fetch. If None, fetches all markets.

  • params (dict) – Optional parameters (not used currently)

Returns

Dict mapping symbols to ticker data:

{

”ETH/USD”: {…}, “BTC/USD”: {…}, …

}

Return type

dict

Example:

# Fetch all tickers
tickers = gmx.fetch_tickers()

# Fetch specific symbols
tickers = gmx.fetch_tickers(["ETH/USD", "BTC/USD"])
fetch_apy(symbol=None, period='30d', params=None)

Fetch APY (Annual Percentage Yield) data for GMX markets.

Retrieves yield data from GMX REST API with disk caching support. Can fetch APY for a specific market or all markets at once.

Parameters
  • symbol (str | None) – CCXT market symbol (e.g., “ETH/USDC:USDC”). If None, returns APY for all markets as a dictionary.

  • period (str) – Time period for APY calculation. Valid values: ‘1d’, ‘7d’, ‘30d’, ‘90d’, ‘180d’, ‘1y’, ‘total’ Default: ‘30d’

  • params (dict | None) – Optional parameters (not used currently)

Returns

If symbol is specified: float APY value or None if not found If symbol is None: dict mapping symbols to APY values

Raises

ValueError – If period is invalid

Return type

dict[str, Any] | float | None

Example:

# Fetch 30-day APY for specific market
apy = gmx.fetch_apy("ETH/USDC:USDC", period="30d")
print(f"ETH/USDC APY: {apy * 100:.2f}%")

# Fetch APY for all markets
all_apy = gmx.fetch_apy(period="7d")
for symbol, apy_value in all_apy.items():
    print(f"{symbol}: {apy_value * 100:.2f}%")
fetch_currencies(params=None)

Fetch currency/token metadata.

Returns information about all tradeable tokens including decimals, addresses, and symbols.

Parameters

params (dict) – Optional parameters (not used currently)

Returns

Dict mapping currency codes to metadata:

{
”ETH”: {

“id”: “0x82aF49447D8a07e3bd95BD0d56f35241523fBab1”, “code”: “ETH”, “name”: “Ethereum”, “active”: True, “fee”: None, “precision”: 18, “limits”: {

”amount”: {“min”: None, “max”: None}, “withdraw”: {“min”: None, “max”: None}

}, “info”: {…}

}

Return type

dict

Example:

currencies = gmx.fetch_currencies()
eth_decimals = currencies["ETH"]["precision"]
parse_trade(trade, market=None)

Parse trade data to CCXT format.

GMX doesn’t have traditional public trades, so we derive this from position change events (opens and closes).

Parameters
  • trade (dict) – Position change event from Subsquid

  • market (dict) – Market structure

Returns

CCXT-formatted trade:

{

”id”: “0x123…”, “order”: None, “timestamp”: 1234567890000, “datetime”: “2021-01-01T00:00:00.000Z”, “symbol”: “ETH/USD”, “type”: None, “side”: “buy”, # or “sell” “takerOrMaker”: None, “price”: 3350.0, “amount”: 10.5, “cost”: 35175.0, “fee”: {…}, “info”: {…},

}

Return type

dict

fetch_trades(symbol, since=None, limit=None, params=None)

Fetch recent public trades for a market.

Note: GMX doesn’t have traditional public trades. This method derives trade data from position change events via Subsquid GraphQL.

Parameters
  • symbol (str) – CCXT symbol (e.g., “ETH/USD”)

  • since (int) – Timestamp in milliseconds to fetch trades from

  • limit (int) – Maximum number of trades to return

  • params (dict) – Optional parameters (not used currently)

Returns

List of CCXT-formatted trades

Return type

list[dict]

Example:

# Get last 50 trades
trades = gmx.fetch_trades("ETH/USD", limit=50)

# Get trades since yesterday
since = int((datetime.now() - timedelta(days=1)).timestamp() * 1000)
trades = gmx.fetch_trades("ETH/USD", since=since)
fetch_time(params=None)

Fetch current server time.

For GMX (blockchain-based), this returns the timestamp of the latest Arbitrum block.

Parameters

params (dict) – Optional parameters (not used currently)

Returns

Current timestamp in milliseconds

Return type

int

Example:

server_time = gmx.fetch_time()
print(f"Server time: {server_time}")
fetch_status(params=None)

Fetch API operational status.

Checks if GMX API and Subsquid endpoints are responding.

Parameters

params (dict) – Optional parameters (not used currently)

Returns

Status information:

{

”status”: “ok”, # or “maintenance” “updated”: 1234567890000, “datetime”: “2021-01-01T00:00:00.000Z”, “eta”: None, “url”: None, “info”: {…},

}

Return type

dict

Example:

status = gmx.fetch_status()
if status["status"] == "ok":
    print("API is operational")
fetch_balance(params=None)

Fetch account token balances.

Returns wallet balances for all supported tokens. Requires user_wallet_address to be set in GMXConfig.

Parameters

params (dict) – Optional parameters - wallet_address: Override default wallet address from config

Returns

CCXT-formatted balance:

{
”ETH”: {

“free”: 1.5, # Available balance “used”: 0.0, # Locked in positions (not implemented yet) “total”: 1.5, # Total balance

}, “USDC”: {…}, “free”: {…}, # Summary of all free balances “used”: {…}, # Summary of all used balances “total”: {…}, # Summary of all total balances “info”: {…}, # Raw balance data

}

Return type

dict

Example:

# Initialize with wallet address
config = GMXConfig(web3, user_wallet_address="0x...")
gmx = GMX(config)
balance = gmx.fetch_balance()
eth_balance = balance["ETH"]["free"]
parse_order(order, market=None)

Parse order/position data to CCXT format.

Parameters
  • order (dict) – Order/position data from GMX

  • market (dict) – Market structure

Returns

CCXT-formatted order:

{"id": "ETH_long", "clientOrderId": None, "timestamp": 1234567890000, "datetime": "2021-01-01T00:00:00.000Z", "lastTradeTimestamp": None, "symbol": "ETH/USD", "type": "market", "side": "buy", "price": 3350.0, "amount": 10.5, "cost": 35175.0, "average": 3350.0, "filled": 10.5, "remaining": 0.0, "status": "open", "fee": None, "trades": [], "info": {...}}

Return type

dict

parse_position(position, market=None)

Parse position data to CCXT format.

Parameters
  • position (dict) – Position data from GMX

  • market (dict) – Market structure

Returns

CCXT-formatted position:

{"id": "ETH_long_0x123...", "symbol": "ETH/USD", "timestamp": 1234567890000, "datetime": "2021-01-01T00:00:00.000Z", "isolated": False, "hedged": False, "side": "long", "contracts": 10.5, "contractSize": 1, "entryPrice": 3350.0, "markPrice": 3400.0, "notional": 35700.0, "leverage": 5.0, "collateral": 7140.0, "initialMargin": 7140.0, "maintenanceMargin": 357.0, "initialMarginPercentage": 0.20, "maintenanceMarginPercentage": 0.01, "unrealizedPnl": 525.0, "liquidationPrice": 2680.0, "marginRatio": 0.05, "percentage": 7.35, "info": {...}}

Return type

dict

fetch_open_orders(symbol=None, since=None, limit=None, params=None)

Fetch open orders (positions) for the account.

In GMX, open positions are treated as “open orders”. Requires user_wallet_address to be set in GMXConfig.

Parameters
  • symbol (str) – Filter by symbol (optional)

  • since (int) – Not used (GMX returns current positions)

  • limit (int) – Maximum number of orders to return

  • params (dict) – Optional parameters - wallet_address: Override default wallet address

Returns

List of CCXT-formatted orders

Return type

list[dict]

Example:

# Initialize with wallet address
config = GMXConfig(web3, user_wallet_address="0x...")
gmx = GMX(config)
orders = gmx.fetch_open_orders()
eth_orders = gmx.fetch_open_orders(symbol="ETH/USD")
fetch_my_trades(symbol=None, since=None, limit=None, params=None)

Fetch user’s trade history.

Uses RPC-first approach: 1. First checks local order cache for recent trades (immediate blockchain data) 2. Then fetches historical trades from Subsquid GraphQL 3. Merges and deduplicates results

This solves the race condition where Freqtrade fetches trades immediately after order execution, before the Subsquid indexer has processed them.

Requires user_wallet_address to be set in GMXConfig.

Parameters
  • symbol (str) – Filter by symbol (optional)

  • since (int) – Timestamp in milliseconds to fetch trades from

  • limit (int) – Maximum number of trades to return

  • params (dict) – Optional parameters - wallet_address: Override default wallet address

Returns

List of CCXT-formatted trades

Return type

list[dict]

Example:

config = GMXConfig(web3, user_wallet_address="0x...")
gmx = GMX(config)
trades = gmx.fetch_my_trades(limit=50)

# Filter by symbol
eth_trades = gmx.fetch_my_trades(symbol="ETH/USD")
fetch_positions(symbols=None, params=None)

Fetch all open positions for the account.

Returns detailed position information with full metrics (leverage, PnL, liquidation price, etc.). Requires user_wallet_address to be set in GMXConfig.

Parameters
  • symbols (list[str]) – Filter by list of symbols (optional)

  • params (dict) – Optional parameters - wallet_address: Override default wallet address

Returns

List of CCXT-formatted positions

Return type

list[dict]

Example:

config = GMXConfig(web3, user_wallet_address="0x...")
gmx = GMX(config)

# Fetch all positions
positions = gmx.fetch_positions()

# Filter specific symbols
positions = gmx.fetch_positions(symbols=["ETH/USD", "BTC/USD"])

# Access position details
for pos in positions:
    print(f"{pos['symbol']}: {pos['side']} {pos['contracts']} @ {pos['entryPrice']}")
    print(f"  Leverage: {pos['leverage']}x")
    print(f"  PnL: ${pos['unrealizedPnl']:.2f} ({pos['percentage']:.2f}%)")
    print(f"  Liquidation: ${pos['liquidationPrice']:.2f}")
set_leverage(leverage, symbol=None, params=None)

Set leverage for a symbol (or all symbols if not specified).

Note: This only stores leverage settings locally for future order creation. GMX leverage is set per-position when creating the order, not globally.

Parameters
  • leverage (float) – Leverage multiplier (e.g., 5.0 for 5x leverage)

  • symbol (str) – Symbol to set leverage for (e.g., “ETH/USD”). If None, sets default for all symbols

  • params (dict) – Optional parameters (reserved for future use)

Returns

Leverage info dictionary

Return type

dict

Example:

gmx = GMX(config)

# Set leverage for specific symbol
gmx.set_leverage(5.0, "ETH/USD")

# Set default leverage for all symbols
gmx.set_leverage(10.0)
fetch_leverage(symbol=None, params=None)

Get current leverage setting(s).

Returns stored leverage configuration. If no leverage has been set, returns default of 1.0 (no leverage).

Parameters
  • symbol (str) – Symbol to get leverage for. If None, returns all leverage settings

  • params (dict) – Optional parameters (reserved for future use)

Returns

Leverage info dictionary or list of dictionaries

Return type

dict | list[dict]

Example:

gmx = GMX(config)

# Get leverage for specific symbol
info = gmx.fetch_leverage("ETH/USD")
print(f"ETH/USD leverage: {info['leverage']}x")

# Get all leverage settings
all_leverage = gmx.fetch_leverage()
add_margin(symbol, amount, params=None)

Add margin to an existing position.

Note: This method is not yet implemented and requires GMX contract integration.

Parameters
  • symbol (str) – Symbol of the position (e.g., “ETH/USD”)

  • amount (float) – Amount of collateral to add (in USD)

  • params (dict) – Optional parameters

Raises

NotImplementedError – Method requires GMX contract integration

Return type

dict

Example:

# This will raise NotImplementedError
gmx.add_margin("ETH/USD", 1000.0)
reduce_margin(symbol, amount, params=None)

Remove margin from an existing position.

Note: This method is not yet implemented and requires GMX contract integration.

Parameters
  • symbol (str) – Symbol of the position (e.g., “ETH/USD”)

  • amount (float) – Amount of collateral to remove (in USD)

  • params (dict) – Optional parameters

Raises

NotImplementedError – Method requires GMX contract integration

Return type

dict

Example:

# This will raise NotImplementedError
gmx.reduce_margin("ETH/USD", 500.0)
parse_ohlcv(ohlcv, market=None)

Parse a single OHLCV candle from GMX format to CCXT format.

GMX returns: [timestamp_seconds, open, high, low, close] CCXT expects: [timestamp_ms, open, high, low, close, volume]

Parameters
  • ohlcv (list) – Single candle data from GMX [timestamp_s, open, high, low, close]

  • market (dict[str, Any] | None) – Market information dictionary (optional)

Returns

Parsed candle in CCXT format [timestamp_ms, open, high, low, close, volume]

Return type

list

Note

Volume is set to 0 as GMX doesn’t provide it

parse_timeframe(timeframe)

Convert timeframe string to duration in seconds.

Parameters

timeframe (str) – Timeframe string (e.g., “1m”, “1h”, “1d”)

Returns

Duration in seconds

Return type

int

Example:

seconds = gmx.parse_timeframe("1h")  # Returns 3600
seconds = gmx.parse_timeframe("1d")  # Returns 86400
milliseconds()

Get current Unix timestamp in milliseconds.

Returns

Current timestamp in milliseconds

Return type

int

Example:

now = gmx.milliseconds()
print(f"Current time: {now} ms")
safe_integer(dictionary, key, default=None)

Safely extract an integer value from a dictionary.

Parameters
  • dictionary (dict[str, Any]) – dictionary to extract from

  • key (str) – Key to look up

  • default (int | None) – Default value if key not found

Returns

Integer value or default

Return type

int | None

safe_string(dictionary, key, default=None)

Safely extract a string value from a dictionary.

Parameters
  • dictionary (dict[str, Any]) – dictionary to extract from

  • key (str) – Key to look up

  • default (str | None) – Default value if key not found

Returns

String value or default

Return type

str | None

safe_number(dictionary, key, default=None)

Safely extract a numeric value from a dictionary.

Parameters
  • dictionary (dict[str, Any]) – dictionary to extract from

  • key (str) – Key to look up

  • default (float | None) – Default value if key not found

Returns

Float value or default

Return type

float | None

safe_timestamp(dictionary, key, default=None)

Safely extract a timestamp and convert to milliseconds.

Parameters
  • dictionary (dict[str, Any]) – dictionary to extract from

  • key (str) – Key to look up

  • default (int | None) – Default value if key not found

Returns

Timestamp in milliseconds or default

Return type

int | None

iso8601(timestamp)

Convert timestamp in milliseconds to ISO8601 string.

Parameters

timestamp (int | None) – Timestamp in milliseconds

Returns

ISO8601 formatted datetime string

Return type

str | None

sum(a, b)

Add two numbers safely.

Parameters
  • a (float) – First number

  • b (float) – Second number

Returns

Sum of a and b

Return type

float

omit(dictionary, keys)

Create a new dictionary excluding specified keys.

Parameters
  • dictionary (dict[str, Any]) – Source dictionary

  • keys (list[str]) – list of keys to exclude

Returns

New dictionary without the specified keys

Return type

dict[str, Any]

create_order(symbol, type, side, amount, price=None, params=None)

Create and execute a GMX order.

This method creates orders on GMX protocol with CCXT-compatible interface. Orders are automatically signed with the wallet provided during initialization and submitted to the Arbitrum blockchain.

Example Usage:

from eth_defi.hotwallet import HotWallet
from eth_defi.gmx.ccxt import GMX
from eth_defi.gmx.config import GMXConfig
from web3 import Web3

# Initialize with wallet
web3 = Web3(Web3.HTTPProvider("https://arb1.arbitrum.io/rpc"))
config = GMXConfig(web3=web3)
wallet = HotWallet.from_private_key("0x...")
gmx = GMX(config, wallet=wallet)

# Approach 1: CCXT standard (amount in base currency)
order = gmx.create_order(
    "ETH/USD",
    "market",
    "buy",
    0.5,  # 0.5 ETH
    params={
        "leverage": 3.0,
        "collateral_symbol": "USDC",
    },
)

# Approach 2: GMX extension (size_usd in USD)
order = gmx.create_order(
    "ETH/USD",
    "market",
    "buy",
    0,  # Ignored when size_usd is provided
    params={
        "size_usd": 1000,  # $1000 position
        "leverage": 3.0,
        "collateral_symbol": "USDC",
    },
)

print(f"Order created: {order['id']}")  # Transaction hash
print(f"Status: {order['status']}")  # 'open' or 'failed'
Parameters
  • symbol (str) – Market symbol (e.g., ‘ETH/USD’, ‘BTC/USD’)

  • type (str) – Order type (‘market’ or ‘limit’)

  • side (str) – Order side (‘buy’ for long, ‘sell’ for short)

  • amount (float) – Order size in base currency contracts (e.g., ETH for ETH/USD). Use params[‘size_usd’] for USD-based sizing.

  • price (float | None) – Price for limit orders. For market orders, used to convert amount to USD if provided.

  • params (dict | None) –

    Additional parameters: - size_usd (float): GMX Extension - Order size in USD (alternative to amount parameter) - leverage (float): Leverage multiplier (default: 1.0) - collateral_symbol (str): Collateral token (default: ‘USDC’) - slippage_percent (float): Slippage tolerance (default: 0.003) - execution_buffer (float): Gas buffer multiplier (default: 2.2) - auto_cancel (bool): Auto-cancel if execution fails (default: False) - wait_for_execution (bool): Wait for keeper execution via Subsquid/EventEmitter (default: True).

    Set to False for fork tests where Subsquid won’t have the order data.

Returns

CCXT-compatible order structure with transaction hash and status

Return type

dict

Raises

ValueError – If wallet not provided, parameters invalid, or market doesn’t exist

create_market_buy_order(symbol, amount, params=None)

Create a market buy order (long position).

Convenience wrapper around create_order() for market buy orders.

Parameters
  • symbol (str) – Market symbol (e.g., ‘ETH/USD’)

  • amount (float) – Order size in base currency contracts (e.g., ETH for ETH/USD). Use params[‘size_usd’] for USD-based sizing.

  • params (dict | None) – Additional parameters (see create_order). Use ‘size_usd’ for direct USD sizing.

Returns

CCXT-compatible order structure

Return type

dict

create_market_sell_order(symbol, amount, params=None)

Create a market sell order (close long position).

Convenience wrapper around create_order() for market sell orders.

Parameters
  • symbol (str) – Market symbol (e.g., ‘ETH/USD’)

  • amount (float) – Order size in base currency contracts (e.g., ETH for ETH/USD). Use params[‘size_usd’] for USD-based sizing.

  • params (dict | None) – Additional parameters (see create_order). Use ‘size_usd’ for direct USD sizing.

Returns

CCXT-compatible order structure

Return type

dict

create_limit_order(symbol, side, amount, price, params=None)

Create a limit order that triggers at specified price.

Creates a GMX LIMIT_INCREASE order that remains pending until the market price reaches the trigger price. Unlike market orders which execute immediately, limit orders allow you to enter positions at specific price levels.

Example:

# Limit long order - buy ETH if price drops to $3000
order = gmx.create_limit_order(
    "ETH/USD",
    "buy",
    0,  # Ignored when size_usd is provided
    3000.0,  # Trigger price
    params={
        "size_usd": 1000,
        "leverage": 2.5,
        "collateral_symbol": "ETH",
    },
)

# Limit short order - short ETH if price rises to $4000
order = gmx.create_limit_order(
    "ETH/USD",
    "sell",
    0,
    4000.0,
    params={
        "size_usd": 1000,
        "leverage": 2.0,
        "collateral_symbol": "USDC",
    },
)
Parameters
  • symbol (str) – Market symbol (e.g., ‘ETH/USD’)

  • side (str) – Order side (‘buy’ for long, ‘sell’ for short)

  • amount (float) – Order size in base currency (or 0 if using size_usd in params)

  • price (float) – Trigger price at which the order executes (USD)

  • params (dict | None) – Additional parameters (see create_order)

Returns

CCXT-compatible order structure with transaction hash

Return type

dict

clear_order_cache()

Clear the in-memory order cache.

Call this when switching strategies or starting a fresh session to avoid stale order data from previous runs.

reset_failure_counter()

Reset consecutive failure counter and resume trading.

Call this method manually after investigating and resolving the cause of consecutive transaction failures. This will:

  • Reset the consecutive failure counter to 0

  • Resume trading if it was paused

  • Clear the pause reason

Example
# After fixing gas issues or other problems
gmx.reset_failure_counter()

# Trading will resume on next create_order() call

Warning

Only call this after investigating and resolving the root cause of the failures. Resetting without fixing the underlying issue may lead to more wasted gas.

cancel_order(id, symbol=None, params=None)

Cancel an order.

Not supported by GMX - orders execute immediately via keeper system.

Raises

NotSupported – GMX doesn’t support order cancellation

Parameters
  • id (str) –

  • symbol (str | None) –

  • params (dict | None) –

fetch_order(id, symbol=None, params=None)

Fetch order by ID (transaction hash).

Returns the order that was created with the given transaction hash. For orders with status “open”, this method checks the GMX DataStore and EventEmitter to determine if the keeper has executed the order.

GMX uses a two-phase execution model: 1. Order Creation - User submits, receives status “open” 2. Keeper Execution - Keeper executes, status changes to “closed” or “cancelled”

This method is called by Freqtrade to poll for order status updates.

Parameters
  • id (str) – Order ID (transaction hash of order creation)

  • symbol (str | None) – Symbol (not used, for CCXT compatibility)

  • params (dict | None) – Additional parameters (not used)

Returns

CCXT-compatible order structure

Return type

dict

Raises

OrderNotFound – If order with given ID doesn’t exist

fetch_order_book(symbol, limit=None, params=None)

Fetch order book.

Not supported by GMX - uses liquidity pools instead of order books.

Raises

NotSupported – GMX uses liquidity pools, not order books

Parameters
  • symbol (str) –

  • limit (int | None) –

  • params (dict | None) –

fetch_closed_orders(symbol=None, since=None, limit=None, params=None)

Fetch closed orders.

Not supported by GMX - use fetch_my_trades() instead.

Raises

NotSupported – GMX doesn’t track closed orders

Parameters
  • symbol (str | None) –

  • since (int | None) –

  • limit (int | None) –

  • params (dict | None) –

fetch_orders(symbol=None, since=None, limit=None, params=None)

Fetch all orders.

Not supported by GMX - use fetch_positions() and fetch_my_trades() instead.

Raises

NotSupported – GMX doesn’t track pending orders

Parameters
  • symbol (str | None) –

  • since (int | None) –

  • limit (int | None) –

  • params (dict | None) –

async close()

Close exchange connection and clean up resources.

GMX exchange doesn’t maintain persistent WebSocket connections or HTTP sessions that need cleanup, but this method is provided for compatibility with the async CCXT exchange interface.

This method can be called in async cleanup code or context managers.

Return type

None

assign_default_deposit_withdraw_fees(fee, currency=None)
@ignore

Takes a depositWithdrawFee structure and assigns the default values for withdraw and deposit :param dict fee: A deposit withdraw fee structure :param dict currency: A currency structure, the response from self.currency() :returns dict: A deposit withdraw fee structure

static base58_to_binary(s)

encodes a base58 string to as a big endian integer

cancel_order_with_client_order_id(clientOrderId, symbol=None, params={})

create a market order by providing the symbol, side and cost :param str clientOrderId: client order Id :param str symbol: unified symbol of the market to create an order in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
cancel_orders_with_client_order_ids(clientOrderIds, symbol=None, params={})

create a market order by providing the symbol, side and cost :param str[] clientOrderIds: client order Ids :param str symbol: unified symbol of the market to create an order in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
check_required_argument(methodName, argument, argumentName, options=[])
@ignore
param str methodName

the name of the method that the argument is being checked for

param str argument

the argument’s actual value provided

param str argumentName

the name of the argument being checked(for logging purposes)

param str[] options

a list of options that the argument can be

returns None

Parameters

methodName (str) –

check_required_credentials(error=True)
@ignore
param boolean error

raise an error that a credential is required if True

returns boolean

True if all required credentials have been set, otherwise False or an error is thrown is param error=true

check_required_margin_argument(methodName, symbol, marginMode)
@ignore
param str symbol

unified symbol of the market

param str methodName

name of the method that requires a symbol

param str marginMode

is either ‘isolated’ or ‘cross’

Parameters
convert_type_to_account(account)

@ignore Must add accountsByType to self.options to use self method

param str account

key for account name in self.options[‘accountsByType’]

returns

the exchange specific account name or the isolated margin id for transfers

create_market_buy_order_with_cost(symbol, cost, params={})

create a market buy order by providing the symbol and cost :param str symbol: unified symbol of the market to create an order in :param float cost: how much you want to trade in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_market_order_with_cost(symbol, side, cost, params={})

create a market order by providing the symbol, side and cost :param str symbol: unified symbol of the market to create an order in :param str side: ‘buy’ or ‘sell’ :param float cost: how much you want to trade in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_market_order_with_cost_ws(symbol, side, cost, params={})

create a market order by providing the symbol, side and cost :param str symbol: unified symbol of the market to create an order in :param str side: ‘buy’ or ‘sell’ :param float cost: how much you want to trade in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_market_sell_order_with_cost(symbol, cost, params={})

create a market sell order by providing the symbol and cost :param str symbol: unified symbol of the market to create an order in :param float cost: how much you want to trade in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_order_with_take_profit_and_stop_loss(symbol, type, side, amount, price=None, takeProfit=None, stopLoss=None, params={})

create an order with a stop loss or take profit attached(type 3) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float [takeProfit]: the take profit price, in units of the quote currency :param float [stopLoss]: the stop loss price, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :param str [params.takeProfitType]: not available on all exchanges ‘limit’ or ‘market’ :param str [params.stopLossType]: not available on all exchanges ‘limit’ or ‘market’ :param str [params.takeProfitPriceType]: not available on all exchanges ‘last’, ‘mark’ or ‘index’ :param str [params.stopLossPriceType]: not available on all exchanges ‘last’, ‘mark’ or ‘index’ :param float [params.takeProfitLimitPrice]: not available on all exchanges limit price for a limit take profit order :param float [params.stopLossLimitPrice]: not available on all exchanges stop loss for a limit stop loss order :param float [params.takeProfitAmount]: not available on all exchanges the amount for a take profit :param float [params.stopLossAmount]: not available on all exchanges the amount for a stop loss :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_order_with_take_profit_and_stop_loss_ws(symbol, type, side, amount, price=None, takeProfit=None, stopLoss=None, params={})

create an order with a stop loss or take profit attached(type 3) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float [takeProfit]: the take profit price, in units of the quote currency :param float [stopLoss]: the stop loss price, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :param str [params.takeProfitType]: not available on all exchanges ‘limit’ or ‘market’ :param str [params.stopLossType]: not available on all exchanges ‘limit’ or ‘market’ :param str [params.takeProfitPriceType]: not available on all exchanges ‘last’, ‘mark’ or ‘index’ :param str [params.stopLossPriceType]: not available on all exchanges ‘last’, ‘mark’ or ‘index’ :param float [params.takeProfitLimitPrice]: not available on all exchanges limit price for a limit take profit order :param float [params.stopLossLimitPrice]: not available on all exchanges stop loss for a limit stop loss order :param float [params.takeProfitAmount]: not available on all exchanges the amount for a take profit :param float [params.stopLossAmount]: not available on all exchanges the amount for a stop loss :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_orders_ws(orders, params={})

create a list of trade orders :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters

orders (List[ccxt.base.types.OrderRequest]) –

create_stop_loss_order(symbol, type, side, amount, price=None, stopLossPrice=None, params={})

create a trigger stop loss order(type 2) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float stopLossPrice: the price to trigger the stop loss order, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_stop_loss_order_ws(symbol, type, side, amount, price=None, stopLossPrice=None, params={})

create a trigger stop loss order(type 2) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float stopLossPrice: the price to trigger the stop loss order, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_take_profit_order(symbol, type, side, amount, price=None, takeProfitPrice=None, params={})

create a trigger take profit order(type 2) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float takeProfitPrice: the price to trigger the take profit order, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_take_profit_order_ws(symbol, type, side, amount, price=None, takeProfitPrice=None, params={})

create a trigger take profit order(type 2) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float takeProfitPrice: the price to trigger the take profit order, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_trailing_amount_order(symbol, type, side, amount, price=None, trailingAmount=None, trailingTriggerPrice=None, params={})

create a trailing order by providing the symbol, type, side, amount, price and trailingAmount :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency, or number of contracts :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders :param float trailingAmount: the quote amount to trail away from the current market price :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_trailing_amount_order_ws(symbol, type, side, amount, price=None, trailingAmount=None, trailingTriggerPrice=None, params={})

create a trailing order by providing the symbol, type, side, amount, price and trailingAmount :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency, or number of contracts :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders :param float trailingAmount: the quote amount to trail away from the current market price :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_trailing_percent_order(symbol, type, side, amount, price=None, trailingPercent=None, trailingTriggerPrice=None, params={})

create a trailing order by providing the symbol, type, side, amount, price and trailingPercent :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency, or number of contracts :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders :param float trailingPercent: the percent to trail away from the current market price :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_trailing_percent_order_ws(symbol, type, side, amount, price=None, trailingPercent=None, trailingTriggerPrice=None, params={})

create a trailing order by providing the symbol, type, side, amount, price and trailingPercent :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency, or number of contracts :param float [price]: the price for the order to be filled at, in units of the quote currency, ignored in market orders :param float trailingPercent: the percent to trail away from the current market price :param float [trailingTriggerPrice]: the price to activate a trailing order, default uses the price argument :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_trigger_order(symbol, type, side, amount, price=None, triggerPrice=None, params={})

create a trigger stop order(type 1) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float triggerPrice: the price to trigger the stop order, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
create_trigger_order_ws(symbol, type, side, amount, price=None, triggerPrice=None, params={})

create a trigger stop order(type 1) :param str symbol: unified symbol of the market to create an order in :param str type: ‘market’ or ‘limit’ :param str side: ‘buy’ or ‘sell’ :param float amount: how much you want to trade in units of the base currency or the number of contracts :param float [price]: the price to fulfill the order, in units of the quote currency, ignored in market orders :param float triggerPrice: the price to trigger the stop order, in units of the quote currency :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
static ecdsa(request, secret, algorithm='p256', hash=None, fixed_length=False)

ECDSA signing with support for multiple algorithms and coincurve for SECP256K1. Args:

request: The message to sign secret: The private key (hex string or PEM format) algorithm: The elliptic curve algorithm (‘p192’, ‘p224’, ‘p256’, ‘p384’, ‘p521’, ‘secp256k1’) hash: The hash function to use (defaults to algorithm-specific hash) fixed_length: Whether to ensure fixed-length signatures (for deterministic signing) Note: coincurve produces non-deterministic signatures

Returns:

dict: {‘r’: r_value, ‘s’: s_value, ‘v’: v_value}

Note:

If coincurve is not available or fails for SECP256K1, the method automatically falls back to the standard ecdsa implementation.

enable_demo_trading(enable)

enables or disables demo trading mode :param boolean [enable]: True if demo trading should be enabled, False otherwise

Parameters

enable (bool) –

feature_value(symbol, methodName=None, paramName=None, defaultValue=None)

self method is a very deterministic to help users to know what feature is supported by the exchange :param str [symbol]: unified symbol :param str [methodName]: view currently supported methods: https://docs.ccxt.com/#/README?id=features :param str [paramName]: unified param value, like: triggerPrice, `stopLoss.triggerPrice`(check docs for supported param names) :param dict [defaultValue]: return default value if no result found :returns dict: returns feature value

Parameters
feature_value_by_type(marketType, subType, methodName=None, paramName=None, defaultValue=None)

self method is a very deterministic to help users to know what feature is supported by the exchange :param str [marketType]: supported only: “spot”, “swap”, “future” :param str [subType]: supported only: “linear”, “inverse” :param str [methodName]: view currently supported methods: https://docs.ccxt.com/#/README?id=features :param str [paramName]: unified param value(check docs for supported param names) :param dict [defaultValue]: return default value if no result found :returns dict: returns feature value

Parameters
fetch(url, method='GET', headers=None, body=None)

Perform a HTTP request and return decoded JSON data

fetch_deposits_withdrawals(code=None, since=None, limit=None, params={})

fetch history of deposits and withdrawals :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None :param int [limit]: max number of deposit/withdrawals to return, default is None :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a list of transaction structures <https://docs.ccxt.com/?id=transaction-structure>

Parameters
fetch_index_ohlcv(symbol, timeframe='1m', since=None, limit=None, params={})

fetches historical index price candlestick data containing the open, high, low, and close price of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int [since]: timestamp in ms of the earliest candle to fetch :param int [limit]: the maximum amount of candles to fetch :param dict [params]: extra parameters specific to the exchange API endpoint

@returns {} A list of candles ordered, open, high, low, close, None

Parameters
fetch_margin_adjustment_history(symbol=None, type=None, since=None, limit=None, params={})

fetches the history of margin added or reduced from contract isolated positions :param str [symbol]: unified market symbol :param str [type]: “add” or “reduce” :param int [since]: timestamp in ms of the earliest change to fetch :param int [limit]: the maximum amount of changes to fetch :param dict params: extra parameters specific to the exchange api endpoint :returns dict[]: a list of margin structures <https://docs.ccxt.com/?id=margin-loan-structure>

Parameters
fetch_mark_ohlcv(symbol, timeframe='1m', since=None, limit=None, params={})

fetches historical mark price candlestick data containing the open, high, low, and close price of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int [since]: timestamp in ms of the earliest candle to fetch :param int [limit]: the maximum amount of candles to fetch :param dict [params]: extra parameters specific to the exchange API endpoint :returns float[][]: A list of candles ordered, open, high, low, close, None

Parameters
fetch_order_with_client_order_id(clientOrderId, symbol=None, params={})

create a market order by providing the symbol, side and cost :param str clientOrderId: client order Id :param str symbol: unified symbol of the market to create an order in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: an order structure <https://docs.ccxt.com/?id=order-structure>

Parameters
fetch_orders_by_status_ws(status, symbol=None, since=None, limit=None, params={})

watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data :param str symbol: unified symbol of the market to fetch the order book for :param int [limit]: the maximum amount of order book entries to return :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: A dictionary of order book structures <https://docs.ccxt.com/?id=order-book-structure> indexed by market symbols

Parameters
fetch_position_history(symbol, since=None, limit=None, params={})

fetches the history of margin added or reduced from contract isolated positions :param str [symbol]: unified market symbol :param int [since]: timestamp in ms of the position :param int [limit]: the maximum amount of candles to fetch, default=1000 :param dict params: extra parameters specific to the exchange api endpoint :returns dict[]: a list of position structures <https://docs.ccxt.com/?id=position-structure>

Parameters
fetch_positions_for_symbol(symbol, params={})

fetches all open positions for specific symbol, unlike fetchPositions(which is designed to work with multiple symbols) so self method might be preffered for one-market position, because of less rate-limit consumption and speed :param str symbol: unified market symbol :param dict params: extra parameters specific to the endpoint :returns dict[]: a list of position structure <https://docs.ccxt.com/?id=position-structure> with maximum 3 items - possible one position for “one-way” mode, and possible two positions(long & short) for “two-way”(a.k.a. hedge) mode

Parameters

symbol (str) –

fetch_positions_for_symbol_ws(symbol, params={})

fetches all open positions for specific symbol, unlike fetchPositions(which is designed to work with multiple symbols) so self method might be preffered for one-market position, because of less rate-limit consumption and speed :param str symbol: unified market symbol :param dict params: extra parameters specific to the endpoint :returns dict[]: a list of position structure <https://docs.ccxt.com/?id=position-structure> with maximum 3 items - possible one position for “one-way” mode, and possible two positions(long & short) for “two-way”(a.k.a. hedge) mode

Parameters

symbol (str) –

fetch_positions_history(symbols=None, since=None, limit=None, params={})

fetches the history of margin added or reduced from contract isolated positions :param str [symbol]: unified market symbol :param int [since]: timestamp in ms of the position :param int [limit]: the maximum amount of candles to fetch, default=1000 :param dict params: extra parameters specific to the exchange api endpoint :returns dict[]: a list of position structures <https://docs.ccxt.com/?id=position-structure>

Parameters
fetch_premium_index_ohlcv(symbol, timeframe='1m', since=None, limit=None, params={})

fetches historical premium index price candlestick data containing the open, high, low, and close price of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param int [since]: timestamp in ms of the earliest candle to fetch :param int [limit]: the maximum amount of candles to fetch :param dict [params]: extra parameters specific to the exchange API endpoint :returns float[][]: A list of candles ordered, open, high, low, close, None

Parameters
fetch_transactions(code=None, since=None, limit=None, params={})
@deprecated

DEPRECATED use fetchDepositsWithdrawals instead :param str code: unified currency code for the currency of the deposit/withdrawals, default is None :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None :param int [limit]: max number of deposit/withdrawals to return, default is None :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a list of transaction structures <https://docs.ccxt.com/?id=transaction-structure>

Parameters
fetch_transfer(id, code=None, params={})

fetches a transfer :param str id: transfer id :param [str] code: unified currency code :param dict params: extra parameters specific to the exchange api endpoint :returns dict: a transfer structure <https://docs.ccxt.com/?id=transfer-structure>

Parameters
fetch_transfers(code=None, since=None, limit=None, params={})

fetches a transfer :param str id: transfer id :param int [since]: timestamp in ms of the earliest transfer to fetch :param int [limit]: the maximum amount of transfers to fetch :param dict params: extra parameters specific to the exchange api endpoint :returns dict: a transfer structure <https://docs.ccxt.com/?id=transfer-structure>

Parameters
filter_by_array_positions(objects, key, values=None, indexed=True)
@ignore

Typed wrapper for filterByArray that returns a list of positions

Parameters

key (Union[str, int]) –

filter_by_array_tickers(objects, key, values=None, indexed=True)
@ignore

Typed wrapper for filterByArray that returns a dictionary of tickers

Parameters

key (Union[str, int]) –

handle_margin_mode_and_params(methodName, params={}, defaultValue=None)
@ignore
param dict [params]

extra parameters specific to the exchange API endpoint

returns Array

the marginMode in lowercase by params[“marginMode”], params[“defaultMarginMode”] self.options[“marginMode”] or self.options[“defaultMarginMode”]

Parameters

methodName (str) –

handle_market_type_and_params(methodName, market=None, params={}, defaultValue=None)

@ignore @param methodName the method calling handleMarketTypeAndParams

param Market market

param dict params

param str [params.type]

type assigned by user

param str [params.defaultType]

same.type

param str [defaultValue]

assigned programatically in the method calling handleMarketTypeAndParams

returns [str, dict]

the market type and params with type and defaultType omitted

Parameters
  • methodName (str) –

  • market (Optional[ccxt.base.types.MarketInterface]) –

handle_post_only(isMarketOrder, exchangeSpecificPostOnlyOption, params={})
@ignore
param str type

Order type

param boolean exchangeSpecificBoolean

exchange specific postOnly

param dict [params]

exchange specific params

returns Array

Parameters
  • isMarketOrder (bool) –

  • exchangeSpecificPostOnlyOption (bool) –

  • params (Any) –

handle_request_network(params, request, exchangeSpecificKey, currencyCode=None, isRequired=False)
Parameters
  • params (dict) –

    • extra parameters

  • request (dict) –

    • existing dictionary of request

  • exchangeSpecificKey (str) –

    • the key for chain id to be set in request

  • currencyCode (dict) –

    • (optional) existing dictionary of request

  • isRequired (boolean) –

    • (optional) whether that param is required to be present

Returns dict[]
  • returns [request, params] where request is the modified request object and params is the modified params object

handle_time_in_force(params={})

@ignore Must add timeInForce to self.options to use self method

returns str

returns the exchange specific value for timeInForce

handle_trigger_direction_and_params(params, exchangeSpecificKey=None, allowEmpty=False)
@ignore
returns [str, dict]

the trigger-direction value and omited params

Parameters
integer_precision_to_amount(precision)
@ignore

handles positive & negative numbers too. parsePrecision() does not handle negative numbers, but self method handles :param str precision: The number of digits to the right of the decimal :returns str: a string number equal to 1e-precision

Parameters

precision (Optional[str]) –

is_post_only(isMarketOrder, exchangeSpecificParam, params={})
@ignore
param str type

Order type

param boolean exchangeSpecificParam

exchange specific postOnly

param dict [params]

exchange specific params

returns boolean

True if a post only order, False otherwise

Parameters

isMarketOrder (bool) –

network_code_to_id(networkCode, currencyCode=None)
@ignore

tries to convert the provided networkCode(which is expected to be an unified network code) to a network id. In order to achieve self, derived class needs to have ‘options->networks’ defined. :param str networkCode: unified network code :param str currencyCode: unified currency code, but self argument is not required by default, unless there is an exchange(like huobi) that needs an override of the method to be able to pass currencyCode argument additionally :returns str|None: exchange-specific network id

Parameters
network_id_to_code(networkId=None, currencyCode=None)
@ignore

tries to convert the provided exchange-specific networkId to an unified network Code. In order to achieve self, derived class needs to have “options[‘networksById’]” defined. :param str networkId: exchange specific network id/title, like: TRON, Trc-20, usdt-erc20, etc :param str|None currencyCode: unified currency code, but self argument is not required by default, unless there is an exchange(like huobi) that needs an override of the method to be able to pass currencyCode argument additionally :returns str|None: unified network code

Parameters
number

alias of float

parse_deposit_withdraw_fees(response, codes=None, currencyIdKey=None)
@ignore
param object[]|dict response

unparsed response from the exchange

param str[]|None codes

the unified currency codes to fetch transactions fees for, returns all currencies when None

param str currencyIdKey

should only be None when response is a dictionary the object key that corresponds to the currency id

returns dict

objects with withdraw and deposit fees, indexed by currency codes

Parameters

codes (Optional[List[str]]) –

parse_incomes(incomes, market=None, since=None, limit=None)
@ignore

parses funding fee info from exchange response :param dict[] incomes: each item describes once instance of currency being received or paid :param dict market: ccxt market :param int [since]: when defined, the response items are filtered to only include items after self timestamp :param int [limit]: limits the number of items in the response :returns dict[]: an array of funding history structures <https://docs.ccxt.com/?id=funding-history-structure>

Parameters
parse_liquidations(liquidations, market=None, since=None, limit=None)
@ignore

parses liquidation info from the exchange response :param dict[] liquidations: each item describes an instance of a liquidation event :param dict market: ccxt market :param int [since]: when defined, the response items are filtered to only include items after self timestamp :param int [limit]: limits the number of items in the response :returns dict[]: an array of liquidation structures <https://docs.ccxt.com/?id=liquidation-structure>

Parameters
parse_precision(precision)
@ignore
param str precision

The number of digits to the right of the decimal

returns str

a string number equal to 1e-precision

Parameters

precision (str) –

safe_bool(dictionary, key, defaultValue=None)
@ignore

safely extract boolean value from dictionary or list :returns bool | None:

Parameters
safe_bool_2(dictionary, key1, key2, defaultValue=None)
@ignore

safely extract boolean value from dictionary or list :returns bool | None:

Parameters
safe_bool_n(dictionaryOrList, keys, defaultValue=None)
@ignore

safely extract boolean value from dictionary or list :returns bool | None:

Parameters
safe_dict(dictionary, key, defaultValue=None)
@ignore

safely extract a dictionary from dictionary or list :returns dict | None:

Parameters
safe_dict_2(dictionary, key1, key2, defaultValue=None)
@ignore

safely extract a dictionary from dictionary or list :returns dict | None:

Parameters
safe_dict_n(dictionaryOrList, keys, defaultValue=None)
@ignore

safely extract a dictionary from dictionary or list :returns dict | None:

Parameters
static safe_either(method, dictionary, key1, key2, default_value=None)

A helper-wrapper for the safe_value_2() family.

safe_list(dictionaryOrList, key, defaultValue=None)
@ignore

safely extract an Array from dictionary or list :returns Array | None:

Parameters
safe_list_2(dictionaryOrList, key1, key2, defaultValue=None)
@ignore

safely extract an Array from dictionary or list :returns Array | None:

Parameters
safe_list_n(dictionaryOrList, keys, defaultValue=None)
@ignore

safely extract an Array from dictionary or list :returns Array | None:

Parameters
set_sandbox_mode(enabled)

set the sandbox mode for the exchange :param boolean enabled: True to enable sandbox mode, False to disable it

Parameters

enabled (bool) –

static truncate(num, precision=0)

Deprecated, use decimal_to_precision instead

static truncate_to_string(num, precision=0)

Deprecated, todo: remove references from subclasses

un_watch_bids_asks(symbols=None, params={})

unWatches best bid & ask for symbols :param str[] symbols: unified symbol of the market to fetch the ticker for :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a ticker structure <https://docs.ccxt.com/?id=ticker-structure>

Parameters

symbols (Optional[List[str]]) –

un_watch_my_trades(symbol=None, params={})

unWatches information on multiple trades made by the user :param str symbol: unified market symbol of the market orders were made in :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict[]: a list of order structures <https://docs.ccxt.com/?id=order-structure>

Parameters

symbol (Optional[str]) –

un_watch_ohlcv(symbol, timeframe='1m', params={})

watches historical candlestick data containing the open, high, low, and close price, and the volume of a market :param str symbol: unified symbol of the market to fetch OHLCV data for :param str timeframe: the length of time each candle represents :param dict [params]: extra parameters specific to the exchange API endpoint :returns int[][]: A list of candles ordered, open, high, low, close, volume

Parameters
  • symbol (str) –

  • timeframe (str) –

watch_mark_price(symbol, params={})

watches a mark price for a specific market :param str symbol: unified symbol of the market to fetch the ticker for :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a ticker structure <https://docs.ccxt.com/?id=ticker-structure>

Parameters

symbol (str) –

watch_mark_prices(symbols=None, params={})

watches the mark price for all markets :param str[] symbols: unified symbol of the market to fetch the ticker for :param dict [params]: extra parameters specific to the exchange API endpoint :returns dict: a ticker structure <https://docs.ccxt.com/?id=ticker-structure>

Parameters

symbols (Optional[List[str]]) –

withdraw_ws(code, amount, address, tag=None, params={})

make a withdrawal :param str code: unified currency code :param float amount: the amount to withdraw :param str address: the address to withdraw to :param str tag: :param dict [params]: extra parameters specific to the bitvavo api endpoint :returns dict: a transaction structure <https://docs.ccxt.com/?id=transaction-structure>

Parameters
exception GMXOrderFailedException

Bases: ccxt.base.errors.ExchangeError

Raised when a GMX order fails at the protocol level despite transaction success.

This occurs when GMX emits OrderCancelled or OrderFrozen events, which can happen even when the keeper transaction succeeds (receipt.status == 1).

Common failure reasons:

  • MaxOpenInterestExceeded: Pool has hit its open interest limit

  • InsufficientPoolAmount: Not enough liquidity in the pool

  • OrderNotFulfillableAtAcceptablePrice: Price moved beyond slippage tolerance

  • MinPositionSize: Order size is below minimum

  • InvalidDecreaseOrderSize: Decrease size doesn’t match position

Variables
  • order_key – The 32-byte GMX order key

  • status – Order status: “cancelled” or “frozen”

  • reason – Human-readable reason string from GMX event

  • decoded_error – Decoded error message from reasonBytes (e.g., “MaxOpenInterestExceeded($1,234.56, $1,000.00)”)

  • error_selector – 4-byte error selector hex string (e.g., “2bf127cf”)

  • reason_bytes – Raw reasonBytes from the GMX event

  • tx_hash – Transaction hash of the failed order

  • receipt – Full transaction receipt

Example usage:

try:
    order = gmx.create_order("ETH/USD", "market", "buy", 100)
except GMXOrderFailedException as e:
    print(f"Order failed: {e.decoded_error}")
    print(f"Order key: {e.order_key.hex()}")
    # Handle failure - do NOT treat as successful order
__init__(order_key, status, reason, decoded_error, error_selector, reason_bytes, tx_hash, receipt)
Parameters
  • order_key (bytes) –

  • status (str) –

  • reason (str | None) –

  • decoded_error (str | None) –

  • error_selector (str | None) –

  • reason_bytes (bytes | None) –

  • tx_hash (str) –

  • receipt (dict) –

__new__(**kwargs)
add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception InsufficientHistoricalDataError

Bases: ccxt.base.errors.ExchangeError

Raised when GMX returns insufficient historical data for requested time range.

This typically occurs when: 1. Backtesting requests data older than GMX’s retention period 2. The market didn’t exist for the entire requested time range 3. There are gaps in historical data due to API issues

Attributes:

symbol: Market symbol that was requested timeframe: Candlestick interval requested requested_start: Unix timestamp (ms) of the requested start time available_start: Unix timestamp (ms) of the earliest available data available_end: Unix timestamp (ms) of the latest available data candles_received: Number of candles actually received

__init__(symbol, timeframe, requested_start, available_start, available_end, candles_received)
Parameters
  • symbol (str) –

  • timeframe (str) –

  • requested_start (int | None) –

  • available_start (int | None) –

  • available_end (int | None) –

  • candles_received (int) –

__new__(**kwargs)
add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Modules

eth_defi.gmx.ccxt.async_support

Async support for GMX CCXT exchange.

eth_defi.gmx.ccxt.errors

Custom exceptions for GMX CCXT exchange.

eth_defi.gmx.ccxt.exchange

CCXT-Compatible Wrapper for GMX Protocol.

eth_defi.gmx.ccxt.monkeypatch

Monkeypatch CCXT to add GMX exchange support without forking.

eth_defi.gmx.ccxt.properties

eth_defi.gmx.ccxt.validation

Validation utilities for GMX CCXT exchange data.