Complete Workflows
End-to-end examples of common trading workflows using the Deriv API
Options Trading Workflow (REST + WebSocket)
Complete Integration
This workflow demonstrates how to use REST APIs for account setup and WebSocket APIs for real-time trading.
Steps:
- REST: Create an Options trading account
- REST: Get OTP token for WebSocket authentication
- WebSocket: Connect using the OTP token
- WebSocket: Perform trading operations
Step 1: Create Options Account (REST)
create-account.js
javascript
1// Create a demo Options trading account
2const response = await fetch('https://api.derivws.com/trading/v1/options/accounts', {
3 method: 'POST',
4 headers: {
5 'Deriv-App-ID': 'YOUR_APP_ID',
6 'Content-Type': 'application/json'
7 },
8 body: JSON.stringify({
9 currency: 'USD',
10 group: 'row',
11 account_type: 'demo'
12 })
13});
14
15const result = await response.json();
16console.log('Account created:', result.data.account_id);
17// Output: DOT90004580
18
19// Save the account ID for next steps
20const accountId = result.data.account_id;Step 2: Get OTP for WebSocket Authentication (REST)
get-otp.js
javascript
1// Get OTP token for WebSocket connection
2const otpResponse = await fetch(
3 `https://api.derivws.com/trading/v1/options/accounts/${accountId}/otp`,
4 {
5 method: 'POST',
6 headers: {
7 'Deriv-App-ID': 'YOUR_APP_ID'
8 }
9 }
10);
11
12const otpResult = await otpResponse.json();
13console.log('OTP URL:', otpResult.data.url);
14// Output: wss://api.derivws.com/trading/v1/options/ws/demo?otp=abc123xyz789
15
16// Extract OTP from URL
17const url = new URL(otpResult.data.url);
18const otp = url.searchParams.get('otp');
19console.log('OTP Token:', otp);Step 3: Connect to WebSocket with OTP
connect-websocket.js
javascript
1// Connect to Options WebSocket using OTP
2const ws = new WebSocket(`wss://api.derivws.com/trading/v1/options/ws/demo?otp=${otp}`);
3
4ws.onopen = () => {
5 console.log('Connected to Options trading WebSocket');
6 // Connection is now authenticated and ready for trading
7};
8
9ws.onmessage = (msg) => {
10 const data = JSON.parse(msg.data);
11 console.log('Received:', data);
12};
13
14ws.onerror = (error) => {
15 console.error('WebSocket error:', error);
16};
17
18ws.onclose = () => {
19 console.log('WebSocket connection closed');
20};Step 4: Start Trading Operations
trading-operations.js
javascript
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 Example
Here's a complete working example combining all steps:
complete-workflow.js
javascript
1async function setupOptionsTrading() {
2 const APP_ID = 'YOUR_APP_ID';
3 const API_BASE = 'https://api.derivws.com';
4
5 try {
6 // Step 1: Create Options account
7 const accountResponse = await fetch(`${API_BASE}/trading/v1/options/accounts`, {
8 method: 'POST',
9 headers: {
10 'Deriv-App-ID': APP_ID,
11 'Content-Type': 'application/json'
12 },
13 body: JSON.stringify({
14 currency: 'USD',
15 group: 'row',
16 account_type: 'demo'
17 })
18 });
19
20 const accountData = await accountResponse.json();
21 const accountId = accountData.data.account_id;
22 console.log('✓ Account created:', accountId);
23
24 // Step 2: Get OTP
25 const otpResponse = await fetch(
26 `${API_BASE}/trading/v1/options/accounts/${accountId}/otp`,
27 {
28 method: 'POST',
29 headers: { 'Deriv-App-ID': APP_ID }
30 }
31 );
32
33 const otpData = await otpResponse.json();
34 const url = new URL(otpData.data.url);
35 const otp = url.searchParams.get('otp');
36 console.log('✓ OTP obtained');
37
38 // Step 3: Connect to WebSocket
39 const ws = new WebSocket(`wss://api.derivws.com/trading/v1/options/ws/demo?otp=${otp}`);
40
41 ws.onopen = () => {
42 console.log('✓ WebSocket connected');
43
44 // Step 4: Start trading
45 // Subscribe to balance updates
46 ws.send(JSON.stringify({
47 balance: 1,
48 subscribe: 1,
49 req_id: 1
50 }));
51
52 // Subscribe to ticks
53 ws.send(JSON.stringify({
54 ticks: "1HZ100V",
55 subscribe: 1,
56 req_id: 2
57 }));
58 };
59
60 ws.onmessage = (msg) => {
61 const data = JSON.parse(msg.data);
62
63 if (data.msg_type === 'balance') {
64 console.log('Balance:', data.balance.balance, data.balance.currency);
65 }
66
67 if (data.msg_type === 'tick') {
68 console.log('Tick:', data.tick.quote);
69 }
70 };
71
72 return ws;
73
74 } catch (error) {
75 console.error('Setup failed:', error);
76 throw error;
77 }
78}
79
80// Run the setup
81setupOptionsTrading().then(ws => {
82 console.log('Trading setup complete. WebSocket ready for operations.');
83}).catch(err => {
84 console.error('Failed to setup trading:', err);
85});Authentication Workflow
Two-Step Process
Authentication requires two API calls: first get a session token, then authorize the connection.
Steps:
- Connect to WebSocket endpoint
- Send
get_session_tokenrequest with one-time token - Receive session token in response
- Send
authorizerequest with session token - Receive authorization confirmation
- Connection is now authorized for trading operations
authentication.js
javascript
1const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3');
2
3ws.onopen = () => {
4 // Step 1: Get session token
5 ws.send(JSON.stringify({
6 get_session_token: "YOUR_ONE_TIME_TOKEN",
7 req_id: 1
8 }));
9};
10
11ws.onmessage = (msg) => {
12 const data = JSON.parse(msg.data);
13
14 // Step 2: Authorize with session token
15 if (data.msg_type === 'get_session_token') {
16 ws.send(JSON.stringify({
17 authorize: data.get_session_token.token,
18 req_id: 2
19 }));
20 }
21
22 // Step 3: Now authenticated!
23 if (data.msg_type === 'authorize') {
24 console.log('Authenticated:', data.authorize.loginid);
25 // Ready to make authenticated requests
26 }
27};Complete Trading Workflow
End-to-End Trading Process
This workflow shows how to authenticate, get market data, create a proposal, buy a contract, and monitor it.
Steps:
- Establish connection and authenticate
- Get active symbols using
active_symbols - Subscribe to tick stream for chosen symbol using
ticks - Get contract proposal using
proposal(with subscribe) - Monitor real-time price updates
- When ready, buy contract using
buy - Subscribe to contract updates using
proposal_open_contract - Monitor contract status in real-time
- Optionally sell early using
sell - Check portfolio using
portfolio
trading-workflow.js
javascript
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}));Market Data Workflow
No Authentication Required
You can access market data without authentication. Perfect for building chart applications or market monitors.
Steps:
- Connect to WebSocket (no auth needed)
- Request
active_symbolsto see available markets - Subscribe to
ticksfor real-time price updates - Optionally get
ticks_historyfor historical data - Use
contracts_forto see available contract types - Stream continues until
forgetor disconnect
market-data.js
javascript
1const ws = new WebSocket('wss://ws.binaryws.com/websockets/v3');
2
3ws.onopen = () => {
4 // Get available symbols
5 ws.send(JSON.stringify({
6 active_symbols: "brief",
7 product_type: "basic",
8 req_id: 1
9 }));
10
11 // Subscribe to tick stream
12 ws.send(JSON.stringify({
13 ticks: "1HZ100V",
14 subscribe: 1,
15 req_id: 2
16 }));
17
18 // Get historical data
19 ws.send(JSON.stringify({
20 ticks_history: "1HZ100V",
21 count: 100,
22 end: "latest",
23 style: "ticks",
24 req_id: 3
25 }));
26};
27
28ws.onmessage = (msg) => {
29 const data = JSON.parse(msg.data);
30
31 if (data.msg_type === 'active_symbols') {
32 console.log('Available symbols:', data.active_symbols);
33 }
34
35 if (data.msg_type === 'tick') {
36 console.log('Current price:', data.tick.quote);
37 // Update your chart here
38 }
39
40 if (data.msg_type === 'history') {
41 console.log('Historical data:', data.history);
42 // Initialize your chart here
43 }
44};Common Patterns
Subscription Management
How to manage WebSocket subscriptions effectively
- Always store subscription IDs
- Use
forgetto unsubscribe - Use
forget_allto clear all - Clean up subscriptions before disconnect
Error Handling
Best practices for handling API errors
- Always check for
errorfield - Implement exponential backoff for retries
- Log errors with context
- Handle network disconnections gracefully
Request IDs
How to track requests and responses
- Use unique
req_idfor 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