Digital Asset Market Data: Collection and Parsing in Practice

    This article walks through a practical approach to building a market data pipeline for digital assets, starting from a sample ticker snapshot. It covers internal data modeling with Decimal and normalized timestamps, input validation to catch missing fields, type drift, and logical contradictions, collection and scheduling that prioritize stability with retries and circuit breaking, storage designed around query patterns, monitoring for data quality, and common pitfalls to avoid. Readers will gain a reusable data engineering pattern for consistent and trustworthy market data.

    1. Start with the Data Structure Behind a Market Snapshot

    When building a market data system, the first step is usually not writing code but understanding the raw data structure. Below is a typical market snapshot (timestamped 2026-11-24 14:22:40):

    1. {
    2. "symbol": "GLMUSDT",
    3. "market_type": "CRYPTO",
    4. "base_asset": "GLM",
    5. "quote_asset": "USDT",
    6. "price": 0.09139,
    7. "quote_currency": "USD",
    8. "change_24h": 0.002697,
    9. "change_rate_24h": 3.041,
    10. "open_24h": 0.08869,
    11. "high_24h": 0.09269,
    12. "low_24h": 0.08759,
    13. "market_cap": 90541500,
    14. "rank": 168,
    15. "update_time": "2026-11-24 14:22:40"
    16. }

    Although this data has only a few fields, it already covers the core dimensions of a market data system: trading pair identifier, market type, latest traded price, 24-hour change, range high and low, market cap and rank, and timestamp. For real engineering work, you need to abstract these fields into a unified internal model rather than letting the raw structure leak directly into the business layer.

    2. Field Modeling: Separating Data That “Looks the Same”

    The most easily confused aspect of raw data is the measurement basis. The latest price, open price, high price, and low price belong to the price dimension; the change amount is an absolute difference; the change rate is a relative ratio; market cap and rank belong to the scale dimension. If you uniformly convert everything to float without distinction, aggregation, backtesting, or display will easily go wrong later.

    A recommended internal model:

    1. from dataclasses import dataclass
    2. from decimal import Decimal
    3. @dataclass(frozen=True)
    4. class TickerSnapshot:
    5. symbol: str
    6. market_type: str
    7. price: Decimal
    8. open_24h: Decimal
    9. high_24h: Decimal
    10. low_24h: Decimal
    11. change_24h: Decimal
    12. change_rate_24h: Decimal
    13. market_cap: Decimal
    14. rank: int
    15. update_time: str # Normalizing to UTC ISO8601 is safer

    There are two key decisions here. First, price fields use Decimal instead of float to avoid tail differences caused by binary floating point during accumulation and comparison. Second, timestamps should have their time zone and format normalized at the entry point, rather than letting each downstream component handle strings on its own.

    3. Data Validation: Blocking “Dirty Data” at the Pipeline Entry

    The three most common anomalies in market data are: missing fields, type drift, and logical contradictions. Logical contradictions mean the data is internally inconsistent, for example the latest price falls outside the day’s high-low range, or the change rate deviates too much from the result of dividing the change amount.

    1. def validate(t: TickerSnapshot) -> list[str]:
    2. errs = []
    3. if not (t.low_24h <= t.price <= t.high_24h):
    4. errs.append("price out of 24h range")
    5. if t.high_24h < t.low_24h:
    6. errs.append("invalid high/low")
    7. expected = (t.price - t.open_24h) / t.open_24h * 100
    8. if abs(expected - t.change_rate_24h) > 0.05:
    9. errs.append("change rate mismatch")
    10. if t.rank <= 0 or t.market_cap <= 0:
    11. errs.append("invalid scale fields")
    12. return errs

    The value of validation is to “fail early.” Placing validation in the collection layer can intercept problems before data is persisted, avoiding contamination of downstream metric calculations and alerting rules. For data that fails validation, it is recommended to route it into a separate quarantine queue rather than discarding it directly, which makes traceback easier.

    4. Collection and Scheduling: Stability Over Real-Time

    The engineering difficulty of market data collection lies not in parsing but in stability. Common practices include: scheduled polling with exponential backoff retries, recording the latency and status code of each request, deduplicating consecutive snapshots of the same trading pair, and rate limiting at the entry point to protect the upstream.

    The scheduling layer needs to define three semantics clearly: fetch interval, data freshness threshold, and failure circuit-breaking conditions. For example, you can set “if refreshes fail several consecutive times, pause collection for that trading pair and alert,” to avoid generating large amounts of invalid data during an outage.

    Pseudocode illustration:

    1. async def poll(fetcher, symbol, interval=5, max_fail=5):
    2. fails = 0
    3. while True:
    4. try:
    5. raw = await fetcher(symbol)
    6. snap = parse(raw)
    7. errs = validate(snap)
    8. if errs:
    9. await quarantine.put((snap, errs))
    10. else:
    11. await clean_queue.put(snap)
    12. fails = 0
    13. except Exception:
    14. fails += 1
    15. if fails >= max_fail:
    16. await alert(f"{symbol} fetch aborted")
    17. break
    18. await asyncio.sleep(interval)

    5. Storage and Query: Design Around Access Patterns

    The access pattern for market data is usually “query by trading pair + time range,” so storage design should revolve around time partitioning. You can partition by day or by hour, include the trading pair as part of the partition key, and use columnar storage to improve aggregation query efficiency. For scenarios that only need the latest value, maintain a separate latest snapshot to avoid a full scan every time.

    If data volume grows to the point where hot-cold tiering is needed, recent data can be placed in high-performance storage while historical data is pushed down to object storage, with a unified query layer hiding the differences. This uses general capability categories and is not bound to any specific vendor implementation.

    6. Monitoring and Alerting: Making Data Quality Observable

    Collection alone is not enough; you must monitor the pipeline itself. It is recommended to cover at least four metrics: collection success rate, parsing failure rate, validation interception rate, and data latency. Latency can be approximated by “current time minus snapshot timestamp,” and if it keeps increasing, it indicates an upstream or network anomaly.

    Alerting rules should avoid noise. You can adopt a strategy of “only alert after N consecutive cycles are triggered” and route different severity levels to different channels. Log services and monitoring/alerting are general infrastructure capabilities, and standard cloud components can be reused directly.

    7. Common Pitfalls and Best Practices

    First, do not treat display precision as calculation precision; display can truncate, but calculation must retain sufficient precision. Second, do not assume timestamps are always trustworthy; normalize to UTC at the entry point. Third, do not rely on a single data source for critical decisions; multi-source cross-validation can significantly reduce misjudgment. Fourth, change-related fields must distinguish “absolute difference” from “relative ratio,” and the naming should reflect the difference. Fifth, market cap and rank are derived metrics and should be annotated with their calculation basis and update time to avoid being misused as real-time truth.

    8. Summary

    The value of this market snapshot lies not in any specific number but in demonstrating a reusable data engineering pattern: unified modeling, entry validation, stable collection, storage by access pattern, and full-chain observability. Implementing this pattern, whether for market display, metric calculation, or risk control alerting, yields a consistent and trustworthy data foundation. If running in a cloud environment such as Baidu AI Cloud, you can directly combine general capabilities like object storage, message queues, container platforms, and monitoring/alerting to quickly build an elastic and scalable market data pipeline.