Python + Deriv API: How to Build Your First Automated Trading Bot
π Quick Summary
- Deriv offers an official API with WebSocket β the only options broker with a documented API
- You can build bots in Python that trade automatically on demo or live accounts
- AI (ChatGPT/Claude) can generate the entire bot code for you
- This tutorial goes from zero to a working bot with copy-paste code
- Everything tested on a demo account β no risk
β οΈ Prerequisites
This tutorial is advanced level. You need Python installed on your computer and basic command-line knowledge. If you’ve never coded, start with the Deriv Bot (no code).
β‘ To follow this tutorial you need a Deriv account + API token.
Create Free Deriv Account β1. Why the Deriv API?
Deriv is the only binary options broker with an official API. That means:
| Feature | Deriv API | IQ Option API |
|---|---|---|
| Type | Official | Unofficial (community) |
| Documentation | Complete (api.deriv.com) | Partial (GitHub) |
| Authentication | OAuth 2.0 + Token | Direct login/password |
| Ban risk | Zero β encouraged | Possible |
| Protocol | WebSocket (real-time) | WebSocket |
| Support | Official + community | Community only |
2. Initial setup
Create your Deriv account
Go to deriv.com and create an account. The demo account is enabled automatically.
Generate an API Token
Go to api.deriv.com β Dashboard β API Token Manager. Create a token with permissions: Read, Trade, Payments. Copy and save it β you’ll use it in the code.
Install Python dependencies
Open the terminal and run:
pip install websockets asyncio
3. Your first bot β complete code
This bot connects to Deriv via WebSocket, checks the demo account balance, and executes a Rise/Fall trade on Volatility 75 Index.
"""
Trading Bot β Deriv API + Python
IA Trader Pro β iatraderpro.com/
Author: Dan Machado
IMPORTANT: Use only on a DEMO account!
"""
import asyncio
import json
import websockets
# ============================================
# CONFIG β Edit here
# ============================================
API_TOKEN = "YOUR_TOKEN_HERE" # Paste your Deriv API token
SYMBOL = "R_75" # Volatility 75 Index
CONTRACT_TYPE = "CALL" # CALL = Rise, PUT = Fall
DURATION = 5 # Duration in ticks
DURATION_UNIT = "t" # t = ticks, s = seconds, m = minutes
STAKE = 1.0 # Stake amount in USD
CURRENCY = "USD" # Account currency
NUM_TRADES = 5 # Number of trades to execute
API_URL = "wss://ws.derivws.com/websockets/v3?app_id=1089"
# ============================================
# BOT FUNCTIONS
# ============================================
async def connect_and_trade():
"""Connects to Deriv API and executes trades."""
async with websockets.connect(API_URL) as ws:
# 1. Authenticate with token
print("π Authenticating...")
await ws.send(json.dumps({
"authorize": API_TOKEN
}))
auth_response = json.loads(await ws.recv())
if "error" in auth_response:
print(f"β Authentication error: {auth_response['error']['message']}")
return
balance = auth_response["authorize"]["balance"]
account = auth_response["authorize"]["loginid"]
print(f"β
Connected! Account: {account} | Balance: ${balance}")
# 2. Check if asset is available
print(f"\nπ Checking asset {SYMBOL}...")
await ws.send(json.dumps({
"active_symbols": "brief",
"product_type": "basic"
}))
symbols_response = json.loads(await ws.recv())
symbol_found = False
for sym in symbols_response.get("active_symbols", []):
if sym["symbol"] == SYMBOL:
symbol_found = True
print(f"β
Asset found: {sym['display_name']}")
break
if not symbol_found:
print(f"β Asset {SYMBOL} not found or unavailable")
return
# 3. Execute trades
wins = 0
losses = 0
total_profit = 0
for i in range(NUM_TRADES):
print(f"\n{'='*40}")
print(f"π€ Trade {i+1}/{NUM_TRADES}")
print(f"{'='*40}")
# Buy contract
print(f"π Buying {CONTRACT_TYPE} | Stake: ${STAKE} | Duration: {DURATION}{DURATION_UNIT}")
await ws.send(json.dumps({
"buy": 1,
"price": STAKE,
"parameters": {
"contract_type": CONTRACT_TYPE,
"symbol": SYMBOL,
"duration": DURATION,
"duration_unit": DURATION_UNIT,
"currency": CURRENCY,
"basis": "stake",
"amount": STAKE
}
}))
buy_response = json.loads(await ws.recv())
if "error" in buy_response:
print(f"β Buy error: {buy_response['error']['message']}")
continue
contract_id = buy_response["buy"]["contract_id"]
buy_price = buy_response["buy"]["buy_price"]
print(f"β
Contract opened! ID: {contract_id} | Price: ${buy_price}")
# Wait for result
print("β³ Waiting for result...")
# Subscribe to contract updates
await ws.send(json.dumps({
"proposal_open_contract": 1,
"contract_id": contract_id,
"subscribe": 1
}))
# Wait until contract closes
while True:
response = json.loads(await ws.recv())
if "proposal_open_contract" in response:
contract = response["proposal_open_contract"]
if contract.get("is_sold"):
profit = contract["profit"]
total_profit += profit
if profit > 0:
wins += 1
print(f"π’ PROFIT: +${profit:.2f}")
else:
losses += 1
print(f"π΄ LOSS: ${profit:.2f}")
# Cancel subscription
if "id" in response.get("subscription", {}):
await ws.send(json.dumps({
"forget": response["subscription"]["id"]
}))
await ws.recv()
break
# Pause between trades
await asyncio.sleep(2)
# 4. Final summary
print(f"\n{'='*40}")
print(f"π FINAL SUMMARY")
print(f"{'='*40}")
print(f"Total trades: {NUM_TRADES}")
print(f"Wins: {wins} β
")
print(f"Losses: {losses} β")
print(f"Win rate: {(wins/NUM_TRADES)*100:.1f}%")
print(f"Total profit/loss: ${total_profit:.2f}")
print(f"{'='*40}")
# ============================================
# RUN
# ============================================
if __name__ == "__main__":
print("π€ IA Trader Pro β Deriv API Bot")
print("π MODE: Demo Account")
print("β οΈ For educational purposes only\n")
asyncio.run(connect_and_trade())
4. How to run
Save the code
Create a file called deriv_bot.py and paste the code above. Replace YOUR_TOKEN_HERE with your actual token.
Run from terminal
python deriv_bot.py β The bot will connect, authenticate, and execute 5 trades automatically.
Analyze the results
At the end, the bot shows: trades executed, win rate, total profit/loss. All on demo.
5. Customize with AI
Now that you have the base working, use ChatGPT or Claude to power it up:
π€ Prompt for AI
AI will rewrite the entire code with all these features. That’s the power of combining Python + Deriv API + AI.
6. API reference
| Endpoint | What it does |
|---|---|
| authorize | Authenticate with token |
| active_symbols | List available assets |
| ticks | Real-time price stream |
| buy | Buy contract (option/CFD) |
| sell | Sell contract before expiry |
| proposal | Simulate contract pricing |
| proposal_open_contract | Open contract status |
| balance | Check balance |
| transaction | Transaction stream |
| profit_table | Profit/loss history |
Full documentation: api.deriv.com
β οΈ Important notice
This code is for educational purposes. Always use demo first. Trading bots can lose money. Never trade with capital you can’t afford to lose. Test extensively before considering a live account.
π Keep learning
β Deriv Bot: No-Code Bots (Complete Guide)
β How to Use AI to Build Trading Indicators
β Deriv Review 2026
β Start Here β Beginner’s Guide
π Need a Deriv account + API token? Create one free in 2 minutes.
Create Free Deriv Account βIQ Option? See Python + IQ Option API (unofficial)