Skip to main content

Universal Order Book Engine

Architecture for Any Asset, Any Market, Any Representation

Version: 1.0 Date: December 2024 Status: Design Specification


Table of Contents

PartTitleDescription
IExecutive SummaryVision, scope, and key differentiators
IIDesign PhilosophyCore principles and the universal abstraction
IIICore AbstractionsLONG/SHORT model, outcomes, market groups
IVMulti-Outcome MarketsBeyond binary: runners, selections, legs
VSynthetic Matching EngineCross-outcome and implied odds matching
VIAsian Handicap Native SupportLines, quarters, push, and synthetic matching
VIIMulti-Representation FrameworkOdds, prices, percentages, and hybrids
VIIIUniversal Data ModelStructures that work for any asset
IXMatching AlgorithmDirect, synthetic, and priority rules
XScope & BoundariesWhat Order Book does and does NOT do
XISystem ArchitectureComponents, data flow, event sourcing
XIIThe PipelineFive-stage deterministic pipeline
XIIIDurability & RecoveryEvent journal, fsync, crash recovery
XIVKubernetes & DeploymentK8s topology, HA, persistent volumes
XVOperations & MonitoringPrometheus, Grafana, alerting, runbooks
XVISecurityTrust boundaries, mTLS, input validation
XVIITesting StrategyTest pyramid, property tests, determinism
XVIIIAsset Class ImplementationsBetting, options, futures, prediction markets
XIXExtensibility & PluginsAdding new asset classes and representations
XXPerformance ConsiderationsMaintaining speed with flexibility
XXIComparison: SmartBets vs UniversalWhat changes, what stays the same
XXIIFAQCommon questions answered
XXIIIGlossaryTerm definitions
Appendix AMermaid Diagram IndexQuick reference to all diagrams
Appendix BDeep Dive FAQDetailed layman explanations

Appendix B Sections:

SectionTopic
B.1Balance Race Condition - Why LOCK, not just CHECK
B.2Asian Handicaps for Beginners - Full walkthrough
B.3Options Trading Demystified - Greeks explained
B.4Three-Way Synthetic Matching - Step by step
B.5Summary - How it all connects

Part I: Executive Summary

The Vision

One matching engine to rule them all.

The Universal Order Book Engine is designed to be a single, unified matching engine that can power:

  • Sports betting exchanges (BACK/LAY)
  • Prediction markets (YES/NO)
  • Stock exchanges (BUY/SELL)
  • Options markets (with Greeks and margin)
  • Futures markets (with expiry and settlement)
  • Cryptocurrency spot and derivatives
  • Any future asset class we haven't imagined yet

Why Universal?

The insight is simple: all tradeable instruments are fundamentally the same.

Whether you're betting on Manchester United, buying Apple stock, or trading Bitcoin futures, you're doing the same thing: expressing a directional view at a price, waiting to be matched with someone who disagrees.

Key Differentiators

FeatureTraditional DesignUniversal Design
Market ModelBinary (BACK/LAY or BID/ASK)N-outcome with relationships
MatchingDirect onlyDirect + Synthetic
Asian HandicapWorkaroundsNative first-class support
Asset ClassesOne per systemInfinite via adapters
RepresentationsFixed (odds or price)Pluggable, mixable
LiquidityFragmented per outcomeUnified via synthetic matching

The Universal Truth

At the core of every tradeable instrument is this structure:

POSITION = (DIRECTION, OUTCOME, PRICE, QUANTITY, COLLATERAL)

Everything else—BACK/LAY, BID/ASK, YES/NO, CALL/PUT—is just a representation layer on top of this universal truth.

Diagram Explanation:

This mind map shows the three pillars of the Universal Order Book:

PillarWhat It Means
Asset ClassesAny tradeable instrument can be modeled
CapabilitiesFeatures that go beyond traditional matching
GuaranteesSame reliability as the SmartBets-specific design

Part II: Design Philosophy

The Abstraction Ladder

Every trading system can be understood as layers of abstraction:

Diagram Explanation:

LayerPurposeExample
User InterfaceHuman-friendly language"Bet on Man Utd"
RepresentationDomain-specific formatDecimal odds, USD price
Universal ModelNormalized structureLONG/SHORT + probability/price
Matching EngineAsset-agnostic matchingSame engine for all

The Core Insight

All two-sided markets are isomorphic.

DomainSide ASide BPrice Meaning
BettingBACKLAYDecimal odds (2.0 = 50% implied)
StocksBUYSELLCurrency (USD, EUR)
PredictionYESNOProbability (0-100%)
OptionsBUYSELLPremium + Greeks
FuturesLONGSHORTFuture price

The Universal Order Book uses LONG and SHORT as the canonical directions, with adapters that translate to/from domain-specific representations.

Design Principles

PrincipleMeaningImplementation
Representation AgnosticCore doesn't know about odds/pricesAdapters translate at boundaries
Outcome AgnosticBinary, multi-runner, continuousUnified outcome model
Settlement AgnosticEngine matches, plugins settlePluggable settlement framework
Synthetic-FirstCross-outcome matching is defaultImplied odds engine built-in

Part III: Core Abstractions

The Universal Position Model

Instead of BACK/LAY or BID/ASK, we use a universal direction model:

Diagram Explanation:

UniversalBettingTradingPredictionMeaning
LONGBACKBUYYESProfit if outcome occurs
SHORTLAYSELLNOProfit if outcome doesn't occur

The Outcome Hierarchy

Markets can have multiple outcomes with relationships:

Diagram Explanation:

LevelWhat It RepresentsExample
EventReal-world occurrenceFootball match
MarketType of bet/tradeMatch winner, handicap
OutcomeSpecific selectionMan Utd win, Over 2.5

Outcome Relationships

Outcomes can have mathematical relationships that enable synthetic matching:

Relationship Types:

TypeMeaningExampleSynthetic Matching
Mutually ExclusiveExactly one must happen1X2 marketSHORT on A+B = LONG on C
ComplementaryTwo outcomes sum to 100%Over/UnderLONG Over = SHORT Under
OrderedSequential handicap linesAsian HandicapCross-line synthetic
IndependentNo relationshipDifferent eventsNo synthetic matching

Part IV: Multi-Outcome Markets

Beyond Binary: The Multi-Runner Model

Traditional order books handle binary outcomes: this price, buy or sell. Real-world markets are more complex.

Diagram Explanation:

ModelOutcomesExampleOur Support
Binary2Over/Under, Yes/No✅ Full
Three-Way31X2 (Win/Draw/Win)✅ Full
Multi-RunnerNHorse race, election✅ Full
ContinuousPrice of a stock✅ Via bucketing

Market Types Supported

Per-Outcome Order Books

Each outcome in a multi-outcome market has its own order book:

Diagram Explanation:

ConceptImplementationBenefit
Per-Outcome BooksEach selection has LONG + SHORTIndependent liquidity per runner
Unified MarketAll outcomes share market metadataConsistent rules, single settlement
Cross-Outcome LinkOutcomes know about siblingsEnables synthetic matching

Overround and Book Balance

Multi-outcome markets have an important concept: overround (the sum of implied probabilities).

Overround Explained:

ScenarioOverroundWhat It MeansOur Response
= 100%FairZero-sum marketIdeal state
> 100%OverHouse edge built inNormal for bookmakers
< 100%UnderArbitrage opportunitySynthetic matching exploits this

Part V: Synthetic Matching Engine

What Is Synthetic Matching?

