News & Updates

How To Use Deriv API With Python: A Complete Guide

By Spencer Vaughn 9 min read 4863 views

How To Use Deriv API With Python: A Complete Guide

If you’ve ever stared at the Deriv API docs and thought, “There’s got to be an easier way,” you’re not alone. Python makes that jump from documentation to functional code surprisingly smooth—once you know the right steps. Below, I walk through the whole process, from setting up a sandbox environment to handling tricky error messages, all while keeping the tone casual enough to stay readable.

Why Python?

Python’s readability and extensive library ecosystem make it a natural fit for interacting with web APIs. With just a few lines of code you can:

  • Authenticate securely.
  • Send quotes, place trades, and retrieve account history.
  • Automate routine checks without breaking a sweat.

And because Deriv’s endpoints return JSON, Python’s json module feels right at home.

Setting Up Your Workspace

First things first: you’ll need a clean Python environment. I recommend using venv so your dependencies don’t clash with other projects.

Step‑by‑step

  • Open a terminal and navigate to your desired folder.
  • Run python -m venv deriv_env to create the virtual environment.
  • Activate it:
    • Windows: deriv_env\Scripts\activate
    • macOS/Linux: source deriv_env/bin/activate
  • Install the required packages:
    pip install requests websocket-client

That’s it—your sandbox is ready.

Authentication: Getting a Token

The Deriv API uses a token‑based system. You’ll request a token with your API key, then attach that token to every subsequent call.

Sample code

import requests

API_KEY = 'YOUR_API_KEY_HERE'

url = 'https://api.deriv.com/v3/auth_token'

response = requests.post(url, json={'app_id': 1089, 'api_key': API_KEY})

data = response.json()

if data.get('error'):

print('Authentication failed:', data['error'])

else:

token = data['oauth_token']

print('Token acquired:', token[:8] + '...')

Notice the quick check for error. The Deriv docs warn that an expired or malformed key returns a 401; catching that early saves you a lot of head‑scratching later.

Making Your First API Call

With a token in hand, you can start pulling live market data. Let’s fetch the latest tick for the synthetic “R_100” index.

import json

tick_url = 'https://api.deriv.com/v3/tick'

payload = {

'ticks': 1,

'symbols': ['R_100'],

'subscribe': 1,

'passthrough': {'request': 'first_tick'}

}

headers = {'Authorization': f'Bearer {token}'}

tick_resp = requests.post(tick_url, json=payload, headers=headers)

tick_data = tick_resp.json()

print(json.dumps(tick_data, indent=2))

A single line of JSON appears—your first real interaction. If the response looks empty, double‑check that the symbol spelling matches the docs (they’re case‑sensitive).

Handling WebSocket Streams

Many traders prefer real‑time streams over polling. Deriv’s WebSocket endpoint lets you subscribe to price updates, order events, and more.

Quick WebSocket example

import websocket

import json

def on_message(ws, message):

data = json.loads(message)

print('Update:', data)

def on_error(ws, error):

print('Error:', error)

def on_close(ws):

print('Connection closed')

ws = websocket.WebSocketApp(

f'wss://ws.deriv.com/websockets/v3?app_id=1089&l=EN',

on_message=on_message,

on_error=on_error,

on_close=on_close,

header={'Authorization': f'Bearer {token}'}

)

ws.run_forever()

Notice how the on_message callback simply prints the incoming payload. In production you’d route those figures into a data store or trading engine.

Managing Errors and Retries

API hiccups happen. A 429 status signals “rate limit exceeded.” Rather than abort, implement exponential back‑off—a small wait that doubles with each retry.

import time

def safe_request(url, json_payload, headers, tries=3):

delay = 1

for attempt in range(tries):

resp = requests.post(url, json=json_payload, headers=headers)

if resp.status_code == 200:

return resp.json()

elif resp.status_code == 429:

print('Rate limit hit, sleeping...')

time.sleep(delay)

delay *= 2

else:

resp.raise_for_status()

raise Exception('Max retries exceeded')

This pattern keeps your script courteous to Deriv’s servers and reduces the chance of getting blocked.

Best Practices You’ll Appreciate

  • Keep the token secure. Store it in environment variables, never hard‑code it.
  • Validate responses. Even a 200 status can hide error fields in the JSON payload.
  • Respect rate limits. The docs recommend no more than 30 calls per second per IP.
  • Use sandbox first. Deriv provides a demo environment ( demo.deriv.com ) where you can test without risking real money.
  • Log responsibly. Capture request/response pairs for debugging, but scrub sensitive data before persisting.

Where to Find More Help

The official Deriv API reference remains the gold standard. Pair it with these community resources for a smoother ride:

Take a moment to bookmark the WebSocket documentation page; it updates frequently with new event types.

Documentation in Python: The Ultimate Guide (Part 1) - EmiTechLogic
API Documentation Explained (2025 Guide): Types & Benefits - Dev-doc
GitHub - deriv-com/python-deriv-api: Python bindings for deriv.com ...
Deriv API: How to create a Deriv API Token - Trading System - YouTube

Written by Spencer Vaughn

Spencer Vaughn is a Chief Correspondent with over a decade of experience covering breaking trends, in-depth analysis, and exclusive insights.