Replay and backtesting#
Replay any market's orderbook history and backtest strategies with the program's real fees and matching rules.
This page shows how to record a market, check that a replay reproduces its fills, backtest a
strategy on it and read execution-quality metrics. The engine is the seesaw-replay binary. It
runs the program's own matching code over the recorded account bytes, so fills, fees and
collateral are the program's, not an estimate.
Before you start#
- Build the engine:
cargo build --release -p seesaw-replay, then puttarget/releaseon yourPATHor setSEESAW_REPLAY_BINto the binary. - Know the program commit of the deployment you record and the
wirevalue ofspec/launch/version-policy.jsonat that commit. A recording made against other rules is refused.
Record a market#
RPC cannot read accounts at a past slot, so a recording starts from a checkpoint. Take the checkpoint first, let the market trade, then record everything after it:
seesaw replay record <market> --out start.json --program-commit <sha> --wire-digest <digest>
seesaw replay record <market> --checkpoint start.json --out market.json --program-commit <sha> --wire-digest <digest>
Add --source indexer to read the event stream from the indexer instead of RPC. A checkpoint
taken right after the market is created, before any order, records the whole market.
The checkpoint also captures the market's settlement mint. Simulation and metrics reports use its
precision for currencyDecimals and keep quantities and quote amounts in atoms. Older recordings
without mint data report currencyDecimals: null.
For markets with current spline seats, the recorder discovers the attached seats
and saves their bytes and event sequences at the same slot as the market and book.
It rejects a checkpoint if the collected seats disagree with the on-chain count.
Replay and simulation check each captured seat's recorder sequence separately
from the market sequence, and verify the recorded fields of spline fills and
shape updates against the recorder bytes.
The replay-recorded-fill journey takes a live checkpoint before an IOC,
compares the RPC and indexer histories, and checks replay and zero-latency
simulation against the landed fill and fee. Both stack modes retain the
recording and engine reports in the run artifacts.
Replay and reproduce#
seesaw replay run market.json
The report says match when every recorded fill was reproduced field by field: maker, order id,
price, quantity, collateral, taker fee, the five fee legs and the supply deltas. On a difference it
names the first transaction, event and field. To see the book, the computed fills and the
recorded fills at one transaction:
seesaw replay reproduce market.json --until <signature>
Backtest a strategy#
Write the orders to test as a strategy file:
{
"strategy": "orderList",
"orders": [
{
"beforeSignature": "<signature>",
"side": "buyYes",
"priceBps": 5400,
"quantity": "1000000",
"orderType": "ioc",
"execution": { "minFillQuantity": "1000000", "maxQuoteInput": "600000" }
}
]
}
Each order fires right before a recorded transaction (beforeSignature) or at a time
(atUnixTimestamp). The optional execution object also accepts validUntil,
restingExpiresAt, minQuoteOutput, and expectedFeeEpoch. The engine applies
the program's checks at the simulated landing time. Quantities and quote amounts
are decimal strings in atoms. Then run it:
seesaw replay simulate market.json --strategy orders.json --latency-ms 400 --missing-liquidity 0.25 --seed 7
Set execution.splineSeats to the checkpoint seat addresses in instruction order
to include those seats in a strategy order. Missing-liquidity simulation thins
the public order book. It keeps the selected spline quotes and accounts for
their fills, quote amounts, and fees.
--latency-msapplies each strategy order after every recorded instruction before its creation time plus the latency.--latency-slotswaits until a recorded instruction at or after the submission slot plus the delay. When both latency flags are set, both bounds must be met. The simulator applies eligible actions before that instruction and reports each applied order'sappliedSlot. Actions with an unmet latency bound when the history ends count towardpendingBeyondHistory.--missing-liquidityremoves that share of each other maker's resting quantity before a strategy order matches (--missing-mode ordersremoves whole orders, chosen with--seed). The liquidity is restored afterwards, so the recorded history still replays.--resolution-delay-secand--settlement-delay-secadd nonnegative delays toredeemableAt. The report usesresolutionObservedAtwhen the checkpoint or replayed history contains resolution. Otherwise it estimates from scheduled close.
builtin:one-sided-quoter rests one post-only bid 200 bps under mid and places it again when it
fills. Strategy orders are checked against the maker price band and rejected with the band
reason. The report counts displacedRecordedFills: recorded orders that fill differently, or no
longer apply, because the strategy took their liquidity.
Read execution-quality metrics#
seesaw replay metrics market.json --trader <address>
The metrics are:
- slippage against the mid and the best opposite price at the order's start, in bps
- fill rate per order (later fills of a resting remainder included) and in total
- quote survival: time to first fill, cancel or end, and the share still resting at 1, 10, 60 and 600 s
- markout: the last visible book mid at 1, 10, 60 and 600 s after each fill, signed for the trader's side. Horizons past the recording have no markout.
- the five fee legs per fill and in total, with the check that they sum to the collected fee
Amounts are atoms of the settlement currency. A quote still resting when the history ends counts only at horizons it was observed for. Spline maker fills use the outcome the seat acquires and the price it pays for that outcome. Maker markout uses that outcome's book mid. When the selected simulation owner owns the seat, the position summary also includes the acquired inventory, collateral spent, and maker rebate.
What replay models#
- Matching:
PlaceOrder, plus owner-fundedSwapWithFreeFundsandPlaceLimitWithFreeFunds. Prefunded replay checks the owner's tracked free balance. Replay uses the live spline matching and accounting rules for supplied seats captured in the checkpoint, including the market issuance cap. - Book changes from their events:
CancelOrder,CancelMultipleOrdersById,ReduceOrder, the prefunded bulk cancel and reduce variants,ReclaimExpiredOrder,ReclaimExpiredOrders, andForceCancelMarketOrders. - Ledger post-state:
DepositFundsandWithdrawFunds. - Live config updates: replay applies
UpdateOperationalParamsin chain order, including config-only transactions. Later instructions use the resulting order, expiry, and spline settings. Treasury rotations update all eight shards in order. Later fills use that mapping for the default settlement currency. - Idle-seat evacuation: replay clears the authenticated ledger slot and applies the market and position effects. It verifies the funded evacuation's recorded payout and preserves silent zero-balance evacuations in both recording modes.
- Closer-reward top-ups: replay checks the funder and configured budget in the recorder receipt. Both recording modes retain already-funded retries. Lamport balances are outside the checkpoint.
- Bounded cancellation: owner-authorized
CancelOwnerOrdersreplays the program's session cursor, indexed removals, and ledger refunds. - Order cancellation and reduction: wallet-funded routes release their tracked locks. Free-funds routes also credit the release to the user's free balance. Replay uses the program's cancellation and collateral math.
- Batch reclaim:
ReclaimExpiredOrdersrestores quote and claimable shares to the ledger. During the grace interval, released shares go to the maker quote reserve, so replay releases the ledger lock without crediting free shares. - Single-order reclaim: Unresolved-market buy orders replay from refund and economic events. For sell orders, RPC and indexer recordings also capture the escrow token instruction. A wallet transfer releases the share lock. An escrow burn releases the lock, credits free shares, and reduces token supply in the replayed market. For strategy orders, replay checks stop eligibility against the maker's ledger seat and credits any supplied strategy account when its capital epoch matches the order.
- Terminal reclaim: After resolution, a reclaim credits a bid's remaining collateral or an ask's settlement value to the maker's ledger. Replay uses the native payout or the exact payout in external market metadata and updates the tracked position and outstanding share supply.
- Emergency force cancellation: Replay checks the admin or pauser against the recorded config and enforces the armed status and slot delay. It then applies the wallet or ledger refund and verifies the resulting economic state.
Every other route stops the run with UnmodeledRoute and its name. The engine never skips a
route.
Known limits#
- Replay scope: strategy-authorized orders and cancellation, intervening seat publications and lifecycle changes, and tick-bound matching with a supplied Market Tick account require additional state. Older sell-order reclaim and force-cancellation recordings without the escrow token instruction still need a fresh ledger checkpoint. Replay also needs a tracked strategy account when a reclaim supplies one. Terminal reclaims require the maker's tracked position. Before the close grace period elapses, replay also needs maker signer evidence for a sell reclaim. A maker who is also the reclaim caller already supplies that evidence. Managed orders use batch reclaim.
- Account-bound checks: replay skips wallet balance and vault solvency checks that require account bytes beyond the checkpoint.
- Fill evidence: replay computes and compares the
MakerFillApplieddeltas. The recording supplies the referral route and builder cap when the checkpoint lacks them. - No market impact model: recorded orders after a strategy fill replay unchanged.
- Strategy position: it is tracked from its fills. The missing-liquidity model projects matched balances into the original book's ledger indexes.
Examples#
- Rust, the in-process engine:
packages/replay/examples/replay_market.rs(cargo run -p seesaw-replay --example replay_market). - Rust, the SDK client:
packages/sdk-rust/examples/replay_client.rs. - TypeScript, recording plus the binary:
packages/core/examples/16-replay-market.ts. - Python, the SDK client:
packages/sdk-python/examples/replay_market.py.
The Rust and Python SDK clients take a local engine executable and a recording
file. Build the engine with cargo build --locked --release -p seesaw-replay,
then set SEESAW_REPLAY_BIN to the executable path when running the examples.
Both clients support replay, reproduction up to a transaction, simulation and
recorded-fill metrics. Append replay, reproduce <signature>, simulate, or
metrics [trader] after the recording path in either example to print the
selected JSON report. The simulate example uses the built-in one-sided quoter
with 400 ms latency. With an explicit operation, both examples exit 2 after
printing a discrepancy report. The clients return that report when the engine exits
with code 2. The recording source remains the TypeScript SDK or
seesaw replay record.
Use a trusted engine binary. Both SDK clients cap stdout at 256 MiB. The caller owns any wall-clock deadline for the local engine process.
The CLI embeds the original engine JSON in its report envelope, preserving integer digits in fields such as simulated positions and fee metrics.
To check all four SDK operations, set SEESAW_REPLAY_RECORDING to the fresh
replay-captures/surfpool-order-controls.recording.json artifact and
SEESAW_REPLAY_BIN to the built engine. The example harness checks both clients
against the same capture, requires fills in the replay report, and reproduces
the final successful Seesaw transaction by signature.
node scripts/run_registered_examples.mjs --id rust-replay-client
node scripts/run_registered_examples.mjs --id python-replay-market