Build Candlestick Bars from a Raw Price Feed
SQL & DataModel answerLast updated
Parse a string of price-timestamp ticks, bucket them into fixed-width time windows, compute OHLC stats, and forward-fill any empty windows.
Build Candlestick Bars from a Raw Price Feed
A trading system receives price updates as a flat string of price:timestamp tokens, separated by commas. Your job is to turn that raw feed into a sequence of candlestick (OHLC) bars.
Input format
"3:0,2:1,4:2,10:3,10:8,11:8"
Each token is price:timestamp. The price is a number; the timestamp is a non-negative integer representing seconds from some epoch.
What you need to produce
Group ticks into 10-second windows: [0, 10), [10, 20), [20, 30), … For every window from the first occupied one to the last occupied one, output a record with:
| field | meaning |
|---|---|
bucket_start | the window's left edge (0, 10, 20, …) |
open | price of the earliest tick in the window (by timestamp; ties broken by arrival order) |
close | price of the latest tick in the window (same ordering) |
low | minimum price in the window |
high | maximum price in the window |
If a window contains no ticks, forward-fill it: copy every field from the previous window's close. Consecutive empty windows must chain (each copies from the one before it, which may itself have been filled).
Example
Input: "3:0,2:1,4:2,10:3,10:4,10:5,10:6,10:7,10:8,10:9,10:10,11:8"
Output:
bucket_start=0, open=3, close=10, low=2, high=11
bucket_start=10, open=10, close=10, low=10, high=10
Notice that 11:8 arrives late in the string but belongs to timestamp 8, so it does not become the close of window 0; the tick at timestamp 9 (10:9) is later and wins.
Requirements
Write a Python function with this signature:
def ohlc_bars(data: str, interval: int = 10) -> list[dict]:
...
- Raise
ValueErroron a non-positive interval or a malformed token. - Return
[]for empty or whitespace-only input. - Handle out-of-order ticks and duplicate timestamps correctly.
Hints
Hint 1
A tick belongs to bucket k = timestamp // interval. Python's floor division works for any integer timestamp, including negatives.
Hint 2
Sort ticks by (timestamp, arrival_index) before aggregating so that 'first' and 'last' reflect event time, not the order tokens appeared in the string.
Hint 3
Walk every bucket id from min to max in a single loop. Keep a prev_close variable; when a bucket has no ticks, set all four fields to prev_close. A chain of empty buckets fills itself automatically because you update prev_close after each iteration.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three distinct sub-problems: parsing, aggregating, and gap-filling. Keeping them as separate steps makes each one easy to reason about and test.
Step 1 — Parse and record arrival order
Split on commas, then split each token on :. The left side is the price, the right side is the timestamp. Store each tick as (timestamp, arrival_index, price). Raise ValueError immediately on anything that does not fit that shape — silent skips hide bugs.
Step 2 — Sort by event time
Sort the list by (timestamp, arrival_index). After the sort, ticks within the same bucket appear in the correct chronological order, with arrival index as a stable tie-breaker for simultaneous timestamps. This one sort is the only thing that makes "open" and "close" correct; skipping it is the most common mistake on this type of problem.
Step 3 — Aggregate into a dict keyed by bucket id
bucket_id = timestamp // interval
For each tick in sorted order, look up its bucket. If the bucket is new, set all four values to the current price. Otherwise, update close to the current price (always), and update low / high if the price is a new extremum. Because ticks are already sorted, the first tick sets open and the last tick seen sets close — no special tracking needed.
Step 4 — Emit contiguous buckets with forward-fill
Iterate b from min(bars) to max(bars) inclusive. If b is in the dict, read its four values normally. If not, set all four to prev_close. Either way, update prev_close = close before moving to the next bucket. Consecutive empty buckets chain automatically because prev_close holds the filled value from the window just emitted.
Worked example
Input: "3:0,2:1,4:2,10:3,10:4,10:5,10:6,10:7,10:8,10:9,10:10,11:8"
After sorting by (ts, arrival_index), the ticks for bucket 0 run from ts=0 through ts=9. The last tick in that range is 10:9 (arrival index 9), not 11:8 (arrival index 11), because timestamp 9 > timestamp 8. So close = 10, not 11.
Gap example: "5:1,7:35" → buckets 0, 10, 20, 30. Buckets 10 and 20 each get (5,5,5,5). Bucket 30 gets (7,7,7,7).
Complexity
- Time: O(n log n + B), where n = number of ticks and B = number of buckets from first to last. The sort dominates.
- Space: O(n + B).
Streaming optimization (worth mentioning): avoid the sort entirely by tracking (min_ts, min_arrival, open_price) and (max_ts, max_arrival, close_price) per bucket and replacing only when the new key is strictly smaller or larger. That brings time to O(n + B) and works on a live stream where you emit a bar once a watermark passes the bucket's right edge.
Edge cases
| Case | Behaviour |
|---|---|
| Empty / whitespace input | return [] |
| Single tick | one bar with all four fields equal |
| Duplicate timestamps | tie-broken by arrival index |
| Out-of-order ticks | handled by the sort |
| Very large gap between ticks | B can be huge; consider a lazy generator or ask the interviewer whether to cap output |
| Non-positive interval | raise ValueError |
| Float prices | comparisons work; mention Decimal if exact monetary arithmetic matters |
Python solution
from typing import Dict, List
def ohlc_bars(data: str, interval: int = 10) -> List[Dict[str, float]]:
"""
Parse 'price:timestamp' ticks and return OHLC bars per `interval` seconds.
Bar fields: bucket_start, open, close, low, high.
open/close follow timestamp order; ties are broken by arrival order.
Windows with no ticks are forward-filled from the previous window's close.
"""
if interval <= 0:
raise ValueError("interval must be a positive integer")
# 1. Parse into (timestamp, arrival_index, price)
ticks = []
for idx, token in enumerate(data.split(",")):
token = token.strip()
if not token:
continue
parts = token.split(":")
if len(parts) != 2:
raise ValueError(f"malformed tick: {token!r}")
price, ts = float(parts[0]), int(parts[1])
ticks.append((ts, idx, price))
if not ticks:
return []
# 2. Sort by event time, then arrival order as tie-breaker
ticks.sort()
# 3. Aggregate: bucket_id -> [open, close, low, high]
bars: Dict[int, List[float]] = {}
for ts, _, price in ticks:
b = ts // interval
bar = bars.get(b)
if bar is None:
bars[b] = [price, price, price, price] # open, close, low, high
else:
bar[1] = price # close: last tick seen wins
if price < bar[2]:
bar[2] = price # new low
if price > bar[3]:
bar[3] = price # new high
# 4. Walk every bucket in range, forward-filling gaps
result: List[Dict[str, float]] = []
prev_close: float = 0.0
for b in range(min(bars), max(bars) + 1):
if b in bars:
o, c, lo, hi = bars[b]
else:
o = c = lo = hi = prev_close
result.append({
"bucket_start": b * interval,
"open": o,
"close": c,
"low": lo,
"high": hi,
})
prev_close = c
return result
if __name__ == "__main__":
feed = "3:0,2:1,4:2,10:3,10:4,10:5,10:6,10:7,10:8,10:9,10:10,11:8"
for bar in ohlc_bars(feed):
print(bar)
# {'bucket_start': 0, 'open': 3.0, 'close': 10.0, 'low': 2.0, 'high': 11.0}
# {'bucket_start': 10, 'open': 10.0,'close': 10.0, 'low': 10.0, 'high': 10.0}
Common mistakes to avoid
- Swapping price and timestamp — the token format is
price:timestamp, which is the reverse of the table header. Always confirm the contract. - Using insertion order for open/close — if ticks arrive out of order, the first token in the string is not necessarily the earliest event. Sort first.
- Breaking the forward-fill chain — if you reset
prev_closeonly on real buckets, a second consecutive empty bucket will use a stale value. Updateprev_closeon every iteration, including filled ones. - Ignoring the gap-size risk — two ticks one hour apart produce 360 empty buckets. Mention a generator or lazy output if the interviewer pushes on scale.