gmx.price_sanity

Documentation for eth_defi.gmx.price_sanity Python module.

GMX Price Sanity Check Module.

This module provides functionality to compare GMX oracle (mark/index) prices against ticker ‘last’ prices to detect stale data or price manipulation, especially for low liquidity tokens.

The price sanity check compares two independent price sources: - Oracle prices from /signed_prices/latest endpoint (used for on-chain execution) - Ticker prices from /prices/tickers endpoint (market ticker data)

When the deviation between these prices exceeds a configurable threshold (default 3%), the system can take various actions such as logging warnings, using the oracle price, or raising an exception to prevent potentially problematic trades.

Example:

from eth_defi.gmx.price_sanity import (
    check_price_sanity,
    PriceSanityCheckConfig,
    PriceSanityAction,
)
from eth_defi.gmx.core.oracle import OraclePrices
from eth_defi.gmx.api import GMXAPI

# Fetch prices from both sources
oracle_prices = OraclePrices("arbitrum").get_recent_prices()
ticker_prices = GMXAPI(chain="arbitrum").get_tickers()

# Configure sanity check
config = PriceSanityCheckConfig(
    enabled=True,
    threshold_percent=0.03,  # 3%
    action=PriceSanityAction.use_oracle_warn,
)

# Perform sanity check
result = check_price_sanity(
    oracle_price=oracle_prices["0x82aF49447D8a07e3bd95BD0d56f35241523fBab1"],
    ticker_price=ticker_prices[0],  # First ticker
    token_address="0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
    token_decimals=18,
    config=config,
)

# Check result
if not result.passed:
    print(f"Price deviation: {result.deviation_percent:.2%}")
    print(f"Action taken: {result.action_taken}")

Functions

check_price_sanity(oracle_price, ...)

Compare oracle and ticker prices and determine action.

get_oracle_price_usd(oracle_data, token_decimals)

Extract USD price from oracle data.

get_ticker_price_usd(ticker_data, token_decimals)

Extract USD price from ticker data.

Classes

PriceSanityAction

Actions to take when price deviation exceeds threshold.

PriceSanityCheckConfig

Configuration for price sanity checks.

PriceSanityCheckResult

Result of price sanity check comparison.

Exceptions

PriceSanityException

Raised when price sanity check fails and action is raise_exception.

class PriceSanityAction

Bases: enum.Enum

Actions to take when price deviation exceeds threshold.

use_oracle_warn = 'use_oracle_warn'

Use oracle price and log warning

use_ticker_warn = 'use_ticker_warn'

Use ticker price and log warning

raise_exception = 'raise_exception'

Raise PriceSanityException to block the operation

class PriceSanityCheckConfig

Bases: object

Configuration for price sanity checks.

enabled: bool

Whether price sanity checks are enabled

threshold_percent: float

Deviation threshold as decimal (0.03 = 3%)

action: eth_defi.gmx.price_sanity.PriceSanityAction

Action to take when deviation exceeds threshold

__init__(enabled=True, threshold_percent=0.03, action=PriceSanityAction.use_oracle_warn)
Parameters
Return type

None

class PriceSanityCheckResult

Bases: object

Result of price sanity check comparison.

passed: bool

Whether the check passed (deviation within threshold)

deviation_percent: float

Deviation as decimal (0.045 = 4.5%)

oracle_price_usd: float

Oracle price in USD

ticker_price_usd: float

Ticker price in USD

action_taken: eth_defi.gmx.price_sanity.PriceSanityAction

Action taken based on configuration

token_address: str

Token address that was checked

timestamp: datetime.datetime

Timestamp when check was performed

reason: Optional[str]

Optional reason for failure (e.g., “ticker_fetch_failed”)

__init__(passed, deviation_percent, oracle_price_usd, ticker_price_usd, action_taken, token_address, timestamp, reason=None)
Parameters
Return type

None

exception PriceSanityException

Bases: ccxt.base.errors.ExchangeError

Raised when price sanity check fails and action is raise_exception.

This exception is raised when the deviation between oracle and ticker prices exceeds the configured threshold and the action is set to raise_exception.

Parameters

result – The PriceSanityCheckResult containing details about the failure

__init__(result)
Parameters

result (eth_defi.gmx.price_sanity.PriceSanityCheckResult) –

__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.

get_oracle_price_usd(oracle_data, token_decimals)

Extract USD price from oracle data.

Calculates the median of maxPriceFull and minPriceFull from oracle data and converts it to USD based on token decimals.

Parameters
  • oracle_data (dict) – Oracle price data dictionary with maxPriceFull and minPriceFull

  • token_decimals (int) – Number of decimals for the token (e.g., 18 for ETH)

Returns

Price in USD

Raises

ValueError – If price data is missing or invalid

Return type

float

get_ticker_price_usd(ticker_data, token_decimals)

Extract USD price from ticker data.

Calculates the midpoint of maxPrice and minPrice from ticker data and converts it to USD based on token decimals.

Parameters
  • ticker_data (dict) – Ticker price data dictionary with maxPrice and minPrice

  • token_decimals (int) – Number of decimals for the token (e.g., 18 for ETH)

Returns

Price in USD

Raises

ValueError – If price data is missing or invalid

Return type

float

check_price_sanity(oracle_price, ticker_price, token_address, token_decimals, config)

Compare oracle and ticker prices and determine action.

This function compares prices from two independent sources (oracle and ticker) and calculates the deviation. If the deviation exceeds the configured threshold, it takes the specified action (log warning, use oracle, or raise exception).

The deviation is calculated as:

Parameters
  • oracle_price (dict) – Oracle price data from OraclePrices.get_recent_prices()

  • ticker_price (dict) – Ticker price data from GMXAPI.get_tickers()

  • token_address (str) – Token address being checked

  • token_decimals (int) – Number of decimals for the token

  • config (eth_defi.gmx.price_sanity.PriceSanityCheckConfig) – Configuration for the sanity check

Returns

PriceSanityCheckResult with comparison details and action taken

Return type

eth_defi.gmx.price_sanity.PriceSanityCheckResult