Malformed configuration and malformed tick data are two of the most common ways a Deriv bot fails silently or fails expensively. The fix is not more defensive `if` statements inside strategy logic; it is a validation layer that rejects bad data at the boundary, before any decision is made. This article describes how to define strict schemas for bot configuration files and incoming Deriv WebSocket payloads, how to fail fast when they are violated, and how to log structured errors that remain useful during both backtests and live runs.
Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.
Why validation belongs at the boundary
A trading bot has two inputs: its configuration and the market data stream. Everything else is derived. If either input is allowed to be loosely typed, every downstream function must assume the worst, and the failure surfaces later as a wrong stake, a wrong duration, or a strategy that quietly stops trading.
Consider a configuration file where `stake` is read as a string. In JavaScript, `”10″ > 5` is true and `”10″ + 1` is `”101″`. A bot that computes `stake + 1` after a loss may submit a stake one hundred times larger than intended. Deriv’s API will accept the contract if the balance allows it. The strategy logic did nothing wrong; the boundary did.
The same applies to tick payloads. Deriv’s WebSocket stream sends messages with a `msg_type` field. A subscription confirmation, a tick, a proposal response, and an error message can all arrive on the same socket. A handler that treats every message as a tick will eventually read `undefined` as a price. Schema validation makes the contract between the socket and the strategy explicit: only messages matching the tick schema reach the strategy, and everything else is routed or rejected.
The Deriv API documentation describes the message envelope and the fields available for each `msg_type`. The validation layer should encode exactly that shape, not a loose approximation of it.
Designing the configuration schema
A configuration schema should be strict about types, ranges, and required fields, and permissive about nothing that affects money. The following rules are a reasonable baseline for a DBot-style strategy, expressed as a schema in pseudo-code:
config:
stake: number, > 0, <= balance * 0.02, multiple of 0.01
duration: integer, >= 1, <= 10, unit in {"t","s","m"}
contract_type: enum {"CALL","PUT","DIGITOVER","DIGITUNDER","ACCU","MULT"}
symbol: string, matches known active symbols
max_daily_loss: number, > 0, <= balance * 0.05
max_drawdown: number, > 0, <= balance * 0.10
max_consec_losses: integer, >= 1, <= 20
stop_after_losses: boolean
Two properties matter here. First, the stake ceiling is expressed relative to balance, not as an absolute number, so the schema enforces the ORSTAC 1% rule (with a 2% ceiling) at parse time rather than at order time. Second, the session limits are required fields with no defaults. A missing `maxdailyloss` is a schema violation, not an invitation to trade without one.
For Multipliers, the risk controls differ: stop loss and take profit are set by price, not by stake alone. The schema for a Multipliers configuration should therefore require `stoplossprice` and `takeprofitprice` and reject a configuration that omits them. For fixed-stake contracts such as Rise/Fall and Digits, the stake is the maximum loss per contract, so the schema’s stake ceiling is the primary per-contract control, and the session limits are the primary aggregate control.
Validation should also reject unknown keys. If a configuration contains `martingale_multiplier`, the parser should either accept it with an explicit hard cap on steps and stake, or reject it. Silently ignoring unknown keys is how a strategy ends up running a progression nobody intended. ORSTAC recommends against martingale; where a progression exists, the schema must cap the number of steps and the maximum stake, and a ruin test should be run before any live use.
Worked example. Suppose the account balance is 500 USD. The 1% rule gives a per-contract ceiling of 5 USD; the 2% ceiling gives 10 USD. A configuration with `stake: 12` fails the schema because 12 > 10. A configuration with `stake: 8` passes the per-contract check but leaves only 500 / 8 = 62.5 contracts of headroom before the balance is exhausted, so the session limits must be tighter than that. If `maxdailyloss` is set to 25 USD (5% of 500), the bot stops after 25 / 8 = 3.125, i.e. three losing contracts at 8 USD (24 USD lost) and would exceed the limit on the fourth. The schema should therefore also require `maxdailyloss` to be an integer multiple of `stake`, or the runtime should compute the effective stop as `floor(maxdailyloss / stake)` contracts. In this case that is floor(25 / 8) = 3 contracts, for a maximum daily loss of 24 USD. This is an illustrative example, not a recommendation of any particular stake or limit.
Validating the WebSocket stream
The Deriv WebSocket connection is a single channel carrying many message types. The validation layer should dispatch on `msg_type` and validate each type against its own schema before handing it to any consumer. A minimal set for a bot that trades ticks:
- Receive the raw message and parse JSON. Reject and log if parsing fails.
- Read `msg_type`. If absent, reject and log.
- Route by `msg_type`:
- `tick`: require `tick.symbol`, `tick.quote` (finite number), `tick.epoch` (integer), and `tick.id` if present. Reject if `quote` is not finite or `epoch` is not increasing relative to the last accepted tick for that symbol.
- `proposal`: require `proposal.id`, `proposal.askprice`, `proposal.payout`. Reject if `askprice` is not finite or not positive.
- `buy`: require `buy.contractid`, `buy.buyprice`, `buy.payout`. Reject if `contract_id` is missing.
- `error`: require `error.code` and `error.message`. Route to the error handler; never to strategy logic.
- Any unrecognised `msg_type` is logged at debug level and dropped.
Two details matter. First, the tick schema should reject non-monotonic epochs per symbol. Deriv’s synthetic indices stream continuously, but reconnects and subscription changes can deliver a stale tick; a strategy that computes returns from a stale tick will produce a spurious signal. Second, the proposal and buy schemas should reject missing IDs. A buy response without a `contract_id` cannot be reconciled against the portfolio, and a bot that proceeds anyway will lose track of open positions.
The official Deriv API libraries provide typed clients that reduce some of this work, but they do not enforce your strategy’s constraints. A typed client tells you a `quote` is a number; it does not tell you the number is fresh, finite, and from the expected symbol. The schema layer sits above the client and enforces those constraints.
Failing fast and logging structured errors
Fail-fast means the bot stops at the first schema violation rather than continuing with partial data. In a live run, the correct response to a malformed tick is to reject the tick and, if the stream continues to violate the schema, to halt trading and alert. In a backtest, the correct response is to abort the run and report the offending record, because a backtest that silently skips malformed rows produces a result that cannot be reproduced.
Structured logging makes the difference between a debuggable failure and a mystery. Each rejection should emit a single JSON object with, at minimum: `timestamp`, `phase` (`config` or `stream`), `msg_type`, `symbol`, `reason`, and the raw payload (truncated). For configuration errors, include the field path and the rejected value. For stream errors, include the last accepted epoch so the gap is visible.
A short pseudo-code sketch:
function accept(msg):
parsed = tryParseJson(msg)
if parsed is error:
log({phase:"stream", reason:"json_parse", raw:truncate(msg)})
return REJECT
schema = schemas[parsed.msg_type]
if schema is undefined:
log({phase:"stream", reason:"unknown_msg_type", msg_type:parsed.msg_type})
return DROP
result = schema.validate(parsed)
if not result.ok:
log({phase:"stream", msg_type:parsed.msg_type,
reason:result.reason, path:result.path, raw:truncate(msg)})
return REJECT
return ACCEPT(parsed)
The same function is used in backtests, with the log written to the run’s output directory. A backtest that reports zero rejections and a live run that reports many is a signal that the replay data and the live stream differ in shape, which is itself worth knowing before risking money.
Limitations
Schema validation does not make a strategy profitable, and it does not detect a strategy that is correctly typed but wrong. It does not verify that the payout used in an expectancy calculation matches the payout actually offered at execution, and it does not prevent losses from a valid configuration that was simply a bad idea. It does not replace the hard session limits; it enforces that they exist and are well-formed. It also cannot detect every platform-side change: if Deriv alters a field name or adds a new `msg_type`, the schema will reject messages that are in fact valid, and the bot will halt. That is the intended failure mode, but it requires a process for reviewing and versioning the schema when the API changes, and the API documentation should be checked before each schema revision. Finally, validation adds latency; for tick-driven strategies the cost is small relative to network latency, but it should be measured rather than assumed.
Frequently Asked Questions
Does schema validation replace the bot’s own risk limits?
No. It enforces that the limits are present and well-formed; the runtime must still apply them on every contract.
Should the bot halt or continue when a tick fails validation?
Halt on repeated failures for the same symbol, because a persistent schema violation means the stream is no longer what the strategy was tested against.
Can the same schema be used for backtests and live runs?
Yes, and it should be, so that a backtest rejection and a live rejection are directly comparable in the logs.
Key Takeaways
- Validate configuration and stream payloads at the boundary, before strategy logic runs.
- Express stake and session limits as schema constraints, not runtime afterthoughts.
- Reject unknown configuration keys rather than ignoring them, especially progression settings.
- Log every rejection as a structured record with phase, reason, and raw payload.
- Use the same validation layer in backtests and live runs so failures are comparable.
The validation layer described here is small, testable, and independent of any particular strategy. It is the first component in the open-source bots published in the ORSTAC repository, which run on Deriv; a free demo account is available to test them before any real-money use. Questions and schema proposals are 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.
