Building a Reliable Market Data Pipeline: Collection and Parsing Practices for Digital Assets
This article explains how to engineer a market data pipeline for digital asset trading and quantitative research, where ticker data is high-frequency, heterogeneous, prone to gaps, and time-sensitive. It covers building a semantic model across identity, price, and derived layers; using Decimal instead of float for prices; normalizing timestamps to UTC milliseconds and separating event time from ingestion time; five categories of data quality checks with tiered handling; a five-stage batch-and-stream architecture from collection and buffering to parsing, storage, and serving; observability and cost control through hot-cold tiering; and common pitfalls to avoid. The goal is data that is trustworthy, traceable, and replayable.
1. Background: Why Market Data Pipelines Need Engineering Design
In digital asset trading and quantitative research, market data is the most fundamental and most easily underestimated input. On the surface it is just a set of numeric fields, but in real systems it has four characteristics at once: high frequency, heterogeneity, missing data, and time sensitivity. Any mishandling at one stage gets amplified downstream into backtest bias, risk control misjudgments, or alert storms.
Take a typical spot market snapshot as an example. Its semantics can be abstracted into the following structure (field names have been neutralized):
{"symbol": "OPENUSDT","market_type": "CRYPTO","base_asset": "OPEN","quote_asset": "USDT","last_price": 0.07971,"quote_currency": "USD","change_24h": 0.0005993,"change_pct_24h": 0.758,"open_24h": 0.07911,"high_24h": 0.08381,"low_24h": 0.07831,"market_cap": 27898300,"rank": 455,"updated_at": "2026-11-24 17:10:29"}
This data looks simple, but it hides four typical engineering problems. First, precision and consistency validation of price and change percentage. Second, unclear statistical scope (a 24-hour rolling window) and timestamp time zone. Third, unstable sources for derived metrics such as market cap and rank. Fourth, duplicate computation caused by mixing snapshot data with incremental data. Let us break these down layer by layer.
2. Field Abstraction: Build the Semantic Model Before Storage
The most common mistake in engineering practice is writing the API response body directly to storage. Field naming is often coupled to business logic, and once the upstream changes, the entire downstream chain is affected. A more robust approach is to define the domain model first, then do the mapping.
It is recommended to split market data into three layers:
- Identity layer: trading pair, market type, base asset, and quote asset. The identity layer must be unique and immutable; use “market type + trading pair” as the primary key.
- Price layer: last price, open, high, and low. The price layer should be passed as fixed-point numbers or high-precision strings to avoid cumulative errors from binary floating point on very small prices (such as the 0.07 magnitude).
- Derived layer: change amount, change percentage, market cap, and rank. The derived layer can be derived from the price layer and circulating supply, and should not be the single source of truth.
An illustrative model definition:
from dataclasses import dataclassfrom decimal import Decimal@dataclass(frozen=True)class TickerSnapshot:market_type: str # e.g. CRYPTO / SPOTsymbol: str # e.g. OPENUSDTlast: Decimal # last price, use Decimal instead of floatopen_24h: Decimalhigh_24h: Decimallow_24h: Decimalchange_pct: Decimal # derived from last and open_24h, then validatedts: int # normalized to UTC millisecond timestamp
The key constraint here is that the change percentage should not be trusted unconditionally. Recompute it from last and open_24h; if the deviation from the reported value exceeds a threshold, mark it as suspicious data rather than discarding it outright. In the sample above, (0.07971 - 0.07911) / 0.07911 ≈ 0.758%, which matches the reported value, showing that this snapshot is internally consistent. In a real stream, consistency checks can filter out a significant proportion of dirty data.
3. Time Semantics: Make “Updated At” a Computable First-Class Citizen
All analysis of market data is built on the time axis. The time provided by raw data often lacks time zone information, which is the most hidden pitfall. Engineering should enforce two rules:
- Normalize at the entry point. All time fields are converted to UTC millisecond timestamps at the ingestion layer, and rendered in the user’s time zone at the presentation layer.
- Distinguish event time from ingestion time. The former is the moment the market data occurred, the latter is the moment the system received it. The difference between the two is the end-to-end latency, which is one of the core metrics of data quality.
from datetime import datetime, timezonedef normalize(raw: str) -> int:# Assume upstream carries no time zone; interpret as UTC to avoid local time zone pollutiondt = datetime.strptime(raw, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)return int(dt.timestamp() * 1000)
It should be emphasized that the 24-hour change is essentially a rolling-window statistic, not daily candle data. Using it as daily data will produce systematic bias around midnight. The correct approach is to keep the raw snapshot and let downstream recompute any window on demand.
4. Data Quality: Five Categories of Checks and Handling Strategies
A production-grade pipeline must have a built-in validation layer, covering at least the following five categories:
- Structural validation: missing required fields or type mismatches go directly to the dead letter queue.
- Range validation: price must be positive; high must not be lower than low; last price should fall within the day’s high-low range. In the sample,
0.07831 ≤ 0.07971 ≤ 0.08381holds. - Consistency validation: cross-validate the change percentage against the value derived from prices.
- Time-series validation: timestamp regression, duplication, abnormal intervals (long gaps in the stream).
- Mutation validation: when the change between adjacent snapshots exceeds a threshold, downgrade to “pending confirmation” to avoid abnormal prices triggering downstream risk control.
For handling, tiered strategies are recommended: repairable data gets standardized repair, unrepairable data is isolated and archived, suspicious data is tagged and passed through. Never silently discard, otherwise problems are delayed until the analysis stage.
5. Architecture: A General Batch-and-Stream Solution
A maintainable market data pipeline typically has five stages:
- Collection: poll the snapshot API on a schedule, apply token bucket rate limiting per trading pair to avoid triggering upstream throttling.
- Buffering: write raw messages to a message queue to decouple collection from parsing and handle traffic spikes.
- Parsing: stateless consumers complete field mapping, unit normalization, and validation, outputting standard events.
- Storage: hot data goes into a time-series or columnar store, raw messages are archived to object storage to meet traceability and replay needs.
- Serving: provide query and subscription capabilities externally, with monitoring and alerting to observe latency and failure rates.
If using Baidu AI Cloud, the above stages can correspond to general capabilities such as message queues, object storage, container platforms, log services, and monitoring and alerting, replacing self-built operations with managed services and focusing effort on validation rules and business semantics.
The trade-off between incremental and full data also needs to be clear: snapshot APIs are inherently full. If downstream needs per-trade changes, do the diff at the parsing layer and only publish changed fields downstream, which reduces bandwidth and duplicate computation.
def diff(prev: TickerSnapshot, cur: TickerSnapshot) -> dict:keys = ("last", "high_24h", "low_24h", "change_pct")return {k: getattr(cur, k) for k in keys if getattr(prev, k) != getattr(cur, k)}
6. Observability and Cost Control
The operational focus of a market data pipeline is three metrics: end-to-end latency, data completeness rate, and validation failure rate. Set up an independent dashboard per trading pair, and tier alerts for stream interruptions: log brief gaps only, and escalate to notification when multiple consecutive cycles are missing.
On cost, raw messages are far larger than parsed events, so hot-cold tiering is necessary: keep near-real-time data in high-performance storage, compress and archive historical data, and decompress and replay on demand when backtesting is needed. Sampling and downsampling should only be applied to presentation scenarios, not to risk control and settlement chains.
7. Summary of Common Pitfalls
- Using floating point to carry prices, causing precision drift on very small prices.
- Trusting reported change percentage, market cap, and rank without cross-validation.
- Ignoring time zones, causing cross-day statistical misalignment.
- Coupling collection with parsing, blocking the entire chain during traffic spikes.
- Silently discarding abnormal data, deferring problems to explode at the analysis stage.
In summary, the value of market data lies not in “having fetched it” but in “whether what was fetched is trustworthy, traceable, and replayable.” Get the three things solid — field semantics, time semantics, and quality validation — and subsequent backtesting, monitoring, and risk control have a reliable foundation.
