🐍 Tutorial Avanzado

Python + Deriv API: Cómo Crear Tu Primer Bot de Trading Automatizado

Por Dan Machado · Actualizado Abril 2026 · Lectura: 20 min · Nivel: Avanzado

📋 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ísticaDeriv APIIQ Option API
TipoOficialNo oficial (comunitaria)
DocumentaciónCompleta (api.deriv.com)Parcial (GitHub)
AutenticaciónOAuth 2.0 + TokenLogin/contraseña directo
Riesgo de bloqueoCero — fomentadoPosible
ProtocoloWebSocket (tiempo real)WebSocket
SoporteOficial + comunidadSolo comunidad

2. Configuración inicial

01

Crea tu cuenta Deriv

Ve a deriv.com y crea una cuenta. La cuenta demo se activa automáticamente.

02

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.

03

Instala las dependencias de Python

Abre la terminal y ejecuta:

Terminal 📋 Copiar
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.

Python — Bot Deriv API 📋 Copiar
"""
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

01

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.

02

Ejecuta desde la terminal

python deriv_bot.py — El bot se conectará, autenticará y ejecutará 5 trades automáticamente.

03

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

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.

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

EndpointQué hace
authorizeAutenticarse con token
active_symbolsListar activos disponibles
ticksStream de precios en tiempo real
buyComprar contrato (opción/CFD)
sellVender contrato antes del vencimiento
proposalSimular precio del contrato
proposal_open_contractEstado del contrato abierto
balanceVerificar balance
transactionStream de transacciones
profit_tableHistorial 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.

🚀 ¿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)

DM

Dan Machado

Especialista en IA + Trading. Más en Empieza Aquí.

⚠️ El trading implica riesgo. Código educativo. Contiene enlaces de afiliado a Deriv. Aviso Legal.