Synthetic matching is the killer feature that maximizes liquidity. It matches orders that don't directly oppose each other by using mathematical relationships between outcomes.

The Insight: If someone wants to go LONG on Horse A, they're effectively going SHORT on "not Horse A" (i.e., all other horses). The synthetic matching engine finds these equivalences.

The Mathematics of Synthetic Matching

In a mutually exclusive market, these are equivalent:

Formula:

SHORT(Outcome_A) ≡ LONG(Outcome_B) + LONG(Outcome_C) + ... + LONG(Outcome_N)

Where: P(A) + P(B) + P(C) + ... + P(N) = 100%

How Synthetic Matching Works

Diagram Explanation:

StepWhat HappensWhy It Matters
1. Check DirectLook for opposing orderFast path if available
2. Calculate SyntheticCombine other outcomesFind hidden liquidity
3. Compare PricesIs synthetic price acceptable?Only match if beneficial
4. ExecuteCreate trades on all legsAtomically matched

Synthetic Matching Example: 3-Way Market

Consider a 1X2 football market (Home/Draw/Away):

Calculation:

If you LONG both Draw and Away in the right proportions, you've effectively created a SHORT on Home:

Implied Home probability = 1 - (1/3.50 + 1/3.00)
= 1 - (0.286 + 0.333)
= 1 - 0.619
= 0.381
= 2.62 odds

If we can LONG Draw @ 3.50 and Away @ 3.00,
we create synthetic SHORT Home @ 2.62

Synthetic Matching Benefits

BenefitWithout SyntheticWith Synthetic
LiquidityOnly direct counterpartiesAll related outcomes contribute
SpreadCan be wideCompressed by synthetic competition
ArbitrageCan exist between outcomesAutomatically eliminated
Fill RateLowerSignificantly higher

Part VI: Asian Handicap Native Support

Why Asian Handicap Needs Special Treatment

Asian Handicap is one of the most popular betting markets globally, but it has unique characteristics that don't fit traditional binary models:

The Challenge:

Line TypeOutcomesTraditional Binary?Our Solution
Half-Goal2 (Win/Lose)✅ YesStandard binary market
Whole-Goal3 (Win/Lose/Push)❌ NoPush-aware outcome
Quarter-Goal4 (Win/Lose/Half-Win/Half-Lose)❌ NoAtomic split order

Quarter-Goal Lines: Native Atomic Orders

The key innovation is treating quarter-goal lines as atomic orders that internally split into two half-goal lines:

Diagram Explanation:

ConceptWhat HappensBenefit
Atomic OrderUser submits one orderSimple UX
Internal SplitEngine creates two legsProper matching
Unified SettlementBoth legs settle togetherCorrect payout

Handicap Line Relationships

Asian Handicap lines have a natural ordering that enables synthetic matching:

Line Relationship Rules:

If You HaveYou Can Synthetically CreateHow
LONG -0.5 + LONG -1.5LONG -1.0Average the positions
SHORT -1.0LONG +1.0 (same team)Flip the sign
LONG Team A -1.0SHORT Team B +1.0Opposite team

Cross-Line Synthetic Matching

The synthetic matching engine can match across handicap lines:

Push Outcome Handling

Whole-goal lines can result in a "push" where stakes are returned:

Push Implementation:

AspectHow We Handle It
Order MatchingNormal LONG/SHORT matching
Position TrackingTrack push-eligible lines
SettlementThree-way: Win, Lose, or Push
CollateralFull collateral still required

Complete Asian Handicap Support Matrix

Full Feature List:

FeatureSupportImplementation
Half-goal lines✅ NativeStandard binary outcome
Whole-goal lines✅ NativePush-aware three-way outcome
Quarter-goal lines✅ NativeAtomic split order type
Direct matching✅ NativeStandard LONG/SHORT
Cross-line synthetic✅ NativeAdjacent line aggregation
Cross-team synthetic✅ NativeSign-flip equivalence
Push settlement✅ NativeThree-way settlement plugin
Split settlement✅ NativePer-leg settlement aggregation

Part VII: Multi-Representation Framework

The Problem: Different Domains, Different Languages

Every asset class speaks a different language:

The Challenge: How do we build one engine that speaks all these languages?

The Solution: Representation Adapters

The Universal Order Book uses adapters to translate between domain-specific representations and the internal universal model:

Diagram Explanation:

LayerPurposeExample
External APIDomain-specific interface"BACK at 2.50 odds"
AdapterTranslation layer2.50 odds → 400,000 BP
Universal CoreInternal representationBasis points (BP)

Internal Price Representation

Internally, all prices are stored as basis points (1/10,000th units) to avoid floating-point issues:

Conversion Table:

RepresentationExampleTo Basis PointsFormula
Decimal Odds2.50400,000 BP1,000,000 / odds
Percentage40%400,000 BPpercentage × 10,000
American ++150400,000 BP1,000,000 / (1 + american/100)
American --200666,667 BP1,000,000 × abs(american) / (100 + abs(american))
Fractional3/2400,000 BP1,000,000 / (1 + numerator/denominator)
USD Price$150.251,502,500 BPprice × 10,000

Representation Adapter Interface

Each adapter implements a standard interface:

Adapter Methods:

MethodPurposeExample (Odds)
toInternalConvert to basis points2.50 → 400,000
toExternalConvert from basis points400,000 → 2.50
validatePriceCheck if price is valid0.99 → false (< 1.0)
formatForDisplayHuman-readable string400,000 → "2.50"
getTickSizeMinimum price increment100 BP (0.01 odds)
roundToTickSnap to valid tick2.503 → 2.50

Tick Sizes and Price Grids

Different representations have different tick sizes:

Why Variable Ticks?

ReasonExplanation
Meaningful Increments0.01 difference at 1.50 odds matters; at 100 odds, it doesn't
Reduce NoiseFewer valid prices = less queue jumping
Match Industry StandardsBetfair uses this grid; traders expect it

Hybrid Markets: Mixing Representations

The most powerful feature: a single market can support multiple representations simultaneously:

Diagram Explanation:

InterfaceUser SeesInternalTranslation
BettingBACK @ 1.80LONG @ 555,556 BP1/1.80 = 55.6%
PredictionYES @ 55¢LONG @ 550,000 BPDirect
TradingBUY @ $0.55LONG @ 550,000 BP× 10,000

The Key Insight: All three interfaces are contributing to the same liquidity pool. A prediction market trader and a bettor can match against each other without knowing it!

Cross-Representation Matching

Representation Configuration Per Market

Markets can be configured with allowed representations:

Configuration Options:

SettingOptionsExample
Primary RepresentationOdds, Price, PercentageOdds for betting
Allowed RepresentationsList of enabled adapters[Odds, Percentage]
Default for DisplayWhich to show by defaultOdds
Tick GridWhich tick structureBetfair-style

Part VIII: Universal Data Model

Entity Hierarchy

The data model is organized in a clear hierarchy:

Entity Descriptions:

EntityPurposeCardinality
PlatformRoot container1
Asset ClassType of tradeableMany (betting, stocks, etc.)
EventReal-world occurrenceMany per asset class
MarketTrading venue for eventMany per event
OutcomePossible resultMany per market
Order BookLONG + SHORT queues1 per outcome
Price LevelOrders at same priceMany per book
OrderIndividual orderMany per level

Core Entities

Event

FieldTypeDescription
event_idUUIDUnique identifier
nameStringEvent name
asset_classAssetClassType of asset
start_timeTimestampWhen event starts
end_timeTimestampWhen event ends
statusEventStatusSCHEDULED, LIVE, CLOSED, SETTLED
metadataMapAdditional properties
marketsListMarkets for this event

