Price-Time Order Matching
Learn this problemProblem statement
Process a finite ordered batch of limit orders for one asset. Each input row has the form [side, orderId, price, quantity], where side is "BUY" or "SELL".
An incoming buy may match resting sells priced at or below its limit. An incoming sell may match resting buys priced at or above its limit. Always choose the best resting price first: the lowest sell price for a buy and the highest buy price for a sell. At one price, match the earliest resting order first.
Each fill uses the resting order's price and the largest quantity possible. Continue matching a partially filled incoming order while it crosses the opposite book. Any unfilled quantity then rests at the back of its price level.
Return one String[][] containing these rows in order:
- Every fill in execution order as
["TRADE", buyId, sellId, price, quantity]. - Every remaining buy as
["BUY", orderId, price, quantity], ordered by descending price and then arrival time. - Every remaining sell as
["SELL", orderId, price, quantity], ordered by ascending price and then arrival time.
Function
matchOrders(orders: String[][]) → String[][]Examples
Example 1
orders = [["BUY","b1","100","5"],["SELL","s1","90","2"],["SELL","s2","100","4"],["BUY","b2","101","2"]]return = [["TRADE","b1","s1","100","2"],["TRADE","b1","s2","100","3"],["TRADE","b2","s2","100","1"],["BUY","b2","101","1"]]The two incoming sells fill resting buy b1 at its resting price. The final buy consumes the one-unit remainder of s2, then rests with one unit.
Example 2
orders = [["SELL","s1","105","2"],["SELL","s2","103","1"],["BUY","b1","106","2"],["BUY","b2","104","3"]]return = [["TRADE","b1","s2","103","1"],["TRADE","b1","s1","105","1"],["BUY","b2","104","3"],["SELL","s1","105","1"]]Buy b1 takes the lower-priced sell first. Buy b2 does not cross the remaining sell, so both orders rest in their respective books.
Constraints
1 <= orders.length <= 100000.- Every row contains exactly four strings:
side,orderId,price, andquantity. sideis"BUY"or"SELL".- Order IDs are non-empty and unique.
priceandquantityare base-10 positive integers at most10^9.- The returned rows fit in memory.