Bot Engineering

Structured Logging and Trace IDs for Deriv Bot Debugging

· 8 min read

A Deriv bot that logs only “trade opened” and “trade closed” cannot explain why a contract was placed, which signal fired, or where a request stalled. The fix is structured JSON logging with a correlation trace ID that is created once per evaluation cycle and carried through the WebSocket request, the strategy decision, and the order execution record. With that in place, one filter on a trace ID reconstructs the full decision path of a single trade, and a failed connection can be diagnosed from the log rather than by re-running the bot. This article describes a concrete schema and lifecycle for DBot and Deriv API builds, with a worked example and the limits of the method.

Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.

The trace ID and the log schema

The unit of correlation should be the decision cycle, not the trade. A cycle begins when the bot evaluates whether to act and ends when it either places a contract or decides not to. Generate one identifier at the start of the cycle and pass it as a field, not as part of a message string. A UUID or a monotonic counter combined with a session ID both work; the requirement is uniqueness within the session and stability across the asynchronous steps of that cycle.

Every record should share a small fixed schema so that downstream queries are simple. A practical minimum:

  • `ts`: ISO 8601 timestamp with milliseconds, in UTC.
  • `level`: `debug`, `info`, `warn`, `error`.
  • `event`: a short stable name such as `ws.open`, `tick.received`, `strategy.evaluated`, `order.request`, `order.result`, `limit.hit`.
  • `trace_id`: the cycle identifier.
  • `session_id`: identifies the bot run, so restarts are distinguishable.
  • `account`: `demo` or `real`, plus the login ID if your setup allows it.
  • `symbol`, `contract_type`: present on market and order events.
  • `payload`: an object whose shape depends on `event`.

Keep the payload typed and boring. Numbers as numbers, booleans as booleans, no interpolated prose. A log line that reads `”stake”: 0.35` can be aggregated; `”msg”: “staking 0.35″` cannot.

For DBot, the practical route is a dedicated logging block sequence: a “Create variable” block for the trace ID at the top of each evaluation, then “Notify” or a journal-style output block that emits a JSON string built from variables. DBot’s block model does not give you a native structured logger, so the discipline is to construct the JSON object explicitly and never concatenate free text into it. For code-based bots using the official Deriv API libraries, the same schema maps directly onto your language’s JSON logger.

Carrying the ID through the WebSocket lifecycle

The WebSocket layer is where correlation earns its keep, because Deriv API calls are asynchronous and can interleave. Attach the `trace_id` to every request the bot sends and to every response handler that resolves it.

A minimal sequence:

  1. On connect, log `ws.open` with `session_id` and the endpoint, no trace ID yet.
  2. On `authorize`, log `ws.auth` with the account type. Do not log the token.
  3. On each tick or candle relevant to the symbol, log `tick.received` with the trace ID of the cycle it feeds.
  4. When a `proposal` request is sent, log `proposal.request` with the trace ID, stake, duration and contract type.
  5. When the proposal response arrives, log `proposal.result` with the same trace ID and the returned payout or an error code.
  6. On `buy`, log `order.request`, then `order.result` with the contract ID.
  7. On subscription updates for that contract, log `order.update` with the contract ID and the trace ID that opened it.

The rule is that a response handler must never guess which request it belongs to. If the API returns a `reqid` (the Deriv API supports request identifiers on many calls), store the mapping from `reqid` to `traceid` and resolve it on arrival. If you do not use `reqid`, keep one outstanding request per trace at a time, which is simpler but constrains concurrency.

Pseudo-code for the mapping:

pending = {}
on_send(req, trace_id):
    req.req_id = next_id()
    pending[req.req_id] = trace_id
    log("proposal.request", trace_id, {stake, duration, contract_type})

on_message(msg):
    trace_id = pending.pop(msg.req_id, None)
    if trace_id is None:
        log("ws.orphan", null, {req_id: msg.req_id, error: msg.error})
        return
    log("proposal.result", trace_id, {payout: msg.proposal.payout, error: msg.error})

The `ws.orphan` event matters. An orphan response means your mapping is broken or a response arrived after you discarded the trace; either way it is a bug worth seeing.

Strategy decisions and order execution

The strategy layer should log the inputs and the verdict, not just the verdict. For a Rise/Fall bot, the decision record needs the values that produced the signal: the last N closes or digit history, the computed indicator, the threshold, and the boolean outcome. For Digits contracts, log the digit distribution window you actually used. For Accumulators, log the current growth rate and the barrier logic. For Multipliers, log the price-based stop loss and take profit levels, since those are the only contract type where price stops exist.