Market

FieldTypeDescription
market_idUUIDUnique identifier
event_idUUIDParent event
market_typeMarketTypeType of market
nameStringMarket name
statusMarketStatusOPEN, SUSPENDED, CLOSED
representationsListSupported price formats
tick_gridTickGridValid price increments
synthetic_enabledBooleanAllow synthetic matching
settlement_typeSettlementTypeHow to settle
relationship_typeRelationshipTypeMUTUALLY_EXCLUSIVE, COMPLEMENTARY, ORDERED, INDEPENDENT
outcomesListPossible outcomes

Outcome

FieldTypeDescription
outcome_idUUIDUnique identifier
market_idUUIDParent market
nameStringOutcome name
statusOutcomeStatusACTIVE, SUSPENDED, WON, LOST, VOID
long_bookBTreeMapOrders betting FOR
short_bookBTreeMapOrders betting AGAINST
total_matchedAmountTotal volume matched
volume_24hAmount24-hour volume
last_matched_pricePriceMost recent trade price

Order

FieldTypeDescription
order_idUUIDUnique identifier
client_order_idStringClient-provided ID
sequence_numberu64Global sequence for ordering
outcome_idUUIDWhich outcome
directionDirectionLONG or SHORT
priceBasisPointsInternal price (0-1,000,000)
quantityAmountSize of order
filled_quantityAmountHow much has matched
statusOrderStatusPENDING, OPEN, PARTIALLY_FILLED, FILLED, CANCELLED
created_atTimestampWhen created
updated_atTimestampLast modification
expires_atTimestampOptional expiration
order_typeOrderTypeLIMIT, MARKET, IOC, FOK
time_in_forceTimeInForceGTC, GTD, IOC, FOK
parent_order_idUUIDFor composite orders (quarter-lines)
legsListOrder legs for composite orders

State Machine: Order Lifecycle

State Transitions:

FromToTrigger
PENDINGOPENOrder passes validation
PENDINGREJECTEDInvalid price, quantity, etc.
OPENPARTIALLY_FILLEDMatched some quantity
OPENFILLEDMatched all quantity
OPENCANCELLEDCancel request
OPENEXPIREDTTL exceeded
PARTIALLY_FILLEDFILLEDRemaining matched
PARTIALLY_FILLEDCANCELLEDCancel remainder

State Machine: Market Lifecycle

Indexing Strategy

For fast lookups, we maintain multiple indexes:

Index Performance:

LookupIndex UsedTime Complexity
Order by IDPrimary HashMapO(1)
Order by client IDby_client_orderO(1)
User's ordersby_userO(1) + O(orders)
Best priceOrderBook BTreeO(1) first element
All at pricePriceLevel queueO(1)

Part IX: Matching Algorithm

Matching Priority: Price-Time with Synthetic

The matching algorithm follows this priority:

Priority Rules:

PriorityRuleRationale
1. PriceBetter price always winsFair to liquidity providers
2. DirectDirect match before syntheticSimpler, faster execution
3. TimeFIFO within same priceRewards early liquidity

Direct Matching Flow

Synthetic Matching Flow

Synthetic Matching: Mutually Exclusive Example

For a 3-way market (Home/Draw/Away):

Trade Execution

When a match occurs, trades are created:

Matching Invariants

These invariants must ALWAYS hold:

Invariant Enforcement:

InvariantEnforcement Mechanism
No crossed booksMatch any crossable orders immediately
Price improvementExecute at resting order's price
Quantity conservationAtomic update of both orders
Atomic executionTransaction around synthetic
No self-tradeCheck user_id before matching
DeterministicSingle-threaded, no randomness

Part X: Scope & Boundaries

What the Order Book Does

The Order Book has one job: match orders. It does this job extremely well.

What the Order Book Does NOT Do

These are explicitly NOT the Order Book's responsibility:

Clear Separation of Concerns

The Contract

ComponentInputOutputGuarantees
Backend → Order BookPre-validated ordersTrade eventsOrders have valid balance
Order Book → BackendTrade eventsSettlement actionsEvents are durable, ordered
Backend → UserSettlement resultsFund transfersCorrect payouts

Why This Separation?

ConcernWhy NOT in Order BookBenefit
SettlementDifferent per asset class, needs oracle integrationOrder Book stays generic
BalanceRequires user context, database accessOrder Book stays fast
AuthSecurity boundary, needs tokensOrder Book stays simple
RiskBusiness rules, complianceOrder Book stays focused

The Order Book is a pure matching engine. It receives pre-validated orders and produces deterministic trade events. Everything else is the Backend's responsibility.


Part XI: System Architecture

High-Level Component Diagram

Component Descriptions:

ComponentResponsibilityScaling
gRPC GatewayOrder submission, queriesHorizontal
WebSocket GatewayReal-time streamingHorizontal
Market RouterRoute to correct engine shardHorizontal
SequencerAssign global sequence numbersSingle (HA pair)
Event JournalDurable event logReplicated
Matching EngineCore matching logicSharded by market
Synthetic EngineCross-outcome matchingPer shard
Settlement EnginePosition settlementHorizontal

Data Flow: Order Lifecycle

Sharding Strategy

For horizontal scaling, markets are sharded:

Sharding Rules:

RuleImplementationBenefit
Shard by Markethash(market_id) mod NRelated orders go to same shard
Event AffinityAll markets for event on same shardEnables cross-market synthetic
Hot Market IsolationPopular markets get dedicated shardPrevent hotspots
Dynamic RebalancingMove markets between shardsHandle load changes

Event Sourcing Architecture


Part XII: The Pipeline - Detailed Architecture

The Five-Stage Pipeline

The heart of the Universal Order Book is a deterministic pipeline inspired by the LMAX Disruptor architecture:

Pipeline Stages:

StageComponentResponsibilityThreading
1. GatewaygRPC/WebSocketAccept connections, validate formatMulti-threaded
2. SequencerMonotonic CounterAssign global orderingSingle-threaded
3. JournalAppend-only LogDurability before processingSingle-threaded
4. EngineMatching CoreMatch orders, update stateSingle-threaded
5. PublisherEvent Fan-outNotify subscribersMulti-threaded

The Danger Zone: Durability Boundary

The critical insight: never acknowledge until durable.

The Guarantee:

Crash PointClient Received ACK?Order Status
Before fsyncNoLost (client retries)
During fsyncNoLost (client retries)
After fsync, before engineYesWill be replayed
After engineYesProcessed, will be replayed

Sequencer: The Source of Truth

Sequence Number Rules:

RuleExplanation
MonotonicEach number > previous, always
Gapless1, 2, 3, 4... never 1, 2, 4
GlobalSame sequence across all markets
PersistentCounter saved to disk, restored on restart

Part XIII: Durability & Recovery

The Event Journal

The journal is an append-only log that records every event before processing:

Journal Entry Format

Each journal entry has a self-describing binary format:

Field Descriptions:

FieldSizePurpose
Magic4 bytesIdentifies valid entry (0xORDRBOOK)
Version1 byteFormat version for upgrades
Length4 bytesTotal entry size for seeking
Sequence8 bytesGlobal sequence number
EventType2 bytesOrderReceived, TradeExecuted, etc.
Timestamp8 bytesNanosecond precision
PayloadVariableProtobuf-encoded event data
CRC324 bytesCorruption detection

The fsync Barrier

The fsync call is the durability boundary:

fsync Strategies:

