Building a Reliable Digital Asset Market Data Pipeline: Collection, Parsing, and Validation
This article walks through the engineering practice of collecting and parsing digital asset market data, using a real snapshot record as the starting point. It explains why market data is deceptively complex across semantic, precision, and time-series layers, then covers domain modeling with strong types and Decimal, layered validation for structure, consistency, and business sanity, time-series handling such as deduplication, alignment, and OHLCV resampling, storage selection by access pattern, and observability for catching silent data failures. It closes with common pitfalls and practical engineering recommendations for building a market data foundation that supports both real-time response and historical replay.
1. Background: Why Market Data Is Simple to Read but Hard to Build
In the development of digital asset systems, market data is usually the first type of data to be integrated, yet it is also the most prone to problems. Consider a single record captured during collection, whose raw form looks roughly like this:
Code: GLMPair: GLMUSDTMarket Type: CRYPTOLast Price: 0.09359Quote Currency: USD24h Change: 0Change %: 0.000%Open: 0.09359High: 0.09539Low: 0.09119Market Cap: 93.7331MMarket Cap Rank: 164Updated At: 2026-12-01 19:52:38
This record contains four kinds of information: price, range, market cap, and rank, plus a timestamp. On the surface it is just “a snapshot of one coin on one trading pair,” but in an engineering implementation it involves complexity on at least three layers:
- Semantic layer: The same “change” may be an absolute value in one data source and a percentage in another; the same “market cap” may be circulating market cap or fully diluted valuation.
- Precision layer: Price fields are extremely sensitive to decimal places, and using binary floating point introduces cumulative error.
- Time-series layer: Market data is a high-frequency time series; a single snapshot is meaningless and must be incrementally aligned and deduplicated against timestamps.
Therefore, this article does not discuss the usage experience of any specific platform or tool. Instead, it abstracts the topic into a general technical problem: how to build a reliable, scalable, and observable digital asset market data pipeline.
2. Data Model Design: From Flat Text to Strongly Typed Structures
Raw text is meant for humans; programs need strongly typed structures. The first step is to define the domain model and make field semantics and constraints explicit.
from dataclasses import dataclassfrom decimal import Decimalfrom datetime import datetime@dataclass(frozen=True)class MarketSnapshot:symbol: str # Trading pair, e.g. GLMUSDTmarket_type: str # Market type, e.g. CRYPTObase_asset: str # Base asset, e.g. GLMquote_asset: str # Quote asset, e.g. USDlast: Decimal # Last priceopen: Decimal # Open pricehigh: Decimal # High pricelow: Decimal # Low pricechange_abs: Decimal # 24h absolute changechange_pct: Decimal # 24h change percentagemarket_cap: Decimal # Market caprank: int # Market cap rankts: datetime # Data update time
There are three key design points:
- Use Decimal instead of float: Price and market cap carry monetary semantics, and exact decimal representation is the industry-standard practice.
- Guarantee immutability with frozen=True: Once a market snapshot is generated it should not be modified in place, which avoids data races in multi-threaded environments.
- Split base/quote assets:
GLMUSDTis a concatenated string and must be split into a base asset and a quote asset; otherwise later tasks such as exchange-rate conversion and cross-market aggregation cannot be handled.
3. Parsing and Validation: Keeping Dirty Data Out of the System
The core of the parsing stage is not “can it be read,” but “do we dare to use what was read.” A layered validation strategy is recommended.
3.1 Structural Validation
Confirm that required fields are present and type-convertible. Records missing a timestamp should be discarded outright, because data that cannot be located in the time sequence has no value to downstream consumers.
3.2 Consistency Validation
The price range must satisfy low <= open,last <= high. If last falls outside [low, high], the data was likely truncated or incorrectly concatenated during transmission.
The absolute change and the change percentage should satisfy an approximate relationship:
def check_consistency(s: MarketSnapshot, eps: Decimal = Decimal("0.0001")) -> bool:if not (s.low <= s.last <= s.high):return Falseif s.open == 0:return Falseexpected = (s.last - s.open) / s.open * Decimal("100")return abs(expected - s.change_pct) <= eps
In the example above, both the last price and the open price are 0.09359, with a change of 0 and a change percentage of 0.000%, so the consistency check passes. Meanwhile, the roughly 4.6% amplitude between the high of 0.09539 and the low of 0.09119 shows that although the price fluctuated within 24 hours, it had returned to its original level relative to the open. This kind of “large amplitude, small net change” pattern is a normal sample in data validation and should not be misjudged as an anomaly.
3.3 Business Sanity Validation
A market cap rank of 164 and a market cap of about 93.7 million should sit within the same order-of-magnitude range. If the rank suddenly jumps to a single digit while the market cap does not change accordingly, it is usually jitter in the upstream aggregation logic. The pipeline should require “confirmation over N consecutive updates” before updating the rank, to avoid frequent flickering in downstream displays.
4. Time-Series Handling: Deduplication, Alignment, and Downsampling
The real value of market data comes from the time series. Engineering must handle three problems:
- Deduplication: Use
(symbol, ts)as the idempotency key, and overwrite rather than append on duplicate pushes. - Alignment: Different data sources have different update frequencies and must be resampled into fixed time windows (such as 1 minute or 5 minutes).
- Downsampling and aggregation: Storing all raw high-frequency data is costly, so raw data is usually kept short-term while only OHLCV aggregates are retained long-term.
def resample_ohlcv(rows, window_seconds=60):buckets = {}for r in rows:key = r.ts.timestamp() // window_secondsb = buckets.setdefault(key, {"open": r.last, "high": r.last,"low": r.last, "close": r.last})b["high"] = max(b["high"], r.last)b["low"] = min(b["low"], r.last)b["close"] = r.lastreturn buckets
This logic embodies the minimal closed loop of aggregation: use the window’s starting price as the open, take the in-window extremes as the high and low, and use the window’s last value as the close. A real system must also handle window boundaries and timezone unification; it is recommended to store everything in UTC across the entire pipeline and localize only at the presentation layer.
5. Storage and Query: Choosing by Access Pattern
Storage selection should be driven by query patterns, not by technical preference:
- Time-series database: Suitable for time-range scans and downsampled queries, and a common choice for primary market data storage.
- Relational database: Suitable for storing dimensional information such as asset metadata and trading pair configuration.
- Object storage: Suitable for archiving cold data and batch backfill computation.
- Cache layer: Suitable for serving reads of the latest snapshot and reducing pressure from hot queries.
A practical partitioning strategy is to partition by symbol + date, giving historical replay a natural pruning capability during scans. An illustrative query looks like this:
SELECT window_start, open, high, low, closeFROM ohlcv_1mWHERE symbol = 'GLMUSDT'AND window_start >= :from_tsAND window_start < :to_tsORDER BY window_start;
6. Observability: Monitoring Data Quality Itself
The most easily overlooked issue in a market data pipeline is “silent data failure”—the service does not crash, but the data has already stopped. Independent data quality monitoring must be established:
- Freshness monitoring: Alert when the gap between the current time and the latest timestamp exceeds a threshold.
- Gap detection: Judge the link as broken when several consecutive windows have no new data.
- Field drift detection: A sudden drop of a field’s standard deviation to zero may mean the upstream is returning a constant placeholder value.
- Validation failure rate: A sudden spike in the proportion of consistency-check failures usually means the upstream format has changed.
Monitoring and alerting capabilities are typically implemented through a cloud platform’s logging service and monitoring/alerting offerings, delivered in three stages: metric reporting, threshold rules, and notification channels. The key is to treat “data quality” as a first-class metric, on par with latency and error rate.
7. Common Pitfalls and Engineering Recommendations
- Do not store prices as floating point, and do not defer precision handling to the presentation layer; precision must be fixed at the data entry point.
- Do not trust a single data source; for key fields, cross-validate with a second source, and on conflict, arbitrate using both the update time and consistency-check results.
- Do not treat timestamps as strings; string comparison is highly error-prone in cross-timezone scenarios.
- Do not ignore schema evolution; newly added upstream fields should be compatible, and the parsing layer should pass through unknown fields rather than erroring out directly.
- Do not go live without replay capability; the pipeline must support re-running over a specified time range so historical data can be repaired.
8. Summary
A seemingly ordinary market snapshot unfolds into a complete engineering chain of data modeling, precision handling, consistency validation, time-series aggregation, storage selection, and observability. Only by thinking through the field semantics and failure modes of each stage can you build a market data foundation that both responds in real time and supports historical replay. To quickly build a prototype, you can rely on general capabilities such as the container platform, object storage, and monitoring/alerting on Baidu AI Cloud to handle deployment and operations, focusing your effort on the data model and validation logic—the parts that truly determine quality.
