Skip to main content

What is JSON-RPC?

JSON-RPC is a stateless, light-weight remote procedure call (RPC) protocol that uses JSON (RFC 7159) for data encoding. The Deribit API implements JSON-RPC 2.0 specification with specific extensions and limitations. Key features:
  • Simple request/response model with bidirectional communication support
  • Standardized error handling with structured error objects
  • Transport-agnostic design (HTTP, WebSocket, etc.)
  • Stateless protocol (each request is independent)
  • Type-safe parameter passing via named parameters only
JSON-RPC 2.0 Feature Limitations:The following JSON-RPC 2.0 specification features are not supported by the Deribit API:
  • Positional parameters: Only named parameters (object properties) are accepted
  • Batch requests: Each request must be sent individually; batching multiple requests in a single message is not supported
  • Notifications as requests: While the server sends notification messages (subscriptions), clients cannot send notification-style requests (requests without id field are rejected)
Attempting to use unsupported features will result in error responses with appropriate error codes.
WebSocket is the preferred transport mechanism because it’s faster, supports bidirectional communication, and enables real-time subscriptions. HTTP has fundamental limitations: subscriptions and cancel on disconnect are not supported due to HTTP’s request-response model.

Request Format

Basic Structure

All requests must conform to the JSON-RPC 2.0 request structure:
{
  "jsonrpc": "2.0",
  "method": "public/get_instruments",
  "params": {
    "currency": "BTC",
    "kind": "future"
  },
  "id": 42
}

Field Specifications

FieldTypeRequiredDescription
jsonrpcstringYesJSON-RPC protocol version. Must be exactly "2.0"
methodstringYesMethod to be invoked. Format: {scope}/{method_name} (e.g., public/get_time, private/buy). Must match an available API method exactly
paramsobjectConditionalParameter values for the method. Must be an object with named properties. Field names must match expected parameter names exactly (case-sensitive). Can be omitted if method requires no parameters
idinteger|stringYesRequest identifier. Must be unique within the connection context. The response will contain the same identifier. For WebSocket connections, use a monotonically increasing integer or UUID to ensure proper request/response correlation

Request ID Management

Critical for WebSocket connections: Since WebSocket is full-duplex and responses may arrive out of order, proper request ID management is essential:
  • Use unique IDs: Each request must have a unique identifier within the connection lifetime
  • Monotonically increasing integers: Recommended pattern: start at 1, increment for each request
  • UUIDs: Alternative for distributed systems where multiple clients may share connection pools
  • Store pending requests: Maintain a map of request_id -> callback/promise to route responses correctly

Parameter Validation

  • Named parameters only: All parameters must be passed as object properties
  • Case-sensitive: Parameter names are case-sensitive (currencyCurrency)
  • Type validation: Parameters are validated server-side; incorrect types will result in error responses
  • Optional parameters: Omit optional parameters entirely rather than passing null or empty values

HTTP REST Requests

Endpoint: https://www.deribit.com/api/v2/{method} (production)
Endpoint: https://test.deribit.com/api/v2/{method} (test environment)
Technical Specifications:
  • HTTP Methods: Both GET and POST are supported
  • Content-Type: application/json required when sending JSON-RPC in request body
  • Parameter Passing:
    • GET: Parameters can be passed as URL query string (URL-encoded) or in request body as JSON-RPC
    • POST: Parameters passed in request body as JSON-RPC
  • Connection Lifetime: Each HTTP connection expires after 15 minutes of inactivity
  • Keep-Alive: HTTP/1.1 keep-alive is supported but connections are terminated after 15 minutes regardless
curl "https://www.deribit.com/api/v2/public/get_instruments?currency=BTC&kind=future"

Authenticated Requests

For private methods, authentication is required. The mechanism differs by transport.

Response Format

Success Response

