Python + Deriv API: अपना पहला Automated Trading Bot कैसे बनाएँ
📋 त्वरित सारांश
- 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 है। इसका मतलब है:
| 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 जोखिम | शून्य — प्रोत्साहित | संभावित |
| Protocol | WebSocket (real-time) | WebSocket |
| Support | Official + community | केवल community |
2. प्रारंभिक setup
अपना Deriv account बनाएँ
deriv.com पर जाएँ और एक account बनाएँ। Demo account automatically enabled होता है।
एक API Token generate करें
api.deriv.com → Dashboard → API Token Manager पर जाएँ। permissions के साथ एक token बनाएँ: Read, Trade, Payments। इसे copy करें और save करें — आप इसे code में उपयोग करेंगे।
Python dependencies install करें
Terminal खोलें और run करें:
pip install websockets asyncio
3. आपका पहला bot — complete code
यह bot WebSocket के माध्यम से Deriv से connect करता है, demo account balance check करता है, और Volatility 75 Index पर एक Rise/Fall trade execute करता है।
"""
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 करें
Code save करें
deriv_bot.py नाम की file बनाएँ और ऊपर का code paste करें। YOUR_TOKEN_HERE को अपने actual token से replace करें।
Terminal से run करें
python deriv_bot.py — Bot connect करेगा, authenticate करेगा, और 5 trades automatically execute करेगा।
Results analyze करें
अंत में, bot दिखाता है: executed trades, win rate, total profit/loss। सब demo पर।
5. AI के साथ Customize करें
अब जब आपके पास base काम कर रहा है, इसे power up करने के लिए ChatGPT या Claude का उपयोग करें:
🤖 AI के लिए Prompt
AI इन सभी features के साथ पूरा code rewrite करेगा। यही है Python + Deriv API + AI को combine करने की शक्ति।
6. API reference
| Endpoint | क्या करता है |
|---|---|
| authorize | Token के साथ authenticate |
| active_symbols | उपलब्ध assets list करें |
| ticks | Real-time price stream |
| buy | Contract खरीदें (option/CFD) |
| sell | Expiry से पहले contract बेचें |
| proposal | Contract pricing simulate करें |
| proposal_open_contract | Open contract status |
| balance | Balance check करें |
| transaction | Transaction stream |
| profit_table | Profit/loss history |
पूरी documentation: api.deriv.com
⚠️ महत्वपूर्ण नोटिस
यह code शैक्षिक उद्देश्यों के लिए है। हमेशा पहले demo का उपयोग करें। Trading bots पैसे खो सकते हैं। ऐसी पूंजी से कभी ट्रेड न करें जिसे खोने का आप जोखिम नहीं उठा सकते। Live account पर विचार करने से पहले extensively test करें।
📚 सीखते रहें
→ Deriv Bot: No-Code Bots (पूरी Guide)
→ Trading Indicators बनाने के लिए AI का उपयोग कैसे करें
→ Deriv Review 2026
→ यहाँ से शुरू करें — Beginner की Guide
🚀 Deriv account + API token चाहिए? 2 मिनट में मुफ्त बनाएँ।
मुफ्त Deriv Account बनाएँ →IQ Option? Python + IQ Option API (unofficial) देखें
