Code Examples
Ready-to-use code examples for integrating with the Deriv API
Quick Start
browser-example.html
html
1<!DOCTYPE html>
2<html>
3<head>
4 <title>Deriv API Example</title>
5</head>
6<body>
7 <h1>Deriv API WebSocket Example</h1>
8 <div id="status">Connecting...</div>
9 <div id="output"></div>
10
11 <script>
12 const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3');
13 const statusDiv = document.getElementById('status');
14 const outputDiv = document.getElementById('output');
15
16 ws.onopen = () => {
17 statusDiv.textContent = 'Connected';
18
19 // Get active symbols (no auth required)
20 ws.send(JSON.stringify({
21 active_symbols: 'brief',
22 product_type: 'basic',
23 req_id: 1
24 }));
25
26 // Subscribe to tick stream
27 ws.send(JSON.stringify({
28 ticks: '1HZ100V',
29 subscribe: 1,
30 req_id: 2
31 }));
32 };
33
34 ws.onmessage = (event) => {
35 const data = JSON.parse(event.data);
36
37 if (data.msg_type === 'active_symbols') {
38 outputDiv.innerHTML += '<h3>Active Symbols:</h3>';
39 data.active_symbols.forEach(symbol => {
40 outputDiv.innerHTML += ``;
41 });
42 }
43
44 if (data.msg_type === 'tick') {
45 outputDiv.innerHTML += ``;
46 }
47 };
48
49 ws.onerror = (error) => {
50 statusDiv.textContent = 'Error: ' + error.message;
51 };
52
53 ws.onclose = () => {
54 statusDiv.textContent = 'Disconnected';
55 };
56 </script>
57</body>
58</html>Common Use Cases
Real-Time Price Chart
Subscribe to tick data and update a chart in real-time
1// Subscribe to ticks
2ws.send(JSON.stringify({
3 ticks: "1HZ100V",
4 subscribe: 1,
5 req_id: 1
6}));
7
8// Handle tick updates
9ws.onmessage = (event) => {
10 const data = JSON.parse(event.data);
11
12 if (data.msg_type === 'tick') {
13 const price = data.tick.quote;
14 const time = new Date(data.tick.epoch * 1000);
15
16 // Update your chart
17 chart.addDataPoint(time, price);
18 }
19};Get Contract Proposal
Request a price for a specific contract type
1// Get multiplier proposal
2ws.send(JSON.stringify({
3 proposal: 1,
4 amount: 10,
5 basis: "stake",
6 contract_type: "MULTDOWN",
7 currency: "USD",
8 duration_unit: "s",
9 multiplier: 10,
10 underlying_symbol: "1HZ100V",
11 subscribe: 1,
12 req_id: 1
13}));
14
15// Handle proposal response
16ws.onmessage = (event) => {
17 const data = JSON.parse(event.data);
18
19 if (data.msg_type === 'proposal') {
20 console.log('Proposal ID:', data.proposal.id);
21 console.log('Ask Price:', data.proposal.ask_price);
22 console.log('Spot:', data.proposal.spot);
23 }
24};Buy and Monitor Contract
Purchase a contract and subscribe to its status updates
1let contractId;
2
3// Buy contract with proposal ID
4ws.send(JSON.stringify({
5 buy: "PROPOSAL_ID_FROM_PREVIOUS_RESPONSE",
6 price: 100,
7 req_id: 1
8}));
9
10ws.onmessage = (event) => {
11 const data = JSON.parse(event.data);
12
13 // After purchase, get contract ID
14 if (data.msg_type === 'buy') {
15 contractId = data.buy.contract_id;
16 console.log('Contract purchased:', contractId);
17
18 // Subscribe to contract updates
19 ws.send(JSON.stringify({
20 proposal_open_contract: 1,
21 contract_id: contractId,
22 subscribe: 1,
23 req_id: 2
24 }));
25 }
26
27 // Monitor contract status
28 if (data.msg_type === 'proposal_open_contract') {
29 const contract = data.proposal_open_contract;
30 console.log('Current P&L:', contract.profit);
31 console.log('Status:', contract.status);
32
33 // Check if contract is finished
34 if (contract.is_sold) {
35 console.log('Contract closed. Final profit:', contract.profit);
36 }
37 }
38};Error Handling Pattern
error-handling.js
javascript
1class DerivAPIClient {
2 constructor(url) {
3 this.url = url;
4 this.ws = null;
5 this.requestMap = new Map();
6 this.reconnectAttempts = 0;
7 this.maxReconnectAttempts = 5;
8 }
9
10 connect() {
11 this.ws = new WebSocket(this.url);
12
13 this.ws.onopen = () => {
14 console.log('Connected');
15 this.reconnectAttempts = 0;
16 };
17
18 this.ws.onmessage = (event) => {
19 const data = JSON.parse(event.data);
20
21 // Check for errors
22 if (data.error) {
23 console.error('API Error:', data.error);
24 this.handleError(data.error, data.req_id);
25 return;
26 }
27
28 // Handle successful response
29 this.handleResponse(data);
30 };
31
32 this.ws.onerror = (error) => {
33 console.error('WebSocket Error:', error);
34 };
35
36 this.ws.onclose = () => {
37 console.log('Disconnected');
38 this.handleReconnect();
39 };
40 }
41
42 handleError(error, reqId) {
43 // Get original request from map
44 const request = this.requestMap.get(reqId);
45
46 // Implement retry logic for specific errors
47 if (error.code === 'RateLimit') {
48 console.log('Rate limited, retrying after delay...');
49 setTimeout(() => this.send(request), 5000);
50 } else if (error.code === 'NetworkError') {
51 console.log('Network error, reconnecting...');
52 this.connect();
53 } else {
54 console.error('Unrecoverable error:', error.message);
55 }
56 }
57
58 handleReconnect() {
59 if (this.reconnectAttempts < this.maxReconnectAttempts) {
60 this.reconnectAttempts++;
61 const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
62 console.log(`Reconnecting in ${delay}ms... (attempt ${this.reconnectAttempts})`);
63 setTimeout(() => this.connect(), delay);
64 } else {
65 console.error('Max reconnection attempts reached');
66 }
67 }
68
69 send(request) {
70 if (this.ws.readyState === WebSocket.OPEN) {
71 this.requestMap.set(request.req_id, request);
72 this.ws.send(JSON.stringify(request));
73 } else {
74 console.error('WebSocket is not open');
75 }
76 }
77
78 handleResponse(data) {
79 // Remove from request map
80 this.requestMap.delete(data.req_id);
81
82 // Process response based on msg_type
83 console.log('Response:', data);
84 }
85}
86
87// Usage
88const client = new DerivAPIClient('wss://ws.binaryws.com/websockets/v3');
89client.connect();