Asked at IMC Trading, Hudson River Trading
Theory: Order Books and MatchingRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
The first thing any matching engine does: take an incoming order, walk the resting side of the book, and work out what it trades against.
Implement fill_order(levels, qty, limit_price, side).
levels is the resting opposite side, already in book order, best price
first. Each entry is (price, available) with integer ticks and lots. For a
buy these are asks in ascending price; for a sell they are bids in
descending price.qty is the incoming quantity, a non-negative integer.limit_price bounds what the order will accept: a buy will not pay above
it, a sell will not accept below it.side is 'B' or 'S'.Walk the levels in order, consuming as much as the incoming order still needs at each. A level may be consumed partially, leaving the rest resting.
Return (fills, remaining) where fills is the list of (price, quantity)
actually traded, in the order they occurred, and remaining is the unfilled
quantity.
fill_order([(100, 5), (101, 10), (102, 7)], 12, 101, "B")
# ([(100, 5), (101, 7)], 0)
fill_order([(100, 5), (101, 10)], 20, 100, "B")
# ([(100, 5)], 15)
The first fills 5 at the touch and 7 of the 10 at the next level, leaving 3 resting there. The second cannot pay 101, so it stops after the first level with 15 lots unfilled.
0 <= len(levels) <= 2 * 10^5, quantities and prices are positive integers.Run your code to check it against the sample tests. Results appear here.