Skip to main content

What you’ll build

In this tutorial, you will build a simple mean reversion workflow that:
  1. streams mark-price updates,
  2. calculates a rolling mean,
  3. measures current deviation from that mean,
  4. enters only when the deviation breaches a fixed threshold,
  5. exits or cancels when the signal normalizes.

Prerequisites

Step 1: Collect a rolling mark-price series

Use one symbol and one mark-price subscription. Store enough recent values to compute:
  1. a rolling mean,
  2. the current distance from that mean,
  3. 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.
This gives you a basic hysteresis model so the bot does not flip constantly near the center line.

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.
Skip the update when the deviation is inside your neutral band.

Step 4: Avoid stacking risk on repeated signals

Before sending another request:
  1. check whether a working order already represents the same view,
  2. cancel stale orders if the mean has moved materially,
  3. keep one bounded inventory target instead of averaging repeatedly into the same move.
The first successful version should prefer discipline over frequency.

Step 5: Price and size the order conservatively

For each candidate order:
  1. round amount and price to the allowed product increments,
  2. keep notional small,
  3. remain inside the effective price-band and margin constraints,
  4. 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:
  1. build the order,
  2. sign and encrypt it through the normal request path,
  3. submit once,
  4. 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:
  1. close or reduce the position,
  2. cancel stale working orders,
  3. 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:
  1. one threshold breach,
  2. one submitted order,
  3. one tracked lifecycle path,
  4. one clean exit or cancellation when the signal normalizes.

Next routes

Last modified on April 12, 2026