~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

OA: Crypto order management system

medium 2 levels ~45 min Coinbase

Level 1 Consume order events

A crypto exchange publishes every change to its orders as a text event on a queue. Build OrderTracker, the service that reads those events and can say where each order stands.

An event is one string with five comma-separated fields; spaces around a field don't matter:

"<order_id>, <side>, <symbol>, <quantity>, <event_type>"
  • order_id and symbol are non-empty strings (e.g. "a17", "ETH-USD"), side is "BUY" or "SELL".
  • quantity is a positive integer written in decimal digits.
  • event_type is "NEW" (an order for quantity units was placed) or "FILLED" (another quantity units of that order were executed).
  • Fields are case-sensitive: buy or new in lowercase is an unknown side or event type.

Implement:

  • consume(event: str) -> bool: apply the event and return True, or return False and change nothing if it is rejected. Reject:
    • a malformed event: not exactly five fields, an empty id or symbol, an unknown side or event type, or a quantity that isn't a positive integer;
    • NEW for an id that already exists;
    • FILLED for an unknown id, with a side or symbol that differs from the order's, or for more units than the order still has open (a fully filled order has none).
  • status(order_id) -> str | None: "OPEN" if nothing has been executed yet, "PARTIALLY_FILLED" if some but not all units have been, "FILLED" if all have. None for an unknown id.
  • filled(order_id) -> int | None: units executed so far, None for an unknown id.
t = OrderTracker()
t.consume("a1, BUY, BTC-USD, 10, NEW")        # True
t.consume("a1,BUY,BTC-USD,4,FILLED")          # True     spacing doesn't matter
t.status("a1"), t.filled("a1")                 # ("PARTIALLY_FILLED", 4)
t.consume("a1, SELL, BTC-USD, 1, FILLED")     # False    wrong side
t.consume("a1, BUY, BTC-USD, 7, FILLED")      # False    only 6 units open
t.consume("a1, BUY, BTC-USD, 6, FILLED")      # True
t.status("a1")                                 # "FILLED"
t.consume("a2, BUY, BTC-USD, 0, NEW")         # False    quantity must be positive
t.consume("a2, HOLD, BTC-USD, 3, NEW")        # False    unknown side
t.status("a2")                                 # None
Show hint

Parse with [f.strip() for f in event.split(",")] and validate everything before touching state. A dict from id to a small record (side, symbol, quantity, filled) answers every query in O(1).

Level 2 unlocks when level 1 passes.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

0:00
Ctrl ' run · Ctrl ↵ submit
esc