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
ABI selector for |
|
ABI selector for |
|
ABI selector for |
|
Derive Chain block time in seconds (OP Stack L2, 2s blocks). |
Functions
|
Fetch funding rate history for a Derive perpetual instrument. |
|
Fetch instrument details including on-chain contract addresses. |
|
Fetch the current open interest for a Derive perpetual instrument. |
|
Fetch open interest for a Derive perp from on-chain state. |
|
Fetch open interest, perp price, and index price for multiple instruments in one RPC call. |
|
Fetch all active perpetual instrument names from Derive. |
Classes
A single funding rate snapshot from Derive. |
|
A daily on-chain snapshot for a Derive perpetual instrument. |
|
Result of a single instrument from |
- class OpenInterestEntry
Bases:
objectA 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.
- timestamp: datetime.datetime
Snapshot timestamp (naive UTC, aligned to midnight)
- 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).Noneif 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).Noneif the call reverted (contract not yet deployed).
- __init__(instrument, timestamp, timestamp_ms, open_interest, perp_price=None, index_price=None)
- Parameters
instrument (str) –
timestamp (datetime.datetime) –
timestamp_ms (int) –
open_interest (decimal.Decimal) –
perp_price (decimal.Decimal | None) –
index_price (decimal.Decimal | None) –
- Return type
None
- class FundingRateEntry
Bases:
objectA single funding rate snapshot from Derive.
Represents one hourly funding rate observation for a perpetual instrument.
- timestamp: datetime.datetime
Snapshot timestamp (naive UTC)
- funding_rate: decimal.Decimal
Hourly funding rate as a decimal fraction (e.g.
Decimal("0.00001234"))
- __init__(instrument, timestamp, timestamp_ms, funding_rate)
- Parameters
instrument (str) –
timestamp (datetime.datetime) –
timestamp_ms (int) –
funding_rate (decimal.Decimal) –
- 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_instrumentsendpoint withinstrument_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"). IfNone, 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
- 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_historyendpoint. 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
DeriveFundingRateDatabasefor bulk historical fetches.Note
The Derive API requires the parameter names
start_timestampandend_timestamp(notstart_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
- 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/statisticsendpoint. 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
OpenInterestEntrytimestamped at the current moment, orNoneif open interest is zero (instrument not yet listed).- Raises
ValueError – If the API returns an error response.
- Return type
- 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 historicaleth_callgoing back to chain genesis.This is the only way to retrieve historical open interest data — the public
/public/statisticsREST endpoint always returns the current live value regardless of anyend_timeparameter.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_addressfor the instrument, as returned by the/public/get_all_instrumentsendpoint.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
0for perpetuals.
- Returns
Open interest in the base currency as a
Decimal, orNoneif 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:
objectResult 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.
Noneif reverted or zero.
- perp_price: decimal.Decimal | None
Mark/perp price in USD.
Noneif reverted.
- index_price: decimal.Decimal | None
Spot/index price in USD.
Noneif reverted.
- __init__(open_interest, perp_price, index_price)
- Parameters
open_interest (decimal.Decimal | None) –
perp_price (decimal.Decimal | None) –
index_price (decimal.Decimal | None) –
- 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
aggregate3to batch three view function calls per instrument:openInterest(uint256 subId)— OI in base currencygetPerpPrice()— mark/perp price in USDgetIndexPrice()— spot/index price in USD
For N instruments this sends 3×N subcalls in a single RPC round-trip. Each call uses
allowFailure=Trueso a single contract reverting (e.g. not yet deployed at that block) does not fail the whole batch.- Parameters
- Returns
List of
PerpSnapshotMulticallResultin the same order ascontract_addresses.- Raises
Exception – Transient RPC errors propagate to the caller.
- Return type
- 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