Implement a simplified trading simulation in three parts.
Part 1 — Process market data / exchange interaction (order book)
Design a minimal limit-order-book simulator for a single symbol.
Events
Each event is one of:
-
NEW orderId side price qty
-
side
is
B
(buy) or
S
(sell)
-
Add a limit order.
-
CANCEL orderId
-
Remove the remaining quantity of that order (if it exists).
Matching rules
When a new order arrives, immediately match it against resting orders on the opposite side using:
-
Price priority
: best price first (highest buy, lowest sell).
-
Time priority
: FIFO among orders at the same price.
A match produces one or more trades. A trade is:
-
tradePrice
= resting order’s price
-
tradeQty
= min(incomingRemaining, restingRemaining)
Output
For every input event, output the list of trades generated by that event (may be empty).
Part 2 — Execute for one client with participation rate
A single client submits a parent order:
-
clientId
,
side
, total target quantity
Q
, and participation rate
p
(0 < p <= 1).
You also receive a time-ordered stream of market prints (executed market volume):
At each print, you may execute some quantity for the client, but must satisfy at all times:
executedSoFar≤⌊p⋅marketVolumeSoFar⌋
Where marketVolumeSoFar is the cumulative sum of marketQty from prints up to time t.
Output
For each print, output how many shares you execute for the client at that time (0 if none), until the client reaches Q or prints end.
Part 3 — Multiple clients and fairness
Now there are multiple simultaneous clients, each with (Q_i, p_i).
At each PRINT, compute executions for all clients such that:
-
For every client
i
:
executed_i <= floor(p_i * marketVolumeSoFar)
.
-
No client executes more than its remaining quantity.
-
Total executed at a print does not exceed that print’s
marketQty
.
-
If there isn’t enough available volume to satisfy everyone’s allowed amount, allocate
fairly
by prioritizing the client(s) with the smallest
Qiexecutedi
ties broken by smaller clientId.
Task
Implement the simulator for all three parts.
Notes
-
You may assume all inputs are validly formatted.
-
You should state and handle edge cases like canceling unknown orders, or
p_i * marketVolumeSoFar
allowing more than remaining.