One event, `strategy.evaluated`, with a payload containing `inputs`, `rule`, and `decision` (one of `enter`, `skip`, `blocked`) is enough. When `decision` is `skip` or `blocked`, include the reason. A `blocked` decision from a hard limit is not an error; it is the risk system working, and it should be logged at `info` with the limit name and the current value.

The execution record then closes the cycle: `order.request` carries the stake and the trace ID, `order.result` carries the contract ID and the API’s confirmation. Link the contract ID back to the trace ID in a small in-memory map so that later `order.update` and settlement events can be joined. If the bot restarts, that map is lost; persist it to a local file if restart diagnosis matters to you.

Worked example

Consider a demo account with a balance of 1,000 units. The bot is configured with a 1% per-contract risk ceiling and a daily loss limit of 5% of the starting balance, which is 50 units. On a fixed-stake contract the stake is the maximum loss, so the permitted stake is at most 10 units.

At 09:14:02.118 UTC the bot evaluates a Rise/Fall signal on a synthetic index. The trace ID is `c7f1a2`. The strategy requires the last 20 closes to show a mean above the 20-period value by more than 0.10; the observed difference is 0.14, so `decision` is `enter`. The bot requests a proposal for a stake of 10 units. The proposal returns a payout of 19.5 units, meaning a net profit of 9.5 units on a win and a loss of 10 units on a loss. The break-even win rate for this payout is 10 / 19.5 ≈ 0.513, or about 51.3%. The bot buys; the contract ID is returned and stored against `c7f1a2`.

Suppose the contract loses. The session loss is now 10 units, which is 20% of the 50-unit daily limit. The next cycle, trace `c7f1a3`, logs `strategy.evaluated` with `decision: enter` again, and the bot stakes another 10 units. If it loses, the session loss is 20 units, 40% of the limit. A third loss brings it to 30 units, 60%. A fourth to 40 units, 80%. A fifth loss would reach 50 units, the limit, and the bot must stop by itself and log `limit.hit` with `limit: daily_loss`, the value 50, and the trace ID of the triggering cycle.

Reading the log for `c7f1a2` alone yields: the tick that fed the cycle, the indicator value 0.14 against the 0.10 threshold, the stake, the payout, the contract ID, and the settlement. That is the full decision path of one trade without re-running anything.

Limitations

This approach does not make a strategy correct, and it does not reduce risk; it only makes behaviour observable. It cannot recover events that were never logged, and if the bot crashes before flushing a buffer, the last records may be lost, so write synchronously or flush on every event when diagnosing a live issue. It does not validate that the strategy’s inputs were the right ones to use, only that they were the ones used. Correlation across a restart requires persisting the contract-to-trace map, which many simple bots will not do. Finally, the Deriv API’s behaviour around request identifiers and subscription updates depends on the specific calls and platform settings; verify the exact fields in the Deriv API documentation for the contracts you trade rather than assuming the mapping above is universal.

Frequently Asked Questions

Does structured logging change how the bot trades? No, logging is observational and should not alter the decision path, but the extra work per cycle can add latency, so measure it on a demo account before relying on tight timing.

Can I use this with DBot’s block interface? Yes, in a limited form, by building JSON strings from variables in a dedicated block sequence and emitting them through a notify or journal block, though you will not get the ergonomics of a native logger.

What should I never put in the logs? Never log the API token or full account credentials, and treat login IDs and balances as sensitive when sharing logs for diagnosis.

Key Takeaways

  • One trace ID per decision cycle, generated at evaluation and carried through proposal, buy, and settlement.
  • Log inputs and the verdict, not just the outcome, so a skip or block can be explained.
  • Use a fixed JSON schema with typed fields so records can be queried and aggregated.
  • Map `reqid` to `traceid` to resolve asynchronous WebSocket responses without guessing.
  • Hard limits should log `limit.hit` at `info`, because stopping is correct behaviour, not an error.

The pattern above is small enough to add to an existing bot in an afternoon, and the payoff is that every trade becomes auditable from its own log line. Open-source bots that follow these conventions, including DBot block layouts and Deriv API examples, are available in the ORSTAC repository. The bots run on Deriv, where a free demo account is available to test them, and discussion of logging schemas and bot structure happens in the ORSTAC Telegram group. Start on demo, record a sample, and only then consider minimum stake on a real account.

Trading involves significant risk and you can lose your entire stake. Test every strategy on a demo account first.