Deriv API
Documentación
Avanzado

Flujos de trabajo completos

Ejemplos de extremo a extremo de flujos de trabajo de trading comunes usando Deriv API

Requisitos previos

  1. Inicie sesión en developers.deriv.com: Cree una cuenta o inicie sesión con sus credenciales para acceder al panel de control.
  2. Registre una nueva aplicación: Navegue al panel de control y registre una nueva aplicación bajo su cuenta. Elija el tipo de aplicación apropiado según su caso de uso:
    • Tipo PAT: Elija esto cuando las redirecciones del navegador no sean prácticas y la entrada manual de tokens sea aceptable. Por ejemplo, herramientas de escritorio, aplicaciones CLI o clientes nativos. El usuario genera un Personal Access Token en Deriv y lo pega en su aplicación.
    • Tipo OAuth: Elija esto cuando su producto pueda manejar redirecciones del navegador y necesite un flujo delegado estándar con autorización del usuario. Por ejemplo, paneles web o aplicaciones de navegador. OAuth 2.0 emite tokens de corta duración y minimiza el intercambio de credenciales a largo plazo.

    Esto generará un nuevo App ID. Sus App IDs heredados no funcionarán con las nuevas APIs.

  3. Generar un token de autorización:
    • Si usa tipo PAT: En el Panel de Control, vaya a la sección de tokens de API. Cree un nuevo PAT (Personal Access Token) y seleccione los alcances apropiados (por ejemplo, trade, account_manage). Copie y almacene su token de forma segura. No puede visualizarse nuevamente después de su creación.
    • Si usa tipo OAuth: No necesita generar un token manualmente. Proceda al flujo de autenticación OAuth 2.0 descrito a continuación. El flujo proporcionará un token de acceso de corta duración después de una autenticación exitosa. Asegúrese de tener su client_id, client_secret y un redirect_uri HTTPS registrado.
  4. Configure sus encabezados de solicitud: Cada solicitud REST API debe incluir ambos encabezados requeridos:
required-headers.jsjavascript
1// Required headers for ALL REST API calls
2headers: {
3  'Authorization': 'Bearer YOUR_AUTHORIZATION_TOKEN',  // Authorization token (PAT or JWT)
4  'Deriv-App-ID': 'YOUR_APP_ID',                      // App ID from your registered application
5  'Content-Type': 'application/json'
6}

Flujo de trabajo de trading de Options (REST + WebSocket)

  1. REST: Obtenga una URL WebSocket autenticada mediante el endpoint OTP (requiere su token de autorización)
  2. WebSocket: Conéctese usando la URL autenticada de la respuesta OTP
  3. WebSocket: Realizar operaciones de trading

Paso 1: Obtener URL WebSocket autenticada (REST)

get-otp.jsjavascript
1// Get authenticated WebSocket URL via OTP endpoint
2// Note: This REST call requires your authorization token
3const otpResponse = await fetch(
4  `https://api.derivws.com/trading/v1/options/accounts/${accountId}/otp`,
5  {
6    method: 'POST',
7    headers: {
8      'Authorization': 'Bearer YOUR_AUTHORIZATION_TOKEN',  // PAT or JWT token
9      'Deriv-App-ID': 'YOUR_APP_ID'
10    }
11  }
12);
13
14const otpResult = await otpResponse.json();
15const wsUrl = otpResult.data.url;
16console.log('Authenticated WebSocket URL:', wsUrl);
17// Output: wss://api.derivws.com/trading/v1/options/ws/demo?otp=abc123xyz789

Paso 2: Conectarse al WebSocket

connect-websocket.jsjavascript
1// Connect to Options WebSocket using the authenticated URL from OTP response
2// The URL already contains the correct endpoint (demo/real) and authentication
3const ws = new WebSocket(wsUrl);
4
5ws.onopen = () => {
6  console.log('Connected to Options trading WebSocket');
7  // Connection is now authenticated and ready for trading
8};
9
10ws.onmessage = (msg) => {
11  const data = JSON.parse(msg.data);
12  console.log('Received:', data);
13};
14
15ws.onerror = (error) => {
16  console.error('WebSocket error:', error);
17};
18
19ws.onclose = () => {
20  console.log('WebSocket connection closed');
21};

Paso 3: Iniciar Operaciones de Trading

