Python + Deriv API: Cómo Crear Tu Primer Bot de Trading Automatizado
📋 Resumen Rápido
- Deriv ofrece una API oficial con WebSocket — el único bróker de opciones con API documentada
- Puedes crear bots en Python que operan automáticamente en cuenta demo o real
- La IA (ChatGPT/Claude) puede generar todo el código del bot por ti
- Este tutorial va de cero a un bot funcional con código listo para copiar
- Todo probado en cuenta demo — sin riesgo
⚠️ Prerrequisitos
Este tutorial es de nivel avanzado. Necesitas Python instalado en tu computadora y conocimientos básicos de línea de comandos. Si nunca has programado, empieza por Deriv Bot (sin código).
⚡ Para seguir este tutorial necesitas una cuenta en Deriv + token de API.
Crear Cuenta Deriv Gratis →1. ¿Por qué la Deriv API?
Deriv es el único bróker de opciones binarias con API oficial. Eso significa:
| Característica | Deriv API | IQ Option API |
|---|---|---|
| Tipo | Oficial | No oficial (comunitaria) |
| Documentación | Completa (api.deriv.com) | Parcial (GitHub) |
| Autenticación | OAuth 2.0 + Token | Login/contraseña directo |
| Riesgo de bloqueo | Cero — fomentado | Posible |
| Protocolo | WebSocket (tiempo real) | WebSocket |
| Soporte | Oficial + comunidad | Solo comunidad |
2. Configuración inicial
Crea tu cuenta Deriv
Ve a deriv.com y crea una cuenta. La cuenta demo se activa automáticamente.
Genera un Token de API
Ve a api.deriv.com → Dashboard → API Token Manager. Crea un token con permisos: Read, Trade, Payments. Cópialo y guárdalo — lo usarás en el código.
Instala las dependencias de Python
Abre la terminal y ejecuta:
pip install websockets asyncio
3. Tu primer bot — código completo
Este bot se conecta a Deriv vía WebSocket, verifica el balance de la cuenta demo y ejecuta un trade Rise/Fall en 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("🔐 Autenticando...")
await ws.send(json.dumps({
"authorize": API_TOKEN
}))
auth_response = json.loads(await ws.recv())
if "error" in auth_response:
print(f"❌ Error de autenticación: {auth_response['error']['message']}")
return
balance = auth_response["authorize"]["balance"]
account = auth_response["authorize"]["loginid"]
print(f"✅ Conectado! Cuenta: {account} | Balance: ${balance}")
# 2. Check if asset is available
print(f"\n📊 Verificando activo {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"✅ Activo encontrado: {sym['display_name']}")
break
if not symbol_found:
print(f"❌ Activo {SYMBOL} no encontrado o no disponible")
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"📈 Comprando {CONTRACT_TYPE} | Stake: ${STAKE} | Duración: {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"❌ Error en compra: {buy_response['error']['message']}")
continue
contract_id = buy_response["buy"]["contract_id"]
buy_price = buy_response["buy"]["buy_price"]
print(f"✅ Contrato abierto! ID: {contract_id} | Precio: ${buy_price}")
# Wait for result
print("⏳ Esperando resultado...")
# 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"🟢 GANANCIA: +${profit:.2f}")
else:
losses += 1
print(f"🔴 PÉRDIDA: ${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"📊 RESUMEN FINAL")
print(f"{'='*40}")
print(f"Total trades: {NUM_TRADES}")
print(f"Ganadores: {wins} ✅")
print(f"Perdedores: {losses} ❌")
print(f"Win rate: {(wins/NUM_TRADES)*100:.1f}%")
print(f"Ganancia/pérdida total: ${total_profit:.2f}")
print(f"{'='*40}")
# ============================================
# RUN
# ============================================
if __name__ == "__main__":
print("🤖 IA Trader Pro — Bot Deriv API")
print("📌 MODO: Cuenta Demo")
print("⚠️ Solo con fines educativos\n")
asyncio.run(connect_and_trade())
4. Cómo ejecutarlo
Guarda el código
Crea un archivo llamado deriv_bot.py y pega el código de arriba. Reemplaza YOUR_TOKEN_HERE por tu token real.
Ejecuta desde la terminal
python deriv_bot.py — El bot se conectará, autenticará y ejecutará 5 trades automáticamente.
Analiza los resultados
Al final, el bot muestra: trades ejecutados, win rate, ganancia/pérdida total. Todo en demo.
5. Personalízalo con IA
Ahora que tienes la base funcionando, usa ChatGPT o Claude para potenciarlo:
🤖 Prompt para IA
La IA reescribirá todo el código con todas estas funcionalidades. Ese es el poder de combinar Python + Deriv API + IA.
6. Referencia de la API
| Endpoint | Qué hace |
|---|---|
| authorize | Autenticarse con token |
| active_symbols | Listar activos disponibles |
| ticks | Stream de precios en tiempo real |
| buy | Comprar contrato (opción/CFD) |
| sell | Vender contrato antes del vencimiento |
| proposal | Simular precio del contrato |
| proposal_open_contract | Estado del contrato abierto |
| balance | Verificar balance |
| transaction | Stream de transacciones |
| profit_table | Historial de ganancias/pérdidas |
Documentación completa: api.deriv.com
⚠️ Aviso importante
Este código es con fines educativos. Siempre usa demo primero. Los bots de trading pueden perder dinero. Nunca operes con capital que no puedas permitirte perder. Prueba mucho antes de considerar cuenta real.
📚 Sigue aprendiendo
→ Deriv Bot: Bots Sin Código (Guía Completa)
→ Cómo Usar IA para Crear Indicadores de Trading
→ Reseña Deriv 2026
→ Empieza Aquí — Guía para Principiantes
🚀 ¿Necesitas cuenta Deriv + token de API? Crea una gratis en 2 minutos.
Crear Cuenta Deriv Gratis →¿IQ Option? Mira Python + IQ Option API (no oficial)
