Automated trading requires reliable infrastructure and real-time data feeds. Building a custom script on top of financial markets can save execution time and eliminate emotional errors, but it demands precise configuration of authentication tokens, endpoints, and rate limits.
The Deriv API provides developers with both REST endpoints for account provisioning and WebSocket channels for low-latency streaming and trade execution. Setting up an automated trading pipeline involves registering an application, managing proper scopes, handling WebSocket connections correctly, and respecting platform thresholds.
Account Setup and Application Registration
Before writing code, you need a functional trading account and a registered application ID within the Deriv ecosystem. Wallet accounts cannot execute trades directly via the API; you must use a standard real or virtual trading account (CR or VR) to place orders.
- Log into your account and navigate to the API token settings page in your dashboard.
- Register a new application under the applications tab to generate your unique App ID. Configure your redirect URLs and set markup commissions if you plan to distribute your application.
- Generate a Personal Access Token (PAT). Select the appropriate access scopes based on your system requirements.
Understanding API Token Scopes
Selecting correct scopes ensures your application functions without triggering permission errors. The available scopes dictate what your script can access:
- Read: Grants visibility into market data, asset indices, and basic account information without execution rights.
- Trade: Permits contract purchases, sales, and portfolio management. This scope is mandatory for active trading scripts.
- Payments: Allows inter-account fund transfers and interaction with payment agents.
- Admin: Provides full access to security settings and user details. Avoid using admin tokens in automated scripts to minimize exposure risks.
Establishing Connection: REST vs. WebSocket
The platform splits functionality into two distinct communication layers. REST handles setup routines, while WebSockets manage live data and execution.
REST Endpoints for Setup
REST calls are stateless and suit initialization tasks, account creation, or retrieving historical records. Endpoints require an authorization header containing your Bearer token, along with your application ID when using personal access tokens. For instance, initializing an options account or generating a temporary one-time password (OTP) for WebSocket secure tunneling happens via REST.
WebSocket Streams for Execution
Real-time market feeds, ticks, candles, and order placements require a persistent WebSocket connection. Connecting to the endpoint wss://[ws.derivws.com/websockets/v3?app_id=YOUR_APP_ID](https://ws.derivws.com/websockets/v3?app_id=YOUR_APP_ID) opens the communication channel. Once connected, your script must authorize the session immediately by sending an authorization request with your token:
{
"authorize": "YOUR_API_TOKEN"
}
Writing Your First Automated Trade Script
To execute a trade programmatically, your script must first request a contract proposal to check pricing and payout parameters, then send a buy instruction based on the returned proposal ID.
Here is a conceptual Python pattern using a WebSocket connection framework to request a tick stream and evaluate conditions:
import json
import websocket
def on_message(ws, message):
data = json.loads(message)
msg_type = data.get("msg_type")
if msg_type == "authorize":
print("Authorization successful. Subscribing to ticks...")
ws.send(json.dumps({"ticks": "R_100"}))
elif msg_type == "tick":
price = data["tick"]["quote"]
print(f"Current price of R_100: {price}")
# Implement your trading logic here
def on_open(ws):
print("Connection opened. Authorizing...")
ws.send(json.dumps({"authorize": "YOUR_API_TOKEN"}))
if __name__ == "__main__":
app_id = "1089" # Replace with your App ID
url = f"wss://ws.derivws.com/websockets/v3?app_id={app_id}"
ws = websocket.WebSocketApp(url, on_open=on_open, on_message=on_message)
ws.run_forever()
Managing Rate Limits and System Thresholds
Exceeding platform request limits results in temporary IP bans or connection drops. The API enforces strict rate limits depending on the protocol and the specific call category.
- WebSocket Limits: High-frequency calls like
proposal,buy, andsellshare a bucket capped around 360 requests per minute and 14,400 per hour. Account balance requests share a tighter limit of 100 per minute. - REST Limits: Logged-in REST requests face a strict threshold of 80 requests per minute per user account, alongside IP-based windows.
- Ping Management: Keep connections alive using the
pingcommand, which sits outside standard request budgets. Each connection supports up to 10 pings per second.
Common Integration Mistakes
Automated scripts often fail during live execution due to predictable oversights. Avoid these common pitfalls to ensure high uptime:
- Hardcoding tokens directly into source files instead of using environment variables risks credential leaks.
- Neglecting automatic reconnection logic causes scripts to crash permanently when network interruptions occur.
- Ignoring contract expiration parameters or failing to handle asynchronous error responses from the WebSocket stream will leave orders hanging without confirmation.
Frequently Asked Questions
Can I run my trading script using a demo account?
Yes. You can test all strategy scripts and WebSocket commands by generating a token from a virtual demo account or utilizing virtual funds. The WebSocket URL remains identical, but transactions settle against virtual balances.
Why am I receiving an authorization error on trade calls?
This usually happens because the API token was generated from a Wallet account or a Read-only profile instead of a real trading account with the Trade scope enabled. Verify your token permissions in the dashboard settings.
How do I handle sudden network disconnections in my code?
Implement a wrapper around your WebSocket client that listens for close events. When a disconnection occurs, the script should wait for a brief exponential backoff period before attempting to re-establish the socket and re-send the authorization payload.
What is the maximum number of simultaneous WebSocket connections allowed?
Production architectures should limit open persistent connections per user session. Opening excessive concurrent sockets from a single IP address can trigger automated rate-limiting protocols.