A recorder that writes Deriv WebSocket tick and candle streams to disk is the foundation of any honest backtest. The core requirements are simple: buffer incoming messages so a slow disk never stalls the socket, normalize every timestamp to a single unambiguous epoch, and run integrity checks that prove the file you replay is the file you captured. This guide describes a practical design for that recorder, with explicit arithmetic where numbers appear, and it assumes you already understand that a dataset is only as trustworthy as the checks you run on it.
Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.
Why a local recorder beats on-the-fly backtesting
Deriv’s API exposes market data over WebSocket, and the official Deriv API documentation and Deriv API libraries describe the subscription model: you send a `ticks` or `candles` subscribe request, and the server pushes updates until you forget the stream. If you backtest against data you fetch at test time, you inherit whatever the server currently retains and whatever the connection happens to deliver. You also cannot reproduce a past run exactly, because the stream is not the same twice.
A local recorder fixes that. It captures the raw stream once, writes it durably, and lets you replay it deterministically. The same tick sequence then drives the same decisions in the same order, which is the only way to compare two bot configurations fairly. For synthetic indices and forex alike, the synthetic indices overview is worth reading to understand that these streams are generated continuously, so a recorder that drops messages silently will produce gaps that look like market behaviour but are not.
The rule from the ORSTAC premises applies directly: no data, no claim. A recorded sample is the minimum evidence before any strategy discussion, and it should come from a demo account first.
Buffering: decouple the socket from the disk
The most common failure in a naive recorder is writing to disk inside the WebSocket message handler. Disk latency varies, and a single slow flush can back up the socket buffer, causing the client to miss or drop messages. The fix is a bounded in-memory queue between the socket and a writer thread.
Design it as follows. The socket handler parses each message minimally and appends a record to a queue. A separate writer thread drains the queue in batches and appends to a file. If the queue reaches its capacity, you must decide explicitly: either block the socket (risk of disconnection) or drop and count the drop. Never drop silently. A recorder that loses messages without recording the loss is worse than no recorder, because the resulting file looks complete.
A short pseudo-code sketch:
queue = BoundedQueue(capacity=N)
on_message(msg):
record = {recv_ts: now_epoch_ms(), payload: msg}
if not queue.try_push(record):
dropped_counter += 1
log_warning("queue full")
writer_thread():
while running:
batch = queue.pop_batch(max=1000, timeout=1s)
append_to_file(batch)
flush_if_needed()
The `recv_ts` field is your local receive time. It is not the exchange time and must never be confused with it. Keep both. The server message typically carries its own timestamp for ticks and candle open times; store the raw payload untouched and add your receive time alongside it.
Choose the queue capacity from measured throughput. If a busy synthetic index delivers roughly 1 message per second per symbol, a capacity of a few thousand covers minutes of writer stall. If you subscribe to many symbols or candles, measure first and size accordingly. The capacity is a trade-off, not a constant.
Timestamp normalization
Timestamp confusion is the second most common source of broken backtests. Three clocks matter: the server’s event time, your local receive time, and the file write time. Only the first two belong in the dataset, and they must be stored in a single unit.
Normalize everything to integer epoch milliseconds in UTC. Deriv candle payloads typically express open time in epoch seconds, while tick payloads may carry epoch seconds as well; converting seconds to milliseconds is a multiplication by 1000, and doing it inconsistently is how you get candles that appear hours apart. Write the conversion once, in one function, and apply it to every record.
Store a schema version with each file. A minimal record for a tick might be:
- `schema`: integer version
- `symbol`: string
- `serverepochms`: integer
- `recvepochms`: integer
- `quote`: number as received
- `raw`: the original payload string
Keeping `raw` means you can re-derive fields later without re-capturing. For candles, store the open time as `serverepochms` and keep the OHLC values as received; do not recompute them from ticks unless you document that you did, because the server’s aggregation is authoritative for the stream you subscribed to.
One subtlety: clock skew. Your `recvepochms` depends on the local machine clock, which may drift. Record a periodic time check against a known reference if you can, or at minimum log the offset between consecutive server timestamps and your receive times. A large persistent offset indicates a problem with your host, not the market. State the uncertainty rather than hiding it.
Receive time is for diagnostics and ordering. Event time is for replay. Do not mix them.
Integrity checks
A file that opens is not a file that is correct. Integrity checks are what turn a capture into a dataset. Run them at write time and again before any backtest.
At write time, maintain a running count of records and a rolling checksum over the serialized records. On clean shutdown, write a footer containing the record count, the first and last server timestamps, the drop counter, and the checksum. On startup, if a footer is missing, treat the file as truncated and say so.
Before replay, run these checks:
- Monotonicity: server timestamps should be non-decreasing within a symbol. A decrease means either a duplicate or an out-of-order delivery; flag it.
- Gaps: compute the interval between consecutive ticks and compare against the expected cadence for that symbol. Report the largest gap and its location.
- Duplicates: hash consecutive raw payloads and count repeats.
- Completeness: compare the record count in the footer against the count on disk.
- Drop accounting: if the drop counter is non-zero, the file is not a clean sample; label it.
Worked example. Suppose you record a single synthetic index for one hour and the server delivers one tick per second. The expected count is 60 seconds × 60 minutes = 3600 ticks. Your footer reports 3591 records and a drop counter of 9. The arithmetic is 3600 − 3591 = 9, which matches the drop counter, so the file is internally consistent but incomplete by 9 ticks. You should not present that hour as a clean sample. If instead the footer reported 3600 records with a drop counter of 9, the counts contradict each other and the file should be rejected outright. This is an illustrative example, not a measurement.
A second check on candles: if you subscribe to one-minute candles for 24 hours, the expected count is 24 × 60 = 1440 candles. A file with 1438 candles and a largest gap of two minutes has two missing periods; report them explicitly rather than interpolating.
Limitations
This approach does not solve everything. It cannot recover messages the server never sent, and it cannot fix a subscription that was configured with the wrong symbol or granularity. It does not validate that the quotes themselves are correct; it only proves the file matches what your client received. Clock skew on the recording host is measured, not eliminated. It does not make a strategy profitable, and a clean dataset is a precondition for testing, not evidence of edge. Multipliers and fixed-stake contracts differ in how risk is controlled, and no recorder changes that. Finally, replay determinism depends on your bot consuming events in file order; if your strategy reads wall-clock time internally, replay will diverge.
Frequently Asked Questions
Should I record ticks or candles?
Record both if your strategy uses both, but record ticks as the primary source because candles can be re-aggregated from ticks while the reverse is impossible.
How long should a demo sample be before trusting a backtest?
There is no universal number; the sample must be long enough to include the session conditions your strategy will face, and it should be split into in-sample and out-of-sample portions before any conclusion.
Can I use these files with Deriv Bot directly?
Deriv Bot runs strategies as block logic, so replay typically means feeding the recorded stream into your own harness or a Deriv Bot test setup; the file format is yours to define, and the integrity checks matter more than the container.
Key Takeaways
- Buffer between socket and disk, and count every drop rather than hiding it.
- Normalize all timestamps to integer epoch milliseconds in UTC and keep the raw payload.
- Write a footer with counts, checksum, and drop counter; verify it before replay.
- Run monotonicity, gap, duplicate, and completeness checks before any backtest.
- A clean dataset is necessary but not sufficient; expectancy and drawdown still decide.
The recorder described here is the data layer that sits under any serious bot, and the ORSTAC repository hosts open-source bots you can run against recorded samples. Use Deriv as the platform, where a free demo account is available to test the bots, and bring your recorder designs and integrity-check results to the ORSTAC Telegram group for discussion.
Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.
