What Is the Deribit API?
The Deribit API provides programmatic access to one of the world’s leading cryptocurrency derivatives exchanges. It allows you to:
-
Access market data in real-time
-
Place and manage orders automatically
-
Monitor your positions and account balance
-
Build custom trading algorithms
The Deribit API allows users to interact programmatically with the exchange to process orders and manage data.
Deribit offers two API interfaces:
-
REST API: Perfect for occasional requests like placing orders or checking account information
-
WebSocket API: Ideal for real-time data streaming and high-frequency trading
Getting Started with Deribit API
Creating API Keys
Before you can start trading, you’ll need to generate API credentials:
-
Log in to your Deribit account
-
Navigate to “Account” → “API” → “API tab”
-
Click “Create New Key”
-
Set appropriate permissions (read, trade, withdraw)
-
Confirm your email to proceed
-
Note that the client id will be part of the API key generation process
-
Copy and securely store your API key and secret
Once the API key is created, it will be ready for use in your applications.
Security tip: Never share your API credentials and consider restricting API access to specific IP addresses.
Setting Up Your Development Environment
You’ll need:
-
A programming language of your choice (Python, JavaScript, etc.)
-
The appropriate Deribit client library or HTTP client
-
Basic understanding of JSON and API concepts
The server will handle requests and responses between your application and the Deribit exchange.
For Python users, here’s a quick installation example:
pip install deribit-api
Making Your First API Call
Authentication
Most API endpoints require authentication. Here's a basic Python example:
import deribit_api
client = deribit_api.RestClient(
key = "YOUR_API_KEY",
secret = "YOUR_API_SECRET",
url = "https://www.deribit.com"
)
# Test connection
result = client.getaccountsummary()
print(result)
It is crucial to keep your access secret confidential to prevent unauthorized access to your user accounts.
Understanding API Rate Limits
Deribit enforces rate limits to ensure fair usage:
-
Without authentication: 20 requests per minute
-
With authentication: 100 requests per minute
-
WebSocket connections: 10 per minute
Exceeding these limits results in temporary IP blocking.
Monitoring your API usage status can help you stay within the rate limits and avoid disruptions.
Working with Market Data
Retrieving Market Information
Before placing trades, you'll want to get current market data:
# Get BTC-USD instrument details
instruments = client.getinstruments(currency="BTC")
# Get current BTC-PERPETUAL price
orderbook = client.getorderbook(instrument="BTC-PERPETUAL")
best_bid_price = orderbook['bids'][0]['price']
best_ask_price = orderbook['asks'][0]['price']
It is important to ensure that the market data you retrieve is up-to-date to make informed trading decisions.
Subscribing to Real-Time Data with WebSockets
For high-frequency trading, WebSockets provide real-time updates:
import websocket
import json
def on_message(ws, message):
data = json.loads(message)
print(data)
ws = websocket.WebSocketApp(
“wss: //www.deribit.com/ws/api/v2”,
on_message = on_message
)
# Subscribe to BTC - PERPETUAL order book
ws.send(json.dumps({
“
jsonrpc”: “2.0”,
“id”: 1,
“method”: “public / subscribe”,
“params”: {
“
channels”: [“book.BTC - PERPETUAL.none .10 .100 ms”]
}
}))
ws.run_forever()
Using WebSockets ensures that your data is continuously updated in real-time.
Placing and Managing Orders
Order Types Explained
Deribit supports several order types:
Order Type | Description | Best Use Case |
---|---|---|
Market | Executes immediately at best available price | When speed is more important than price |
Limit | Executes only at specified price or better | When price is more important than immediate execution |
Stop Market | Market order triggered at specified price | For limiting losses (stop loss) |
Stop Limit | Limit order triggered at specified price | For controlled entries/exits at specific prices |
Deribit also supports trading options contracts, which can be used for various trading strategies.
Placing Orders via API
Here’s how to place a basic limit order:
# Buy 1 BTC-PERPETUAL contract at $30,000
order = client.buy(
instrument = "BTC-PERPETUAL",
amount = 1,
price = 30000,
type = "limit"
)
print(f "Order placed: {order['order']['order_id']}")
You should carefully select the parameters for your order to ensure it meets your trading objectives.
Modifying and Canceling Orders
Sometimes you’ll need to update, change, or cancel existing orders:
# Edit an existing order
edit_result = client.edit(
order_id = "your_order_id",
amount = 2, # New amount
price = 31000 # New price
)
# Cancel an order
cancel_result = client.cancel(order_id="your_order_id")
# Cancel all orders
cancel_all = client.cancelall()
Position Management
Checking Current Positions
Monitor your open positions:
positions = client.positions()
for position in positions:
print(f” Instrument: {
position[‘instrument_name’]
}”)
print(f” Size: {
position[‘size’]
}”)
print(f” Average price: {
position[‘average_price’]
}”)
You can compile a list of your open positions to monitor your trading activity effectively.
Setting Up Position Alerts
Create alerts for position changes:
# Using WebSockets to monitor position changes
ws.send(json.dumps({
"jsonrpc": "2.0",
"id": 2,
"method": "private/subscribe",
"params": {
"channels": ["user.portfolio.BTC"]
}
}))
You can configure your alert settings to receive notifications for position changes.
Risk Management Strategies
Implementing Stop Losses
Protect your capital with automated stop losses:
# Place a stop loss order
stop_loss = client.sell(
instrument = "BTC-PERPETUAL",
amount = 1,
type = "stop_market",
trigger = "mark_price",
stop_price = 29000 # Trigger price
)
When setting up automated stop losses, it is crucial to secure your account with a strong password to ensure the safety of your API access and account information.
Calculating Position Sizing
Determine appropriate position sizes based on your risk tolerance:
# Calculate position size based on risk percentage
def calculate_position_size(account_balance, risk_percentage, entry_price, stop_price):
risk_amount = account_balance * (risk_percentage / 100)
price_difference = abs(entry_price - stop_price)
contract_value = 1 # For BTC contracts
position_size = risk_amount / (price_difference * contract_value)
return position_size
# Example: Risk 1% of a $10,000 account
size = calculate_position_size(10000, 1, 30000, 29500)
print(f "Recommended position size: {size} contracts")
Building Trading Strategies
Simple Moving Average Crossover
Here's a basic example of a moving average crossover strategy:
import pandas as pd
import numpy as np
import time
# Get historical data
def get_history(instrument, interval, count):
history = client.getlasttrades(instrument, count, interval)
prices = [trade['price']
for trade in history['trades']
]
return prices
while True:
prices = get_history("BTC-PERPETUAL", "1", 100)
df = pd.DataFrame(prices, columns = ['price'])
df['sma20'] = df['price'].rolling(20).mean()
df['sma50'] = df['price'].rolling(50).mean()
# Check for crossover
if df['sma20'].iloc[-2] < df['sma50'].iloc[-2] and df['sma20'].iloc[-1] > df['sma50'].iloc[-1]:
# Buy signal
client.buy(instrument="BTC-PERPETUAL", amount=1, type="market")
print("BUY SIGNAL EXECUTED")
elif df['sma20'].iloc[-2] > df['sma50'].iloc[-2] and df['sma20'].iloc[-1] < df['sma50'].iloc[-1]:
# Sell signal
client.sell(instrument="BTC-PERPETUAL", amount=1, type="market")
print("SELL SIGNAL EXECUTED")
time.sleep(60) # Check every minute
You can add additional indicators to enhance the effectiveness of your moving average crossover strategy.
Volatility-Based Grid Trading
This strategy places multiple orders at calculated intervals based on market volatility. The grid trading strategy includes placing multiple orders at calculated intervals based on market volatility:
def setup_grid(instrument, center_price, grid_levels, grid_spacing_percentage):
orders = []
for i in range(1, grid_levels + 1):
# Calculate buy price below center
buy_price = center_price * (1 - (i * grid_spacing_percentage / 100))
buy_order = client.buy(instrument = instrument, amount = 1, price = buy_price, type = "limit")
orders.append(buy_order)
# Calculate sell price above center
sell_price = center_price * (1 + (i * grid_spacing_percentage / 100))
sell_order = client.sell(instrument = instrument, amount = 1, price = sell_price, type = "limit")
orders.append(sell_order)
return orders
# Setup a grid with 5 levels and 1% spacing
current_price = client.getorderbook("BTC-PERPETUAL")['mark_price']
grid_orders = setup_grid("BTC-PERPETUAL", current_price, 5, 1)
Advanced Topics
WebHooks for Trade Notifications
Set up external notifications for trade events:
import requests
def send_webhook(event_type, data):
webhook_url = “https: //your-webhook-endpoint.com/trading-events”
payload = {
“event”: event_type,
“data”: data,
“timestamp”: time.time()
}
requests.post(webhook_url, json = payload)
You may need to sign up for external notification services to receive trade event alerts.
Backtesting Your Strategy
Test your trading logic against historical data:
def backtest_strategy(instrument, days_back, strategy_function):
# Get historical data
end_timestamp = int(time.time())
start_timestamp = end_timestamp - (days_back * 24 * 60 * 60)
historical_data = client.getlasttrades(
instrument = instrument,
start_timestamp = start_timestamp,
end_timestamp = end_timestamp,
count = 5000
)
# Run strategy simulation
return strategy_function(historical_data)
Backtesting your strategy helps ensure its effectiveness before deploying it in a production environment.
Common Challenges and Solutions
Handling API Errors
Implement proper error handling in your code:
try:
result = client.buy(instrument = ”BTC - PERPETUAL”, amount = 1, type = ”market”)
except Exception as e:
print(f” Error placing order: {str(e)}”)
# Implement retry logic or fallback behavior
if "rate limit" in str(e).lower():
time.sleep(10) # Wait before retrying
retry_result = client.buy(instrument = "BTC-PERPETUAL", amount = 1, type = "market")
Dealing with Latency
Minimize latency impact on your trading:
-
Use the WebSocket API for real-time data
-
Consider using a VPS closer to Deribit’s servers
-
Implement connection monitoring with automatic reconnection
Navigating to the appropriate page on the Deribit platform can help you optimize performance and reduce latency.
# Monitor connection health
last_message_time = time.time()
def on_message(ws, message):
global last_message_time
last_message_time = time.time()
# Process message...
def connection_monitor():
while True:
if time.time() - last_message_time > 30: # No message
for 30 seconds
print("Connection may be stale, reconnecting...")
ws.close()
# Reinitialize connection
time.sleep(5)
Conclusion
The Deribit API offers a powerful toolkit for crypto derivatives trading, from basic order placement to complex algorithmic strategies. As you develop your trading system, remember these key points:
-
Start with small test trades before scaling up
-
Implement proper risk management
-
Test thoroughly in the testnet environment
-
Monitor your automated systems continuously
-
Stay within API rate limits to avoid disruptions
With the right approach, the Deribit API can help you execute sophisticated trading strategies with precision and reliability. Whether you're a retail trader or managing institutional funds, programmatic trading can significantly enhance your crypto trading operations.