Deribit SDK
Complete reference for ctx.deribit — programmatic options & futures trading on Deribit from worker code.
Deribit V2 API
This SDK wraps the Deribit V2 JSON-RPC API over HTTP. Live and testnet environments supported. Server mode required — Deribit's CORS policy blocks browser requests.
Setup
- Add a Deribit trading block to your workspace canvas.
- Open the inspector → API Keys → pick a key (Settings → API Keys → Deribit to add new).
- Connect the block to your Worker block via an edge.
- The worker must run in Server mode (Deribit blocks browser CORS).
ctx.deribitis now available.
def tick(ctx):
px = ctx.deribit.get_ticker("BTC-PERPETUAL")["last_price"]
ctx.log.info(f"BTC perp: {px}")If no Deribit block is connected:
RuntimeError: No trading block connected. Connect a Deribit block to this worker.Currencies & Modes
Deribit denominates everything by currency (margin coin), not by symbol. The supported currencies are BTC, ETH, SOL, USDC, USDT, MATIC, XRP (subject to change — fetch via get_currencies).
Account modes (api_mode on key):
| Mode | Endpoint | Notes |
|---|---|---|
live | www.deribit.com | Real funds |
testnet | test.deribit.com | Synthetic test environment |
There's no demo / paper mode on Deribit — testnet is the only sandbox.
Instrument naming follows {ASSET}-{EXPIRY/PERP}-{STRIKE}-{C|P}:
| Pattern | Example | Meaning |
|---|---|---|
{COIN}-PERPETUAL | BTC-PERPETUAL | Perpetual swap |
{COIN}-{EXPIRY} | BTC-27JUN25 | Dated future |
{COIN}-{EXPIRY}-{STRIKE}-{C|P} | BTC-27JUN25-100000-C | Call option |
Market Data
get_ticker
Latest ticker for an instrument. Includes mark price, IV (for options), open interest.
ctx.deribit.get_ticker(instrument_name: str = "BTC-PERPETUAL") -> dictReturns: {"instrument_name", "last_price", "best_bid_price", "best_ask_price", "mark_price", "index_price", "open_interest", "mark_iv" (options), "delta", "gamma", "vega", "theta", "rho" (Greeks for options), …}
t = ctx.deribit.get_ticker("BTC-27JUN25-100000-C")
ctx.log.info(f"IV: {t['mark_iv']}, delta: {t['greeks']['delta']}")WebSocket cache
PRO/MAX plans return cached ticker data at 0ms latency from the live WS stream — no REST call.
get_instrument
Full metadata for one instrument: tick_size, min_trade_amount, contract_size, expiration, settlement period, taker/maker commission, option_type, strike, kind.
ctx.deribit.get_instrument(instrument_name: str) -> dictm = ctx.deribit.get_instrument("BTC-PERPETUAL")
tick = m["tick_size"] # 0.5
min_qty = m["min_trade_amount"] # 10
maker_fee = m["maker_commission"]get_instruments
List all instruments for a currency, optionally filtered by kind.
ctx.deribit.get_instruments(currency: str = "BTC", kind: str = "option") -> dict
# kind: "future" | "option" | "spot" | "future_combo" | "option_combo"get_combos
List multi-leg combo instruments (vertical spreads, condors, calendar spreads…) for a currency.
ctx.deribit.get_combos(currency: str = "BTC", state: str = None) -> dict
# state: "rfq" | "active" | "inactive"get_currencies
All supported margin currencies on Deribit.
ctx.deribit.get_currencies() -> listget_index_price
Underlying index price (basket of spot prices Deribit tracks).
ctx.deribit.get_index_price(index_name: str = "btc_usd") -> dict
# index_name: "btc_usd" | "eth_usd" | "btc_usdc" | …get_order_book
Order book depth.
ctx.deribit.get_order_book(instrument_name: str, depth: int = 10) -> dictReturns: {"bids": [[price, size]], "asks": [[price, size]], "best_bid_price", "best_ask_price", "mark_price", "open_interest", …}
get_book_summary_by_currency
Aggregate book summary for all instruments of a currency.
ctx.deribit.get_book_summary_by_currency(currency: str = "BTC", kind: str = None) -> dictget_last_trades_by_currency
Recent public trades aggregated by currency.
ctx.deribit.get_last_trades_by_currency(currency: str = "BTC", count: int = 100) -> dictget_tradingview_chart_data
OHLCV candle data in TradingView format.
ctx.deribit.get_tradingview_chart_data(
instrument_name: str = "BTC-PERPETUAL",
resolution: str = "60", # "1" | "3" | "5" | "10" | "15" | "30" | "60" | "120" | "180" | "360" | "720" | "1D"
start_timestamp: int = None,
end_timestamp: int = None,
) -> dictcandles = ctx.deribit.get_tradingview_chart_data("BTC-PERPETUAL", resolution="60")
closes = candles["close"] # list of last 1h candlesget_mark_price_history
Mark-price history for an instrument.
ctx.deribit.get_mark_price_history(
instrument_name: str = "BTC-PERPETUAL",
start_timestamp: int = None,
end_timestamp: int = None,
) -> dictget_funding_rate_history
Historical funding rate (perps).
ctx.deribit.get_funding_rate_history(
instrument_name: str = "BTC-PERPETUAL",
start_timestamp: int = None,
end_timestamp: int = None,
) -> dictget_funding_rate_value
Funding rate value over a window.
ctx.deribit.get_funding_rate_value(
instrument_name: str = "BTC-PERPETUAL",
start_timestamp: int = None,
end_timestamp: int = None,
) -> dictget_delivery_prices
Historical delivery / settlement prices.
ctx.deribit.get_delivery_prices(index_name: str = "btc_usd", count: int = 20) -> dictget_expirations
Upcoming expiry timestamps for futures and options.
ctx.deribit.get_expirations(currency: str = "BTC", kind: str = "option") -> dictget_historical_volatility
Realised vol time series (daily).
ctx.deribit.get_historical_volatility(currency: str = "BTC") -> dictget_volatility_index_data
Deribit volatility index (DVOL) candles.
ctx.deribit.get_volatility_index_data(
currency: str = "BTC",
resolution: str = "3600", # seconds
start_timestamp: int = None,
end_timestamp: int = None,
) -> dictget_trade_volumes
Platform-wide 24h trading volumes.
ctx.deribit.get_trade_volumes() -> dictAccount & Positions
get_account_summary
Balance, equity, margin, P&L for a currency.
ctx.deribit.get_account_summary(currency: str = "BTC") -> dictReturns: {"balance", "equity", "available_funds", "available_withdrawal_funds", "initial_margin", "maintenance_margin", "delta_total", "session_upl", "session_rpl", "futures_pl", "options_pl", "options_delta", "options_gamma", "options_vega", "options_theta", …}
get_account_summaries
Summaries for ALL currencies at once.
ctx.deribit.get_account_summaries() -> dictget_positions
All open positions for a currency.
ctx.deribit.get_positions(currency: str = "BTC") -> dictWebSocket cache
PRO/MAX: cached at 0ms.
simulate_portfolio
What-if calculator: compute margin / Greeks for a hypothetical portfolio.
ctx.deribit.simulate_portfolio(
currency: str = "BTC",
add_positions: list = [], # [{"instrument_name", "amount", "side"}, …]
) -> dictsim = ctx.deribit.simulate_portfolio(
currency="BTC",
add_positions=[
{"instrument_name": "BTC-27JUN25-100000-C", "amount": 1, "side": "buy"},
{"instrument_name": "BTC-27JUN25-110000-C", "amount": 1, "side": "sell"},
],
)
ctx.log.info(f"Required margin: {sim['initial_margin']}")get_margins
Required margin for a hypothetical order.
ctx.deribit.get_margins(
instrument_name: str = "BTC-PERPETUAL",
amount: float = 0.1,
price: float = None,
) -> dictget_transaction_log
Account ledger: trades, settlements, transfers, fees.
ctx.deribit.get_transaction_log(currency: str = "BTC", count: int = 20) -> dictget_settlement_history
Historical settlements (option exercise / delivery).
ctx.deribit.get_settlement_history(currency: str = "BTC", count: int = 20) -> dictOrders
place_order
Place a single order. Auto-routes buy/sell.
ctx.deribit.place_order(
instrument_name: str,
side: str, # "buy" | "sell"
amount: float, # contracts (10 = 10 contracts)
order_type: str = "market", # "market" | "limit" | "stop_market" | "stop_limit"
price: float = None, # required for limit / stop_limit
) -> dict# Buy 1 BTC perp at market
r = ctx.deribit.place_order("BTC-PERPETUAL", "buy", 10, "market") # 10 = $10 (BTC contract = $10)
# Limit-sell call option
r = ctx.deribit.place_order(
instrument_name="BTC-27JUN25-100000-C",
side="sell", amount=1,
order_type="limit", price=0.05, # in BTC
)edit_order
Modify an unfilled order (qty + price).
ctx.deribit.edit_order(order_id: str, amount: float, price: float) -> dictcancel_order
Cancel a single order.
ctx.deribit.cancel_order(order_id: str) -> dictcancel_all
Cancel all orders, optionally filtered by currency.
ctx.deribit.cancel_all(currency: str = None) -> dictcancel_all_by_instrument
Cancel all orders for one instrument.
ctx.deribit.cancel_all_by_instrument(
instrument_name: str,
order_type: str = None, # "all" | "limit" | "stop"
) -> dictclose_position
Close a position immediately at market.
ctx.deribit.close_position(
instrument_name: str = "BTC-PERPETUAL",
type: str = "market", # "market" | "limit"
price: float = None,
) -> dictget_orders / get_open_orders
Active (unfilled) orders.
ctx.deribit.get_orders(currency: str = "BTC") -> dict
ctx.deribit.get_open_orders(currency: str = "BTC") -> listWebSocket cache
PRO/MAX: cached at 0ms.
get_order_state
State of a single order.
ctx.deribit.get_order_state(order_id: str) -> dictget_order_history_by_currency
Full order history.
ctx.deribit.get_order_history_by_currency(currency: str = "BTC", count: int = 20) -> dictget_user_trades
User's filled trades with fees.
ctx.deribit.get_user_trades(currency: str = "BTC", count: int = 20) -> dictSafety / Heartbeat
Critical for HFT bots: ensure orders self-cancel if the worker crashes or the network drops.
enable_cancel_on_disconnect
Auto-cancel all orders if the connection drops.
ctx.deribit.enable_cancel_on_disconnect(scope: str = "connection") -> dict
# scope: "connection" (only this conn) | "account" (account-wide)def setup(ctx):
# Account-wide kill switch — if ANY connection from this account drops,
# everything cancels. Strongest safety setting.
ctx.deribit.enable_cancel_on_disconnect("account")disable_cancel_on_disconnect
Turn off the dead-man switch.
ctx.deribit.disable_cancel_on_disconnect(scope: str = "connection") -> dictset_heartbeat
Server-side heartbeat probes — server sends test_request every N seconds. If the worker doesn't respond, the server drops the connection (and combined with cancel_on_disconnect: all orders are killed).
ctx.deribit.set_heartbeat(interval_secs: int = 30) -> dictCommon Patterns
Testnet during development
Set the API-key mode to testnet in Settings → API Keys → Deribit. All worker calls auto-route to test.deribit.com. Mint test BTC at test.deribit.com.
Error handling
def tick(ctx):
try:
positions = ctx.deribit.get_positions("BTC")
except Exception as e:
ctx.log.error(f"Deribit unreachable: {e}")
returnDeribitAPIError (extends ExchangeAPIError) is raised for API errors with code and msg attributes. Network failures raise httpx.HTTPStatusError.
WebSocket caching
PRO+ subscribes to public + private streams in the background. Methods get_ticker, get_account_summary, get_positions, get_orders auto-prefer the cache when fresh.
Server-only
Deribit blocks browser-origin CORS. data.deribit block has serverOnly: true — workers must run in Server mode (PRO+ plan).
Recipes
Covered call income strategy
Sell weekly OTM calls against a long perp position.
def setup(ctx):
# Safety net: if the worker dies, everything cancels
ctx.deribit.enable_cancel_on_disconnect("account")
ctx.deribit.set_heartbeat(30)
def tick(ctx):
pos = ctx.deribit.get_positions("BTC")
perp_size = next((float(p["size"]) for p in pos["result"]
if p["instrument_name"] == "BTC-PERPETUAL"), 0)
if perp_size <= 0:
ctx.log.info("No long position — skipping")
return
# Find the nearest weekly OTM call ~5% above spot
spot = float(ctx.deribit.get_index_price("btc_usd")["index_price"])
target = spot * 1.05
instruments = ctx.deribit.get_instruments("BTC", kind="option")["result"]
calls = [i for i in instruments
if i["option_type"] == "call"
and i["strike"] >= target
and i["expiration_timestamp"]]
calls.sort(key=lambda x: (x["expiration_timestamp"], x["strike"]))
if not calls:
return
target_call = calls[0]
name = target_call["instrument_name"]
# Already short this call?
short = next((p for p in pos["result"] if p["instrument_name"] == name), None)
if short and float(short["size"]) < 0:
return
# Sell 1 contract per BTC of long exposure
contracts = max(1, int(perp_size / 1))
ctx.deribit.place_order(name, "sell", contracts, "market")
ctx.log.info(f"Sold {contracts}x {name}")Delta-neutral straddle harvest
Buy a straddle every Monday, hedge delta dynamically.
def tick(ctx):
summary = ctx.deribit.get_account_summary("BTC")
delta = float(summary.get("delta_total", 0))
# Re-hedge if delta drifts more than 0.05 BTC
if abs(delta) > 0.05:
side = "sell" if delta > 0 else "buy"
size = abs(delta) * 10 # BTC perp contract = $10
ctx.deribit.place_order("BTC-PERPETUAL", side,
round(size), "market")
ctx.log.info(f"Re-hedged: {side} {size} perp to flatten delta {delta:.4f}")Vol surface scanner
Find IV-rich strikes across the entire option chain.
def tick(ctx):
summary = ctx.deribit.get_book_summary_by_currency("BTC", kind="option")
rich = sorted(summary["result"],
key=lambda x: (x.get("mark_iv") or 0),
reverse=True)[:5]
for opt in rich:
ctx.log.info(
f"{opt['instrument_name']:30} IV={opt['mark_iv']:5.1f}% "
f"vol24={opt.get('volume_usd', 0):.0f}"
)Reference
| Deribit endpoint | SDK method |
|---|---|
/public/ticker | get_ticker |
/public/get_instrument | get_instrument |
/public/get_instruments | get_instruments |
/public/get_combos | get_combos |
/public/get_currencies | get_currencies |
/public/get_index_price | get_index_price |
/public/get_order_book | get_order_book |
/public/get_book_summary_by_currency | get_book_summary_by_currency |
/public/get_last_trades_by_currency | get_last_trades_by_currency |
/public/get_tradingview_chart_data | get_tradingview_chart_data |
/public/get_mark_price_history | get_mark_price_history |
/public/get_funding_rate_history | get_funding_rate_history |
/public/get_funding_rate_value | get_funding_rate_value |
/public/get_delivery_prices | get_delivery_prices |
/public/get_expirations | get_expirations |
/public/get_historical_volatility | get_historical_volatility |
/public/get_volatility_index_data | get_volatility_index_data |
/public/get_trade_volumes | get_trade_volumes |
/private/get_account_summary | get_account_summary |
/private/get_account_summaries | get_account_summaries |
/private/get_positions | get_positions |
/private/simulate_portfolio | simulate_portfolio |
/private/get_margins | get_margins |
/private/get_transaction_log | get_transaction_log |
/private/get_settlement_history | get_settlement_history |
/private/buy /private/sell | place_order |
/private/edit | edit_order |
/private/cancel | cancel_order |
/private/cancel_all | cancel_all |
/private/cancel_all_by_instrument | cancel_all_by_instrument |
/private/close_position | close_position |
/private/get_open_orders_by_currency | get_orders / get_open_orders |
/private/get_order_state | get_order_state |
/private/get_order_history_by_currency | get_order_history_by_currency |
/private/get_user_trades_by_currency | get_user_trades |
/private/enable_cancel_on_disconnect | enable_cancel_on_disconnect |
/private/disable_cancel_on_disconnect | disable_cancel_on_disconnect |
/private/set_heartbeat | set_heartbeat |