Questions / Quant development, Trading system components

Sweeping an ask book

Foundation, about 5 minutes. Question D362.

A buy for 700 with limit 101.0 sweeps the asks. What does it print?

import heapq
asks = [(101.0, 1, 300), (100.5, 2, 200), (100.5, 3, 400), (102.0, 4, 500)]
heapq.heapify(asks)            # (price, arrival, qty)
want, cost = 700, 0.0
while want and asks and asks[0][0] <= 101.0:
    p, t, q = heapq.heappop(asks)
    take = min(q, want)
    want -= take
    cost += take * p
    if q > take:
        heapq.heappush(asks, (p, t, q - take))
print(cost)

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 70400 USD

  1. Heap order: 100.5 (t2, 200), 100.5 (t3, 400), 101.0 (300).
  2. Fill 200 + 400 at 100.5 = 60,300.
  3. 100 at 101.0 = 10,100.
  4. Cost 70,400.

Interview shortcut. 600 × 100.5 + 100 × 101.

Takeaway. Price-time priority: best price first, earliest order within a price.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More trading system components questions