What you’ll build
In this tutorial, you will build a simple mean reversion workflow that:- streams mark-price updates,
- calculates a rolling mean,
- measures current deviation from that mean,
- enters only when the deviation breaches a fixed threshold,
- exits or cancels when the signal normalizes.
Prerequisites
- A working
ddx-pythonsetup. - The transport and lifecycle pattern from Building Your First Trading Bot.
- The moving-window pattern from Implementing a Moving Average Crossover Strategy.
Step 1: Collect a rolling mark-price series
Use one symbol and one mark-price subscription. Store enough recent values to compute:- a rolling mean,
- the current distance from that mean,
- the previous distance so you can see whether the market is snapping back or still drifting away.
Step 2: Define the entry and exit thresholds
Keep the first strategy simple:- one entry threshold for opening a reversion trade,
- one tighter exit threshold for standing down again.
Step 3: Choose one side from the deviation
Use one direction rule:- if price is far above the rolling mean, prepare one short-biased action,
- if price is far below the rolling mean, prepare one long-biased action.
Step 4: Avoid stacking risk on repeated signals
Before sending another request:- check whether a working order already represents the same view,
- cancel stale orders if the mean has moved materially,
- keep one bounded inventory target instead of averaging repeatedly into the same move.
Step 5: Price and size the order conservatively
For each candidate order:- round amount and price to the allowed product increments,
- keep notional small,
- remain inside the effective price-band and margin constraints,
- reject the trade if the exposure would be harder to unwind than to open.
Step 6: Submit and record the signal state
When a deviation qualifies:- build the order,
- sign and encrypt it through the normal request path,
- submit once,
- store the rolling mean, current deviation, and side with the order identity.
Step 7: Exit when the signal normalizes
After entry, continue consuming the mark-price stream. When the deviation collapses back into the exit band:- close or reduce the position,
- cancel stale working orders,
- confirm the lifecycle events reflect the expected unwind.
Step 8: Finish with one controlled entry and one controlled exit
This tutorial is complete when you have:- one threshold breach,
- one submitted order,
- one tracked lifecycle path,
- one clean exit or cancellation when the signal normalizes.