Community Report

Structuring a Deriv Bot Codebase for Maintainable Strategy Iteration

· 7 min read

A Deriv bot becomes hard to change when data fetching, entry logic, risk checks and order placement are interleaved in one block graph or one script. The practical fix is to split the bot into four layers with explicit, narrow interfaces: data ingestion, signal logic, risk, and execution. Each layer should be testable in isolation, so a new strategy variant can be swapped in without touching stake sizing or session limits. This guide describes that refactor for DBot and for bots built on the Deriv API, and how to verify that a change stays where you put it.

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

The four layers and their contracts

The value of the split is not architectural elegance. It is that each layer has a contract you can state in one sentence, and a test that fails when the contract is broken.

  • Data ingestion receives market ticks or candles from the Deriv WebSocket API (or the corresponding DBot blocks) and emits a normalised, timestamped series. It owns reconnects, subscription management, and gap handling. It does not decide anything.
  • Signal logic receives the normalised series and emits a signal object: direction or contract type, a proposed duration or barrier, and a reason code. It has no knowledge of balance, stake, or open positions.
  • Risk receives the signal plus account state (balance, open exposure, session P&L, consecutive losses) and returns either an approved order with a stake, or a rejection with a reason. It is the only layer allowed to size a stake and the only layer allowed to halt trading.
  • Execution receives an approved order and places it, tracks the contract to settlement, and reports the outcome back to risk. It does not re-evaluate the signal.

Two rules keep the boundaries honest. First, dependencies point one way: execution may call risk for approval, risk may call nothing upward, signal logic never reads the balance. Second, every cross-layer message is a plain data structure with a version field, so a change in one layer’s output is visible in the interface rather than buried in a shared global.

For DBot users, the mapping is direct. Data ingestion is the tick or candle collection blocks feeding a variable. Signal logic is the condition tree that sets a decision variable. Risk is a set of condition blocks that gate the trade and compute the stake. Execution is the trade block plus the journal. The refactor mostly consists of naming those variables, refusing to read one layer’s internals from another, and putting the risk gates physically between the decision and the trade block.

In DBot the “interface” is the set of named variables you pass between block groups. Treat those names as a contract and do not reuse them for other purposes.

Worked example: stake sizing and session limits

Consider a fixed-stake Rise/Fall bot on a synthetic index. Assume a demo balance of 1,000 USD, a per-contract risk ceiling of 1% (10 USD), and a session with a daily loss limit of 5% (50 USD) and a maximum of three consecutive losses.

The risk layer computes the stake as the minimum of the per-contract ceiling and the remaining daily budget. At session start both are 10 USD and 50 USD, so stake = 10 USD.

Suppose the first three contracts all lose. Cumulative loss is 3 × 10 = 30 USD. The consecutive-loss counter reaches 3, which equals the limit, so risk rejects the next signal and the bot halts for the session. Note what did not happen: the stake did not increase after losses. A martingale variant would have staked 10, then 20, then 40, for a cumulative 70 USD after three losses, which exceeds the 50 USD daily limit on the third contract alone. That is precisely why ORSTAC recommends against martingale; where a community bot uses a progression anyway, the risk layer must carry a hard cap on both step count and stake, plus a ruin test on demo data before any live use.

Now suppose instead the sequence is loss, win, loss, loss. With a payout of 0.95 on stake, a win returns 9.50 USD profit on a 10 USD stake, so cumulative P&L after four contracts is −10 + 9.50 − 10 − 10 = −20.50 USD. The consecutive-loss counter resets on the win, so the halt condition is not met; the daily loss budget is now 50 − 20.50 = 29.50 USD, and the stake stays at 10 USD because the per-contract ceiling binds first.

The arithmetic matters less than the placement: all of it lives in one layer. Changing the payout assumption, the ceiling, or the halt rule is a one-file edit with a test around it, not a hunt through the block graph.

Refactoring procedure and interface checks

Work in this order, keeping the bot on a demo account throughout.

  1. Freeze behaviour first. Record a demo run of the existing bot and save the trade journal. This is your regression baseline; without it you cannot tell a refactor from a behaviour change.
  2. Extract data ingestion. Wrap tick and candle access behind one function or block group that returns a fixed-shape series. Verify by replaying the same instrument and comparing the series to the baseline timestamps.
  3. Extract signal logic as a pure function. Given a series window, it must return the same decision for the same input every time. Test it against historical windows and confirm the decisions match the baseline journal at the same ticks.
  4. Extract risk. Move every stake calculation and every halt condition here. Write unit checks for the boundaries: exactly at the ceiling, one unit above, counter at limit minus one, counter at limit.
  5. Reduce execution to placement and reporting. It should contain no conditional logic about whether to trade.
  6. Re-run the baseline. The refactored bot’s journal should match the original’s decisions and stakes on the same demo replay. Differences are either bugs or undocumented behaviour you have now made explicit; classify each one.

For interface checks, assert on the message shapes rather than on internal state. A signal object missing its reason code, or a risk approval without a stake, should fail loudly at the boundary. Version the objects so a later change to signal semantics forces a visible bump rather than silently altering what risk receives.

Backtesting belongs to the signal layer and is a filter, not proof. Use large samples, hold out an out-of-sample period, and report how many configurations you tried, because a search over many parameter sets will produce good-looking results by chance. Judge candidates by expectancy, break-even rate and drawdown, not win rate alone; a high win rate with a low payout can still lose money. The break-even win rate for a payout of 0.95 is 1 / (1 + 0.95) ≈ 0.513, so a strategy winning 51% of contracts at that payout has negative expectancy before costs.

Rules should be written before trading, and any change should follow a process: state a hypothesis, test it on demo and in backtest, version the change, then deploy. Never change rules immediately after a loss; that is how a disciplined bot becomes a discretionary one with extra steps.

Limitations

This structure does not make a strategy profitable, and it does not validate one. It does not remove execution differences between demo and live, such as latency, requotes, or fills that behave differently under load; demo trading removes financial risk but not behavioural or execution differences. It does not protect against platform-side changes to contract specifications, payout schedules, or available durations, which is why the risk layer should read limits from configuration rather than hard-coding them. It does not substitute for the platform’s own controls, and where stop loss or take profit by price is mentioned, note that those exist for Multipliers; for fixed-stake contracts, risk is controlled by stake, duration and session limits. Finally, layered code cannot fix a rule set that was never written down.

Frequently Asked Questions

Does splitting a bot into layers change its results? No, a correct refactor should reproduce the baseline journal exactly on the same demo replay; any difference is a behaviour change you must explain.

Where do session limits belong? In the risk layer, because it is the only layer permitted to halt trading and to compute stake from remaining budget.

Can I test a new signal without retesting risk? Yes, provided the signal object’s shape and version are unchanged and the risk layer’s unit checks still pass; that isolation is the point of the split.

Key Takeaways

  • Four layers with one-way dependencies: data ingestion, signal logic, risk, execution.
  • Only the risk layer sizes stakes and halts trading; only execution places orders.
  • Keep a demo baseline journal and require the refactor to reproduce it.
  • Judge strategies by expectancy, break-even rate and drawdown, and report how many configurations you tried.
  • Fixed-stake contracts cap loss through stake, duration and session limits; price-based stop loss applies to Multipliers.

The ORSTAC repository hosts open-source bots structured along these lines, and the Deriv API documentation plus the official API libraries cover the transport details for each layer. The bots run on Deriv, where a free demo account is available to test them, and DBot itself is documented on the Deriv Bot page; instrument specifics for synthetic indices are on the synthetic indices page. Discussion of refactors, interface conventions and demo results 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.