Building a Digital Asset Market Data Pipeline: Collection and Parsing in Practice
This article walks through the practical design of a market data pipeline for digital assets, covering the challenges that make ticker data harder to handle than it first appears. It explains how to model snapshot fields into a stable structure, why high-precision decimals matter for prices, and how dual timestamps solve time and timezone ambiguity. It then details validation rules, a layered collection architecture, incremental pulling with idempotent writes, aggregation and serving, and observability with cost control. Readers will get a reusable approach to collecting, parsing, and serving market data reliably.
1. Background: Why Market Data Pipelines Are Harder Than They Look
In digital asset trading, quantitative research, and risk control, market data is the most fundamental and most easily underestimated component. Many teams focus their energy on strategy and matching logic, only to discover in production that data delays of a few hundred milliseconds, inconsistent field units, chaotic timestamp timezones, and null values during extreme market conditions all introduce systematic bias into upstream calculations.
Take a typical snapshot as an example. Fields such as the trading pair identifier, latest traded price, quote currency, 24-hour price change and change percentage, open price, high price, low price, circulating market cap, market cap ranking, and data update time form the minimum viable set for market data parsing. It looks simple, but when it comes to persistence, aggregation, and external serving, the problems to handle are far more complex than the fields themselves.
The goal of this article is not to discuss the investment value of any particular asset, but to abstract this kind of market snapshot into a general-purpose data structure and provide a reusable collection and parsing approach.
2. Field Modeling: Abstracting the Snapshot into a Stable Structure
The first step is to build a data model decoupled from the business. It is recommended to divide fields into four categories:
- Identity fields: trading pair code, asset code, market type, quote currency. Market type distinguishes spot, derivatives, and so on; different market types may have different field semantics and precision rules.
- Price fields: latest price, open price, high price, low price. Prices must use a high-precision decimal type; storing them directly as binary floating point is prohibited, otherwise tail differences will appear during accumulation and comparison.
- Derived fields: price change and change percentage. These two fields can be derived from the latest price and open price; when persisting, both the raw and computed values should be kept to support traceback and verification.
- Metadata fields: market cap, market cap ranking, update time. Market cap and ranking are aggregate metrics whose update frequency is usually lower than that of price, so they should be stored in separate tables from high-frequency market data.
A sample structure definition is as follows:
from decimal import Decimalfrom dataclasses import dataclass@dataclass(frozen=True)class TickerSnapshot:symbol: str # Trading pair identifiermarket_type: str # Market typequote_currency: str # Quote currencylast: Decimal # Latest priceopen: Decimal # Open pricehigh: Decimal # High pricelow: Decimal # Low pricechange: Decimal # Price changechange_pct: Decimal # Change percentagemarket_cap: Decimal # Market caprank: int # Market cap rankingts: int # Update time, in milliseconds
Unifying prices as Decimal and completing the conversion from string to high-precision numeric at the entry point is the most economical way to avoid precision problems.
3. Time and Timezone: The Most Overlooked Source of Failures
The core tension in market data is the definition of “the same moment.” The update time given by a raw snapshot is often only precise to the second, while the collection path, network transmission, and persistence each incur their own latency. If that time is used directly as the event time, out-of-order results will occur during backfill and replay.
The recommended approach is dual timestamps: one records the time given by the data source, and one records the local receive time. The former is used for business alignment, and the latter for pipeline latency monitoring. The difference between the two is the end-to-end delay, a key metric for judging data freshness.
def to_millis(ts_str: str, tz_offset_hours: int = 0) -> int:# Convert a second-level time string to a millisecond timestamp, explicitly handling timezone offsetfrom datetime import datetime, timezone, timedeltadt = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S")dt = dt.replace(tzinfo=timezone(timedelta(hours=tz_offset_hours)))return int(dt.timestamp() * 1000)
Explicitly declaring the timezone and uniformly using millisecond precision eliminates the vast majority of “the data looks right but the aggregate result is wrong” problems.
4. Data Validation: Blocking Anomalies Before Serving
Set up a group of low-cost, high-value validation rules in the parsing layer:
- Range consistency: the latest price should fall between the low and high prices; if it is out of bounds, the snapshot comes from different batches and should be discarded or flagged.
- Derived consistency: the price change should be approximately equal to the latest price minus the open price, and the change percentage should be approximately equal to the price change divided by the open price; when the deviation exceeds a threshold, the raw fields take precedence and an alert is raised.
- Monotonicity: the high price should be non-decreasing relative to the previous snapshot, and the low price should be non-increasing; a violation is treated as out-of-order data.
- Non-null and dimension: market cap and ranking may be missing but must be explicitly set to null, not replaced with zero values, to avoid polluting mean-type aggregates.
- Freshness: when the difference between the receive time and the data time exceeds a configured window, mark it as stale data for downstream degradation.
It is recommended to write validation results to a separate anomaly stream rather than simply discarding them, to support later data quality attribution.
5. Collection Architecture: Layering and Decoupling
A robust collection architecture is usually divided into four layers:
- Access layer: responsible for high-frequency pulling or subscription, applying rate limiting, retries, and circuit breaking to avoid instantaneous jitter amplifying into an avalanche.
- Parsing layer: completes field mapping, type conversion, and validation, outputting standardized events.
- Buffer layer: uses a message queue to smooth peaks and fill troughs, turning burst traffic into a controllable consumption rate; it also naturally supports multiple downstream subscriptions.
- Storage and serving layer: hot data is placed in low-latency storage for real-time queries, and historical data is archived to object storage, partitioned by time for easy traceback and recomputation.
When deploying on the cloud, you can directly use general-purpose capabilities: a message queue handles buffering and decoupling, object storage handles archiving and low-cost long-term retention, a container platform hosts the elastic scaling of parsing and aggregation services, and logging and monitoring with alerting handle observability. Baidu AI Cloud offers corresponding product forms across these general categories, and you can select based on your team’s existing technology stack.
6. Incremental Pulling and Idempotent Writes
In high-frequency scenarios, full pulls waste bandwidth and amplify rate-limiting risk. A better strategy is incremental updates combined with idempotent writes:
def merge_snapshot(store, snap: TickerSnapshot) -> None:# Overwrite only when the event time is newer, ensuring repeated delivery produces no side effectsprev = store.get(snap.symbol)if prev is None or snap.ts >= prev.ts:store.put(snap.symbol, snap)
Using “trading pair + event time” as the idempotency key makes retries safe. As long as the consumer guarantees that the processing logic is idempotent, it can confidently use at-least-once delivery semantics, trading that for higher availability.
7. Aggregation and External Serving
Raw snapshots are points; the business needs lines and surfaces. Common aggregations include fixed-window open-high-low-close, volume-weighted average price, volatility, and relative strength across trading pairs. Aggregation tasks should support recomputation by event time, because late-arriving data changes the results of historical windows.
For external serving, it is recommended to distinguish two types of interfaces: a real-time query interface returns the latest snapshot and emphasizes low latency; a historical query interface returns range data and emphasizes consistency and replayability. Both share the same standardized data to avoid divergence in definitions.
8. Observability and Cost Control
Monitoring should cover at least four dimensions: collection success rate, end-to-end delay, validation anomaly rate, and storage growth rate. Setting a baseline for each dimension and configuring tiered alerts enables early intervention in failures.
For cost control, note three points: the retention period for hot data should not be too long; archived data should use partition-pruned queries; aggregation tasks should avoid full table scans and rely on precomputation as much as possible. This way, as data volume grows, the cost curve stays closer to linear rather than exponential.
9. Summary
The difficulty of a market data pipeline lies not in any single field, but in the constraints between fields, time semantics, and pipeline reliability. Abstracting the snapshot into a standardized structure with precision constraints, unifying the time basis with dual timestamps, intercepting anomalies with rule-based validation, and ensuring throughput and consistency through buffering, idempotency, and layered storage together build a data foundation that can run for the long term. To get started quickly, you can combine the general cloud product capabilities of Baidu AI Cloud into a complete loop of access, buffering, storage, and monitoring, leaving the engineering focus to the upstream logic that truly creates value.
