Crypto Market Data Collection and Display: A Technical Practice

    This article uses a single crypto market snapshot as a worked example to explain how to build a reliable market data service end to end. It covers data modeling (aligning the 24-hour rolling window, grouping fields, and handling numeric precision for low-priced assets), deriving cross-checkable metrics such as change, change percentage, and amplitude, distinguishing circulating from fully diluted market cap, and enforcing validation so bad data never reaches the display layer. It then addresses multi-source collection and resilient refresh (polling plus push, exponential backoff), tiered hot/warm/cold storage, cache consistency, server-side rendering, and observability, compliance, and best practices. Code samples in Python show parsing, validation, derivation, and rendering. Readers will learn a general, reproducible approach to delivering market data that is fast, accurate, and stable.

    1. Introduction: The Engineering Behind a Single Market Snapshot

    In digital-asset applications, market data is the module users notice most directly. Whether it is a web quote page, a mobile asset panel, or a trading system’s monitoring dashboard, all of them rely on a simple market snapshot. Here is a sample of raw market data:

    1. Symbol: TOKEN, Pair: TOKENUSD, Market type: CRYPTO, Name: Example Asset,
    2. Last price: 0.08879, Currency: USD,
    3. 24h change: 0.0004994, change %: 0.566%,
    4. Open: 0.08829, High: 0.09268, Low: 0.08759,
    5. Market cap: 88.8708M, Market cap rank: 168,
    6. Updated at: 2026-11-24 11:58:39

    This record is dense with information but hides several engineering questions:

    • Which window does “past 24 hours” refer to?
    • Is the “open price” the natural-day open (e.g., 00:00 today) or the starting price of a rolling window?
    • How many decimals should a price like 0.08879 keep?
    • What unit is the market cap “88.8708M” expressed in?
    • Which time zone does “2026-11-24 11:58:39” belong to?

    If these questions trip you up, the quote page will at best flicker and flip colors, and at worst display wrong data that misleads user decisions.

    This article treats that snapshot as a representative case. Rather than focusing on any specific asset, it discusses how to design a general-purpose market data service: how to model fields, how to validate and derive data, how to collect and refresh it, and how to output it in a unified format and display it stably. The solution can be implemented as a backend collection service, a real-time push service, and a frontend rendering component, and can be deployed and operated using the general capabilities of cloud platforms such as Baidu AI Cloud—object storage, message queues, container platforms, log services, and monitoring/alerting.

    2. Data Modeling: Align Definitions Before Discussing Fields

    2.1 Defining the “24-Hour Rolling Window”

    The “past 24 hours” stated in the raw data usually means a rolling 24-hour window in the industry: a time window that ends at the current moment and looks back 24 hours. It has two direct implications:

    1. The open price is the price at the moment 24 hours ago, not the natural-day open (e.g., 00:00 today), and it slides continuously as time passes;
    2. The high and low are the extremes within that rolling window. As the window advances, the extremes are only replaced, never “corrected.”

    Therefore, every metric derived from this group of fields (such as the amplitude introduced later) applies only to the same window and must not be mixed with natural-day candlestick data. When exposing data externally, it is recommended to clearly label it as a “24-hour rolling statistic” in the field description or on the page.

    2.2 Grouping Fields by Semantics

    To ease modeling and validation, the snapshot fields can be divided into five categories:

    Group Fields Example values Engineering notes
    Identity Symbol, name, pair, market type, quote currency TOKEN, Example Asset, TOKENUSD, CRYPTO, USD Used as primary key and filter conditions; symbols may differ across sources, so maintain an internal ID
    Price Last, open, high, low 0.08879, 0.08829, 0.09268, 0.08759 Keep original precision, compute with fixed-point; range constraints are the key validation point
    Statistics Change, change % 0.0004994, 0.566% Must specify the statistical window; they are derived quantities and should be recomputable
    Derived Market cap, market cap rank 88.8708M, 168 Rank depends on a network-wide snapshot; mind the definition and unit of market cap
    Status Updated at 2026-11-24 11:58:39 Represents data freshness; the time zone must be explicit

    The point of this classification is to determine “what is a fact and what is a conclusion.” Last, open, high, and low come from trade records and are factual data; change, change %, market cap, and rank are conclusions computed from those facts. Factual data must be complete and accurate, while conclusion data must be recomputable and consistent with the upstream.

    2.3 Numeric Precision: The Challenge of Low-Priced Assets

    Take the last price of 0.08879 as an example. If the display rounds it to two decimals as 0.09, the relative deviation is about:

    1. (0.09 - 0.08879) / 0.08879 ≈ 1.36%

    This error is far larger than the asset’s roughly 0.57% change that day, meaning that price rounding alone can “eat up” more than twice the real movement. Keeping four decimals gives an error of about 0.0112%; keeping five decimals is exactly lossless.

    Practical recommendations:

    1. At collection and computation time, use a fixed-point decimal type (such as Python’s Decimal) or carry the raw price as a string, to avoid the accumulation of binary floating-point error across multiple operations;
    2. Configure display precision by price magnitude—for example, show 4–5 decimals for assets priced below 1, and keep it consistent across the site;
    3. Compute derived quantities at high precision first, then round uniformly. Follow the industry-standard round-half-up rule to prevent the systematic bias introduced by “truncate first, compute later.”

    3. Derived Metrics: Making the Numbers Cross-Check

    3.1 Change, Change Percentage, and Amplitude

    A quote page usually needs several derived metrics, and each can be verified against the snapshot:

    1. Change: last - open = 0.08879 - 0.08829 = 0.0005, consistent with the upstream’s 0.0004994 (ignoring last-digit rounding);
    2. Change percentage: change ÷ open × 100% = 0.0005 ÷ 0.08829 × 100% ≈ 0.566%, consistent with the upstream’s 0.566%;
    3. Amplitude: (high - low) ÷ open × 100% = (0.09268 - 0.08759) ÷ 0.08829 × 100% ≈ 5.77%;
    4. Inferred circulating supply: market cap ÷ last = 88,870,800 ÷ 0.08879 ≈ 1.001B tokens.

    This set of calculations offers two takeaways:

    • Validate before you display. Both change and change percentage can be recomputed from the price fields; once they don’t match, it means something went wrong in transit or conversion, and you should intercept rather than display.
    • Amplitude reflects risk better than change percentage. The daily gain was only 0.57%, yet the intraday amplitude was close to 5.8%. If you show only the change percentage, users will likely underestimate the asset’s 24-hour volatility. So presenting change percentage and amplitude side by side in the market overview is a simple and effective way to express risk.

    3.2 Defining Market Cap: Circulating vs. Fully Diluted

    “Market cap” does not have a single definition:

    • Circulating market cap: current circulating supply × last price, reflecting the scale of the part that can actually be traded on the market;
    • Fully diluted market cap: maximum supply (or total issued supply) × last price, reflecting the theoretical scale calculated at the upper bound.

    The two can differ by several times for assets whose supply has not been fully released. There are two engineering requirements:

    1. Clearly state which definition is used and label it in the UI, to avoid contradictory numbers from different sources;
    2. A “market cap rank” can be added, but rank is a product of a whole-market snapshot and cannot be self-verified from a single record; it should be computed against a periodic whole-market snapshot as the baseline.

    4. Data Validation: Bad Data Should Not Reach the Display Layer

    Industry experience shows that most problems in a market data pipeline lie not at the collection end but in the field conversion and aggregation stages. There are four common types of bad data:

    1. The high is lower than the low, or the last price falls outside the range;
    2. The last price is 0, negative, or null;
    3. The last price suddenly spikes or drops a hundredfold relative to the previous snapshot;
    4. The updated-at time is stale data, or change and change % are both positive while the last price is actually below the open.

    Price data should all use fixed-point numbers. The code below demonstrates a reusable set of validation and derivation functions:

    1. from dataclasses import dataclass
    2. from datetime import datetime, timedelta, timezone
    3. from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
    4. @dataclass(frozen=True)
    5. class Quote:
    6. symbol: str # Normalized pair identifier
    7. source: str # Data source, for traceability and comparison
    8. last: Decimal # Last price
    9. open: Decimal # Starting price of the 24h rolling window
    10. high: Decimal # Highest price within the window
    11. low: Decimal # Lowest price within the window
    12. ts: datetime # Data time (timezone-aware)
    13. def parse_quote(payload: dict) -> Quote:
    14. """Parse an external payload into a type-constrained Quote; raise on missing or invalid fields.
    15. The payload is in an external format; all numeric values are read as strings first, then converted to fixed-point.
    16. """
    17. try:
    18. return Quote(
    19. symbol=payload["symbol"],
    20. source=payload["source"],
    21. last=Decimal(payload["last"]),
    22. open=Decimal(payload["open"]),
    23. high=Decimal(payload["high"]),
    24. low=Decimal(payload["low"]),
    25. ts=datetime.fromisoformat(payload["ts"]),
    26. )
    27. except (KeyError, TypeError, ValueError, InvalidOperation) as exc:
    28. raise ValueError(f"Failed to parse quote payload: {exc}") from exc
    29. def validate(q: Quote, last_valid: Quote, max_jump: Decimal) -> list[str]:
    30. """Return a list of validation failure reasons; an empty list means it passed."""
    31. errors: list[str] = []
    32. prices = [q.last, q.open, q.high, q.low]
    33. if any(p <= 0 for p in prices):
    34. errors.append("A price field is non-positive")
    35. if not (q.low <= q.open <= q.high and q.low <= q.last <= q.high):
    36. errors.append("Open or last price is outside the [low, high] range")
    37. if last_valid is not None and last_valid.symbol == q.symbol:
    38. # Compare against the last valid record to intercept "needle" anomalies
    39. if abs(q.last - last_valid.last) / last_valid.last > max_jump:
    40. errors.append(f"last price moved more than {max_jump} versus the previous record")
    41. if q.ts < last_valid.ts:
    42. errors.append("data time is earlier than the previous valid record")
    43. return errors
    44. def derive(q: Quote, digits: str = "0.00001") -> dict[str, Decimal]:
    45. """Derive statistics from the snapshot, rounding to the given precision with ROUND_HALF_UP."""
    46. change = (q.last - q.open).quantize(Decimal(digits), rounding=ROUND_HALF_UP)
    47. change_pct = (change / q.open * 100).quantize(Decimal("0.001"), rounding=ROUND_HALF_UP)
    48. amplitude = ((q.high - q.low) / q.open * 100).quantize(
    49. Decimal("0.001"), rounding=ROUND_HALF_UP
    50. )
    51. return {
    52. "change": change,
    53. "change_pct": change_pct,
    54. "amplitude": amplitude,
    55. "sign": "up" if change > 0 else ("down" if change < 0 else "flat"),
    56. }
    57. # Usage example: take the previous record of this snapshot as the baseline,
    58. # with the max-movement threshold set to 20% of the previous price
    59. previous = Quote(
    60. symbol="TOKENUSD", source="source_a",
    61. last=Decimal("0.0885"), open=Decimal("0.0885"),
    62. high=Decimal("0.0890"), low=Decimal("0.0880"),
    63. ts=datetime(2026, 11, 24, 11, 57, 39, tzinfo=timezone.utc),
    64. )
    65. quote = parse_quote({
    66. "symbol": "TOKENUSD", "source": "source_a",
    67. "last": "0.08879", "open": "0.08829",
    68. "high": "0.09268", "low": "0.08759",
    69. "ts": "2026-11-24T11:58:39+00:00",
    70. })
    71. errors = validate(quote, previous, Decimal("0.2"))
    72. if not errors:
    73. print(derive(quote))
    74. # {'change': Decimal('0.00050'), 'change_pct': Decimal('0.566'),
    75. # 'amplitude': Decimal('5.765'), 'sign': 'up'}
    76. else:
    77. print("Quote intercepted:", errors) # This snapshot is dropped and does not reach the display layer

    Design notes:

    1. parse_quote converts all parsing errors into catchable exceptions. A quote payload may have missing fields or malformed formats; the parsing layer should not crash the process, but fail fast and hand off to retry or fallback logic.
    2. validate covers three checks: prices must be positive, prices must fall within [low, high], and there must be no above-threshold jump or time reversal versus the previous valid record. max_jump can be configured by asset characteristics—low-priced, high-volatility assets can be allowed a wider range.
    3. Every division result in derive is explicitly rounded, and the change direction is determined by the rounded change value, ensuring that “sign” and “value” never contradict each other.
    4. Data that fails validation is dropped and logged directly, rather than being displayed “with problems” to users.

    5. Collection and Refresh: Multi-Source Redundancy and Resilient Scheduling

    5.1 Single-Source Risk and Multi-Source Validation

    The first principle of a market data pipeline is not to depend on a single data source. Network jitter, source-side maintenance, field changes, or unit errors can all cause a source to emit wrong data for a period. After collecting from multiple sources in parallel, you can adopt the following merge strategies:

    • Median: with an odd number of sources, take the median price, so a single abnormal source cannot skew the result;
    • Weighted average: assign weights by source stability and latency;
    • Deviation trimming: sources whose deviation from the median exceeds a threshold are excluded from the computation, and an alert is triggered.

    All merge rules should be configurable and observable, making it easy to quickly locate which data path went wrong after an issue appears.

    5.2 Refresh Strategy: Polling, Push, and Scheduling

    1. Combine polling with push. When the source supports long-connection push, prefer receiving real-time increments; when it does not, poll at a fixed interval. The polling interval is a tradeoff: too short increases source-side load and may trigger rate limiting, while too long makes the page “look frozen.”
    2. Exponential backoff retry. Retry recoverable errors such as timeouts and rate limiting with progressively longer intervals—for example, 1s, 2s, 4s—and add random jitter to avoid a “thundering herd” where many tasks retry at once:

      1. import random
      2. import time
      3. def backoff_sleep(attempt: int, base: float = 1.0, cap: float = 60.0) -> None:
      4. delay = min(base * (2 ** attempt), cap) * (0.5 + random.random())
      5. time.sleep(delay)
    3. Combine pull and push. Scheduled jobs handle “fallback reconciliation” to ensure no snapshot is missed for long periods; long connections handle “low-latency updates.” The two are deduplicated by a unified snapshot timestamp.
    4. Decouple collection from display. The collection job continuously writes the latest valid snapshots, while the display layer only reads snapshots and never touches external data sources directly. This way, external source jitter does not affect page availability.

    6. Storage, Caching, and Server-Side Rendering

    6.1 Tiered Hot/Warm/Cold Storage

    Market data is “read-heavy, write-light, with concentrated hot data,” which suits tiered storage:

    • Hot data: the latest snapshot is kept in memory or cache for millisecond-level reads by APIs;
    • Warm data: historical snapshots are written to a time-series database by time, used to generate historical curves and backtests;
    • Cold data: archived files are written to object storage for long-term retention and offline analysis.

    6.2 Cache Consistency

    1. Cache keys uniformly use “internal asset ID + window type,” such as quote:TOKEN:24h, to avoid cache corruption after a symbol rename;
    2. The cache TTL is slightly longer than the refresh cycle, ensuring the page reads at least the last complete cycle of valid data;
    3. Updates use “atomic overwrite after validation passes,” to avoid reading a half-written intermediate state.

    6.3 Server-Side Rendering: Balancing First Paint and Updates

    The numbers on a quote page should stay stable, and text should not jitter due to partial refreshes. Server-side rendering returns a complete structure on the first request, and afterward replaces only the numeric nodes that change. A simplified example (implemented with the Python standard library):

    1. from decimal import Decimal, ROUND_HALF_UP
    2. from html import escape
    3. PRICE_DIGITS = "0.00001" # Price display precision: five decimals
    4. def fmt_price(value: Decimal, digits: str = PRICE_DIGITS) -> str:
    5. return f"{value.quantize(Decimal(digits), rounding=ROUND_HALF_UP):f}"
    6. def render_quote(symbol: str, q: Quote, metrics: dict, updated_at: str) -> str:
    7. # updated_at is passed in after the server formats it in the agreed time zone
    8. name = escape(symbol) # Escape before rendering to prevent external text from injecting into the page
    9. direction = metrics["sign"]
    10. css_class = {"up": "quote-up", "down": "quote-down"}.get(direction, "quote-flat")
    11. sign = "+" if direction == "up" else ""
    12. return f"""
    13. <div class="quote-card">
    14. <div class="quote-name">{name}</div>
    15. <div class="quote-price {css_class}">{fmt_price(q.last)}</div>
    16. <div class="quote-change">
    17. {sign}{metrics['change']} ({sign}{metrics['change_pct']}%)
    18. 24h amplitude {metrics['amplitude']}%
    19. </div>
    20. <div class="quote-meta">24h high {fmt_price(q.high)} ·
    21. low {fmt_price(q.low)}</div>
    22. <div class="quote-time">Updated at {escape(updated_at)}</div>
    23. </div>
    24. """

    The corresponding rendered quote snapshot looks like this:

    1. Example Asset (TOKEN)
    2. 0.08879
    3. +0.00050 (+0.566%) 24h amplitude 5.765%
    4. 24h high 0.09268 · low 0.08759
    5. Updated at 2026-11-24 11:58:39

    Display details also affect the experience:

    • Use different colors for gains and losses, and also use “+/-“ signs, to accommodate color-blind users;
    • Right-align prices and display them in a monospaced font, so numbers do not shift left or right on refresh;
    • When data stops updating, mark it as “delayed” rather than continuing to show stale numbers pretending to be real-time.

    7. Observability, Compliance, and Best Practices

    7.1 Monitoring Metrics

    The “health” of a market data service must be quantifiable. It is recommended to collect at least the following metrics:

    1. Collection success rate: the proportion of snapshots successfully parsed and passing validation per unit time;
    2. Data latency: the difference between the current time and the latest snapshot timestamp;
    3. Validation interception count: categorized by rule, used to detect upstream field changes;
    4. Cross-source deviation: the dispersion of prices across sources; an abnormal widening often means one source is emitting wrong data;
    5. API response time: percentile statistics (e.g., P95, P99), not averages.

    These metrics can be wired into a monitoring and alerting system. For example, set alerts such as “alert if data latency exceeds the threshold for N consecutive minutes” and “alert if the validation interception volume spikes period-over-period,” to detect and locate problems early. Meanwhile, the runtime logs of collection and services are centrally collected and searched through a log service, and archived long-term.

    7.2 Compliance and Risk Disclaimers

    When market data is displayed to the public, note the following:

    • Prominently display “Data is for reference only and does not constitute any investment advice”;
    • Clearly indicate data latency, to avoid users mistaking the data for accurate real-time;
    • Display text such as asset names and symbols must be escaped, to prevent external text from injecting into the page;
    • Do not fabricate or tamper with market data; for abnormal data, prefer to withhold display for now.

    7.3 Best Practices Checklist

    1. Definitions first: before coding, clarify the statistical window, market cap definition, price precision, and time zone conventions;
    2. Fixed-point computation: use fixed-point numbers throughout price-related operations, and round only at the display layer;
    3. Validation upfront: data that violates constraints does not enter the cache or the page;
    4. Multi-source redundancy: cross-validate with at least two data paths to avoid a single point of failure;
    5. Visible state: data freshness is visible to users, and delays are stated explicitly;
    6. Full-chain observability: metrics and logs exist at every stage of collection, validation, and service;
    7. Display standards: consistent decimals, clear change direction, and accessibility considerations.

    8. Conclusion

    Back to the market snapshot at the beginning: a record containing a symbol, last price, change percentage, high/low, market cap rank, and updated-at time may look like just a combination of a few numbers, but behind it lies a complete data engineering effort. From defining the window to numeric precision, from validation rules to multi-source collection, from storage tiering to server-side rendering, every stage determines whether the numbers users finally see are trustworthy and whether the page is stable.

    Only by breaking down and addressing each of these problems one by one can a market data service be fast, accurate, and stable. Market data is just the starting point—the same modeling, validation, and tiering approach also applies to larger-scale data scenarios such as account assets and transaction records.