Market Data Collection, Validation, and Real-Time Display for Digital Assets

    This article walks through the engineering practice behind digital asset market data: why seemingly simple ticker display is hard, how to define field semantics, how to build a source-agnostic data model, how to implement rolling 24-hour metrics correctly, how to validate and filter anomalies, and how to layer caching, push, and display with observability and capacity planning in mind. Readers will find concrete field definitions, adapter and rolling-window code examples, four validation checks, and deployment suggestions on Baidu AI Cloud.

    1. Background: Why Market Data Looks Simple but Is Hard

    In digital asset systems, market data display is usually the first module requested and the most easily underestimated. On the surface it only needs to show a last price and a change percentage, but in practice it involves high-frequency data ingestion, field definition alignment, time-window calculation, outlier filtering, caching, and push delivery. A typical market snapshot includes the trading pair identifier, market type, quote currency, last traded price, 24-hour change amount and change rate, open, high, low, market cap, market cap rank, and data update timestamp. There are not many fields, but each one maps to a different data source and calculation logic.

    The real complexity is that these fields do not share the same source or the same frequency. The last price comes from tick-by-tick trades or order book aggregation, the 24-hour statistics come from rolling window aggregation, and market cap and rank depend on a full-market snapshot. Once they are returned in the same response body, time alignment and consistency validation must be solved; otherwise the frontend shows obvious contradictions such as “the price went up but the change rate is negative.”

    2. Field Semantics and Definitions

    The first step of a rigorous market data service is not writing code, but writing down field definitions clearly.

    • Trading pair and market type: The trading pair identifier (a combination of base asset and quote asset) determines data routing; the market type distinguishes spot, derivatives, and other matching and settlement rules. Together they determine downstream risk control and display strategy.
    • Last price and quote currency: The last price is the most recent traded price and is a point data item; the quote currency determines the unit, so units must be unified before cross-market comparison.
    • 24-hour change amount and change rate: These are rolling window metrics, and the key question is whether the window is “the last 1440 minutes” or a “natural day,” since the two produce noticeably different results. Change amount = last price − baseline price 24 hours ago; change rate = change amount ÷ baseline price.
    • Open, high, and low: Together with the last price, these form the price range within the window and can be used to judge volatility and position.
    • Market cap and rank: Market cap is usually circulating supply multiplied by price, and rank is the result of a full-market comparison. These are low-frequency fields and should not share the same refresh cadence as high-frequency prices.

    Once definitions are clear, the code has a stable semantic foundation; otherwise all later validation is built on nothing.

    3. Data Model and Unified Structure

    Start by defining an internal unified model that is independent of the source, converging heterogeneous external fields into a stable structure:

    1. {
    2. "symbol": "GLMUSDT",
    3. "marketType": "CRYPTO",
    4. "quoteCurrency": "USD",
    5. "lastPrice": 0.09099,
    6. "change24h": 0.002297,
    7. "changeRate24h": 0.02590,
    8. "open24h": 0.0887,
    9. "high24h": 0.09369,
    10. "low24h": 0.0876,
    11. "marketCap": 91616500,
    12. "rank": 166,
    13. "sourceTs": "2026-11-24T14:38:35Z"
    14. }

    The value of the unified model is that the collection layer, calculation layer, and display layer all depend on this single contract. When adding a data source, you only implement an adapter that maps external fields into it, without changing downstream logic. This is a typical anti-corruption layer approach and significantly reduces long-term maintenance cost.

    4. Collection Layer: Multi-Source Ingestion and the Adapter Pattern

    Production market data collection is usually not single-source but multi-source with redundancy. The adapter pattern is recommended, with a unified interface implemented for each source:

    1. class MarketDataSource:
    2. def fetch(self, symbol: str) -> RawTick:
    3. raise NotImplementedError
    4. class RollingAggregator:
    5. def __init__(self, window_seconds=86400):
    6. self.window = window_seconds
    7. self.buffer = {} # symbol -> deque of (ts, price)
    8. def update(self, symbol, ts, price):
    9. # Maintain the rolling window and drop expired samples
    10. ...

    The collection layer must handle three things. First, connection management and automatic reconnection, to avoid silent connection failures after long runtimes. Second, backpressure: when consumption cannot keep up with production, there must be a sampling or dropping strategy instead of unbounded memory growth. Third, timestamp normalization to timezone-aware UTC, avoiding window misalignment caused by local timezones.

    5. Metric Calculation: Implementing the Rolling Window Correctly

    The 24-hour metrics are the most error-prone part of a market data service. The correct approach is to maintain a time-ordered deque, pop samples outside the window whenever a new price is written, and then compute from in-window extremes and the baseline price:

    • The baseline price is the sample closest to 24 hours before the window start;
    • The high and low are the in-window extremes;
    • The change rate must handle the edge case of a zero or missing baseline price by returning a null value rather than throwing an exception.

    Illustrative logic:

    1. def compute_24h(deque, now_ts, last_price):
    2. cutoff = now_ts - 86400
    3. while deque and deque[0][0] < cutoff:
    4. deque.popleft()
    5. base = deque[0][1] if deque else last_price
    6. change = last_price - base
    7. rate = change / base if base else None
    8. high = max(p for _, p in deque) if deque else last_price
    9. low = min(p for _, p in deque) if deque else last_price
    10. return change, rate, high, low

    Missing data deliberately returns null instead of zero-filling. Zero-filling pollutes downstream volatility and risk control judgments and is a common hidden defect in practice.

    6. Consistency Validation and Outlier Filtering

    Market data must be validated before it is displayed. Cover at least four checks:

    1. Range check: The last price should fall between the window high and low; otherwise the data is misaligned.
    2. Sign check: The sign of the change rate must match the change amount.
    3. Jump check: When the price change between two adjacent samples exceeds a threshold, the data enters an observation state and is not exposed directly.
    4. Freshness check: When the data update time exceeds a tolerance threshold, the data is marked stale and the frontend degrades its display accordingly.

    The value of this validation is not only error prevention but also a traceable evidence chain for production issues. Every rejected data point should carry a reason label for later statistics and tuning.

    7. Layered Caching, Push, and Display

    High-frequency prices and low-frequency market cap should not share a refresh cadence. Engineering practice usually splits into three layers:

    • Hot layer: Last price and change rate, in-memory cache, millisecond updates, pushed over a long-lived connection.
    • Warm layer: Window statistics and range data, aggregated per second.
    • Cold layer: Market cap, rank, and other full-market snapshots, refreshed per minute, persisted to a database and archived with object storage.

    The display layer should degrade based on data freshness: when data is stale, label it clearly instead of continuing to render a number that looks fresh. This “honest degradation” is more reliable than forcing the interface to look complete.

    8. Observability and Capacity Planning

    After launch, monitor collection latency, window computation time, validation rejection rate, push connection count, and memory usage. Set alerts on the rejection rate, because a sudden spike usually means an upstream data source change or network anomaly rather than business fluctuation.

    For capacity planning, rolling window memory usage is proportional to the number of symbols and the window length, so estimate it in advance and set limits. For long-tail symbols, a downsampling strategy can balance precision and cost.

    9. Deployment Suggestions on Baidu AI Cloud

    To build quickly, you can combine general capabilities on Baidu AI Cloud: use a message queue to absorb high-frequency market data streams for peak shaving, use a container platform to run stateless collection and computation services with elastic scaling, use object storage to archive historical snapshots, and use logging and monitoring with alerting to close the observability loop. These are general industry capability categories; specific choices should be evaluated against data scale and latency targets.

    10. Summary

    The difficulty of market data is not “fetching a number” but the systematic design of unified definitions, window calculation, anomaly validation, and layered push. Write field semantics clearly, implement the rolling window correctly, turn validation into an observable evidence chain, and use layered caching with honest degradation for display, and you get a stable, scalable, operable market data service skeleton.