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
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:Field Specifications
| Field | Type | Required | Description |
|---|---|---|---|
jsonrpc | string | Yes | JSON-RPC protocol version. Must be exactly "2.0" |
method | string | Yes | Method to be invoked. Format: {scope}/{method_name} (e.g., public/get_time, private/buy). Must match an available API method exactly |
params | object | Conditional | Parameter 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 |
id | integer|string | Yes | Request 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/promiseto route responses correctly
Parameter Validation
- Named parameters only: All parameters must be passed as object properties
- Case-sensitive: Parameter names are case-sensitive (
currency≠Currency) - Type validation: Parameters are validated server-side; incorrect types will result in error responses
- Optional parameters: Omit optional parameters entirely rather than passing
nullor 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/jsonrequired 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
- GET (Query String)
- GET (JSON-RPC Body)
- POST
Authenticated Requests
For private methods, authentication is required. The mechanism differs by transport.Authentication Guide
Comprehensive guide to OAuth 2.0 authentication, token management, and security best practices.
Connection Management
Learn about connection scopes, session management, and connection limits.
Response Format
Success Response
Error Response
Response Fields
| Field | Type | Required | Description |
|---|---|---|---|
jsonrpc | string | Yes | Always "2.0" |
id | integer|string | Yes | Same id that was sent in the request. Used to correlate responses with requests |
result | any | Conditional | Present only if request succeeded. Type and structure depend on the method called |
error | object | Conditional | Present only if request failed. Mutually exclusive with result |
testnet | boolean | Yes | false for production environment, true for test environment |
usIn | integer | Yes | Timestamp when request was received (microseconds since Unix epoch, UTC) |
usOut | integer | Yes | Timestamp when response was sent (microseconds since Unix epoch, UTC) |
usDiff | integer | Yes | Server-side processing time in microseconds (usOut - usIn) |
- Every request with a valid
idwill receive exactly one response - Responses maintain the same
idas the request for correlation resultanderrorare 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:
usDiffshows server-side processing time; compare with total RTT to identify network latency
Error Object
When an error occurs, the response contains anerror object conforming to JSON-RPC 2.0 specification:
| Field | Type | Required | Description |
|---|---|---|---|
code | integer | Yes | Numeric error code indicating the error type. Negative codes are JSON-RPC standard errors; positive codes are Deribit-specific errors |
message | string | Yes | Human-readable error message. For standard JSON-RPC errors, matches specification messages |
data | any | No | Additional error context. May contain structured data, error details, or method-specific error information |
Conditional Response Formats
Certain methods support adetailed 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 thedetailed parameter:
private/cancel_all- Cancel all orders across all currencies and instrument kindsprivate/cancel_all_by_currency- Cancel all orders by currencyprivate/cancel_all_by_currency_pair- Cancel all orders by currency pairprivate/cancel_all_by_instrument- Cancel all orders by instrumentprivate/cancel_all_by_kind_or_type- Cancel all orders by kind or typeprivate/cancel_by_label- Cancel orders by label
detailed=false):
- Returns a single integer representing the total count of cancelled orders
- Response format:
{ "jsonrpc": "2.0", "result": 5, "id": 42 }
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 }
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
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
detailed=trueincreases 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=truewhen 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
- 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
- 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
- Establish Connection: Open WebSocket connection to endpoint
- Authenticate: Send
public/authrequest with credentials - Maintain Connection: Keep connection alive with heartbeat/ping if needed
- Handle Reconnection: Implement reconnection logic with exponential backoff
- Re-authenticate: Re-authenticate and re-subscribe after reconnection
- Request/Response Correlation: Use
idfield to match responses to requests - Notification Messages: Handle server-initiated messages (method:
"subscription") withoutidfield - Message Ordering: Responses may arrive out of order; use
idfor correlation - Backpressure: If client cannot process messages fast enough, connection may be terminated with
connection_too_slowerror
HTTP REST
Endpoints:- Production:
https://www.deribit.com/api/v2/{method} - Test Environment:
https://test.deribit.com/api/v2/{method}
- Protocol: HTTP/1.1 or HTTP/2 over TLS (HTTPS)
- Methods: GET and POST supported
- Content-Type:
application/jsonfor POST requests - Connection Lifetime: 15 minutes maximum per connection
- Keep-Alive: Supported but connections expire after 15 minutes regardless
- 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
- One-off data retrieval
- Simple scripts and automation
- Environments where WebSocket is not available
- Testing and debugging
Notification Messages
JSON-RPC 2.0 defines notification messages as requests without anid field. Deribit uses this mechanism for server-to-client subscription updates.
Notification Format
- No
idfield: Notifications do not include anidfield (per JSON-RPC 2.0 spec) - Method: Always
"subscription"for Deribit notifications - Params Structure: Always contains
channel(string) anddata(any) fields - One-way Communication: Notifications are server-initiated; no response expected
- 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
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
- 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
- Token valid across multiple connections
- Specify
session:namein 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
Instrument Naming
Deribit tradeable assets or instruments use the following system of naming:| Kind | Examples | Template | Comments |
|---|---|---|---|
| Future | BTC-25MAR23, BTC-5AUG23 | BTC-DMMMYY | BTC 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. |
| Perpetual | BTC-PERPETUAL | (empty) | Perpetual contract for currency BTC. |
| Option | BTC-25MAR23-420-C, BTC-5AUG23-580-P | BTC-DMMMYY-STRIKE-K | STRIKE 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
errorfield 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.datafor debugging
3. Monitor timing fields
- Track
usDiffto identify slow server processing - Calculate total RTT:
(current_time - request_time) * 1000000microseconds - 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_slowerrors
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_idfor 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