DEV Community

EmilyL
EmilyL

Posted on

Tutorial: Fix US Stock API Candlestick Gaps with Session-Aware Aggregation

#ai

Have you ever built a candlestick chart for US equities, only to find that the pre-market and after-hours segments look like a broken zipper? We’ve been there while powering financial bloggers’ data dashboards. The good news is that the issue rarely lies in your frontend library—it’s almost always a data modeling problem. In this tutorial, we’ll share how we re-architected our US stock market API pipeline to produce continuous candlestick charts across all trading sessions.

Understanding Why Extended Hours Create Visual Breaks
US stocks trade outside the 09:30–16:00 ET regular window, with official pre-market and after-hours sessions. These sessions contain real trades, but at drastically lower frequencies. A typical implementation that chops the day into fixed 5-minute windows will encounter many intervals with zero trades during extended hours. If your code simply skips those intervals, the time series compresses and the chart displays a price jump. The fix is to stop treating all ticks equally and start respecting the market’s session structure.

Step 1: Force Time Consistency in Your Data Pipeline
We learned early that not all US stock APIs speak the same time language. Some return UTC, others Eastern Time. To avoid candlestick shifts, we normalize every incoming tick to UTC at the ingestion layer. We retain the original exchange timestamp in a separate field for debugging. When rendering a chart for end users, we convert back to Eastern Time. This one practice eliminates entire categories of offset bugs.

Step 2: Label Every Tick with Its Trading Session
We enrich each tick with a session identifier based on its Eastern Time timestamp:

Trading Session Time Range (ET) Handling Method
Pre-Market Before 09:30 Recorded separately
Regular Trading 09:30–16:00 Normal aggregation
After-Hours After 16:00 Processed independently

With this tagging, your aggregation logic can branch. Need a pure regular-session view? Filter by the “Regular Trading” tag. Building a full-day continuous chart? Aggregate each session separately and then merge by timestamp. The chart’s time axis stays linear because no interval is discarded.

Step 3: Aggregate Raw Ticks Instead of Using Pre-Built Candles
In production, we avoid consuming pre-aggregated candlestick data from any API. Instead, we stream raw tick data over WebSocket. By tapping a service like AllTick API, we receive real-time US stock trades with precise timestamps, and we perform the candlestick construction in our own code.

import websocket
import json

def on_message(ws, message):
    # Parse incoming market data
    data = json.loads(message)

    symbol = data.get("symbol")      # Stock ticker
    price = data.get("price")        # Latest trade price
    timestamp = data.get("timestamp") # Trade timestamp

    print(symbol, price, timestamp)

# Establish a WebSocket connection
ws = websocket.WebSocketApp(
    "wss://api.alltick.co/stock/websocket",
    on_message=on_message
)

# Keep listening for new trades
ws.run_forever()
Enter fullscreen mode Exit fullscreen mode

Inside the aggregation loop, we check the timestamp against the session boundaries, place the trade into the appropriate candlestick bucket, and emit completed candles once the bucket’s time is up. This gives us complete command over how pre-market, regular, and after-hours candles merge.

Step 4: Define the Merge Rules Upfront
Before showing charts to your audience, nail down the business rules. Will your daily bar incorporate after-hours prices? Do 5-minute charts during the pre-market appear as standalone segments or blend into the regular session? We document these choices with the content creators we support, so every chart they publish aligns with their analytical narrative.

Result: Charts Your Users Can Trust
Since implementing this pipeline, the financial writers we work with have stopped receiving “why does this chart look broken?” replies. Their content is more authoritative because the underlying data respects actual market structure. If you’re building a US stock chart application, give session-aware aggregation a try—you’ll clean up those extended-hours artifacts for good.

Top comments (0)