trading-operations.jsjavascript
1// Once connected, you can send trading commands through WebSocket
2// Example: Get account balance
3ws.send(JSON.stringify({
4  balance: 1,
5  subscribe: 1,
6  req_id: 1
7}));
8
9// Example: Subscribe to tick stream
10ws.send(JSON.stringify({
11  ticks: "1HZ100V",
12  subscribe: 1,
13  req_id: 2
14}));
15
16// Example: Get price proposal
17ws.send(JSON.stringify({
18  proposal: 1,
19  amount: 10,
20  basis: "stake",
21  contract_type: "MULTDOWN",
22  currency: "USD",
23  duration_unit: "s",
24  multiplier: 10,
25  underlying_symbol: "1HZ100V",
26  subscribe: 1,
27  req_id: 3
28}));
complete-workflow.jsjavascript
1async function setupOptionsTrading() {
2  const AUTH_TOKEN = 'YOUR_AUTHORIZATION_TOKEN';  // PAT or JWT token
3  const APP_ID = 'YOUR_APP_ID';                   // App ID from registered application
4  const API_BASE = 'https://api.derivws.com';
5  const accountId = 'YOUR_ACCOUNT_ID';            // Your demo or real account ID
6
7  try {
8    // Step 1: Get authenticated WebSocket URL (REST, requires authorization token)
9    const otpResponse = await fetch(
10      `${API_BASE}/trading/v1/options/accounts/${accountId}/otp`,
11      {
12        method: 'POST',
13        headers: {
14          'Authorization': `Bearer ${AUTH_TOKEN}`,
15          'Deriv-App-ID': APP_ID
16        }
17      }
18    );
19
20    if (!otpResponse.ok) throw new Error(`HTTP error! status: ${otpResponse.status}`);
21    const otpData = await otpResponse.json();
22    const wsUrl = otpData.data.url;
23    console.log('✓ Authenticated WebSocket URL obtained');
24
25    // Step 2: Connect to WebSocket using the authenticated URL
26    const ws = new WebSocket(wsUrl);
27
28    ws.onopen = () => {
29      console.log('✓ WebSocket connected');
30
31      // Step 3: Start trading
32      // Subscribe to balance updates
33      ws.send(JSON.stringify({
34        balance: 1,
35        subscribe: 1,
36        req_id: 1
37      }));
38
39      // Subscribe to ticks
40      ws.send(JSON.stringify({
41        ticks: "1HZ100V",
42        subscribe: 1,
43        req_id: 2
44      }));
45    };
46
47    ws.onmessage = (msg) => {
48      const data = JSON.parse(msg.data);
49
50      if (data.msg_type === 'balance') {
51        console.log('Balance:', data.balance.balance, data.balance.currency);
52      }
53
54      if (data.msg_type === 'tick') {
55        console.log('Tick:', data.tick.quote);
56      }
57    };
58
59    return ws;
60
61  } catch (error) {
62    console.error('Setup failed:', error);
63    throw error;
64  }
65}
66
67// Run the setup
68setupOptionsTrading().then(ws => {
69  console.log('Trading setup complete. WebSocket ready for operations.');
70}).catch(err => {
71  console.error('Failed to setup trading:', err);
72});

Flujos de trabajo de autenticación

Flujo de trabajo A: Autenticación basada en PAT

Con una aplicación PAT, el usuario genera un token de acceso personal en Deriv y lo introduce o pega manualmente en su aplicación. La aplicación almacena de forma segura el token y lo incluye en las solicitudes API como token bearer. Esto es más adecuado para herramientas de escritorio, aplicaciones CLI y clientes nativos donde las redirecciones del navegador no son prácticas.

  1. Inicie sesión en developers.deriv.com con sus credenciales
  2. Registre una nueva aplicación con tipo PAT en el panel de control
  3. Generar un token PAT con los alcances apropiados
  4. Include Authorization: Bearer <YOUR_AUTHORIZATION_TOKEN> and Deriv-App-ID in all REST request headers
  5. Realice llamadas REST API autenticadas
