Deriv API guide for trading bot development with Python and WebSockets

Everything to Know About Deriv API: A Complete Guide

Trading Tools

In today’s fast-paced financial world, automation is no longer a luxury—it’s a necessity. Traders and developers alike are leveraging APIs to access market data, execute trades, and build custom bots that run strategies 24/7. Among the most powerful APIs in online trading is the Deriv API, offered by Deriv, a trusted platform with millions of users worldwide.

If you’re curious about what Deriv API is, how it works, and how you can use it to build trading bots or apps, this blog post has you covered.

What is Deriv API?

The Deriv API (Application Programming Interface) is a WebSocket-based interface that allows you to connect directly to Deriv’s trading servers. With it, you can:

  • Access real-time market data (ticks, candles, historical prices).

  • Place and manage trading contracts programmatically.

  • Retrieve account information like balances and transaction history.

  • Automate trading strategies without relying on manual clicks.

  • Build custom dashboards, mobile apps, or trading bots tailored to your needs.


Why Use the Deriv API?

  1. Full Automation – Trade 24/7 without fatigue.

  2. Flexibility – Create strategies beyond the limitations of built-in platforms.

  3. Real-Time Speed – Execute trades instantly with WebSockets.

  4. Scalability – Run multiple strategies across different markets simultaneously.

  5. Transparency – Access raw market data and design your risk management.


Features You’ll Love

  • WebSocket-based: Bidirectional, real-time communication with Deriv servers.

  • Market Data APIs: Fetch ticks, candles, active symbols, and asset indexes.

  • Trading APIs: Get contract proposals, place trades, and monitor results.

  • Account APIs: Check balances, portfolio, and transaction history.

  • Cashier APIs: Handle deposits and withdrawals programmatically.

  • Utility APIs: Access error codes, country lists, currencies, and status checks.


Getting Started with Deriv API

Here’s a simple roadmap to begin:

  1. Create a Deriv Account
    Sign up at Deriv.com.

  2. Generate an API Token

    • Log in to your account.

    • Navigate to Security → API Token.

    • Create a token with permissions (e.g., Read, Trade).

  3. Connect via WebSocket
    Use the endpoint:

     
    wss://ws.derivws.com/websockets/v3?app_id=YOUR_APP_ID
     
  4. Send and Receive JSON Messages
    All communication is done using JSON requests and responses.

Best Practices for Using Deriv API

  • Start on Demo – Always test strategies with virtual funds first.

  • Implement Risk Controls – Use stop-loss, take-profit, and stake caps.

  • Log Everything – Keep records of trades for debugging & analysis.

  • Use Keep-Alive Pings – Avoid disconnections after 2 minutes of inactivity.

  • Handle Errors Gracefully – Always check for error fields in API responses.


Who Can Benefit from Deriv API?

  • Traders: Automate trading strategies and save time.

  • Developers: Build apps, bots, and dashboards around live trading.

  • Data Analysts: Stream real-time market data for research.

  • Entrepreneurs: Create trading tools, resell bots, or build SaaS platforms.


Final Thoughts

The Deriv API is more than just a tool—it’s a gateway into the world of algorithmic trading. Whether you’re a hobbyist coder experimenting with strategies or a professional developer building full-scale trading apps, the API gives you access to powerful functionality, real-time data, and flexible trading options.

👉 Ready to get started? Explore the official Deriv API documentation, generate your token, and start building today.

The future of trading is automated—and with Deriv API, you can be ahead of the curve.

Example Code Snippets

Let’s look at some real-world examples from the official Deriv API docs.

 

🔹 JavaScript / Node.js: Connect, Authorize, and Get Proposals

				
					const WebSocket = require('ws');
const { DerivAPIBasic } = require('@deriv/deriv-api/dist/DerivAPIBasic');

const app_id = YOUR_APP_ID;
const endpoint = `wss://ws.derivws.com/websockets/v3?app_id=${app_id}`;
const connection = new WebSocket(endpoint);

connection.on('open', () => {
  console.log('[open] Connected');

  const api = new DerivAPIBasic({ connection });

  // Authorize with token
  api.authorize({ authorize: YOUR_API_TOKEN })
     .then(res => console.log('Authorized:', res))
     .catch(err => console.error('Auth error:', err));

  // Subscribe to a CALL contract proposal
  api.subscribe({
    proposal: 1,
    subscribe: 1,
    amount: 10,
    basis: 'payout',
    contract_type: 'CALL',
    currency: 'USD',
    duration: 1,
    duration_unit: 'm',
    symbol: 'R_100',
    barrier: '+0.1',
  });

  // Keep connection alive
  setInterval(() => {
    api.ping().then(() => console.log('[ping] Sent')).catch(console.error);
  }, 30000);
});

connection.on('message', (data) => {
  const msg = JSON.parse(data);
  if (msg.msg_type === 'proposal') {
    console.log('Proposal:', msg.proposal.longcode, '| Payout:', msg.proposal.payout);
  }
});

				
			

🔹 Python: Authorize, Get Balance, and Subscribe to Ticks

				
					import asyncio
from deriv_api import DerivAPI

async def main():
    app_id = YOUR_APP_ID
    api_token = YOUR_API_TOKEN
    api = DerivAPI(app_id=app_id)

    # Authorize
    resp = await api.authorize(api_token)
    print("Authorize:", resp)

    # Check balance
    bal = await api.balance()
    print("Balance:", bal)

    # Request proposal
    proposal = await api.proposal({
        "proposal": 1,
        "amount": 100,
        "barrier": "+0.1",
        "basis": "payout",
        "contract_type": "CALL",
        "currency": "USD",
        "duration": 60,
        "duration_unit": "s",
        "symbol": "R_100"
    })
    print("Proposal:", proposal)

    # Subscribe to tick stream
    ticks = await api.subscribe({'ticks': 'R_50'})
    disposable = ticks.subscribe(lambda t: print("Tick:", t))

    await asyncio.sleep(10)  # Run for 10s
    disposable.dispose()
    await api.disconnect()

asyncio.run(main())

				
			

🔹 JavaScript: Website Status Check

				
					const WebSocket = require('ws');
const { DerivAPIBasic } = require('@deriv/deriv-api/dist/DerivAPIBasic');

const connection = new WebSocket("wss://ws.derivws.com/websockets/v3?app_id=YOUR_APP_ID");

connection.on('open', () => {
  const api = new DerivAPIBasic({ connection });
  api.websiteStatus().catch(console.error);
});

connection.on('message', (msg) => {
  const data = JSON.parse(msg);
  if (data.msg_type === 'website_status') {
    console.log("Site status:", data.website_status.site_status);
  }
});

				
			

🔹 Python: Simple Balance Fetch

				
					import asyncio
from deriv_api import DerivAPI

async def fetch_balance(token, app_id):
    api = DerivAPI(app_id=app_id)
    await api.authorize(token)
    bal = await api.balance()
    print("Balance:", bal)
    await api.disconnect()

asyncio.run(fetch_balance(YOUR_API_TOKEN, YOUR_APP_ID))