StrategyLatencyDurabilityUse Case
Every write~1-5msMaximumProduction
Batched (10ms)~0.5ms avgHighHigh throughput
Async~0.1msLowDevelopment only

Crash Recovery Process

Recovery Timeline:

PhaseTimeWhat Happens
Load Snapshot~100msRestore state to sequence N
Replay Journal~2ms/1000 eventsApply events N+1 to current
Verify State~10msHash comparison
Total< 3 secondsFor 1M events

Snapshot Strategy

Snapshots accelerate recovery by checkpointing state:

Snapshot Retention:

PolicyKeepPurpose
LatestAlwaysFast recovery
Hourly24 hoursRecent rollback
Daily7 daysInvestigation
Weekly4 weeksAudit

Part XIV: Kubernetes & Deployment

Production Topology

Pod Specifications

Order Book Pod

Resource Configuration:

ResourceRequestLimitRationale
CPU2 cores4 coresSingle-threaded + headroom
Memory4Gi8GiOrder books + journal buffer
Storage100GiN/AJournal + snapshots
IOPS10,000N/Afsync performance

Persistent Volume Configuration

Storage Requirements:

MountSizeI/O PatternBackup
/data/journal80GiSequential writeContinuous
/data/snapshots20GiPeriodic writeHourly to S3
/config1GiRead-onlyConfigMap

High Availability Strategy

Availability Targets:

MetricTargetMeasurement
Uptime99.9%8.7 hours/year downtime
RTO< 30 secondsTime to recover
RPO0No data loss
FailoverAutomaticK8s handles

Deployment Strategy

Deployment Checklist:

StepActionRollback
1Announce maintenance windowN/A
2Stop accepting new ordersResume
3Drain pending ordersWait
4Take snapshotN/A
5Deploy new versionRevert image
6Replay and verifyUse old snapshot
7Resume tradingRollback

Part XV: Operations & Monitoring

Observability Stack

Key Metrics

Critical Metrics:

MetricAlert ThresholdSeverity
matching_latency_p99> 100msCritical
journal_write_latency_p99> 50msCritical
memory_used_bytes> 80% limitWarning
events_per_second< 100 for 5minWarning
up0Critical
sequence_numberNot increasingCritical

Grafana Dashboards

Dashboard Panels:

DashboardKey Panels
OverviewStatus, Orders/sec, P99 latency, Error rate
PerformanceLatency histograms, Throughput, Queue depth
BusinessTrade volume, Spread, Book depth, Active orders
SystemCPU, Memory, Disk I/O, Network
DebugSequence gaps, Journal segments, Match breakdown

Alerting Rules

Runbook: Common Issues


Part XVI: Security

Security Model

The Universal Order Book operates on a defense in depth model:

Trust Boundaries

Trust Levels:

ZoneTrust LevelAccess
UntrustedNonePublic internet
DMZLimitedFiltered traffic
TrustedHighInternal services only

Security Measures

MeasureImplementationPurpose
Network IsolationPrivate subnet, no public IPReduce attack surface
mTLSMutual TLS between servicesAuthenticate both parties
Input ValidationProtobuf schema + business rulesPrevent injection
Self-Trade PreventionCheck user_id before matchPrevent wash trading
Rate LimitingAt gateway levelPrevent DoS
Audit LoggingAll events journaledForensics, compliance

What Order Book Does NOT Handle

Security FunctionHandled ByReason
User authenticationBackendSeparation of concerns
Password managementBackendOrder Book has no user concept
Balance validationBackendOrder Book trusts pre-validation
Fraud detectionBackend + MLRequires user context
KYC/AMLBackendRegulatory requirement

Part XVII: Testing Strategy

Test Pyramid

Test Distribution:

LevelCountTimeCoverage
Unit~200030sCore logic, adapters
Integration~2002minJournal, matching, recovery
E2E~505minFull flow with backend

Critical Test Scenarios

Scenario Details:

ScenarioWhat We TestHow
Crash RecoveryState after replay = state before crashInject crash, compare hashes
Synthetic MatchingImplied odds calculated correctlyProperty-based tests
Asian HandicapPush, half-win, half-lose settle correctlyExhaustive scenarios
Multi-RepOdds trader matches percentage traderCross-format test suite
Self-TradeSame user_id orders don't matchInject self-crossing orders
Sequence GapsGaps detected, processing haltedRemove journal entries

Property-Based Testing

Determinism Testing

The Determinism Guarantee:

Given the same sequence of input events, the engine MUST produce the exact same output, regardless of when or where it runs.


Part XVIII: Asset Class Implementations

Supported Asset Classes

The Universal Order Book supports these asset classes out of the box:

Sports Betting Adapter

Prediction Markets Adapter

Options Adapter

Futures Adapter

Asset Class Comparison

FeatureBettingPredictionEquityOptionsFutures
TerminologyBACK/LAYYES/NOBUY/SELLBUY/SELLLONG/SHORT
Price UnitOddsCentsCurrencyPremiumPrice
SizingStakeSharesSharesContractsContracts
ExpiryEvent timeResolutionNoneFixed dateFixed date
SettlementBinaryBinaryTrade-outExerciseDelivery/Cash
MarginFull stakeFull costT+2Premium + marginMargin
SyntheticMulti-runnerMulti-outcomeN/APut-Call parityCalendar spread

Part XIX: Extensibility & Plugins

Plugin Architecture Overview

The Universal Order Book is designed for extensibility through well-defined plugin interfaces:

Adding a New Asset Class

To add support for a new asset class:

Plugin Interface Contracts

RepresentationPlugin Interface

MethodParametersReturnsDescription
toInternalexternal priceBasisPointsConvert to internal format
toExternalinternal priceExternalPriceConvert to display format
validatepriceResultValidate price is valid
getTickGridnoneTickGridGet valid price increments
formatpriceStringFormat for display

SettlementPlugin Interface

MethodParametersReturnsDescription
getSettlementTypenoneTypeGet settlement type
calculatePayoutposition, resultAmountCalculate winnings
validateSettlementmarketResultValidate settlement valid
getRequiredCollateralorderAmountCollateral needed

ValidationPlugin Interface

MethodParametersReturnsDescription
validateOrderorderResultValidate order is valid
validateMarketmarketResultValidate market config
getConstraintsnoneConstraintsGet validation rules

SyntheticPlugin Interface

MethodParametersReturnsDescription
canSyntheticMatchmarketBooleanIs synthetic enabled
calculateSyntheticorder, booksMatchFind synthetic match
getRelatedOutcomesoutcomeOutcomesGet complementary outcomes

Configuration-Driven Markets

Markets are created via configuration, not code:


Part XX: Performance Considerations

Performance vs Flexibility Trade-offs

Adding universality introduces overhead. Here's how we minimize it:

Performance Targets

MetricSmartBets DesignUniversal DesignOverhead
Throughput10,000 orders/sec8,000 orders/sec20%
P50 Latency5ms6ms20%
P99 Latency50ms60ms20%
Memory per market500KB600KB20%
Recovery time2 seconds2.5 seconds25%

Note: The overhead is acceptable given the massive increase in flexibility.

Optimization Strategies

Benchmarking Approach


Part XXI: Comparison: SmartBets vs Universal

Feature Comparison

FeatureSmartBets DesignUniversal Design
Market ModelBinary (BACK/LAY)N-outcome
Synthetic Matching❌ None✅ Full
Asian Handicap⚠️ Workarounds✅ Native
Multi-Runner❌ Separate markets✅ Single market
Asset ClassesBetting onlyAny asset
RepresentationsOdds onlyPluggable
SettlementBackend handlesPluggable plugins
ComplexitySimpleMore complex
PerformanceOptimal~20% overhead