pat-authentication.jsjavascript
1// PAT-Based Authentication: REST API
2const AUTH_TOKEN = 'YOUR_AUTHORIZATION_TOKEN';  // Your PAT token
3const APP_ID = 'YOUR_APP_ID';
4
5// All REST calls use the authorization token as a Bearer token
6const response = await fetch('https://api.derivws.com/trading/v1/options/accounts', {
7  method: 'POST',
8  headers: {
9    'Authorization': `Bearer ${AUTH_TOKEN}`,    // Authorization token (PAT)
10    'Deriv-App-ID': APP_ID,                      // App ID from registered application
11    'Content-Type': 'application/json'
12  },
13  body: JSON.stringify({
14    currency: 'USD',
15    group: 'row',
16    account_type: 'demo'
17  })
18});
19
20const result = await response.json();
21console.log('Authenticated REST call successful:', result);

Flujo de trabajo B: Autenticación OAuth 2.0

OAuth 2.0 permite a los usuarios otorgar acceso a su aplicación sin compartir su contraseña. Su aplicación redirige al usuario a una página de inicio de sesión y consentimiento de Deriv. Después de que el usuario inicia sesión y aprueba los permisos, Deriv devuelve un código de autorización a su aplicación. Usted intercambia este código por un token de acceso, que luego usa para autenticar solicitudes API. Recomendado para aplicaciones basadas en web que incorporan usuarios finales.

Antes de comenzar

  • Asegúrese de que su URL de redirección esté correctamente registrada en el panel de control
  • La URL de redirección debe usar HTTPS
  • Su aplicación debe manejar redirecciones, leer el código de autorización e intercambiarlo por tokens
  • Debe tener un cliente OAuth 2.0 registrado con credenciales válidas: client_id, client_secret y redirect_uri
  • Todas las URLs de redirección (incluidos los subdirectorios) deben estar en la lista blanca. Las URLs deben coincidir exactamente.

Pasos del flujo OAuth 2.0

  1. Su aplicación redirige al usuario a la página de autorización OAuth 2.0 de Deriv para iniciar sesión y revisar permisos
  2. El servidor de autorización maneja el inicio de sesión y el consentimiento de forma segura
  3. Después del inicio de sesión, Deriv redirige al usuario de vuelta a su aplicación con un código de autorización y parámetro state
  4. Su aplicación intercambia este código por tokens (con PKCE si se utiliza)
  5. El servidor OAuth devuelve el token de acceso (y token de actualización opcional)
  6. Su aplicación almacena y usa de forma segura el token de acceso para llamadas API REST o WebSocket
oauth-authentication.jsjavascript
1// OAuth 2.0 Authentication Flow (Authorization Code with PKCE)
2const CLIENT_ID = 'YOUR_CLIENT_ID';
3const REDIRECT_URI = 'https://your-app.com/callback';
4
5// --- PKCE Helper Functions ---
6function generateCodeVerifier() {
7  const array = new Uint8Array(32);
8  crypto.getRandomValues(array);
9  return btoa(String.fromCharCode(...array))
10    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
11}
12
13async function generateCodeChallenge(verifier) {
14  const encoder = new TextEncoder();
15  const data = encoder.encode(verifier);
16  const digest = await crypto.subtle.digest('SHA-256', data);
17  return btoa(String.fromCharCode(...new Uint8Array(digest)))
18    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
19}
20
21// Step 1: Generate PKCE values and redirect user to authorization endpoint
22const codeVerifier = generateCodeVerifier();
23const codeChallenge = await generateCodeChallenge(codeVerifier);
24const state = crypto.randomUUID();
25
26sessionStorage.setItem('code_verifier', codeVerifier);
27sessionStorage.setItem('oauth_state', state);
28
29const authUrl = new URL('https://auth.deriv.com/oauth2/auth');
30authUrl.searchParams.set('response_type', 'code');
31authUrl.searchParams.set('client_id', CLIENT_ID);
32authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
33authUrl.searchParams.set('scope', 'trade account_manage');
34authUrl.searchParams.set('state', state);
35authUrl.searchParams.set('code_challenge', codeChallenge);
36authUrl.searchParams.set('code_challenge_method', 'S256');
37
38window.location.href = authUrl.toString();
39
40// Step 3: Handle the callback
41const urlParams = new URLSearchParams(window.location.search);
42const authorizationCode = urlParams.get('code');
43const returnedState = urlParams.get('state');
44
45const savedState = sessionStorage.getItem('oauth_state');
46if (returnedState !== savedState) {
47  throw new Error('State mismatch: possible CSRF attack');
48}
49
50// Step 4: Exchange the authorization code for tokens
51const savedVerifier = sessionStorage.getItem('code_verifier');
52const tokenResponse = await fetch('https://auth.deriv.com/oauth2/token', {
53  method: 'POST',
54  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
55  body: new URLSearchParams({
56    grant_type: 'authorization_code',
57    client_id: CLIENT_ID,
58    code: authorizationCode,
59    redirect_uri: REDIRECT_URI,
60    code_verifier: savedVerifier
61  })
62});
63
64const tokenData = await tokenResponse.json();
65const accessToken = tokenData.access_token;
66console.log('Access token obtained, expires in', tokenData.expires_in, 'seconds');
67
68// Step 6: Use the access token for authenticated API calls
69const response = await fetch('https://api.derivws.com/trading/v1/options/accounts', {
70  method: 'GET',
71  headers: {
72    'Authorization': `Bearer ${accessToken}`,
73    'Deriv-App-ID': CLIENT_ID,
74    'Content-Type': 'application/json'
75  }
76});
77
78const result = await response.json();
79console.log('Authenticated API call successful:', result);