{
  "jsonrpc": "2.0",
  "id": 42,
  "result": [
    {
      "tick_size": 2.5,
      "tick_size_steps": [],
      "taker_commission": 0.0005,
      "settlement_period": "month",
      "settlement_currency": "BTC",
      "quote_currency": "USD",
      "price_index": "btc_usd",
      "min_trade_amount": 10,
      "max_liquidation_commission": 0.0075,
      "max_leverage": 50,
      "maker_commission": 0,
      "kind": "future",
      "is_active": true,
      "instrument_name": "BTC-29SEP23",
      "instrument_id": 138583,
      "instrument_type": "reversed",
      "expiration_timestamp": 1695974400000,
      "creation_timestamp": 1664524802000,
      "counter_currency": "USD",
      "contract_size": 10,
      "block_trade_tick_size": 0.01,
      "block_trade_min_trade_amount": 200000,
      "block_trade_commission": 0.00025,
      "base_currency": "BTC"
    },
    {
      "tick_size": 0.5,
      "tick_size_steps": [],
      "taker_commission": 0.0005,
      "settlement_period": "perpetual",
      "settlement_currency": "BTC",
      "quote_currency": "USD",
      "price_index": "btc_usd",
      "min_trade_amount": 10,
      "max_liquidation_commission": 0.0075,
      "max_leverage": 50,
      "maker_commission": 0,
      "kind": "future",
      "is_active": true,
      "instrument_name": "BTC-PERPETUAL",
      "instrument_id": 124972,
      "instrument_type": "reversed",
      "expiration_timestamp": 32503708800000,
      "creation_timestamp": 1534167754000,
      "counter_currency": "USD",
      "contract_size": 10,
      "block_trade_tick_size": 0.01,
      "block_trade_min_trade_amount": 200000,
      "block_trade_commission": 0.00025,
      "base_currency": "BTC"
    }
  ]
}

Error Response

{
  "jsonrpc": "2.0",
  "id": 8163,
  "error": {
    "code": 11050,
    "message": "bad_request"
  },
  "testnet": false,
  "usIn": 1535037392434763,
  "usOut": 1535037392448119,
  "usDiff": 13356
}

Response Fields

FieldTypeRequiredDescription
jsonrpcstringYesAlways "2.0"
idinteger|stringYesSame id that was sent in the request. Used to correlate responses with requests
resultanyConditionalPresent only if request succeeded. Type and structure depend on the method called
errorobjectConditionalPresent only if request failed. Mutually exclusive with result
testnetbooleanYesfalse for production environment, true for test environment
usInintegerYesTimestamp when request was received (microseconds since Unix epoch, UTC)
usOutintegerYesTimestamp when response was sent (microseconds since Unix epoch, UTC)
usDiffintegerYesServer-side processing time in microseconds (usOut - usIn)
Response Guarantees:
  • Every request with a valid id will receive exactly one response
  • Responses maintain the same id as the request for correlation
  • result and error are mutually exclusive (never both present)
The fields testnet, usIn, usOut, and usDiff are Deribit-specific extensions to the JSON-RPC 2.0 specification. They are provided for:
  • Environment identification: Determine if response came from test or production
  • Performance monitoring: Calculate round-trip time and server processing time
  • Latency analysis: usDiff shows server-side processing time; compare with total RTT to identify network latency

Error Object

When an error occurs, the response contains an error object conforming to JSON-RPC 2.0 specification:
FieldTypeRequiredDescription
codeintegerYesNumeric error code indicating the error type. Negative codes are JSON-RPC standard errors; positive codes are Deribit-specific errors
messagestringYesHuman-readable error message. For standard JSON-RPC errors, matches specification messages
dataanyNoAdditional error context. May contain structured data, error details, or method-specific error information
See Error Codes for a complete list of error codes and handling strategies.

Conditional Response Formats

Certain methods support a detailed boolean parameter that modifies the response structure. When detailed=true, the response format changes from a simple count to a comprehensive list of execution reports.

Detailed Response for Cancel Methods

The following methods support the detailed parameter: Default Behavior (detailed=false):
  • Returns a single integer representing the total count of cancelled orders
  • Response format: { "jsonrpc": "2.0", "result": 5, "id": 42 }
Detailed Response (detailed=true):
  • Returns an array of execution report objects
  • Each execution report corresponds to a separate internal cancellation request
  • Provides granular information about successful and failed cancellations per currency, order type, and instrument
  • Response format: { "jsonrpc": "2.0", "result": [{...}, {...}], "id": 42 }
Technical Implementation Details: Internally, cancel_all* methods decompose the cancellation request into multiple sub-requests, each targeting a specific combination of:
  • Currency (e.g., BTC, ETH)
  • Order type (e.g., limit, stop)
  • Instrument book
When detailed=true, the response aggregates execution reports from all sub-requests, allowing clients to:
  • Identify which specific currency/type combinations succeeded or failed
  • Handle partial failures gracefully
  • Debug cancellation issues at a granular level
  • Track cancellation results per instrument or currency
Example Usage:
// Request with detailed=true
{
  "jsonrpc": "2.0",
  "method": "private/cancel_all",
  "params": {
    "detailed": true
  },
  "id": 42
}