Architecture Comparison

When to Use Which

Decision Guide:

ScenarioRecommendation
Sports betting only, simple marketsSmartBets Design
Need Asian Handicap, multi-runnerUniversal Design
Future expansion to other assetsUniversal Design
Maximum performance criticalSmartBets Design
Platform play / multi-verticalUniversal Design

Part XXII: FAQ

General Questions

Q: Why not just use separate systems for different asset classes?

A: Maintenance burden, duplicated logic, inconsistent behavior. One universal engine means one codebase, one ops team, one set of guarantees.

Q: How does synthetic matching affect latency?

A: Synthetic matching only runs when direct matching fails. Direct matches are unchanged. Synthetic adds ~10ms for 3-way markets, ~20ms for 10+ runners.

Q: Can I use the Universal design for SmartBets?

A: Yes! Configure it with sports_betting asset class, BACK/LAY representation, and disable synthetic matching. You get the SmartBets behavior with future expansion capability.

Asian Handicap Questions

Q: How are quarter-goal lines stored?

A: As atomic composite orders. The user submits one order, but internally it's stored as two linked legs on adjacent half-goal lines.

Q: What happens if only one leg of a quarter-goal matches?

A: Both legs must match or neither does. Quarter-goal orders are "all-or-nothing" at the order level (though they can partial fill proportionally).

Q: How does push settlement work?

A: The settlement plugin recognizes when the final margin equals the handicap line exactly, and returns the stake instead of paying out or deducting.

Synthetic Matching Questions

Q: Can synthetic matching create arbitrage?

A: No, it eliminates arbitrage. If prices across outcomes allow risk-free profit, synthetic matching will immediately match those orders.

Q: How fast is synthetic calculation?

A: For a 3-way market: ~1ms. For a 10-runner: ~5ms. For complex Asian Handicap lines: ~3ms. All acceptable.

Q: What if someone games the synthetic engine?

A: Synthetic trades execute at fair prices calculated from the book. There's no information asymmetry to exploit.

Representation Questions

Q: Can the same user use different representations?

A: Yes! User A can submit in odds, User B in percentages. They'll match against each other seamlessly.

Q: How do tick sizes work across representations?

A: Each representation has its own tick grid. Prices are validated in the representation's grid, then converted to basis points for matching.

Q: What about rounding errors?

A: Basis points provide sufficient precision for all representations. Any display rounding is purely cosmetic.

Extension Questions

Q: How do I add a new asset class?

A: Implement the four plugin interfaces (representation, settlement, validation, synthetic), register in the plugin registry, and create market configurations.

Q: Can plugins be loaded at runtime?

A: Yes, the plugin registry supports dynamic loading. However, for performance, we recommend compile-time registration for known asset classes.


Part XXIII: Glossary

TermDefinition
AdapterComponent that translates between external representation and internal model
Asian HandicapBetting market type that applies a goal handicap to level the playing field
Atomic OrderOrder that appears as one to user but internally consists of multiple linked legs
Basis Points (BP)Internal price unit; 10,000 BP = 1% probability or 1.00 currency unit
Complementary OutcomesTwo outcomes that sum to 100% (e.g., Over/Under)
Direct MatchMatch between orders on the same outcome's opposing books
EventReal-world occurrence that markets are based on
Half-Goal LineAsian Handicap line ending in .5 (e.g., -0.5, -1.5)
Implied ProbabilityProbability derived from odds: 1/odds
LONGUniversal direction: profit if outcome occurs
MarketTrading venue for a specific aspect of an event
Multi-RunnerMarket with more than 2 outcomes (e.g., horse race)
Mutually ExclusiveOutcomes where exactly one must occur
OutcomePossible result within a market
OverroundSum of implied probabilities across all outcomes; >100% means house edge
PluginModular component implementing a specific interface
Price-Time PriorityMatching rule: better price first, then earlier time
PushSettlement result where stakes are returned (no win/loss)
Quarter-Goal LineAsian Handicap line ending in .25 or .75
RepresentationHow prices are displayed (odds, percentage, currency)
SettlementProcess of determining and executing payouts
SHORTUniversal direction: profit if outcome doesn't occur
Synthetic MatchMatch created by combining orders across related outcomes
Ternary SettlementSettlement with three outcomes: win, lose, or void
Tick GridValid price levels for a representation
Whole-Goal LineAsian Handicap line without decimal (e.g., 0, -1, -2)

Appendix A: Mermaid Diagram Index

For quick reference, this document contains the following diagrams:

PartDiagramDescription
IMind MapUniversal Order Book capabilities
IIFlowchartAbstraction ladder
IITableDirection mapping across domains
IIIFlowchartUniversal position model
IIIFlowchartOutcome hierarchy
IIIFlowchartOutcome relationships
IVFlowchartMulti-outcome model comparison
IVFlowchartMarket types taxonomy
IVFlowchartPer-outcome order books
IVFlowchartOverround explanation
VFlowchartWith vs without synthetic
VFlowchartSynthetic equivalence
VSequenceSynthetic matching process
VFlowchart3-way market synthetic example
VFlowchartSynthetic benefits
VIFlowchartAsian Handicap types
VIFlowchartQuarter-goal atomic orders
VIFlowchartHandicap line relationships
VISequenceCross-line synthetic matching
VIFlowchartPush outcome handling
VIFlowchartAsian Handicap feature matrix
VIIFlowchartDifferent domain languages
VIIFlowchartRepresentation adapters
VIIFlowchartInternal price representation
VIIFlowchartAdapter interface
VIIFlowchartTick sizes
VIIFlowchartHybrid markets
VIISequenceCross-representation matching
VIIFlowchartMarket representation config
VIIIFlowchartEntity hierarchy
VIIIFlowchartEvent entity
VIIIFlowchartMarket entity
VIIIFlowchartOutcome entity
VIIIFlowchartOrder entity
VIIIState DiagramOrder lifecycle
VIIIState DiagramMarket lifecycle
VIIIFlowchartIndexing strategy
IXFlowchartMatching priority
IXFlowchartDirect matching flow
IXFlowchartSynthetic matching flow
IXFlowchartMutually exclusive example
IXSequenceTrade execution
IXFlowchartMatching invariants
XFlowchartOrder Book responsibilities
XFlowchartWhat Order Book does NOT do
XSequenceSeparation of concerns
XIFlowchartSystem components
XISequenceOrder lifecycle data flow
XIFlowchartSharding strategy
XIFlowchartEvent sourcing
XIIFlowchartFive-stage pipeline
XIISequenceDanger zone - durability boundary
XIIFlowchartSequencer properties
XIIIFlowchartJournal structure
XIIIFlowchartJournal entry format
XIIIFlowchartfsync barrier
XIIIFlowchartCrash recovery process
XIIIFlowchartSnapshot strategy
XIVFlowchartKubernetes production topology
XIVFlowchartOrder Book pod specification
XIVFlowchartPersistent volume configuration
XIVFlowchartHigh availability strategy
XIVFlowchartBlue-green deployment
XVFlowchartObservability stack
XVFlowchartKey metrics categories
XVFlowchartDashboard hierarchy
XVFlowchartAlert severity levels
XVFlowchartCommon issues runbook
XVIFlowchartSecurity layers
XVIFlowchartTrust boundaries
XVIIFlowchartTest pyramid
XVIIFlowchartCritical test scenarios
XVIIFlowchartProperty-based testing
XVIIFlowchartDeterminism verification
XVIIIFlowchartAsset class adapters
XVIIIFlowchartSports betting adapter
XVIIIFlowchartPrediction markets adapter
XVIIIFlowchartOptions adapter
XVIIIFlowchartFutures adapter
XIXFlowchartPlugin architecture
XIXFlowchartAdding new asset class
XIXFlowchartPlugin interfaces
XIXFlowchartConfiguration-driven markets
XXFlowchartPerformance concerns
XXFlowchartOptimization strategies
XXFlowchartBenchmarking approach
XXIFlowchartArchitecture comparison
XXIFlowchartDecision guide

