Crypto Market Data: Practical Approaches to Collection, Calculation, and Display
This article explains how to build a reliable crypto market data pipeline, covering field definitions, metric calculations, data validation, freshness and caching strategies, reference architecture, monitoring, display compliance, and common troubleshooting practices to keep prices, reports, and alerts consistent across a system.
Market data may look like just a few numbers, but in a real system it gets displayed, cached, triggers alerts, feeds statistics, and serves as input for downstream calculations. If a “latest price” lacks a timestamp, uses inconsistent units, or has truncated decimals, pages, reports, and alerts can produce contradictory results. Therefore, the core of market data features is ensuring timeliness, accuracy, and traceability — not simply putting numbers on a page.
1. Field Definitions and Conventions
Typical market data includes the following fields. Define each field clearly before deciding on storage formats.
- Symbol: Identifies the quoted asset and the quote currency, commonly in the form “asset/quote currency”.
- Last price (last): The price of the most recent trade or quote.
- Open, high, low: Price boundaries within a statistical window. The window length (e.g., 24 hours) must match the API documentation.
- Change: The latest price minus the price at the start of the statistical window.
- Change percentage (change_pct): The change divided by the base price, usually expressed as a percentage.
- Market cap and ranking: Calculated by multiplying circulating supply by price. Reliability depends on how frequently the supply data is updated.
- Updated time (updated_at): When the data was produced. It should be normalized to UTC or have an explicit timezone in the field.
When field definitions are unclear, the same value may be interpreted differently across modules. The API documentation should specify the unit, precision, timezone, and update frequency for every field.
2. Metric Calculation Conventions
The standard formula for change percentage is:
change_pct = (last - base) / base × 100
Here, base is the price at the start of the statistical window. Three points matter during implementation:
- Guard against a base price of zero to avoid division-by-zero errors.
- Store and compute prices as strings or Decimal types to avoid floating-point rounding errors.
- Use the same calculation convention everywhere. For example, if the list page rounds while the detail page keeps three decimal places, users will see inconsistent results.
The following example shows a Decimal-based implementation with demonstration values:
from decimal import Decimal, ROUND_HALF_UPdef change_percent(last: str, base: str) -> Decimal | None:last_d = Decimal(last)base_d = Decimal(base)if base_d == 0:return None # Cannot compute when base is 0; return None for the caller to handlepct = (last_d - base_d) / base_d * 100return pct.quantize(Decimal("0.001"), rounding=ROUND_HALF_UP)# Demo data: last price 105.20, base price 100.00print(change_percent("105.20", "100.00")) # Output: 5.200
3. Data Collection and Validation
Market data should pass validation before entering business logic. Common checks include field completeness, numeric ranges, price relationships, and time freshness.
from decimal import DecimalREQUIRED_FIELDS = ["symbol", "last", "open", "high", "low", "updated_at"]def validate_quote(q: dict) -> list[str]:errors = []for key in REQUIRED_FIELDS:if q.get(key) in (None, ""):errors.append(f"missing field: {key}")if errors:return errorslow = Decimal(q["low"])high = Decimal(q["high"])last = Decimal(q["last"])if low > high:errors.append("low greater than high")if not (low <= last <= high):errors.append("last price outside [low, high]")return errors
Records that fail validation should not directly overwrite existing valid data. A safer approach is to keep the last valid record, log the anomaly, and flag the data status on the page.
4. Freshness and Caching Strategy
The value of market data decays quickly over time, so the system must define how old data can be before it is no longer displayable.
- Set a freshness threshold: Compare
updated_atwith the current time. If the threshold is exceeded, mark the data as “possibly stale” in the UI. - Use caching to reduce upstream calls: The cache TTL should be driven by the business scenario. Display pages can tolerate second-level delays, while trigger-based logic requires shorter cycles.
- Choose an appropriate update mechanism: Polling is simple and suits low-frequency display; persistent push connections offer lower latency but add connection-management complexity.
5. Reference Architecture
A common market data pipeline can be decomposed in the following order:
Collection service → Message queue → Cleaning and validation service → Time-series storage and cache → Query service → Frontend display
Each stage has independent responsibilities, making it easier to scale and troubleshoot individually. The message queue handles traffic spikes and decouples components; time-series storage suits time-range queries; the cache absorbs high-frequency reads. Component selection should be evaluated against throughput, latency requirements, and operational cost. If you use cloud services, you can consider general-purpose categories such as message queues, object storage, and monitoring/alerting products from providers like Baidu AI Cloud, and confirm capabilities and configurations against the official documentation.
6. Monitoring and Alerting
Monitoring for a market data service should cover the data pipeline itself, not just server resources. Recommended metrics include:
- Data latency: The difference between the current time and
updated_at, tracked per trading pair. - Collection success rate: The ratio of successfully written records to expected records per unit of time.
- Missing-field rate: The proportion of records failing validation, useful for detecting upstream schema changes.
- Abnormal volatility: When change percentage exceeds a set threshold, first re-check the data source and validation results before deciding whether to notify anyone.
Alerts should point to data problems rather than pushing abnormal price movements directly to users as events. Otherwise, occasional bad data from upstream will trigger large volumes of meaningless notifications.
7. Display and Compliance Notes
Market data pages must balance accuracy with regulatory norms.
- Pages should indicate the data update time and the source category, such as “third-party data source”, so users can judge timeliness.
- Crypto asset prices are highly volatile; page content is for informational reference only and does not constitute investment advice of any kind.
- Display modules should not include content that solicits trading, makes recommendations, or channels users toward trading, to keep the product’s functional boundaries clear.
8. Common Issues and How to Handle Them
- Price discrepancies across data sources: First unify the quote currency and statistical window, then compare data at the same point in time. Never compare two records with misaligned timestamps.
- Timezone confusion: Store all timestamps in UTC in the database, and convert to the user’s timezone only at the presentation layer.
- Floating-point errors: Store amounts and prices as Decimal or fixed-point integers, and apply formatting only at the display layer.
- Field meaning changes: After an upstream API upgrade, use contract tests and field validation to detect changes early, rather than waiting for bad data to appear on the page.
By following the process above, you can confine data quality issues to an observable, recoverable scope and keep displayed results consistent across all modules.
