🐍 Advanced Tutorial

Python + Deriv API: How to Build Your First Automated Trading Bot

By Dan Machado Β· Updated April 2026 Β· Read time: 20 min Β· Level: Advanced

πŸ“‹ 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:

FeatureDeriv APIIQ Option API
TypeOfficialUnofficial (community)
DocumentationComplete (api.deriv.com)Partial (GitHub)
AuthenticationOAuth 2.0 + TokenDirect login/password
Ban riskZero β€” encouragedPossible
ProtocolWebSocket (real-time)WebSocket
SupportOfficial + communityCommunity only

2. Initial setup

01

Create your Deriv account

Go to deriv.com and create an account. The demo account is enabled automatically.

02

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.

03

Install Python dependencies

Open the terminal and run:

Terminal πŸ“‹ Copy
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.

Python β€” Deriv API Bot πŸ“‹ Copy
"""
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

01

Save the code

Create a file called deriv_bot.py and paste the code above. Replace YOUR_TOKEN_HERE with your actual token.

02

Run from terminal

python deriv_bot.py β€” The bot will connect, authenticate, and execute 5 trades automatically.

03

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

I have this Python bot for the Deriv API [paste the code]. Modify it to: 1. Add RSI as an indicator (buy CALL when RSI < 30, PUT when RSI > 70) 2. Implement a $50 total stop loss 3. Implement a $25 total take profit 4. Save results to a CSV file 5. Add Martingale (double stake after a loss, return to original after a win, max 3 doublings) Keep comments in English and add detailed logs.

AI will rewrite the entire code with all these features. That’s the power of combining Python + Deriv API + AI.

6. API reference

EndpointWhat it does
authorizeAuthenticate with token
active_symbolsList available assets
ticksReal-time price stream
buyBuy contract (option/CFD)
sellSell contract before expiry
proposalSimulate contract pricing
proposal_open_contractOpen contract status
balanceCheck balance
transactionTransaction stream
profit_tableProfit/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.

πŸš€ Need a Deriv account + API token? Create one free in 2 minutes.

Create Free Deriv Account β†’

IQ Option? See Python + IQ Option API (unofficial)

DM

Dan Machado

AI + Trading specialist. More at Start Here.

⚠️ Trading involves risk. Educational code. Contains affiliate links to Deriv. Disclaimer.

Similar Posts