// Response with detailed execution reports
{
  "jsonrpc": "2.0",
  "id": 42,
  "result": [
    {
      "order": {
        "order_id": "12345678",
        "instrument_name": "BTC-PERPETUAL",
        "order_state": "cancelled",
        // ... full order details
      }
    },
    {
      "order": {
        "order_id": "87654321",
        "instrument_name": "ETH-PERPETUAL",
        "order_state": "cancelled",
        // ... full order details
      }
    }
    // ... additional execution reports for each currency/type combination
  ]
}
Performance Considerations:
  • detailed=true increases response payload size significantly
  • Processing time may be slightly higher due to aggregation overhead
  • Use detailed=false (default) when only the cancellation count is needed
  • Use detailed=true when granular cancellation tracking is required for error handling or auditing

Transport Protocols

WebSocket (Preferred)

Endpoints:
  • Production: wss://www.deribit.com/ws/api/v2
  • Test Environment: wss://test.deribit.com/ws/api/v2
Technical Specifications:
  • Protocol: WebSocket (RFC 6455) over TLS (WSS)
  • Subprotocol: None required
  • Frame Format: Text frames (UTF-8 encoded JSON)
  • Message Format: Each WebSocket message contains a single JSON-RPC request or response
  • Connection Limits: Maximum 32 connections per IP address
  • Session Limits: Maximum 16 sessions per API key
Advantages:
  • Bidirectional Communication: Full-duplex connection enables server-to-client notifications
  • Lower Latency: Persistent connection eliminates HTTP handshake overhead
  • Real-time Subscriptions: Supports subscription channels for live market data
  • Cancel on Disconnect: Automatic order cancellation on connection loss (when enabled)
  • Session Persistence: Session-scoped authentication persists across reconnections
  • Higher Rate Limits: Authenticated WebSocket connections have higher rate limits than HTTP
Connection Lifecycle:
  1. Establish Connection: Open WebSocket connection to endpoint
  2. Authenticate: Send public/auth request with credentials
  3. Maintain Connection: Keep connection alive with heartbeat/ping if needed
  4. Handle Reconnection: Implement reconnection logic with exponential backoff
  5. Re-authenticate: Re-authenticate and re-subscribe after reconnection
Message Handling:
  • Request/Response Correlation: Use id field to match responses to requests
  • Notification Messages: Handle server-initiated messages (method: "subscription") without id field
  • Message Ordering: Responses may arrive out of order; use id for correlation
  • Backpressure: If client cannot process messages fast enough, connection may be terminated with connection_too_slow error

HTTP REST

Endpoints:
  • Production: https://www.deribit.com/api/v2/{method}
  • Test Environment: https://test.deribit.com/api/v2/{method}
Technical Specifications:
  • Protocol: HTTP/1.1 or HTTP/2 over TLS (HTTPS)
  • Methods: GET and POST supported
  • Content-Type: application/json for POST requests
  • Connection Lifetime: 15 minutes maximum per connection
  • Keep-Alive: Supported but connections expire after 15 minutes regardless
Limitations:
  • No Subscriptions: HTTP’s request-response model cannot support server-initiated messages
  • No Cancel on Disconnect: No persistent connection to monitor for disconnection events
  • Higher Latency: Each request requires TCP/TLS handshake (unless connection pooling/reuse)
  • Lower Rate Limits: Unauthenticated HTTP requests have stricter rate limits
  • No Session Persistence: Each request is independent; no connection state
Use Cases for HTTP:
  • One-off data retrieval
  • Simple scripts and automation
  • Environments where WebSocket is not available
  • Testing and debugging
HTTP Limitations:
  • Subscriptions are not supported via HTTP. Use WebSocket for any subscription-based functionality.
  • Cancel on disconnect is not supported via HTTP. This feature requires a persistent WebSocket connection.
  • For production trading systems, WebSocket is strongly recommended for lower latency and real-time capabilities.

Notification Messages

JSON-RPC 2.0 defines notification messages as requests without an id field. Deribit uses this mechanism for server-to-client subscription updates.

Notification Format

{
  "jsonrpc": "2.0",
  "method": "subscription",
  "params": {
    "channel": "deribit_price_index.btc_usd",
    "data": {
      "timestamp": 1535098298227,
      "price": 6521.17,
      "index_name": "btc_usd"
    }
  }
}
Key Characteristics:
  • No id field: Notifications do not include an id field (per JSON-RPC 2.0 spec)
  • Method: Always "subscription" for Deribit notifications
  • Params Structure: Always contains channel (string) and data (any) fields
  • One-way Communication: Notifications are server-initiated; no response expected
