derive.api

Documentation for eth_defi.derive.api Python module.

Derive.xyz public API functions.

Typed wrappers for public (unauthenticated) Derive API endpoints.

Uses create_derive_session() for HTTP connections with rate limiting and retry logic.

Example:

from eth_defi.derive.api import fetch_perpetual_instruments, fetch_funding_rate_history, fetch_open_interest_onchain
from eth_defi.derive.session import create_derive_session
from web3 import Web3

session = create_derive_session()

# Discover all active perpetual instruments
instruments = fetch_perpetual_instruments(session)
print(instruments)  # ['ETH-PERP', 'BTC-PERP', ...]

# Fetch funding rate history for one instrument
rates = fetch_funding_rate_history(session, "ETH-PERP")
for r in rates:
    print(f"{r.timestamp}: rate={r.funding_rate}")

# Fetch historical open interest on-chain
w3 = Web3(Web3.HTTPProvider("https://rpc.derive.xyz"))
oi = fetch_open_interest_onchain(w3, "0xAf65752C4643E25C02F693f9D4FE19cF23a095E3", block_number=36000000)
print(f"OI: {oi}")  # e.g. Decimal('3355.06')

Module Attributes

PERP_OPEN_INTEREST_SELECTOR

ABI selector for openInterest(uint256 subId) on Derive perp contracts.

PERP_GET_PERP_PRICE_SELECTOR

ABI selector for getPerpPrice() on Derive perp contracts.

PERP_GET_INDEX_PRICE_SELECTOR

ABI selector for getIndexPrice() on Derive perp contracts.

DERIVE_BLOCK_TIME_SECONDS

Derive Chain block time in seconds (OP Stack L2, 2s blocks).

Functions

fetch_funding_rate_history(session, ...[, ...])

Fetch funding rate history for a Derive perpetual instrument.

fetch_instrument_details(session[, ...])

Fetch instrument details including on-chain contract addresses.

fetch_open_interest(session, instrument_name)

Fetch the current open interest for a Derive perpetual instrument.

fetch_open_interest_onchain(w3, ...[, sub_id])

Fetch open interest for a Derive perp from on-chain state.

fetch_perp_snapshots_multicall(w3, ...[, sub_id])

Fetch open interest, perp price, and index price for multiple instruments in one RPC call.

fetch_perpetual_instruments(session[, ...])

Fetch all active perpetual instrument names from Derive.

Classes

FundingRateEntry

A single funding rate snapshot from Derive.

OpenInterestEntry

A daily on-chain snapshot for a Derive perpetual instrument.

PerpSnapshotMulticallResult

Result of a single instrument from fetch_perp_snapshots_multicall().

class OpenInterestEntry

Bases: object

A daily on-chain snapshot for a Derive perpetual instrument.

Contains open interest, mark price (perp price), and index price read from on-chain view functions via Multicall3 at daily intervals.

instrument: str

Instrument name (e.g. "ETH-PERP")

timestamp: datetime.datetime

Snapshot timestamp (naive UTC, aligned to midnight)

timestamp_ms: int

Timestamp in milliseconds since epoch

open_interest: decimal.Decimal

Open interest in the instrument’s base currency (e.g. ETH for ETH-PERP). From openInterest(uint256).

perp_price: decimal.Decimal | None

Mark/perp price in USD (18 decimals on-chain). From getPerpPrice() — the first return value (price). None if the call reverted (contract not yet deployed).

index_price: decimal.Decimal | None

Spot/index price in USD (18 decimals on-chain). From getIndexPrice() — the first return value (price). None if the call reverted (contract not yet deployed).

__init__(instrument, timestamp, timestamp_ms, open_interest, perp_price=None, index_price=None)
Parameters
Return type

None

class FundingRateEntry

Bases: object

A single funding rate snapshot from Derive.

Represents one hourly funding rate observation for a perpetual instrument.

instrument: str

Instrument name (e.g. "ETH-PERP")

timestamp: datetime.datetime

Snapshot timestamp (naive UTC)

timestamp_ms: int

Timestamp in milliseconds since epoch

funding_rate: decimal.Decimal

Hourly funding rate as a decimal fraction (e.g. Decimal("0.00001234"))

__init__(instrument, timestamp, timestamp_ms, funding_rate)
Parameters
Return type

None

fetch_perpetual_instruments(session, currency=None, base_url='https://api.lyra.finance', timeout=30.0)

Fetch all active perpetual instrument names from Derive.

Calls the public get_all_instruments endpoint with instrument_type="perp" to discover available perpetual contracts.

Example:

