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

OA: Crypto trading system

medium 2 levels ~45 min Coinbase

Level 1 Order lifecycle

Build TradingSystem, the order-management core of a small crypto exchange. An order has an id (string), a currency (e.g. "BTC"), a positive integer amount, an integer timestamp, a side ("buy" or "sell") and a state: "live", "paused", "completed" or "canceled". Nothing completes at this level; that comes in level 2.

Implement:

  • place(order_id, currency, amount, timestamp, side) -> bool: create a new live order. Return False (and change nothing) if order_id has ever been used before, in any state. Timestamps never decrease from one place call to the next.
  • pause(order_id) -> bool: a live order becomes paused. False for any other state or an unknown id.
  • resume(order_id) -> bool: a paused order becomes live again. False otherwise.
  • cancel(order_id) -> bool: a live or paused order becomes canceled, permanently. False otherwise (already canceled, unknown, ...).
  • state(order_id) -> str | None: the order's current state, or None for an unknown id.
  • live_orders(currency=None) -> list[str]: the ids of all live orders, oldest placement first. With a currency, only orders in that currency. A resumed order keeps its original place in this list.
ts = TradingSystem()
ts.place("o1", "BTC", 3, 100, "buy")    # True
ts.place("o2", "ETH", 10, 105, "sell")  # True
ts.place("o1", "SOL", 1, 110, "buy")    # False, id taken
ts.pause("o1")                          # True
ts.live_orders()                        # ["o2"]
ts.cancel("o1")                         # True  (paused orders can be canceled)
ts.resume("o1")                         # False (it's canceled now)
ts.state("o1")                          # "canceled"
ts.live_orders("BTC")                   # []
Show hint

A dict from id to a small order object (or dict) is enough here. Python dicts keep insertion order, which is placement order.

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