A Deriv bot is only as reliable as its connection to the Deriv API. When the WebSocket drops mid-session, the bot can miss a contract settlement, fire a duplicate buy, or lose track of its own open positions, and any of these can turn a controlled strategy into an uncontrolled one. This guide describes a disciplined connection layer: how to detect failure, how to reconnect without flooding the server, how to reconcile state after a gap, and how to guarantee that a network interruption never produces a duplicate or orphaned trade. The recommendations apply to DBot and to bots built directly on the Deriv API, and they assume you are testing on a demo account before any real stake.
Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.
Detecting failure and reconnecting deliberately
A WebSocket can fail in ways that are not obvious. The socket may close cleanly, it may hang silently with no `close` event, or it may stay open while the server stops responding to requests. A single `onclose` handler is not enough. You need three independent signals: a transport-level close, a heartbeat timeout, and a request-level timeout.
The Deriv API supports a `ping` request; sending it on a fixed interval and expecting a `pong` gives you a liveness check that does not depend on market activity. If no `pong` arrives within a threshold, treat the connection as dead and close it yourself. Pair this with a per-request timeout so that a `proposal` or `buy` call that never resolves does not block the bot forever.
Reconnection must be rate-limited. A naive loop that reconnects immediately on every failure will hammer the endpoint and may be throttled. Use exponential backoff with jitter: wait a base interval, double it on each consecutive failure, cap it at a maximum, and add a small random offset so that many bots do not reconnect in lockstep. A typical ladder might be 1s, 2s, 4s, 8s, capped at 30s, with a random offset of up to 20 percent of the current interval. Reset the backoff only after a connection has been stable for a defined period, not immediately on open.
A minimal policy in pseudo-code:
on disconnect or heartbeat_timeout or request_timeout:
close socket
attempt = attempt + 1
delay = min(base * 2^(attempt-1), max_delay) * (1 + random(0, 0.2))
schedule reconnect after delay
on open:
resubscribe to required streams (ticks, balance, proposal_open_contract)
request full state snapshot
enter RECONCILING state
on stable for 60s:
attempt = 0
The critical rule is that the bot must not send a `buy` while it is in `RECONCILING`. Trading resumes only after state is confirmed.
State reconciliation after a dropped stream
When the socket returns, the bot’s in-memory view of the world may be stale. The safe approach is to treat the reconnected session as a fresh client that must rebuild state from the server, not from memory. Three things must be reconciled: open contracts, account balance, and any subscription streams.
For open contracts, subscribe to `proposalopencontract` and request the current status of every contract the bot believes is open. The response tells you whether each contract is still active or has settled. Do not assume a contract is open because your local log says so; the server is authoritative. If a contract settled during the gap, record the result and update your session counters (consecutive losses, daily loss) from the server’s data, not from an optimistic local guess.
For balance, request it explicitly rather than trusting the last cached value. A settlement may have occurred during the outage, changing your available capital and therefore your stake sizing.
For streams, resubscribe deliberately. Duplicate subscriptions can produce duplicate callbacks, which in a poorly written bot can look like duplicate signals. Track subscription IDs and forget old ones on reconnect.
A worked example makes the reconciliation cost concrete.
Worked example. Suppose a bot trades a fixed stake of 1.00 USD per contract and has a session limit of 20 trades. Before the outage it had recorded 12 completed trades and one open contract with a 1.00 USD stake. The connection drops for 40 seconds. On reconnect, the bot queries open contracts and finds that the previously open contract settled as a loss during the gap. It must now count 13 completed trades, not 12, and update its consecutive-loss counter. If its rule was “stop after 3 consecutive losses” and this settlement was the third, the correct action is to halt, even though the bot never saw the loss arrive live. Had it trusted its stale counter, it would have continued trading and breached its own limit. The arithmetic here is simple but the failure mode is not: one missed settlement message moved the trade count from 12 to 13 and the loss streak from 2 to 3, and only server reconciliation catches it.
Preventing duplicate and missed trades
The most damaging network failures are the ones that cause a bot to buy twice or to buy when it should have stopped. The root cause is almost always a request whose outcome is unknown: the bot sent a `buy`, the socket died before the response arrived, and the bot cannot tell whether the order was accepted.
The correct pattern is idempotency by reference. Before sending a `buy`, generate a unique client-side identifier and persist it locally. On reconnect, before retrying, query the account’s open and recently closed contracts and check whether a contract matching that identifier or that proposal already exists. Only retry if you can prove the order was not placed. Blind retries are how duplicate trades happen.
Second, gate all order placement on a state machine. The bot should be in `TRADING` only when the socket is confirmed live, subscriptions are active, and reconciliation has completed. Any disconnect transitions it to `HALTED` or `RECONCILING`, and no `buy` may be issued from those states.
Third, enforce session limits from persisted counters, not memory. If the bot restarts or reconnects, it should reload its daily loss, drawdown, and consecutive-loss counters from disk so that a network event cannot reset a limit. This is where resilience meets the ORSTAC premises: hard automatic limits are only hard if they survive a reconnect.
A short DBot-oriented rule set:
- On start, load persisted counters and set state to `RECONCILING`.
- Connect, subscribe to balance and `proposalopencontract`, request a snapshot.
- Reconcile open contracts and balance; update counters from server data.
- Transition to `TRADING` only if no limit is breached.
- On any disconnect, immediately transition to `HALTED` and block `buy`.
- On reconnect, repeat steps 2 to 4 before resuming.
Limitations
This approach does not eliminate risk. It cannot recover a contract that settled at a loss during an outage; it can only ensure the loss is recorded and the limits respond correctly. It does not guarantee that the Deriv API will always respond within your timeouts, and platform-side throttling or maintenance can extend outages beyond your backoff cap. It does not make a strategy profitable, and it does not remove the behavioural gap between demo and live execution. Reconnection logic also adds latency, which matters for short-duration contracts; if your edge depends on sub-second timing, a resilient layer may reduce fill quality, and that trade-off must be measured, not assumed. Finally, the exact behaviour of any request during a partial outage depends on platform settings you do not control, so treat every unknown outcome as “possibly executed” until proven otherwise.
Frequently Asked Questions
Can a bot safely retry a buy after a disconnect?
Only if it first proves the original order was not placed, by querying open and recently closed contracts for a matching identifier. A blind retry is the most common cause of duplicate trades.
Should the bot keep trading while it reconnects?
No. Order placement must be blocked in any state other than a fully reconciled `TRADING` state, because a stale view of balance or open contracts can breach session limits.
Do session limits survive a reconnect or restart?
They do only if counters are persisted to disk and reloaded on start. In-memory counters reset on restart, which silently disables the hard limits the strategy depends on.
Key Takeaways
- Detect failure with three signals: socket close, heartbeat timeout, and request timeout; do not rely on `onclose` alone.
- Reconnect with capped exponential backoff and jitter, and reset the backoff only after a stable period.
- After reconnect, rebuild state from the server: open contracts, balance, and subscriptions, never from memory.
- Prevent duplicates with client-side identifiers and a state machine that blocks `buy` outside a reconciled `TRADING` state.
- Persist session counters so daily loss, drawdown, and consecutive-loss limits survive reconnects and restarts.
Resilient connection management is infrastructure, not edge, but without it even a well-tested strategy can breach its own limits. The ORSTAC repository hosts open-source bots that implement these patterns, and you can run them on Deriv, where a free demo account is available to test the bots before any real stake. For API details, see the Deriv API documentation and the official Deriv API libraries; for market context, see synthetic indices and Deriv Bot. Discussion of implementation details and failure cases is welcome in the ORSTAC Telegram group.
Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.