Appendix B: Frequently Asked Questions - Deep Dive

This appendix provides detailed, layman-friendly explanations for common questions about the Universal Order Book architecture.


B.1: The Balance Race Condition Problem

The Question

"If the backend checks user balance, it's fine, then gives the order to the order book. While the order is in the order book, another order from the same user comes that also reaches the order book after the backend checks. Now at the time of matching, the user doesn't have sufficient funds but the order is still matched. Should the backend check again after matching, or just pass it to Solana?"

The Problem Visualized

Imagine this scenario:

Timeline:
─────────────────────────────────────────────────────────────────────►

User has $100 in their account

T1: User submits Order A for $80
Backend checks: $100 >= $80? ✓ YES
Backend sends Order A to Order Book

T2: User submits Order B for $50
Backend checks: $100 >= $50? ✓ YES (balance hasn't changed yet!)
Backend sends Order B to Order Book

T3: Order Book matches Order A ($80)
T4: Order Book matches Order B ($50)

PROBLEM: User committed $130 but only had $100!

This is called a race condition - two processes (Order A and Order B) are racing, and the result depends on timing.

Why "Check Again After Match" Doesn't Work

You might think: "Just check the balance again when the trade comes back."

Problem: The trade already happened! The counterparty was told their order matched. You can't "un-match" a trade.

If we reject Order B after matching:

User A: "I matched with User B!"
User B: "Actually, nevermind, User B didn't have money"
User A: "But you told me the trade happened!"

This breaks trust in the entire system.

The Solution: LOCK, Don't Just CHECK

The correct approach is to lock (escrow) funds at submission time, not just check them.

WRONG APPROACH: Check
──────────────────────────
"Do you have $80?" → "Yes" → Continue
(But the $80 is still available for other orders!)

RIGHT APPROACH: Lock
──────────────────────────
"Reserve $80 now" → Money moved to locked state → Continue
(Now only $20 is available for other orders!)

The Correct Flow

Timeline with LOCKING:
─────────────────────────────────────────────────────────────────────►

User has: Available = $100, Locked = $0

T1: User submits Order A for $80
Backend LOCKS $80
User now has: Available = $20, Locked = $80
Backend sends Order A to Order Book

T2: User submits Order B for $50
Backend tries to lock $50
Available is only $20
$20 < $50 → REJECTED immediately!
Order B never reaches Order Book

T3: Order Book matches Order A ($80)
No problem - funds were already secured

RESULT: No race condition possible!

Balance States Explained

Think of your money like physical locations:

┌─────────────────────────────────────────────────────────────────────┐
│ YOUR ACCOUNT ($100 total) │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ AVAILABLE │ │ LOCKED │ │ IN POSITION │ │
│ │ │ │ (Escrowed) │ │ (At Risk) │ │
│ │ $100 │ │ $0 │ │ $0 │ │
│ │ │ │ │ │ │ │
│ │ Can place │ │ Reserved │ │ Committed │ │
│ │ new orders │ │ for pending │ │ to matched │ │
│ │ │ │ orders │ │ bets │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘

When you place an order:

BEFORE placing $80 order:
├── Available: $100
├── Locked: $0
└── In Position: $0

AFTER order submitted (before match):
├── Available: $20 ← Reduced immediately!
├── Locked: $80 ← Reserved for this order
└── In Position: $0

AFTER order matches:
├── Available: $20
├── Locked: $0 ← Released
└── In Position: $80 ← Now at risk in the bet

What About Partial Fills?

If your $80 order only partially fills (say, $50 matches):

AFTER partial match ($50 of $80):
├── Available: $20
├── Locked: $30 ← Remaining unmatched portion
└── In Position: $50 ← Matched portion

If you CANCEL the remaining $30:
├── Available: $50 ← $30 returned!
├── Locked: $0
└── In Position: $50

The Answer to Your Question

QuestionAnswer
Should backend check again after trade?NO
Should it pass to Solana to check?NO
What should backend do instead?LOCK funds at submission time
Why?Race condition is prevented before it can happen

Summary

┌─────────────────────────────────────────────────────────────────────┐
│ THE GOLDEN RULE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ Never just CHECK a balance - always LOCK it. │
│ │
│ Checking = "Do you have money?" (informational) │
│ Locking = "I'm taking this money now" (transactional) │
│ │
│ The Order Book only receives pre-funded orders. │
│ The money question is settled BEFORE matching. │
│ │
└─────────────────────────────────────────────────────────────────────┘

B.2: Asian Handicaps Explained for Complete Beginners

What Problem Does Asian Handicap Solve?

Imagine you want to bet on a football match: Manchester City vs Norwich City.

Everyone knows Man City is much stronger. The traditional odds might be:

OutcomeOddsWhat It Means
Man City Win1.10Bet $100, win only $10
Draw8.00Bet $100, win $700
Norwich Win25.00Bet $100, win $2400

The problem: Man City at 1.10 is a terrible bet. You risk $100 to win $10. Even if they're 90% likely to win, one loss wipes out nine wins!

The Asian Handicap Solution

Idea: Give Norwich a "head start" to make it fair.

Instead of betting "Man City wins", you bet "Man City wins by MORE than 2 goals".

This is written as: Man City -2 or equivalently Norwich +2

How to Read Handicap Lines

Norwich +2 means:
"Add 2 goals to Norwich's final score, THEN see who wins"

Example: Real score is Man City 3 - 0 Norwich
Adjusted score: Man City 3 - 2 Norwich
Man City still "wins" the handicap bet

Example: Real score is Man City 2 - 0 Norwich
Adjusted score: Man City 2 - 2 Norwich
It's a TIE! This is called a PUSH.

The Full Range of Handicap Lines

Let's say Man City beats Norwich 2-0. Here's what happens with different handicaps:

HandicapNorwich's Adjusted ScoreResult
Norwich +02-0Man City backers WIN
Norwich +0.52-0.5Man City backers WIN
Norwich +12-1Man City backers WIN
Norwich +1.52-1.5Man City backers WIN
Norwich +22-2PUSH (money returned)
Norwich +2.52-2.5Norwich backers WIN!
Norwich +32-3Norwich backers WIN

Why Half-Goals Exist (+0.5, +1.5, +2.5)

You can't score half a goal in football. So half-goal lines eliminate ties.

With +2 handicap:
- 2-0 final → 2-2 adjusted → PUSH (tie, money back)

With +2.5 handicap:
- 2-0 final → 2-2.5 adjusted → Norwich "wins" (no tie possible)

Half-goal = guaranteed winner, no push

Quarter-Goal Lines (+0.25, +0.75, +1.25, etc.)

Sometimes +2 feels too tight and +2.5 feels too generous. Quarter-goals split the difference.

Here's the secret: A quarter-goal line is actually TWO BETS combined!

Norwich +2.25 means:
├── 50% of your stake on Norwich +2
└── 50% of your stake on Norwich +2.5

It's NOT a real line - it's shorthand for two bets!

Quarter-Goal Outcomes Explained

Let's say you bet $100 on Norwich +2.25 at odds of 1.90:

Scenario 1: Man City wins 1-0

LegHandicapAdjustedResultPayout
Leg 1 ($50)+21-2Norwich WIN$50 × 1.90 = $95
Leg 2 ($50)+2.51-2.5Norwich WIN$50 × 1.90 = $95
TotalFULL WIN$190 (profit $90)

Scenario 2: Man City wins 2-0

LegHandicapAdjustedResultPayout
Leg 1 ($50)+22-2PUSH$50 back
Leg 2 ($50)+2.52-2.5Norwich WIN$50 × 1.90 = $95
TotalHALF WIN$145 (profit $45)

Scenario 3: Man City wins 3-0

LegHandicapAdjustedResultPayout
Leg 1 ($50)+23-2City WINLose $50
Leg 2 ($50)+2.53-2.5City WINLose $50
TotalFULL LOSE$0 (lose $100)

Scenario 4: Man City wins 2-0 (close one)

Wait, that's the same as Scenario 2. Let me do Man City 3-1:

LegHandicapAdjustedResultPayout
Leg 1 ($50)+23-3PUSH$50 back
Leg 2 ($50)+2.53-3.5Norwich WIN$95
TotalHALF WIN$145

The Five Possible Outcomes with Quarter Lines

OutcomeWhat HappensWhen
Full WinBoth legs winMargin < both lines
Half WinOne leg wins, one pushesMargin = lower line
PushBoth legs push(Impossible with quarters)
Half LoseOne leg loses, one pushesMargin = higher line
Full LoseBoth legs loseMargin > both lines

Visual Summary

You bet: Norwich +2.25 for $100

Man City wins by: 1 goal 2 goals 3 goals 4+ goals
│ │ │ │
▼ ▼ ▼ ▼
+2.0 leg ($50): WIN PUSH LOSE LOSE
+2.5 leg ($50): WIN WIN LOSE LOSE
│ │ │ │
▼ ▼ ▼ ▼
Your outcome: FULL WIN HALF WIN HALF LOSE* FULL LOSE
Return: $190 $145 $50** $0

* If exactly 3-1, it's HALF LOSE (push on +2, lose on +2.5)
** Actually for 3-0: lose both legs = $0. For 3-1: $50 back

Why the Order Book Handles This Specially

The Order Book treats quarter-line bets as atomic composite orders:

User places: BACK Norwich +2.25 @ 1.90 for $100

Order Book internally creates:
┌─────────────────────────────────────────┐
│ ATOMIC ORDER GROUP │
│ (must execute together or not at all) │
├─────────────────────────────────────────┤
│ Leg 1: BACK Norwich +2.0 @ 1.90 for $50│
│ Leg 2: BACK Norwich +2.5 @ 1.90 for $50│
└─────────────────────────────────────────┘

Both legs are matched together. You can't have one leg matched and the other not.


B.3: Options Trading Demystified

The Common Misconception

Many people think options are impossibly complex because of terms like:

"Delta, Gamma, Theta, Vega, Rho, Black-Scholes,
implied volatility, time decay, strike price..."

But here's the truth: Most of this complexity is NOT relevant for order matching!

What You Actually Specify When Trading Options

When you place an options order, you specify exactly 6 things:

ParameterExamplePlain English
UnderlyingAAPLWhat stock/asset
Strike Price$150The price threshold
ExpirationJan 17, 2025When does it expire
TypeCallBetting price goes up (or Put for down)
Your Price$5.00How much you'll pay per share
Quantity10 contractsHow many (usually 100 shares each)

That's it! No Greeks in the order.

What Are The Greeks Then?

The Greeks are measurements that describe how an option behaves - they're calculated AFTER you own the option, not when you order it.

Think of it like buying a car:

When you BUY the car, you specify:
- Make: Toyota
- Model: Camry
- Year: 2024
- Color: Blue
- Price: $30,000

The car's CHARACTERISTICS (calculated later):
- Fuel efficiency: 32 mpg
- 0-60 time: 7.5 seconds
- Turning radius: 18 feet

You don't say "I want a car with 32 mpg" - you say
"I want a Camry" and then learn it gets 32 mpg.

OPTIONS WORK THE SAME WAY!

The Greeks Explained Simply

GreekWhat It MeasuresCar Analogy
DeltaHow much option moves when stock moves $1Speed
GammaHow fast Delta changesAcceleration
ThetaValue lost per day from time passingDepreciation
VegaSensitivity to market volatilitySensitivity to road conditions
RhoSensitivity to interest ratesSensitivity to fuel prices

Key insight: You don't order an option by its Greeks. You order it by its specifications (strike, expiry, type), and then the Greeks describe its behavior.

Options Are Just Bets With a Deadline

Strip away the jargon, and an option is just:

A CALL OPTION is a bet that says:
"I bet the stock will be ABOVE the strike price by the expiration date"

A PUT OPTION is a bet that says:
"I bet the stock will be BELOW the strike price by the expiration date"

Example: Apple $150 Call expiring January 2025

Plain English:
"I bet that Apple stock will be above $150 on January 17, 2025"

If I'm right (AAPL is at $170 on that date):
- My option is worth $20 per share ($170 - $150)
- I paid $5 per share
- Profit: $15 per share

If I'm wrong (AAPL is at $140 on that date):
- My option is worthless (why pay $150 for something worth $140?)
- I lose my $5 per share

How Options Map to Our Universal Model

DomainWhat You're Betting OnDirectionPrice
Sports Bet"Man City wins"BACK1.85 odds
Prediction"Trump wins election"YES$0.52
Call Option"AAPL above $150 on Jan 25"BUY$5.00
Put Option"AAPL below $150 on Jan 25"BUY$3.00

The matching is identical in all cases: find someone willing to take the other side at a compatible price.

Where Do Greeks Come In?

Greeks are used by SURROUNDING SERVICES, not the order book:

┌─────────────────────────────────────────────────────────────────────┐
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ PRICING │ │ RISK │ │
│ │ SERVICE │ │ SERVICE │ │
│ │ │ │ │ │
│ │ Calculates │ │ Calculates │ │
│ │ fair price │ │ Greeks for │ │
│ │ using Black- │ │ margin & │ │
│ │ Scholes │ │ hedging │ │
│ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ │ │ │
│ └────────►│ ORDER BOOK │◄─────────┘ │
│ │ │ │
│ │ Doesn't know │ │
│ │ about Greeks! │ │
│ │ │ │
│ │ Just matches: │ │
│ │ "BUY AAPL $150 │ │
│ │ Call @ $5.00" │ │
│ │ vs │ │
│ │ "SELL AAPL $150 │ │
│ │ Call @ $5.00" │ │
│ │ │ │
│ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘

Strike Prices = Handicap Lines

Here's a beautiful parallel:

ASIAN HANDICAP LINES:          OPTIONS STRIKE PRICES:

Norwich +3.0 (very safe) AAPL $120 Call (very likely)
Norwich +2.5 AAPL $130 Call
Norwich +2.0 AAPL $140 Call
Norwich +1.5 AAPL $150 Call (current price)
Norwich +1.0 AAPL $160 Call
Norwich +0.5 AAPL $170 Call
Norwich +0.0 (risky) AAPL $180 Call (unlikely)

Both are "lines" on a spectrum!
The Order Book handles them the same way.

Multi-Leg Options Strategies = Quarter-Goal Bets

Complex options strategies are just composite orders - exactly like quarter-goal Asian Handicaps!

StrategyLegsWhat It Means
Bull Call SpreadBuy $150 Call, Sell $160 Call"AAPL between $150-$160"
StraddleBuy $150 Call, Buy $150 Put"AAPL will move a lot (either direction)"
Iron Condor4 options at different strikes"AAPL will stay in a range"

The Order Book handles these as atomic groups - all legs match together or none do.


B.4: Three-Way Synthetic Matching Explained

The Setup: A Football Match with 3 Outcomes

Consider: Man City vs Liverpool

Three possible outcomes (exactly one will happen):

  • Home Win (Man City wins)
  • Draw
  • Away Win (Liverpool wins)

The Problem: Everyone Wants to BACK

Imagine three users:

  • Alice: Wants to BACK Home Win at odds 2.00
  • Bob: Wants to BACK Draw at odds 3.33
  • Charlie: Wants to BACK Away Win at odds 5.00

In traditional matching, nothing happens! Everyone is betting "for" something, nobody is betting "against" anything.

TRADITIONAL MATCHING:

Home Win book: [BACK Alice $100] ... waiting ... [no LAY orders]
Draw book: [BACK Bob $60] ... waiting ... [no LAY orders]
Away Win book: [BACK Charlie $40] ... waiting ... [no LAY orders]

Result: Everyone waiting. No trades. Frustrated users.

The Key Insight

Here's the magic realization:

If you're betting FOR Home Win...
You're automatically betting AGAINST Draw AND Away Win!

If Home wins → Alice wins, Bob loses, Charlie loses
If Draw → Alice loses, Bob wins, Charlie loses
If Away → Alice loses, Bob loses, Charlie wins

These three people are natural counterparties to each other!

The Mathematics

In a fair market with 3 outcomes, probabilities must sum to 100%:

OutcomeProbabilityFair Odds
Home Win50%2.00
Draw30%3.33
Away Win20%5.00
Total100%

Now, let's verify the synthetic match works:

Alice's bet: BACK Home @ 2.00 for $100

  • If Home wins: Profit $100
  • If Draw: Lose $100
  • If Away: Lose $100

Bob's bet: BACK Draw @ 3.33 for $60

  • If Home wins: Lose $60
  • If Draw: Profit $140 (win $200, stake was $60)
  • If Away: Lose $60

Charlie's bet: BACK Away @ 5.00 for $40

  • If Home wins: Lose $40
  • If Draw: Lose $40
  • If Away: Profit $160 (win $200, stake was $40)

Let's Check if It Balances

OutcomeAliceBobCharlieTOTAL
Home Wins+$100-$60-$40$0
Draw-$100+$140-$40$0
Away Wins-$100-$60+$160$0

The payoffs exactly cancel out! This is a perfect match.

What the Order Book Does

SYNTHETIC MATCHING:

1. Alice submits: BACK Home @ 2.00 for $100

2. Order Book thinks: "Can I synthesize a LAY Home?"

3. Checks other markets:
- Bob has: BACK Draw @ 3.33 for $60 ✓
- Charlie has: BACK Away @ 5.00 for $40 ✓

4. Calculates: Bob + Charlie together = LAY Home!

5. Executes THREE-WAY MATCH:
- Alice matched against (Bob + Charlie)
- All three orders filled!
- Emit 3 trade confirmations

Visual Representation

                         Alice
BACK Home
$100

┌─────────┴─────────┐
│ SYNTHETIC LAY │
│ (Created from │
│ Bob + Charlie) │
└─────────┬─────────┘

┌───────────┴───────────┐
│ │
Bob Charlie
BACK Draw BACK Away
$60 $40

The Synthetic Relationship

┌─────────────────────────────────────────────────────────────────────┐
│ THE THREE-WAY RELATIONSHIP │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ BACK Home = LAY (Draw + Away) │
│ BACK Draw = LAY (Home + Away) │
│ BACK Away = LAY (Home + Draw) │
│ │
│ In other words: │
│ Betting FOR one outcome = Betting AGAINST all others combined │
│ │
└─────────────────────────────────────────────────────────────────────┘

How the Stakes Are Calculated

The stakes must be proportional to the probabilities:

To synthesize LAY Home (liability = $100):

The "NOT Home" probability = P(Draw) + P(Away) = 30% + 20% = 50%

Stake on BACK Draw = $100 × (30% / 50%) = $100 × 0.6 = $60
Stake on BACK Away = $100 × (20% / 50%) = $100 × 0.4 = $40

Total stake: $60 + $40 = $100 ✓

Why This Matters

Without synthetic matching:

MetricResult
Matched orders0
Happy users0
Trading volume$0
Market efficiencyPoor

With synthetic matching:

MetricResult
Matched orders3
Happy users3
Trading volume$200
Market efficiencyExcellent

Extending to 4+ Outcomes (Horse Racing)

The same principle extends to any number of outcomes:

HORSE RACE: 6 Horses

BACK Horse A = LAY (B + C + D + E + F)

If you BACK Horse A, you're betting against ALL other horses.

If someone BACKs each of the other 5 horses in the right proportions,
together they form a synthetic LAY on Horse A.

→ 6-way synthetic match possible!

Summary

┌─────────────────────────────────────────────────────────────────────┐
│ THREE-WAY SYNTHETIC MATCHING │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ KEY INSIGHT: │
│ In mutually exclusive outcomes, everyone betting BACK on │
│ different outcomes are natural counterparties. │
│ │
│ WHAT THE ENGINE DOES: │
│ 1. Recognize that BACK orders on all outcomes complete each other│
│ 2. Calculate proportional stakes │
│ 3. Match them as a group │
│ 4. Ensure payoffs balance to zero in all scenarios │
│ │
│ WHY IT'S POWERFUL: │
│ Creates liquidity where none appeared to exist! │
│ │
└─────────────────────────────────────────────────────────────────────┘

B.5: Summary - How It All Fits Together

The Universal Order Book Philosophy

┌─────────────────────────────────────────────────────────────────────┐
│ │
│ The Order Book has ONE job: Match orders at compatible prices │
│ │
│ Everything else is handled elsewhere: │
│ • Balance management → Backend │
│ • Settlement/Payouts → Backend │
│ • Greeks calculation → Pricing Service │
│ • User authentication → Backend │
│ │
└─────────────────────────────────────────────────────────────────────┘

The Universal Language

Every tradeable thing, regardless of domain, can be expressed as:

ElementDescription
WHATThe specific outcome (team wins, price above X, etc.)
DIRECTIONLONG (for) or SHORT (against)
PRICEWhat you're willing to pay or receive
SIZEHow much exposure

Complex Features Built from Simple Parts

FeatureHow It Works
Asian Handicap QuartersComposite order with 2 legs on adjacent lines
Options SpreadsComposite order with 2+ legs at different strikes
Synthetic MatchingMatching BACK against combined BACKs on other outcomes
Cross-Line MatchingUsing mathematical relationships between related outcomes

The Key Guarantees

GuaranteeHow It's Achieved
No overspendingLock (don't just check) funds at submission
Fair matchingPrice-time priority
Deterministic replaySingle-threaded engine, event journal
No data lossfsync before acknowledgment
Balanced bookSynthetic matches sum to zero in all outcomes

Document End

This architecture specification defines the Universal Order Book Engine - a matching engine capable of supporting any tradeable asset class with full synthetic matching, native Asian Handicap support, pluggable representations, and complete infrastructure for production deployment.