Technical Considerations:
  • Message Ordering: Notifications are sent in order per channel, but different channels may interleave
  • Backpressure: If client cannot process notifications fast enough, connection may be terminated
  • Reconnection: After reconnection, re-subscribe to channels; first notification per channel is typically a full snapshot
See Notifications for detailed information about subscription channels and notification handling.

Connection Management

Connection Limits

  • Per IP: Maximum 32 simultaneous connections (HTTP + WebSocket combined)
  • Per API Key: Maximum 16 active sessions
  • Per Account: Maximum 20 subaccounts
Connection Counting:
  • Each HTTP request creates a temporary connection
  • Each WebSocket connection counts as one persistent connection
  • Both connection-scoped and session-scoped connections count toward limits

Session vs Connection Scope

Connection Scope (default):
  • Token valid only for the specific connection
  • Token invalidated when connection closes
  • Must re-authenticate on reconnection
  • Does not count against session limit
Session Scope:
  • Token valid across multiple connections
  • Specify session:name in authentication request
  • Token persists until session expires or is invalidated
  • Counts against 16-session limit per API key
  • Subsequent requests on same connection can omit token
See Connection Management Best Practices for detailed guidance.

Instrument Naming

Deribit tradeable assets or instruments use the following system of naming:
KindExamplesTemplateComments
FutureBTC-25MAR23, BTC-5AUG23BTC-DMMMYYBTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.
PerpetualBTC-PERPETUAL(empty)Perpetual contract for currency BTC.
OptionBTC-25MAR23-420-C, BTC-5AUG23-580-PBTC-DMMMYY-STRIKE-KSTRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options. In Linear Options d is used as a decimal point for decimal strikes. Example: For XRP_USDC-30JUN23-0d625-C strike is 0.625.

Best Practices

1

Request/Response Handling

1. Use unique request IDs

  • Critical for WebSocket: Responses may arrive out of order
  • Use monotonically increasing integers or UUIDs
  • Maintain a map of pending requests for correlation
  • Implement request timeouts (recommended: 30 seconds)

2. Handle errors appropriately

  • Always check for error field in responses
  • Distinguish between JSON-RPC protocol errors and application errors
  • Implement retry logic for transient errors (rate limits, timeouts)
  • Log error details including error.data for debugging

3. Monitor timing fields

  • Track usDiff to identify slow server processing
  • Calculate total RTT: (current_time - request_time) * 1000000 microseconds
  • Network latency = Total RTT - usDiff
  • Alert on high latency or processing times
2

Transport Selection

4. Use WebSocket for production systems

  • Lower latency for trading operations
  • Required for subscriptions and real-time data
  • Supports cancel on disconnect
  • Higher rate limits for authenticated connections

5. Use HTTP for simple operations

  • One-off data retrieval
  • Scripts and automation
  • Testing and debugging
  • When WebSocket is not available
3

Performance Optimization

6. Implement connection pooling (HTTP)

  • Reuse connections when possible
  • Be aware of 15-minute connection expiration
  • Use HTTP/2 when available for multiplexing

7. Optimize WebSocket usage

  • Keep connections alive and reuse them
  • Avoid connection churn (open/close repeatedly)
  • Implement exponential backoff for reconnections
  • Use session-scoped authentication to reduce token overhead

8. Manage subscriptions efficiently

  • Only subscribe to channels you need
  • Use aggregated intervals (100ms, agg2) when appropriate
  • Unsubscribe from unused channels
  • Monitor for connection_too_slow errors
4

Error Handling & Reconnection

9. Implement robust error handling

  • Handle rate limit errors (10028) with backoff
  • Detect and handle connection failures
  • Implement circuit breakers for repeated failures
  • Log errors with context for debugging

10. Handle reconnections gracefully

  • Re-authenticate after reconnection
  • Re-subscribe to all active channels
  • Handle missed messages (use change_id for order books)
  • Maintain state across reconnections
5

Security

11. Secure credential management

  • Never expose API keys or secrets in client-side code
  • Use environment variables or secure key stores
  • Rotate credentials regularly
  • Implement proper token refresh logic

12. Validate all inputs

  • Validate parameters before sending requests
  • Handle unexpected response structures
  • Sanitize user inputs to prevent injection attacks