Deriv API
Documentation
Avancé

Flux de travail complets

Exemples de bout en bout de flux de travail de trading courants utilisant le Deriv API

Prérequis

  1. Se connecter à developers.deriv.com : Créez un compte ou connectez-vous avec vos identifiants pour accéder au tableau de bord.
  2. Enregistrez une nouvelle application : Naviguez vers le tableau de bord et enregistrez une nouvelle application sous votre compte. Choisissez le type d'application approprié en fonction de votre cas d'utilisation :
    • Type PAT : Choisissez ceci lorsque les redirections de navigateur ne sont pas pratiques et que la saisie manuelle de token est acceptable. Par exemple, outils de bureau, applications CLI ou clients natifs. L'utilisateur génère un Personal Access Token dans Deriv et le colle dans votre application.
    • Type OAuth : Choisissez ceci lorsque votre produit peut gérer les redirections de navigateur et que vous avez besoin d'un flux délégué standard avec autorisation de l'utilisateur. Par exemple, tableaux de bord Web ou applications de navigateur. OAuth 2.0 émet des tokens de courte durée et minimise le partage d'identifiants à long terme.

    Cela générera un nouvel App ID. Vos anciens App IDs ne fonctionneront pas avec les nouvelles API.

  3. Générez un token d'autorisation :
    • Si vous utilisez le type PAT : Dans le Tableau de bord, accédez à la section tokens API. Créez un nouveau PAT (Personal Access Token) et sélectionnez les portées appropriées (par exemple trade, account_manage). Copiez et stockez votre token en toute sécurité. Il ne pourra plus être consulté après sa création.
    • Si vous utilisez le type OAuth : Vous n'avez pas besoin de générer un token manuellement. Procédez au flux d'authentification OAuth 2.0 décrit ci-dessous. Le flux fournira un token d'accès de courte durée après une authentification réussie. Assurez-vous d'avoir votre client_id, client_secret et un redirect_uri HTTPS enregistré.
  4. Configurez vos en-têtes de requête : Chaque demande REST API doit inclure les deux en-têtes requis :
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}

Flux de travail de trading Options (REST + WebSocket)

  1. REST : Obtenez une URL WebSocket authentifiée via le point de terminaison OTP (nécessite votre token d'autorisation)
  2. WebSocket : Connectez-vous à l'aide de l'URL authentifiée de la réponse OTP
  3. WebSocket : Effectuez des opérations de trading

Étape 1 : Obtenir l'URL WebSocket authentifiée (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

Étape 2 : Se connecter au 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};

Étape 3 : Commencer les opérations 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});

Flux d'authentification

Flux de travail A : Authentification basée sur PAT

Avec une application PAT, l'utilisateur génère un Personal Access Token dans Deriv et le saisit manuellement ou le colle dans votre application. L'application stocke le token en toute sécurité et l'inclut dans les demandes API en tant que token bearer. Cela convient mieux aux outils de bureau, applications CLI et clients natifs où les redirections de navigateur ne sont pas pratiques.

  1. Connectez-vous à developers.deriv.com avec vos identifiants
  2. Enregistrez une nouvelle application avec type PAT dans le tableau de bord
  3. Générez un token PAT avec les champs d'application appropriés
  4. Include Authorization: Bearer <YOUR_AUTHORIZATION_TOKEN> and Deriv-App-ID in all REST request headers
  5. Effectuez des appels REST API authentifiés
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);

Flux de travail B : Authentification OAuth 2.0

OAuth 2.0 permet aux utilisateurs d'accorder à votre application un accès sans partager leur mot de passe. Votre application redirige l'utilisateur vers une page de connexion et de consentement Deriv. Après que l'utilisateur se connecte et approuve les permissions, Deriv renvoie un code d'autorisation à votre application. Vous échangez ce code contre un token d'accès, que vous utilisez ensuite pour authentifier les demandes API. Recommandé pour les applications Web intégrant des utilisateurs finaux.

Avant de commencer

  • Assurez-vous que votre URL de redirection est correctement enregistrée dans le tableau de bord
  • L'URL de redirection doit utiliser HTTPS
  • Votre application doit gérer les redirections, lire le code d'autorisation et l'échanger contre des tokens
  • Vous devez avoir un client OAuth 2.0 enregistré avec des informations d'identification valides : client_id, client_secret et redirect_uri
  • Toutes les URL de redirection (y compris les sous-répertoires) doivent être sur liste blanche. Les URL doivent correspondre exactement.

Étapes du flux OAuth 2.0

  1. Votre application redirige l'utilisateur vers la page d'autorisation OAuth 2.0 de Deriv pour se connecter et examiner les permissions
  2. Le serveur d'autorisation gère la connexion et le consentement en toute sécurité
  3. Après la connexion, Deriv redirige l'utilisateur vers votre application avec un code d'autorisation et un paramètre state
  4. Votre application échange ce code contre des tokens (avec PKCE si utilisé)
  5. Le serveur OAuth renvoie le token d'accès (et un token de rafraîchissement facultatif)
  6. Votre application stocke et utilise en toute sécurité le token d'accès pour les appels WebSocket ou REST API
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);

Authentification WebSocket (OTP)

Pour vous connecter à un point de terminaison WebSocket authentifié, vous devez appeler le point de terminaison OTP REST à l'aide de votre token d'autorisation (PAT ou JWT). La réponse contient une URL WebSocket authentifiée à laquelle vous pouvez vous connecter directement. L'URL gère l'authentification pour vous.

Points de terminaison 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};

Flux de trading complet

  1. Établir la connexion et s'authentifier
  2. Obtenez les symboles actifs à l'aide de active_symbols
  3. Abonnez-vous au flux de tick pour le symbole choisi à l'aide de ticks
  4. Obtenez une proposition de contrat à l'aide de proposal (avec abonnement)
  5. Surveillez les mises à jour de prix en temps réel
  6. Lorsque vous êtes prêt, achetez un contrat à l'aide de buy
  7. Abonnez-vous aux mises à jour de contrat à l'aide de proposal_open_contract
  8. Surveillez le statut du contrat en temps réel
  9. Vendez éventuellement plus tôt à l'aide de sell
  10. Vérifiez le portefeuille en utilisant 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}));

Flux de travail de données de marché

  1. Connectez-vous au point de terminaison WebSocket public (aucune authentification nécessaire)
  2. Demandez active_symbols pour voir les marchés disponibles
  3. Abonnez-vous à ticks pour les mises à jour de prix en temps réel
  4. Obtenez éventuellement ticks_history pour les données historiques
  5. Utilisez contracts_for pour voir les types de contrats disponibles
  6. Le flux continue jusqu'à forget ou déconnexion
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};

Dépannage

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

Causes courantes :

  • 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

Solution : 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

Causes courantes :

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

Solution : 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

Causes courantes :

  • 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

Solution : 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

Causes courantes :

  • 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

Solution : 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

Causes courantes :

  • 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

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

Modèles courants

Gestion des abonnements
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.