from eth_defi.derive.api import fetch_perpetual_instruments
from eth_defi.derive.session import create_derive_session

session = create_derive_session()
instruments = fetch_perpetual_instruments(session)
# ['ETH-PERP', 'BTC-PERP', 'SOL-PERP', ...]
Parameters
  • session (requests.sessions.Session) – HTTP session from create_derive_session().

  • currency (str | None) – Optional currency filter (e.g. "ETH", "BTC"). If None, returns all active perps.

  • base_url (str) – Derive API base URL.

  • timeout (float) – HTTP request timeout in seconds.

Returns

Sorted list of instrument names.

Raises

ValueError – If the API returns an error response.

Return type

list[str]

fetch_funding_rate_history(session, instrument_name, start_time=None, end_time=None, base_url='https://api.lyra.finance', timeout=30.0)

Fetch funding rate history for a Derive perpetual instrument.

Calls the public get_funding_rate_history endpoint. No authentication required.

Data is returned at hourly resolution — the native funding rate interval on Derive. The full history is available back to instrument inception (ETH-PERP since 2024-01-05).

For best results, keep the query window to one day at a time and use DeriveFundingRateDatabase for bulk historical fetches.

Note

The Derive API requires the parameter names start_timestamp and end_timestamp (not start_time / end_time). Using the wrong names silently falls back to the most recent 30 days.

Example:

from eth_defi.derive.api import fetch_funding_rate_history
from eth_defi.derive.session import create_derive_session

session = create_derive_session()
rates = fetch_funding_rate_history(session, "ETH-PERP")
for r in rates:
    print(f"{r.timestamp}: {r.funding_rate}")
Parameters
  • session (requests.sessions.Session) – HTTP session from create_derive_session().

  • instrument_name (str) – Perpetual instrument name (e.g. "ETH-PERP").

  • start_time (datetime.datetime | None) – Start of the query window (naive UTC). Defaults to 30 days ago.

  • end_time (datetime.datetime | None) – End of the query window (naive UTC). Defaults to now.

  • base_url (str) – Derive API base URL.

  • timeout (float) – HTTP request timeout in seconds.

Returns

List of funding rate entries sorted by timestamp ascending.

Raises

ValueError – If the API returns an error response.

Return type

list[eth_defi.derive.api.FundingRateEntry]

fetch_open_interest(session, instrument_name, base_url='https://api.lyra.finance', timeout=30.0)

Fetch the current open interest for a Derive perpetual instrument.

Calls the public /public/statistics endpoint. No authentication required.

Warning

This endpoint always returns the current live OI regardless of any timestamp parameter. It does not support historical queries. For historical open interest data, use fetch_open_interest_onchain() which reads on-chain state from the Derive Chain archive node at any historical block.

Example:

from eth_defi.derive.api import fetch_open_interest
from eth_defi.derive.session import create_derive_session

session = create_derive_session()
entry = fetch_open_interest(session, "ETH-PERP")
if entry:
    print(f"{entry.timestamp}: {entry.open_interest}")
Parameters
  • session (requests.sessions.Session) – HTTP session from create_derive_session().

  • instrument_name (str) – Perpetual instrument name (e.g. "ETH-PERP") or aggregate type ("PERP", "ALL", "OPTION", "SPOT").

  • base_url (str) – Derive API base URL.

  • timeout (float) – HTTP request timeout in seconds.

Returns

OpenInterestEntry timestamped at the current moment, or None if open interest is zero (instrument not yet listed).

Raises

ValueError – If the API returns an error response.

Return type

eth_defi.derive.api.OpenInterestEntry | None

PERP_OPEN_INTEREST_SELECTOR = '88e53ec8'

ABI selector for openInterest(uint256 subId) on Derive perp contracts.

Verified on Derive Mainnet Blockscout for ETH-PERP contract 0xAf65752C4643E25C02F693f9D4FE19cF23a095E3.

PERP_GET_PERP_PRICE_SELECTOR = '90f76b18'

ABI selector for getPerpPrice() on Derive perp contracts.

Returns (uint256 price, uint256 confidence) — both 18-decimal.

PERP_GET_INDEX_PRICE_SELECTOR = '58c0994a'

ABI selector for getIndexPrice() on Derive perp contracts.

Returns (uint256 price, uint256 confidence) — both 18-decimal.

DERIVE_BLOCK_TIME_SECONDS = 2

Derive Chain block time in seconds (OP Stack L2, 2s blocks).

fetch_open_interest_onchain(w3, contract_address, block_number, sub_id=0)

Fetch open interest for a Derive perp from on-chain state.

