🐍 Advanced Tutorial

Python + Deriv API: अपना पहला Automated Trading Bot कैसे बनाएँ

लेखक: Dan Machado · अपडेट: मई 2026 · पढ़ने का समय: 20 मिनट · स्तर: Advanced

📋 त्वरित सारांश

  • Deriv WebSocket के साथ official API देता है — एकमात्र options broker जिसके पास documented API है
  • आप Python में bots बना सकते हैं जो demo या live accounts पर automatically trade करते हैं
  • AI (ChatGPT/Claude) आपके लिए पूरा bot code generate कर सकता है
  • यह tutorial copy-paste code के साथ शून्य से एक working bot तक जाता है
  • सब कुछ demo account पर tested — कोई जोखिम नहीं

⚠️ Prerequisites

यह tutorial advanced level है। आपके computer पर Python installed और basic command-line knowledge की ज़रूरत है। यदि आपने कभी code नहीं किया, Deriv Bot (no code) से शुरू करें।

⚡ इस tutorial को follow करने के लिए आपको Deriv account + API token चाहिए।

मुफ्त Deriv Account बनाएँ →

1. Deriv API क्यों?

Deriv एकमात्र binary options broker है जिसके पास official API है। इसका मतलब है:

FeatureDeriv APIIQ Option API
TypeOfficialUnofficial (community)
DocumentationComplete (api.deriv.com)Partial (GitHub)
AuthenticationOAuth 2.0 + TokenDirect login/password
Ban जोखिमशून्य — प्रोत्साहितसंभावित
ProtocolWebSocket (real-time)WebSocket
SupportOfficial + communityकेवल community

2. प्रारंभिक setup

01

अपना Deriv account बनाएँ

deriv.com पर जाएँ और एक account बनाएँ। Demo account automatically enabled होता है।

02

एक API Token generate करें

api.deriv.com → Dashboard → API Token Manager पर जाएँ। permissions के साथ एक token बनाएँ: Read, Trade, Payments। इसे copy करें और save करें — आप इसे code में उपयोग करेंगे।

03

Python dependencies install करें

Terminal खोलें और run करें:

Terminal 📋 Copy
pip install websockets asyncio

3. आपका पहला bot — complete code

यह bot WebSocket के माध्यम से Deriv से connect करता है, demo account balance check करता है, और Volatility 75 Index पर एक Rise/Fall trade execute करता है।

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. कैसे run करें

01

Code save करें

deriv_bot.py नाम की file बनाएँ और ऊपर का code paste करें। YOUR_TOKEN_HERE को अपने actual token से replace करें।

02

Terminal से run करें

python deriv_bot.py — Bot connect करेगा, authenticate करेगा, और 5 trades automatically execute करेगा।

03

Results analyze करें

अंत में, bot दिखाता है: executed trades, win rate, total profit/loss। सब demo पर।

5. AI के साथ Customize करें

अब जब आपके पास base काम कर रहा है, इसे power up करने के लिए ChatGPT या Claude का उपयोग करें:

🤖 AI के लिए Prompt

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 इन सभी features के साथ पूरा code rewrite करेगा। यही है Python + Deriv API + AI को combine करने की शक्ति।

6. API reference

Endpointक्या करता है
authorizeToken के साथ authenticate
active_symbolsउपलब्ध assets list करें
ticksReal-time price stream
buyContract खरीदें (option/CFD)
sellExpiry से पहले contract बेचें
proposalContract pricing simulate करें
proposal_open_contractOpen contract status
balanceBalance check करें
transactionTransaction stream
profit_tableProfit/loss history

पूरी documentation: api.deriv.com

⚠️ महत्वपूर्ण नोटिस

यह code शैक्षिक उद्देश्यों के लिए है। हमेशा पहले demo का उपयोग करें। Trading bots पैसे खो सकते हैं। ऐसी पूंजी से कभी ट्रेड न करें जिसे खोने का आप जोखिम नहीं उठा सकते। Live account पर विचार करने से पहले extensively test करें।

🚀 Deriv account + API token चाहिए? 2 मिनट में मुफ्त बनाएँ।

मुफ्त Deriv Account बनाएँ →

IQ Option? Python + IQ Option API (unofficial) देखें

DM

Dan Machado

AI + Trading specialist। और यहाँ से शुरू करें में।

⚠️ Trading में जोखिम है। Educational code। Deriv के affiliate links शामिल हैं। Disclaimer