Book Buy-Sell Matching System
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-01-27
Problem Statement
Design a simplified Order Matching Engine for a trading system (like a stock exchange), where users can place buy and sell orders for a book (or asset). The system should maintain an order book and perform matching based on price-time priority.
Functional Requirements
1.Place Orders
•Users can place Buy and Sell orders.
•Each order has: id, type (BUY/SELL), price, quantity, timestamp.
2.Order Matching Logic
•Buy Order → Match with lowest-priced available Sell order (price ≤ buy price).
•Sell Order → Match with highest-priced available Buy order (price ≥ sell price).
•If multiple matches are possible:
•Use price priority (best price first).
•If prices are equal, use time priority (earlier order first).
3.Partial Matches
•If order quantity > available match, partially fulfill and keep the rest in the order book.
•If order is fully filled, remove it from the book.
4.Order Book Maintenance
•Maintain two structures:
•Buy Orders (sorted by price desc, then timestamp asc).
•Sell Orders (sorted by price asc, then timestamp asc).
5.Queries
•placeOrder(order) → Executes matches and updates book.
•getOrderBook() → Returns current unmatched orders.
•cancelOrder(orderId) → Cancel an existing order (if unmatched/partially matched).
Non-Functional Requirements
•Thread Safety: Multiple users may place/cancel orders concurrently.
•Performance: Matching should be fast (logarithmic inserts/queries preferred).
•Correctness: Ensure no race conditions (atomic updates).
•Extensibility: Support for multiple instruments (books) in the future.
Example
Input Orders:
1
21: BUY 100 qty at 10
32: SELL 50 qty at 9
43: SELL 70 qty at 10 Processing:
•Order 1 (BUY 100 @ 10) matches with Order 2 (SELL 50 @ 9) → 50 filled.
•Remaining BUY (50 qty @ 10) matches with Order 3 (SELL 70 @ 10) → 50 filled.
•Remaining SELL (20 qty @ 10) stays in the book.
Final Book:
1
2SELL: (20 qty @ 10)
3BUY: []Class Design (Java-like Sketch)
1
2class Order {
3 String id;
4 OrderType type; // BUY or SELL
5 double price;
6 int quantity;
7 long timestamp;
8}
9
10class OrderBook {
11 PriorityQueue<Order> buyOrders; // Max-Heap: highest price first
12 PriorityQueue<Order> sellOrders; // Min-Heap: lowest price first
13
14 public synchronized void placeOrder(Order order) {
15 if (order.type == OrderType.BUY) {
16 matchBuyOrder(order);
17 } else {
18 matchSellOrder(order);
19 }
20 }
21
22 private void matchBuyOrder(Order buy) {
23 while (buy.quantity > 0 && !sellOrders.isEmpty() && sellOrders.peek().price <= buy.price) {
24 Order sell = sellOrders.poll();
25 int tradedQty = Math.min(buy.quantity, sell.quantity);
26 buy.quantity -= tradedQty;
27 sell.quantity -= tradedQty;
28 if (sell.quantity > 0) sellOrders.add(sell); // partially filled sell
29 }
30 if (buy.quantity > 0) buyOrders.add(buy);
31 }
32
33 private void matchSellOrder(Order sell) {
34 while (sell.quantity > 0 && !buyOrders.isEmpty() && buyOrders.peek().price >= sell.price) {
35 Order buy = buyOrders.poll();
36 int tradedQty = Math.min(sell.quantity, buy.quantity);
37 sell.quantity -= tradedQty;
38 buy.quantity -= tradedQty;
39 if (buy.quantity > 0) buyOrders.add(buy); // partially filled buy
40 }
41 if (sell.quantity > 0) sellOrders.add(sell);
42 }
43
44 public synchronized void cancelOrder(String orderId) {
45 // search and remove from queues (needs auxiliary maps for fast lookup)
46 }
47}Key Discussion Points for LLD Round
•Why PriorityQueue for buy/sell book vs. TreeMap (logarithmic operations, sorted order)?
•Handling concurrent order placements/cancellations (locking strategy).
•Trade-offs in throughput vs fairness (single-threaded vs sharded order books).
•Extensions: multi-instrument support, persistence (DB/Log for recovery), trade events publishing.