Code Examples
Ready-to-use code examples for integrating with the Deriv API
Quick Start
browser-example.htmlhtml
<!DOCTYPE html>
<html>
<head>
<title>Deriv API Example</title>
</head>
<body>
<h1>Deriv API WebSocket Example</h1>
<div id="status">Connecting...</div>
<div id="output"></div>
<script>
const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3');
const statusDiv = document.getElementById('status');
const outputDiv = document.getElementById('output');
ws.onopen = () => {
statusDiv.textContent = 'Connected';
// Get active symbols (no auth required)
ws.send(JSON.stringify({
active_symbols: 'brief',
product_type: 'basic',
req_id: 1
}));
// Subscribe to tick stream
ws.send(JSON.stringify({
ticks: '1HZ100V',
subscribe: 1,
req_id: 2
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.msg_type === 'active_symbols') {
outputDiv.innerHTML += '<h3>Active Symbols:</h3>';
data.active_symbols.forEach(symbol => {
outputDiv.innerHTML += ``;
});
}
if (data.msg_type === 'tick') {
outputDiv.innerHTML += ``;
}
};
ws.onerror = (error) => {
statusDiv.textContent = 'Error: ' + error.message;
};
ws.onclose = () => {
statusDiv.textContent = 'Disconnected';
};
</script>
</body>
</html>Common Use Cases
Real-Time Price Chart
Subscribe to tick data and update a chart in real-time
// Subscribe to ticks
ws.send(JSON.stringify({
ticks: "1HZ100V",
subscribe: 1,
req_id: 1
}));
// Handle tick updates
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.msg_type === 'tick') {
const price = data.tick.quote;
const time = new Date(data.tick.epoch * 1000);
// Update your chart
chart.addDataPoint(time, price);
}
};Get Contract Proposal
Request a price for a specific contract type
// Get multiplier proposal
ws.send(JSON.stringify({
proposal: 1,
amount: 10,
basis: "stake",
contract_type: "MULTDOWN",
currency: "USD",
duration_unit: "s",
multiplier: 10,
underlying_symbol: "1HZ100V",
subscribe: 1,
req_id: 1
}));
// Handle proposal response
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.msg_type === 'proposal') {
console.log('Proposal ID:', data.proposal.id);
console.log('Ask Price:', data.proposal.ask_price);
console.log('Spot:', data.proposal.spot);
}
};Buy and Monitor Contract
Purchase a contract and subscribe to its status updates
let contractId;
// Buy contract with proposal ID
ws.send(JSON.stringify({
buy: "PROPOSAL_ID_FROM_PREVIOUS_RESPONSE",
price: 100,
req_id: 1
}));
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// After purchase, get contract ID
if (data.msg_type === 'buy') {
contractId = data.buy.contract_id;
console.log('Contract purchased:', contractId);
// Subscribe to contract updates
ws.send(JSON.stringify({
proposal_open_contract: 1,
contract_id: contractId,
subscribe: 1,
req_id: 2
}));
}
// Monitor contract status
if (data.msg_type === 'proposal_open_contract') {
const contract = data.proposal_open_contract;
console.log('Current P&L:', contract.profit);
console.log('Status:', contract.status);
if (contract.is_sold) {
console.log('Contract closed. Final profit:', contract.profit);
}
}
};Error Handling Pattern
error-handling.jsjavascript
class DerivAPIClient {
constructor(url) {
this.url = url;
this.ws = null;
this.requestMap = new Map();
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('Connected');
this.reconnectAttempts = 0;
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.error) {
console.error('API Error:', data.error);
this.handleError(data.error, data.req_id);
return;
}
this.handleResponse(data);
};
this.ws.onerror = (error) => {
console.error('WebSocket Error:', error);
};
this.ws.onclose = () => {
console.log('Disconnected');
this.handleReconnect();
};
}
handleError(error, reqId) {
const request = this.requestMap.get(reqId);
if (error.code === 'RateLimit') {
console.log('Rate limited, retrying after delay...');
setTimeout(() => this.send(request), 5000);
} else if (error.code === 'NetworkError') {
console.log('Network error, reconnecting...');
this.connect();
} else {
console.error('Unrecoverable error:', error.message);
}
}
handleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
console.log(`Reconnecting in ${delay}ms... (attempt ${this.reconnectAttempts})`);
setTimeout(() => this.connect(), delay);
} else {
console.error('Max reconnection attempts reached');
}
}
send(request) {
if (this.ws.readyState === WebSocket.OPEN) {
this.requestMap.set(request.req_id, request);
this.ws.send(JSON.stringify(request));
} else {
console.error('WebSocket is not open');
}
}
handleResponse(data) {
this.requestMap.delete(data.req_id);
console.log('Response:', data);
}
}
// Usage
const client = new DerivAPIClient('wss://ws.binaryws.com/websockets/v3');
client.connect();Any other questions? Get in touch