Calls openInterest(uint256 subId) on the perp asset contract at the specified historical block. The Derive Chain RPC endpoint (https://rpc.derive.xyz) is an archive node that supports historical eth_call going back to chain genesis.

This is the only way to retrieve historical open interest data — the public /public/statistics REST endpoint always returns the current live value regardless of any end_time parameter.

The returned value is in the instrument’s base currency with 18 decimal places (e.g. ETH for ETH-PERP, BTC for BTC-PERP).

Example:

from web3 import Web3
from eth_defi.derive.api import fetch_open_interest_onchain
from eth_defi.derive.constants import DERIVE_MAINNET_RPC_URL

w3 = Web3(Web3.HTTPProvider(DERIVE_MAINNET_RPC_URL))
# ETH-PERP contract on Derive Mainnet
oi = fetch_open_interest_onchain(
    w3,
    "0xAf65752C4643E25C02F693f9D4FE19cF23a095E3",
    block_number=36000000,
)
print(oi)  # e.g. Decimal('3186.42')
Parameters
  • w3 (web3.main.Web3) – Web3 instance connected to Derive Chain (https://rpc.derive.xyz, chain ID 957).

  • contract_address (str) – The base_asset_address for the instrument, as returned by the /public/get_all_instruments endpoint.

  • block_number (int) – Block number at which to read state. Use estimate_block_at_timestamp() to convert a UTC timestamp to a block number.

  • sub_id (int) – Sub-asset identifier. Always 0 for perpetuals.

Returns

Open interest in the base currency as a Decimal, or None if zero (instrument not yet active at that block).

Raises

Exception – Transient RPC errors (connection failures, timeouts, rate limits) propagate to the caller so the sync loop can abort before advancing the watermark past a hole. Only ContractLogicError (contract revert — meaning the block predates contract deployment) is caught and treated as zero OI.

Return type

decimal.Decimal | None

class PerpSnapshotMulticallResult

Bases: object

Result of a single instrument from fetch_perp_snapshots_multicall().

Groups the three on-chain reads (OI, perp price, index price) for one instrument at one block.

open_interest: decimal.Decimal | None

Open interest in base currency. None if reverted or zero.

perp_price: decimal.Decimal | None

Mark/perp price in USD. None if reverted.

index_price: decimal.Decimal | None

Spot/index price in USD. None if reverted.

__init__(open_interest, perp_price, index_price)
Parameters
Return type

None

fetch_perp_snapshots_multicall(w3, contract_addresses, block_number, sub_id=0)

Fetch open interest, perp price, and index price for multiple instruments in one RPC call.

Uses Multicall3 aggregate3 to batch three view function calls per instrument:

  • openInterest(uint256 subId) — OI in base currency

  • getPerpPrice() — mark/perp price in USD

  • getIndexPrice() — spot/index price in USD

For N instruments this sends 3×N subcalls in a single RPC round-trip. Each call uses allowFailure=True so a single contract reverting (e.g. not yet deployed at that block) does not fail the whole batch.

Parameters
  • w3 (web3.main.Web3) – Web3 instance connected to Derive Chain.

  • contract_addresses (list[str]) – List of perp contract addresses (base_asset_address from the instruments API).

  • block_number (int) – Block number at which to read state.

  • sub_id (int) – Sub-asset identifier. Always 0 for perpetuals.

Returns

List of PerpSnapshotMulticallResult in the same order as contract_addresses.

Raises

Exception – Transient RPC errors propagate to the caller.

Return type

list[eth_defi.derive.api.PerpSnapshotMulticallResult]

fetch_instrument_details(session, base_url='https://api.lyra.finance', timeout=30.0)

Fetch instrument details including on-chain contract addresses.

Returns a mapping of instrument name to instrument metadata dict, including base_asset_address (the on-chain perp contract), scheduled_activation (Unix timestamp of listing), and other fields.

Example:

from eth_defi.derive.api import fetch_instrument_details
from eth_defi.derive.session import create_derive_session

session = create_derive_session()
details = fetch_instrument_details(session)
eth = details["ETH-PERP"]
print(eth["base_asset_address"])  # 0xAf65...
print(eth["scheduled_activation"])  # 1701820800 (Unix timestamp)
Parameters
  • session (requests.sessions.Session) – HTTP session from create_derive_session().

  • base_url (str) – Derive API base URL.

  • timeout (float) – HTTP request timeout in seconds.

Returns

Dict mapping instrument name to metadata dict.

Raises

ValueError – If the API returns an error response.

Return type

dict[str, dict]