Skip to content

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 ​

  1. Add a Deribit trading block to your workspace canvas.
  2. Open the inspector → API Keys → pick a key (Settings → API Keys → Deribit to add new).
  3. Connect the block to your Worker block via an edge.
  4. The worker must run in Server mode (Deribit blocks browser CORS).
  5. ctx.deribit is now available.
python
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):

ModeEndpointNotes
livewww.deribit.comReal funds
testnettest.deribit.comSynthetic test environment

There's no demo / paper mode on Deribit — testnet is the only sandbox.

Instrument naming follows {ASSET}-{EXPIRY/PERP}-{STRIKE}-{C|P}:

PatternExampleMeaning
{COIN}-PERPETUALBTC-PERPETUALPerpetual swap
{COIN}-{EXPIRY}BTC-27JUN25Dated future
{COIN}-{EXPIRY}-{STRIKE}-{C|P}BTC-27JUN25-100000-CCall option

Market Data ​

get_ticker ​

Latest ticker for an instrument. Includes mark price, IV (for options), open interest.

python
ctx.deribit.get_ticker(instrument_name: str = "BTC-PERPETUAL") -> dict

Returns: {"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), …}

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

python
ctx.deribit.get_instrument(instrument_name: str) -> dict
python
m = 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.

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

python
ctx.deribit.get_combos(currency: str = "BTC", state: str = None) -> dict
# state: "rfq" | "active" | "inactive"

get_currencies ​

All supported margin currencies on Deribit.

python
ctx.deribit.get_currencies() -> list

get_index_price ​

Underlying index price (basket of spot prices Deribit tracks).

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

python
ctx.deribit.get_order_book(instrument_name: str, depth: int = 10) -> dict

Returns: {"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.

python
ctx.deribit.get_book_summary_by_currency(currency: str = "BTC", kind: str = None) -> dict

get_last_trades_by_currency ​

Recent public trades aggregated by currency.

python
ctx.deribit.get_last_trades_by_currency(currency: str = "BTC", count: int = 100) -> dict

get_tradingview_chart_data ​

OHLCV candle data in TradingView format.

python
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,
) -> dict
python
candles = ctx.deribit.get_tradingview_chart_data("BTC-PERPETUAL", resolution="60")
closes = candles["close"]   # list of last 1h candles

get_mark_price_history ​

Mark-price history for an instrument.

python
ctx.deribit.get_mark_price_history(
    instrument_name: str = "BTC-PERPETUAL",
    start_timestamp: int = None,
    end_timestamp: int = None,
) -> dict

get_funding_rate_history ​

Historical funding rate (perps).

python
ctx.deribit.get_funding_rate_history(
    instrument_name: str = "BTC-PERPETUAL",
    start_timestamp: int = None,
    end_timestamp: int = None,
) -> dict

get_funding_rate_value ​

Funding rate value over a window.

python
ctx.deribit.get_funding_rate_value(
    instrument_name: str = "BTC-PERPETUAL",
    start_timestamp: int = None,
    end_timestamp: int = None,
) -> dict

get_delivery_prices ​

Historical delivery / settlement prices.

python
ctx.deribit.get_delivery_prices(index_name: str = "btc_usd", count: int = 20) -> dict

get_expirations ​

Upcoming expiry timestamps for futures and options.

python
ctx.deribit.get_expirations(currency: str = "BTC", kind: str = "option") -> dict

get_historical_volatility ​

Realised vol time series (daily).

python
ctx.deribit.get_historical_volatility(currency: str = "BTC") -> dict

get_volatility_index_data ​

Deribit volatility index (DVOL) candles.

python
ctx.deribit.get_volatility_index_data(
    currency: str = "BTC",
    resolution: str = "3600",   # seconds
    start_timestamp: int = None,
    end_timestamp: int = None,
) -> dict

get_trade_volumes ​

Platform-wide 24h trading volumes.

python
ctx.deribit.get_trade_volumes() -> dict

Account & Positions ​

get_account_summary ​

Balance, equity, margin, P&L for a currency.

python
ctx.deribit.get_account_summary(currency: str = "BTC") -> dict

Returns: {"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.

python
ctx.deribit.get_account_summaries() -> dict

get_positions ​

All open positions for a currency.

python
ctx.deribit.get_positions(currency: str = "BTC") -> dict

WebSocket cache

PRO/MAX: cached at 0ms.

simulate_portfolio ​

What-if calculator: compute margin / Greeks for a hypothetical portfolio.

python
ctx.deribit.simulate_portfolio(
    currency: str = "BTC",
    add_positions: list = [],     # [{"instrument_name", "amount", "side"}, …]
) -> dict
python
sim = 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.

python
ctx.deribit.get_margins(
    instrument_name: str = "BTC-PERPETUAL",
    amount: float = 0.1,
    price: float = None,
) -> dict

get_transaction_log ​

Account ledger: trades, settlements, transfers, fees.

python
ctx.deribit.get_transaction_log(currency: str = "BTC", count: int = 20) -> dict

get_settlement_history ​

Historical settlements (option exercise / delivery).

python
ctx.deribit.get_settlement_history(currency: str = "BTC", count: int = 20) -> dict

Orders ​

place_order ​

Place a single order. Auto-routes buy/sell.

python
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
python
# 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).

python
ctx.deribit.edit_order(order_id: str, amount: float, price: float) -> dict

cancel_order ​

Cancel a single order.

python
ctx.deribit.cancel_order(order_id: str) -> dict

cancel_all ​

Cancel all orders, optionally filtered by currency.

python
ctx.deribit.cancel_all(currency: str = None) -> dict

cancel_all_by_instrument ​

Cancel all orders for one instrument.

python
ctx.deribit.cancel_all_by_instrument(
    instrument_name: str,
    order_type: str = None,    # "all" | "limit" | "stop"
) -> dict

close_position ​

Close a position immediately at market.

python
ctx.deribit.close_position(
    instrument_name: str = "BTC-PERPETUAL",
    type: str = "market",      # "market" | "limit"
    price: float = None,
) -> dict

get_orders / get_open_orders ​

Active (unfilled) orders.

python
ctx.deribit.get_orders(currency: str = "BTC") -> dict
ctx.deribit.get_open_orders(currency: str = "BTC") -> list

WebSocket cache

PRO/MAX: cached at 0ms.

get_order_state ​

State of a single order.

python
ctx.deribit.get_order_state(order_id: str) -> dict

get_order_history_by_currency ​

Full order history.

python
ctx.deribit.get_order_history_by_currency(currency: str = "BTC", count: int = 20) -> dict

get_user_trades ​

User's filled trades with fees.

python
ctx.deribit.get_user_trades(currency: str = "BTC", count: int = 20) -> dict

Safety / 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.

python
ctx.deribit.enable_cancel_on_disconnect(scope: str = "connection") -> dict
# scope: "connection" (only this conn) | "account" (account-wide)
python
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.

python
ctx.deribit.disable_cancel_on_disconnect(scope: str = "connection") -> dict

set_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).

python
ctx.deribit.set_heartbeat(interval_secs: int = 30) -> dict

Common 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 ​

python
def tick(ctx):
    try:
        positions = ctx.deribit.get_positions("BTC")
    except Exception as e:
        ctx.log.error(f"Deribit unreachable: {e}")
        return

DeribitAPIError (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.

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

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

python
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 endpointSDK method
/public/tickerget_ticker
/public/get_instrumentget_instrument
/public/get_instrumentsget_instruments
/public/get_combosget_combos
/public/get_currenciesget_currencies
/public/get_index_priceget_index_price
/public/get_order_bookget_order_book
/public/get_book_summary_by_currencyget_book_summary_by_currency
/public/get_last_trades_by_currencyget_last_trades_by_currency
/public/get_tradingview_chart_dataget_tradingview_chart_data
/public/get_mark_price_historyget_mark_price_history
/public/get_funding_rate_historyget_funding_rate_history
/public/get_funding_rate_valueget_funding_rate_value
/public/get_delivery_pricesget_delivery_prices
/public/get_expirationsget_expirations
/public/get_historical_volatilityget_historical_volatility
/public/get_volatility_index_dataget_volatility_index_data
/public/get_trade_volumesget_trade_volumes
/private/get_account_summaryget_account_summary
/private/get_account_summariesget_account_summaries
/private/get_positionsget_positions
/private/simulate_portfoliosimulate_portfolio
/private/get_marginsget_margins
/private/get_transaction_logget_transaction_log
/private/get_settlement_historyget_settlement_history
/private/buy /private/sellplace_order
/private/editedit_order
/private/cancelcancel_order
/private/cancel_allcancel_all
/private/cancel_all_by_instrumentcancel_all_by_instrument
/private/close_positionclose_position
/private/get_open_orders_by_currencyget_orders / get_open_orders
/private/get_order_stateget_order_state
/private/get_order_history_by_currencyget_order_history_by_currency
/private/get_user_trades_by_currencyget_user_trades
/private/enable_cancel_on_disconnectenable_cancel_on_disconnect
/private/disable_cancel_on_disconnectdisable_cancel_on_disconnect
/private/set_heartbeatset_heartbeat

NodeGraph Documentation