orderbook

module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2026 License: MIT

README

📈 orderbook

A fast, embeddable limit-order-book & matching engine in Go —
plus a research harness and an animated, browser-native explainer.

The same engine you go get compiles to WebAssembly and runs live in the browser to teach how order books & market making actually work.

Live demo Spec Stars

Go WebAssembly License MIT Status CI Go Reference Go Report Card

Forks Watchers Last commit Commit activity Repo size Open issues Contributors

Go WASM TypeScript React Vite D3 Tailwind

🟢 Live. The engine, the research experiments, and an animated in-browser demo (Go compiled to WASM) are all shipping. The whole roadmap is done: core engine (M1) → OFI/imbalance signals (M2) → deterministic simulator (M3) → Avellaneda–Stoikov + backtest (M4) → the OFI study (M5) → advanced order types (M6) → surveillance (M7) → auctions + circuit breakers + pro-rata (M8) → WASM demo + market-maker scene (M9/M10) → benchmarks + L3 (M11). See the milestones.


What is this?

orderbook is one repository with three reinforcing goals:

🧱 A library An efficient, embeddable CLOB + matching engine in Go. Integer-exact (int64 ticks/lots), zero-alloc hot path, single-writer, deterministic, price–time priority. go get and drop it into an exchange, a simulator, or a tool. suitable for many
🔬 A research harness Build and honestly backtest microstructure ideas — order-flow imbalance, Kyle's λ, Avellaneda–Stoikov market making, delta/CVD — with reproducible experiments, not screenshots. contemporaneous ≠ predictive
🎬 An animated explainer The same engine compiled to WebAssembly, running live in the browser, teaching how order books and market making work — one animated scene at a time. show, then explain

The three coexist through one rule: strict downward layering — the core library never depends on the research, simulation, or presentation layers.


Highlights

  • 💰 Money is never a float — the engine works in exact int64 ticks and lots; decimals live only at the API boundary (a per-symbol Instrument). No float rounding on the money path (fixing the classic bug in the frozen legacy/ prototype).
  • Low-µs & zero-alloc — O(1) cancel, pooled book nodes/levels, and a caller-buffer match path with 0 allocations/op; cancel-heavy flow runs p50 ~83 ns, p99 ~166 ns, p999 ~209 ns per op.
  • 🧵 Single-writer — one matching goroutine owns the book lock-free (LMAX-style); many producers submit concurrently through an MPSC command queue (matching.Runner).
  • 🎯 Deterministic — same input stream → byte-identical trades & state; enables replay, WAL recovery, and honest backtests.
  • 🧰 Real-world order surface — market, limit, stop/stop-limit, iceberg/hidden, post-only, pegged, OCO/bracket, trailing, auctions.
  • 🛡️ Market integrity built in — self-trade prevention, spoofing/layering detection, stop-cascade protection, rate/velocity limits.
  • 📊 L1 / L2 / L3 (MBO) market data — snapshots + incremental diffs with sequence numbers.
  • 💹 Market making — an Avellaneda–Stoikov quoter with production adaptations (rolling σ/k, inventory bounds, adverse-selection add-on).

See the full design in docs/SPEC.md.


Performance

Core-library microbenchmarks (Apple M-series, Go 1.23, single-threaded) — int64 ticks, pooled book nodes/levels, and the caller-buffer match path (Match):

Benchmark ns/op allocs/op ~ops/sec
top-of-book read (BestBid) 6.3 0 ~160 M
cancel (drain) 253 0 ~4 M
MM cancel/replace (book) 180 0 ~5.5 M
new price level (churn) 292 0 ~3.4 M
match round-trip (Match, maker+taker+trade) 352 0 ~2.8 M
match round-trip (Process convenience) 491 4 ~2 M

Tail latency on a realistic ~90%-cancel / 10%-new flow (Match/Cancel): p50 83 ns · p99 167 ns · p999 292 ns, 0 allocs/op — the p999 stays within ~3.5× of the median. (The absolute numbers include time.Now overhead; the median-to-tail shape is the signal.)

