Simulate Trading Order Fill Rate Limit
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Simulate order executions under a time-windowed volume participation constraint using a sliding window.
You are tasked with evaluating an algorithmic trading execution algorithm. Given a historical stream of public trade records, you need to simulate how much of a client's buy order would be executed and calculate the total cost paid.
Inputs
market_prints: A chronological list of tuples(timestamp, price, volume)representing historical market transactions.timestampis an integer millisecond timestamp,priceis a float, andvolumeis a float.order: A tuple(target_volume, max_participation_rate)representing the client's order parameters.target_volumeis the total volume to fill (float), andmax_participation_rateis a float in[0.0, 1.0].window_size: An integer duration in milliseconds defining the historical look-back window.
Simulation Rules
- Execution Timing & Batching: Process market records sequentially by timestamp. If multiple prints share the same timestamp
T, process them as a single decision event at timeT. - Execution Price: The trade price applied to any fill at timestamp
Tis thepriceof the last print occurring at timestampT. - Participation Limit: At timestamp
T, the maximum volume your algorithm is allowed to execute is bounded bymax_participation_rate * V, whereVis the aggregate market volume of prints that occurred strictly within the half-open time interval[T - window_size, T). - Window Membership: Volume from prints occurring at timestamp
Tdoes not count towardsVat timestampT. Instead, it becomes visible for future timestamps after the decision atTis finalized. - Order Limit: The total accumulated fill volume across all events cannot exceed
target_volume. The fill amount at timestampTismin(remaining_volume, max_participation_rate * V). - Early Exit: Once the order is completely filled (
remaining_volume == 0), processing terminates immediately.
Return a tuple (total_executed_volume, total_cost) as floats.
Constraints
market_printsis sorted in non-decreasing order bytimestamp.- Timestamps are non-negative integers.
window_sizeis a non-negative integer.target_volume >= 0.0and0.0 <= max_participation_rate <= 1.0.- Prices and volumes are non-negative numbers.
Examples
Example 1
Input: process_trades([[100, 10, 50], [150, 10.1, 100], [250, 10.2, 50]], [100, 0.1], 200)
Output: [20, 203.5]
Hints
Hint 1
Group all prints with identical timestamps together so that you use the final print's price for execution at that timestamp.
Hint 2
Maintain a sliding window of historical prints using a queue to efficiently track total volume in the interval [T - window_size, T).
Hint 3
Be careful with timing: pop expired prints from the queue before calculating execution volume, and append the current timestamp's prints to the queue only after executing.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem requires simulating an order execution engine under a strict volume participation constraint over a moving time window [T - window_size, T).
We can iterate through the market_prints stream using a sliding window approach:
- Group by Timestamp: Since multiple market prints can occur at the same millisecond
T, we group all prints sharing timestampT. The trade price used for execution at timestampTis the price of the last print in this group. - Evict Expired Trades: Maintain a queue (
deque) of trades that occurred in the time interval[T - window_size, T). Before evaluating execution at timeT, pop elements from the front of the queue whose timestamps are strictly less thanT - window_size, updating the running summarket_volumeaccordingly. - Execute Order: Compute the allowable execution volume at time
Tasmin(remaining_volume, max_participation_rate * market_volume). Updateexecutedvolume, accumulatedcost, and decrementremaining_volume. - Update Window: Append the current group's trade records into the queue and add their volumes to
market_volume. This ensures current trades are included in the window only for future timestamps (> T). - Early Exit: Terminate the loop as soon as
remaining_volume == 0or all market prints have been processed.
Complexity
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of elements in
market_prints. Each record is pushed into and popped from the double-ended queue at most once. - Space Complexity: $\mathcal{O}(W)$, where $W \le N$ is the maximum number of prints contained in any single
window_sizeduration.
Python 3 Reference Solution
from collections import deque
from typing import List, Tuple
def process_trades(market_prints: List[Tuple[int, float, float]], order: Tuple[float, float], window_size: int) -> Tuple[float, float]:
target_volume, max_participation_rate = order
remaining = target_volume
executed = 0.0
cost = 0.0
window = deque()
market_volume = 0.0
i = 0
n = len(market_prints)
while i < n and remaining > 0:
timestamp = market_prints[i][0]
lower_bound = timestamp - window_size
# Remove elements older than (timestamp - window_size)
while window and window[0][0] < lower_bound:
_, volume = window.popleft()
market_volume -= volume
# Group elements with identical timestamps
j = i
latest_price = market_prints[i][1]
while j < n and market_prints[j][0] == timestamp:
latest_price = market_prints[j][1]
j += 1
# Execute order fill based on current market volume in [T - window_size, T)
quantity = min(remaining, max_participation_rate * market_volume)
if quantity > 0:
executed += quantity
cost += quantity * latest_price
remaining -= quantity
# Push current timestamp prints to the window for future execution events
for k in range(i, j):
_, _, volume = market_prints[k]
window.append((timestamp, volume))
market_volume += volume
i = j
return (executed, cost)