Collecting and Parsing Digital Asset Market Data: A Practical Guide

    This article walks through the practical engineering of collecting and parsing digital asset market data. It covers defining a clear data contract, choosing between polling and push collection with exponential backoff, validating values for consistency and precision, unifying timestamps, designing a tiered storage layer, building aggregation and alerting, and ensuring observability while controlling cost. Readers will learn how to build a stable, trustworthy market data pipeline grounded in consistent semantics, reliable precision, and controllable latency.

    1. Start with a Data Contract, Not Code

    When building a market data system, the first step is not writing code but defining the “data contract.” Take a spot trading pair quote as an example. Its raw information usually includes the instrument code, trading pair identifier, market type, quote currency, latest traded price, 24-hour change amount and change percent, open price, high, low, market cap, market cap rank, and data update time.

    These fields fall into three categories:

    • Identifiers: instrument code, trading pair, market type, and quote currency, used to uniquely determine “what asset this is, in which market, and priced in what currency.”
    • Price fields: latest price, open, high, and low, describing the price range and current state within a statistical period.
    • Derived statistics: change amount, change percent, market cap, and rank, usually computed from base data and therefore more sensitive to timing and methodology.

    The most common pitfall in engineering practice is treating “derived statistics” fields as factual data and writing them directly to storage. Change amount and change percent depend on the starting point of the statistical period, market cap depends on the circulating supply methodology, and rank depends on the full-market sample set. Once the upstream methodology changes, historical data will show incomparable gaps. It is therefore recommended to explicitly annotate each field’s methodology version in the data contract and preserve that identifier in the table schema or message header.

    1. {
    2. "symbol": "GLM",
    3. "pair": "GLMUSDT",
    4. "market": "CRYPTO",
    5. "quote_currency": "USD",
    6. "last": 0.09019,
    7. "open": 0.08839,
    8. "high": 0.09268,
    9. "low": 0.08759,
    10. "change_amount": 0.001798,
    11. "change_percent": 2.034,
    12. "market_cap": 89641800,
    13. "rank": 168,
    14. "ts": "2026-11-24T13:21:22Z",
    15. "schema_version": "v1"
    16. }

    2. Collection Layer Design: Polling, Push, and Backoff

    Market data collection typically uses two modes: active polling and passive push. Polling is simple to implement and keeps state under control, making it suitable for small to medium sets of instruments. Push offers low latency and low resource usage but requires handling reconnection and message deduplication.

    Regardless of the mode, you must implement exponential backoff retry. When the upstream returns rate limits or the network jitters, retrying at a fixed interval worsens congestion. A recommended strategy is an initial interval of 1 second, a multiplier of 2, and a cap of 30 seconds, with added random jitter to avoid multiple instances retrying in sync and forming a “thundering herd.”

    1. import random, time
    2. def fetch_with_backoff(client, attempt=0, base=1.0, cap=30.0):
    3. try:
    4. return client.get_ticker("GLMUSDT")
    5. except Exception:
    6. if attempt >= 6:
    7. raise
    8. delay = min(cap, base * (2 ** attempt)) + random.uniform(0, 0.5)
    9. time.sleep(delay)
    10. return fetch_with_backoff(client, attempt + 1, base, cap)

    The collection layer should also implement multi-instance idempotency. Repeated writes of the same quote at the same moment cause statistical bias. It is recommended to use “trading pair + data time” as the idempotency key and complete deduplication before writing.

    3. Parsing and Validation: Turning “Looks Right” into “Is Right”

    Raw values are often returned as strings or floats, and direct arithmetic introduces precision problems. Price fields should be handled with a high-precision decimal type to avoid the tail differences that binary floating point produces during accumulation and comparison.

    The validation stage should cover at least four rules:

    1. Range consistency: low ≤ open and latest ≤ high; a violation suggests the data may come from different statistical windows.
    2. Derived consistency: change amount should approximately equal latest minus open, and change percent should approximately equal change amount divided by open; flag as suspicious when the deviation exceeds a threshold.
    3. Precision alignment: price precision varies greatly across instruments, so precision must be configured per trading pair; global uniform truncation is prohibited.
    4. Time freshness: when the gap between the data time and the current time exceeds the tolerance window, degrade the handling rather than displaying it directly.
    1. from decimal import Decimal
    2. def validate(t):
    3. last, open_, high, low = map(Decimal, (t["last"], t["open"], t["high"], t["low"]))
    4. assert low <= min(last, open_) and high >= max(last, open_), "price range inconsistent"
    5. expect_change = last - open_
    6. if abs(expect_change - Decimal(str(t["change_amount"]))) > Decimal("0.0005"):
    7. t["suspicious"] = True
    8. return t

    4. Timestamp and Methodology Unification

    The time semantics of market data are easily confused: data generation time, collection time, and storage time are all different. It is recommended that the message layer carry both “business time” and “ingestion time,” using business time for analysis and ingestion time as a reference for troubleshooting.

    Store everything in timezone-aware UTC and convert to the user’s timezone only at the presentation layer. For statistical-period fields, be explicit about whether the period starts at the natural day, a rolling 24 hours, or an exchange-defined window; otherwise cross-source comparison loses meaning.

    5. Storage and Query: Tiered Landing

    A three-tier storage structure is recommended:

    • Hot tier: stores market snapshots from the last few minutes to a few hours, serving real-time dashboards and alerts, emphasizing low-latency reads.
    • Warm tier: minute-aggregated continuous series for trend analysis and backtesting, requiring efficient scans by time range.
    • Cold tier: archives raw details for auditing and methodology traceback, backed by object storage for low cost and near-unlimited capacity.

    For the partition key, a “time + trading pair” combination is recommended so queries naturally prune irrelevant partitions. Writes should use batch commits, with a few hundred records per batch recommended to balance throughput and latency.

    6. Server-Side Aggregation and Alerting

    The aggregation service needs to expose three capabilities: latest snapshot query, range statistics, and anomaly detection. Anomaly detection can start with a simple and robust rule, such as “the absolute change percent exceeds a threshold over N periods while volume expands,” then gradually introduce mean-reversion and volatility models.

    The alerting pipeline should be decoupled into three stages: “detect—decide—notify.” Detection runs at high frequency, decision handles deduplication and silencing, and notification is delivered asynchronously via a message queue, avoiding downstream jitter back-pressuring the main collection path.

    1. collector -> validator -> idempotent write -> hot storage
    2. |-> stream aggregation -> anomaly detection -> alerting
    3. `-> batch archive -> cold storage

    7. Observability and Cost Control

    Observability for a market data system should cover four dimensions: collection success rate, end-to-end latency, validation failure rate, and storage growth rate. For latency metrics, report P50, P95, and P99 simultaneously, since averages hide the long tail.

    For cost control, you can reduce cold-tier write frequency, downsample the warm tier, and set retention periods for historical queries. In environments such as Baidu AI Cloud, you can combine a container platform to host stateless collection and aggregation services, a message queue for pipeline decoupling, object storage for archiving, and logging and monitoring services to close the observability loop, all composed from general capability categories without binding to a specific interface form.

    8. Summary

    The engineering difficulty of market data lies not in “obtaining a number” but in consistent methodology, reliable precision, controllable timeliness, and an observable pipeline. Only by writing the data contract clearly, doing validation up front, tiering storage, and decoupling alerting can you support a stable and trustworthy market data service.