Reproduce with make bench. CI runs them on every push and publishes the numbers to the Benchmarks workflow run summary. Full methodology and notes: docs/BENCHMARKS.md.


Architecture

web/ (React+TS)  ──▶  cmd/obwasm (Go→WASM)  ─┐
                                             │  strict downward layering
   backtest ▸ strategy ▸ sim ▸ signals ▸ marketdata
                                             │
            ══════════ CORE LIBRARY ═════════▼════════
              surveillance ▸ matching ▸ orderbook ▸ types

Research, simulation, and the web demo consume the core. The core depends on nothing above it. Full diagram in the spec.


Quickstart

go get github.com/intrepidkarthi/orderbook/pkg/matching
eng := matching.NewEngine(matching.DefaultConfig("BTC-USD"))

order, _ := types.NewOrder("alice", "BTC-USD", types.SideBuy,
    types.OrderTypeLimit, dec("30000"), dec("0.5"), types.TIFGoodTillCancel)

res := eng.Process(order)          // -> trades, status, remaining
bid, qty, ok := eng.BestBid()

Runnable examples & tools

go run ./examples/basic         # place two orders, watch them match
go run ./examples/marketmaker   # backtest an Avellaneda–Stoikov maker
go run ./examples/signals       # compute book imbalance + OFI

go run ./cmd/obdemo             # end-to-end matching demo
go run ./cmd/obmm               # AS market-making backtest + scorecard
go run ./cmd/ofistudy           # the OFI contemporaneous-vs-predictive study
go run ./cmd/l2capture          # LIVE OFI on real Coinbase data
go run ./cmd/surveil            # spoofing / rate-limit surveillance

Advanced order types (stop, iceberg, post-only, OCO, pegged, trailing), self-trade prevention, circuit breakers, and pro-rata matching all live in pkg/matching — see docs/SPEC.md §5.


Documentation

Doc What's inside
🎓 LEARN.md Order books & market making from scratch — no finance background needed.
📐 SPEC.md Architecture, the real-world order model, core design decisions, performance targets, milestones.
🔬 research-roadmap.md OFI, Kyle's λ, Avellaneda–Stoikov, delta/CVD — each as implementation → experiment → honest write-up.
BENCHMARKS.md Core-library performance, methodology, and how to reproduce.
🎬 DEMO-SPEC.md The animated, WASM-powered explainer: architecture, hosting, and the full scene storyboard.

Roadmap

M0 spec ✅ · M1 core engine ✅ · M2 OFI signals ✅ · M3 simulator + replay ✅ · M4 Avellaneda–Stoikov + backtest ✅ · M5 OFI study ✅ · M6 advanced order types ✅ · M7 surveillance ✅ · M8 auctions + circuit breakers + pro-rata ✅ · M9 WASM demo + Pages ✅ · M10 market-maker demo scene ✅ · M11 benchmarks + L3 ✅. The full roadmap is shipped (int-tick fast path noted as future). Details in the spec.


Provenance

The core design is informed by the author's prior production matching engine: decimal pricing, price–time priority, the map+ladder book structure, and the matching algorithm. This repo is a clean, research- and education-oriented re-implementation — not a copy of that exchange stack.

License

MIT © Karthikeyan NG

Topics: order-book · matching-engine · limit-order-book · clob · market-making · avellaneda-stoikov · order-flow-imbalance · market-microstructure · backtesting · algorithmic-trading · hft · quantitative-finance · webassembly · golang · exchange · price-time-priority

Directories