Autenticación WebSocket (OTP)

Para conectarse a un endpoint WebSocket autenticado, necesita llamar al endpoint REST OTP usando su token de autorización (PAT o JWT). La respuesta contiene una URL WebSocket autenticada a la que puede conectarse directamente. La URL maneja la autenticación por usted.

Endpoints WebSocket:

Public
No authentication required

Use for market data and public information. No login needed.

Demo
Authenticated

Use for demo/virtual account trading operations. The OTP response URL will point to this endpoint for demo accounts.

Real
Authenticated

Use for live/real account trading. The OTP response URL will point to this endpoint for real accounts.

websocket-otp-auth.jsjavascript
1// Step 1: Get authenticated WebSocket URL via REST (requires authorization token)
2const otpResponse = await fetch(
3  `https://api.derivws.com/trading/v1/options/accounts/${accountId}/otp`,
4  {
5    method: 'POST',
6    headers: {
7      'Authorization': 'Bearer YOUR_AUTHORIZATION_TOKEN',  // PAT or JWT token
8      'Deriv-App-ID': 'YOUR_APP_ID'
9    }
10  }
11);
12
13const otpResult = await otpResponse.json();
14const wsUrl = otpResult.data.url;
15// The URL already includes the correct endpoint and authentication
16// Output: wss://api.derivws.com/trading/v1/options/ws/demo?otp=abc123xyz789
17
18// Step 2: Connect to WebSocket using the authenticated URL
19const ws = new WebSocket(wsUrl);
20
21ws.onopen = () => {
22  console.log('WebSocket authenticated and connected');
23  // Ready for trading operations
24};

Flujo de trabajo de trading completo

  1. Establecer conexión y autenticar
  2. Obtenga símbolos activos usando active_symbols
  3. Suscríbase al flujo de ticks para el símbolo elegido usando ticks
  4. Obtenga propuesta de contrato usando proposal (con suscripción)
  5. Supervisar actualizaciones de precios en tiempo real
  6. Cuando esté listo, compre el contrato usando buy
  7. Suscríbase a actualizaciones de contratos usando proposal_open_contract
  8. Supervisar el estado del contrato en tiempo real
  9. Opcionalmente venda anticipadamente usando sell
  10. Verifique el portafolio usando portfolio
trading-workflow.jsjavascript
1// After authentication...
2
3// 1. Get active symbols
4ws.send(JSON.stringify({
5  active_symbols: "brief",
6  req_id: 3
7}));
8
9// 2. Subscribe to ticks
10ws.send(JSON.stringify({
11  ticks: "1HZ100V",
12  subscribe: 1,
13  req_id: 4
14}));
15
16// 3. Get price proposal
17ws.send(JSON.stringify({
18  proposal: 1,
19  amount: 10,
20  basis: "stake",
21  contract_type: "MULTDOWN",
22  currency: "USD",
23  duration_unit: "s",
24  multiplier: 10,
25  underlying_symbol: "1HZ100V",
26  subscribe: 1,
27  req_id: 5
28}));
29
30// 4. Buy the contract (when ready)
31// Use proposal ID from previous response
32ws.send(JSON.stringify({
33  buy: "PROPOSAL_ID_HERE",
34  price: 100,
35  req_id: 6
36}));
37
38// 5. Monitor contract status
39ws.send(JSON.stringify({
40  proposal_open_contract: 1,
41  contract_id: CONTRACT_ID,
42  subscribe: 1,
43  req_id: 7
44}));

Flujo de trabajo de datos de mercado

  1. Conéctese al endpoint WebSocket público (no se necesita autenticación)
  2. Solicite active_symbols para ver los mercados disponibles
  3. Suscríbase a ticks para actualizaciones de precios en tiempo real
  4. Opcionalmente obtenga ticks_history para datos históricos
  5. Use contracts_for para ver los tipos de contratos disponibles
  6. El flujo continúa hasta forget o desconexión
market-data.jsjavascript
1// Connect to the public WebSocket endpoint (no authentication required)
2const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3');
3
4ws.onopen = () => {
5  // Get available symbols
6  ws.send(JSON.stringify({
7    active_symbols: "brief",
8    product_type: "basic",
9    req_id: 1
10  }));
11
12  // Subscribe to tick stream
13  ws.send(JSON.stringify({
14    ticks: "1HZ100V",
15    subscribe: 1,
16    req_id: 2
17  }));
18
19  // Get historical data
20  ws.send(JSON.stringify({
21    ticks_history: "1HZ100V",
22    count: 100,
23    end: "latest",
24    style: "ticks",
25    req_id: 3
26  }));
27};
28
29ws.onmessage = (msg) => {
30  const data = JSON.parse(msg.data);
31
32  if (data.msg_type === 'active_symbols') {
33    console.log('Available symbols:', data.active_symbols);
34  }
35
36  if (data.msg_type === 'tick') {
37    console.log('Current price:', data.tick.quote);
38  }
39
40  if (data.msg_type === 'history') {
41    console.log('Historical data:', data.history);
42  }
43};

Solución de problemas

401 Unauthorized
"You are not authorised to access this resource"

Causas comunes:

  • Missing Authorization: Bearer <YOUR_AUTHORIZATION_TOKEN> header in REST requests
  • Using an expired or invalid authorization token
  • Using a legacy App ID instead of a new App ID registered on developers.deriv.com
  • Mismatched application type, such as using a PAT token with an OAuth-type application, or vice versa

Solución: Ensure your REST requests include Authorization: Bearer YOUR_AUTHORIZATION_TOKEN and use a new App ID registered on developers.deriv.com. Make sure your token type matches your application type.

403 Forbidden
Insufficient permissions

Causas comunes:

  • Authorization token does not have the required scopes for the endpoint
  • You created the token without trade or account_manage scope

Solución: Regenerate your token with the correct scopes selected. At least one scope must be defined when creating a token.

Invalid App ID
App ID not recognised

Causas comunes:

  • Using a legacy App ID with the new API
  • Using an App ID not registered on developers.deriv.com
  • Using an App ID with the wrong type

Solución: Log in to developers.deriv.com and register a new application with the correct type (PAT or OAuth) to get a new App ID.

Expired Access Token
Token no longer valid

Causas comunes:

  • OAuth 2.0 access tokens are short-lived (typically 3600 seconds / 1 hour) and expire automatically
  • PAT tokens can be revoked manually from the dashboard

Solución: For OAuth apps, implement token refresh logic using the refresh token. For PAT apps, generate a new token from the dashboard. Never store tokens in frontend code or expose them in URLs.

OAuth Redirect Failure
Consent flow fails or the app does not redirect the user

Causas comunes:

  • Redirect URL is not whitelisted in the application dashboard
  • Redirect URL includes subdirectories that were not registered
  • Mismatch between the URL used in the OAuth request and the URLs registered in the dashboard

Solución: Ensure all redirect URLs (including subdirectories) are registered in your application settings on developers.deriv.com. The URLs must match exactly.

Patrones Comunes

Gestión de suscripciones
How to manage WebSocket subscriptions effectively
  • Always store subscription IDs
  • Use forget to unsubscribe
  • Use forget_all to clear all
  • Clean up subscriptions before disconnect
Error Handling
Best practices for handling API errors
  • Always check for error field
  • Implement exponential backoff for retries
  • Log errors with context
  • Handle network disconnections gracefully
Request IDs
How to track requests and responses
  • Use unique req_id for each request
  • Match responses using req_id
  • Helps with concurrent requests
  • Essential for debugging
Connection Lifecycle
Managing WebSocket connection state
  • Handle onopen, onclose, onerror
  • Implement auto-reconnect logic
  • Re-authenticate after reconnect
  • Restore subscriptions on reconnect
Click to open live chat support. Get instant help from our support team.