Market Simulator
This design defines a small exchange simulation with one instrument, limit orders and a price-time order book. Its rules are explicit so the matching engine and strategies can be checked separately.
Orders and price levels
Each order has an ID, owner, side, integer tick price, remaining quantity and arrival sequence. Keep bids from highest to lowest price and asks from lowest to highest. At each price, keep orders in arrival order.
Use integer quantities and tick prices to avoid rounding changing comparisons. The simulation's instrument configuration defines tick size and contract multiplier.
Matching rules
An incoming buy matches asks at or below its limit; an incoming sell matches bids at or above its limit. Match against the oldest eligible resting order first. Each fill uses the resting order's price and the smaller remaining quantity.
Continue until the incoming quantity is exhausted or no eligible order remains. Add any remainder to the book. A cancel removes only quantity still resting when the cancel arrives. Define self-trade behaviour explicitly; this design cancels the incoming remainder if its next match would be against the same owner.
Accounts
Each fill changes both participants' cash and inventory by equal and opposite amounts before fees. Record fees separately. Keep pending orders visible to the risk check so several accepted orders cannot each spend the same available budget.
Mark inventory using a documented reference price. A midpoint mark is an accounting choice; it does not mean the inventory could be liquidated there.
Delayed messages
Place submissions, acknowledgements, fills and cancellations in an event queue. Give the strategy separate delays for receiving market data and delivering an order. A quote can become stale while its cancellation is still travelling.
Assign a sequence number to events with equal simulated time so replay is deterministic. Save the initial state, random seed and event log.
Invariants
- No order has negative remaining quantity.
- Every fill has an equal buy and sell quantity.
- Filled and cancelled quantity cannot exceed the submitted quantity.
- Resting orders obey the model's price and arrival priority.
- Cash and inventory reconcile with the fill ledger.
Run matching tests before judging a strategy. Then compare fills, inventory and profit under different delays and order flows. See Market Making, Backtesting and Testing.