Crypto Market Data: Collection, Calculation, and Display in Practice

    Learn how to build a reliable cryptocurrency market data pipeline, from field definitions and decimal arithmetic to validation, collection strategies, and frontend presentation. This article covers Python examples, handling stale and anomalous data, boundary-case testing, and compliance considerations for market data displays.

    1. Background and Problem Definition

    Cryptocurrency markets trade around the clock. Prices change rapidly, and data comes from multiple sources. A typical market data page displays an asset symbol, quote currency, latest price, opening price, high, low, 24-hour price change, percentage change, market capitalization, market cap rank, and update time.

    From an engineering perspective, displaying the numbers is rarely the hardest part. The main challenges are:

    • Timeliness: Once data exceeds an acceptable delay, the displayed price may no longer be useful.
    • Precision: Prices can have many decimal places, and floating-point arithmetic can introduce errors.
    • Consistency: Fields may use different reference times or calculation conventions.
    • Error handling: Upstream data may be missing, arrive out of order, or contain clearly incorrect values.

    This article focuses on technical implementation, not investment decisions. Market data is provided for display and analysis and does not constitute a recommendation to buy or sell.

    2. Field Definitions and the Data Model

    Define each field before designing the model.

    • Latest price: The price of the most recent trade or quote.
    • Opening price: The price at the beginning of the reporting window, usually a calendar day or a rolling 24-hour period.
    • High and low: The maximum and minimum prices within that window.
    • Price change and percentage change: The absolute and relative changes from a reference price.
    • Market capitalization: Typically, circulating supply multiplied by the latest price. Check the provider’s documentation for its definition of circulating supply.
    • Market cap rank: An asset’s position when comparable assets are ranked by market capitalization. This position changes with market conditions.

    Use decimal types rather than binary floating-point types for monetary values. The following model uses Python’s Decimal:

    1. from dataclasses import dataclass
    2. from datetime import datetime
    3. from decimal import Decimal
    4. @dataclass(frozen=True)
    5. class Quote:
    6. symbol: str # Asset symbol
    7. quote_currency: str # Quote currency
    8. last_price: Decimal # Latest price
    9. open_price: Decimal # Opening price
    10. high_price: Decimal # Highest price
    11. low_price: Decimal # Lowest price
    12. market_cap: Decimal | None # May be missing upstream
    13. rank: int | None # May be missing upstream
    14. updated_at: datetime # Timezone-aware update time

    Explicitly marking potentially missing fields as nullable allows type-checking tools to flag code that does not handle missing values, reducing runtime errors.

    3. Calculating Core Metrics

    Common metric definitions are:

    • Price change = latest price − reference price
    • Percentage change = price change ÷ reference price × 100%
    • Price range percentage = (high − low) ÷ opening price × 100%

    The reference price must match the data provider’s convention. Some providers use the opening price of the reporting window; others use the trade price from 24 hours earlier. Document this distinction during integration, or percentage changes may differ across pages even when they appear to describe the same metric.

    1. from decimal import Decimal
    2. def change_metrics(last: Decimal, base: Decimal) -> tuple[Decimal, Decimal]:
    3. """Return price change and percentage change, rounded to three decimals."""
    4. if base <= 0:
    5. raise ValueError("Reference price must be positive")
    6. change = last - base
    7. pct = (change / base * 100).quantize(Decimal("0.001"))
    8. return change, pct
    9. def amplitude(high: Decimal, low: Decimal, open_: Decimal) -> Decimal:
    10. """Return the price range percentage, rounded to three decimals."""
    11. if open_ <= 0:
    12. raise ValueError("Opening price must be positive")
    13. return ((high - low) / open_ * 100).quantize(Decimal("0.001"))

    Align result precision with the display’s rounding policy. If calculations retain many decimal places while displayed prices show only two, users may notice small differences when calculating percentage changes from the visible values.

    4. Data Validation and Exception Handling

    Market data should pass through a consistent validation step before entering the system. Common rules include:

    1. All prices must be positive.
    2. The high must be greater than or equal to the low, and both the latest price and opening price must fall within that range.
    3. Timestamps must include timezone information and must not be in the future.
    4. Data older than the configured threshold should be marked as stale rather than immediately discarded.
    5. Percentage changes whose absolute values exceed a configured threshold should be flagged for manual review or secondary validation.
    1. from datetime import datetime, timezone
    2. from decimal import Decimal
    3. def validate(q: Quote, max_delay_seconds: int = 60) -> list[str]:
    4. errors: list[str] = []
    5. prices = [q.last_price, q.open_price, q.high_price, q.low_price]
    6. if any(p <= 0 for p in prices):
    7. errors.append("One or more prices are non-positive")
    8. if q.high_price < q.low_price:
    9. errors.append("High price is below low price")
    10. if not (q.low_price <= q.last_price <= q.high_price):
    11. errors.append("Latest price is outside the high-low range")
    12. if not (q.low_price <= q.open_price <= q.high_price):
    13. errors.append("Opening price is outside the high-low range")
    14. if q.updated_at.tzinfo is None:
    15. errors.append("Update timestamp is missing timezone information")
    16. else:
    17. now = datetime.now(timezone.utc)
    18. age = (now - q.updated_at).total_seconds()
    19. if age < 0:
    20. errors.append("Update timestamp is in the future")
    21. elif age > max_delay_seconds:
    22. errors.append(f"Data is stale: {int(age)} seconds old")
    23. return errors

    Do not silently discard records that fail validation. Retain the original payload and the reasons for failure so upstream issues can be investigated.

    5. Collection Architecture and Update Strategies

    Market data collection generally uses one of two approaches:

    • Polling: Call a data API at fixed intervals. This is straightforward to implement, but frequent requests can trigger rate limits, while long intervals leave the display behind the market.
    • Push-based updates: Receive incremental updates through a persistent connection or subscription mechanism. This reduces latency but requires reconnection and out-of-order message handling.

    Whichever approach you use, several design choices are important:

    • Retry with backoff: Apply exponential backoff after failures and limit the number of retries to avoid amplifying an outage.
    • Local caching: Keep the latest valid snapshot for each asset and define a cache expiration policy. Serving frontend reads from the cache reduces upstream load and helps keep the page available during brief provider outages.
    • Idempotent writes: Use the asset symbol and update timestamp as a unique key so writing the same record repeatedly has no additional effect.
    • Cross-source comparison: Raise an alert when prices from two sources diverge beyond a configured threshold.

    At the infrastructure level, a general-purpose message queue can carry collected records, a cache service can store the latest snapshots, and logging and monitoring services can track collection success rates, latency distributions, and validation failures. Select these components according to the team’s operational capabilities and budget.

    6. Frontend Presentation

    A market data display should help users understand accurate information quickly, rather than simply present more numbers.

    Key considerations include:

    • Adjust precision to the magnitude of the price. Very low-priced assets need more decimal places, while higher-priced assets can use fewer.
    • Do not communicate price direction through color alone. Plus and minus signs or arrows help users with color vision deficiencies distinguish gains from losses.
    • Abbreviate large values using familiar units. For an English-language display, use units such as millions and billions, with two decimal places.
    1. from decimal import Decimal
    2. def format_market_cap(value: Decimal) -> str:
    3. if value >= Decimal("1e9"):
    4. return f"{value / Decimal('1e9'):.2f}B"
    5. if value >= Decimal("1e6"):
    6. return f"{value / Decimal('1e6'):.2f}M"
    7. return f"{value:.2f}"
    8. def format_change(pct: Decimal) -> str:
    9. sign = "+" if pct > 0 else ""
    10. arrow = "▲" if pct > 0 else ("▼" if pct < 0 else "—")
    11. return f"{arrow} {sign}{pct}%"

    The page should also clearly identify the data source, update time, and whether the data is stale. Every displayed value should be traceable to a defined point in time.

    7. Testing Strategy

    Boundary conditions deserve particular attention when testing market data modules. Recommended cases include:

    • Calculation functions raise the expected exception when the reference price is zero or negative.
    • Validation does not incorrectly flag a latest price that equals the high or low.
    • Future timestamps and timestamps without timezone information produce clear errors.
    • Missing fields appear as placeholders rather than causing the display to crash or showing a misleading zero.
    • Repeatedly receiving the same timestamped record leaves the write result unchanged.

    Implement these cases with the language’s standard unit testing framework and require them to pass in continuous integration.

    8. Compliance and Risk Disclosures

    Cryptocurrency prices are influenced by many factors and can fluctuate significantly. Product design should account for the following:

    • Prominently state that market data is for informational purposes only and does not constitute investment advice.
    • Avoid promotional interpretations of price changes, such as suggesting that a trend is certain to continue.
    • Follow applicable regulations governing financial information displays and data use, and confirm the scope of the upstream provider’s data license.

    9. Conclusion

    Reliable market data systems depend on three foundations: clear field definitions, consistent calculation conventions, and timely detection of anomalous data.

    Use decimal arithmetic and explicit nullable fields in the data model, detect obvious errors during validation, and show timestamps and sources in the interface. Together, these practices provide a practical foundation for a stable, trustworthy market data display.