Path Synopsis
cmd
l2capture command
Command l2capture polls a public exchange's live level-2 order book and computes order-flow imbalance (OFI) and book imbalance in real time using pkg/signals — the same code the simulator study uses, now on real market data.
Command l2capture polls a public exchange's live level-2 order book and computes order-flow imbalance (OFI) and book imbalance in real time using pkg/signals — the same code the simulator study uses, now on real market data.
obdemo command
Command obdemo is a small end-to-end demonstration of the matching engine: it seeds a book with resting liquidity, then sends a crossing limit order and a market sweep, printing the ladder and the trade tape at each step.
Command obdemo is a small end-to-end demonstration of the matching engine: it seeds a book with resting liquidity, then sends a crossing limit order and a market sweep, printing the ladder and the trade tape at each step.
obmm command
Command obmm runs an Avellaneda–Stoikov market maker through the backtest harness against synthetic noise flow and prints its scorecard.
Command obmm runs an Avellaneda–Stoikov market maker through the backtest harness against synthetic noise flow and prints its scorecard.
obwasm command
Command obwasm compiles the matching engine to WebAssembly and exposes a small JSON API to JavaScript, so the browser demo runs the *real* engine rather than a reimplementation (docs/DEMO-SPEC.md §3).
Command obwasm compiles the matching engine to WebAssembly and exposes a small JSON API to JavaScript, so the browser demo runs the *real* engine rather than a reimplementation (docs/DEMO-SPEC.md §3).
ofistudy command
Command ofistudy runs the order-flow-imbalance experiment and prints whether OFI's link to price is contemporaneous or predictive.
Command ofistudy runs the order-flow-imbalance experiment and prints whether OFI's link to price is contemporaneous or predictive.
surveil command
Command surveil replays a scripted order-flow scenario — a genuine trader, a spoofer layering and pulling large orders, and a quote-stuffer — through the surveillance monitor and prints the alerts it raises.
Command surveil replays a scripted order-flow scenario — a genuine trader, a spoofer layering and pulling large orders, and a quote-stuffer — through the surveillance monitor and prints the alerts it raises.
examples
basic command
Basic example: create an engine, rest a sell order, then cross it with a buy and observe the trade and the resulting book.
Basic example: create an engine, rest a sell order, then cross it with a buy and observe the trade and the resulting book.
marketmaker command
Market-maker example: backtest an Avellaneda–Stoikov quoter against synthetic order flow and print its scorecard.
Market-maker example: backtest an Avellaneda–Stoikov quoter against synthetic order flow and print its scorecard.
signals command
Signals example: compute book imbalance and order-flow imbalance (OFI) from two consecutive book snapshots.
Signals example: compute book imbalance and order-flow imbalance (OFI) from two consecutive book snapshots.
pkg
auction
Package auction implements a call-auction uncross: given resting buy and sell interest, it finds the single clearing price that maximises executed volume and reports how much trades there.
Package auction implements a call-auction uncross: given resting buy and sell interest, it finds the single clearing price that maximises executed volume and reports how much trades there.
backtest
Package backtest runs a market-making strategy against synthetic order flow in a real matching engine and reports its performance.
Package backtest runs a market-making strategy against synthetic order flow in a real matching engine and reports its performance.
marketdata
Package marketdata models the input side of a market — order flow — and the tools to record and replay it deterministically.
Package marketdata models the input side of a market — order flow — and the tools to record and replay it deterministically.
matching
Package matching implements a lean, deterministic matching engine over the price–time-priority order book in package orderbook.
Package matching implements a lean, deterministic matching engine over the price–time-priority order book in package orderbook.
orderbook
Package orderbook implements a central limit order book (CLOB) with price–time priority.
Package orderbook implements a central limit order book (CLOB) with price–time priority.
signals
Package signals computes market-microstructure signals from order-book snapshots: book imbalance and order-flow imbalance (OFI) to start.
Package signals computes market-microstructure signals from order-book snapshots: book imbalance and order-flow imbalance (OFI) to start.
sim
Package sim is a deterministic exchange simulator.
Package sim is a deterministic exchange simulator.
strategy
Package strategy implements market-making strategies over the core engine.
Package strategy implements market-making strategies over the core engine.
study
Package study contains reproducible microstructure experiments that put the popular trading claims to the test on controllable, deterministic data.
Package study contains reproducible microstructure experiments that put the popular trading claims to the test on controllable, deterministic data.
surveillance
Package surveillance detects abusive trading patterns from a stream of order-book events.
Package surveillance detects abusive trading patterns from a stream of order-book events.
types
Package types defines the core domain values shared across the order book and matching engine: orders, trades, and the small set of errors they raise.
Package types defines the core domain values shared across the order book and matching engine: orders, trades, and the small set of errors they raise.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL