Building and Parsing a Real-Time Cryptocurrency Market Data System
This article walks through the engineering behind a real-time cryptocurrency market data system. It covers field semantics in the market data model, precision handling with Decimal, the trade-offs between REST polling and WebSocket push, market cap and ranking calculations, and practical data-validation and storage strategies for building a reliable pipeline.
1. Background and Value of Market Data Systems
In the digital asset space, market data is the foundational input for every trading decision, risk control system, and analytics tool. A typical market record includes these core fields: trading code, trading pair, market type, last price, quote currency, 24-hour price change, percentage change, open price, high, low, market cap, market cap ranking, and data update time.
Take a typical market snapshot as an example (using anonymized sample data): a trading pair’s last price is 0.08879 USD, with a 24-hour change of +0.0004994, a percentage change of roughly 0.566%, an open price of 0.08829, a high of 0.09268, a low of 0.08759, a market cap of about 88.87 million USD, and a ranking of 168. Behind these numbers lies an entire technical chain of data collection, computation, and presentation. Understanding this chain is the first step toward building any market data application.
2. Designing the Market Data Model
2.1 Field Semantics
When designing a market data model, the first task is to define the exact semantics of each field:
- Last price: the price of the most recent trade; a high-frequency changing field.
- Open price: the price at the start of the statistical window (usually 00:00 UTC or the start of a rolling 24-hour window). Definitions vary across platforms, so the convention must be confirmed carefully.
- High / low: the extreme values within the statistical window, used for candlestick charts or volatility range assessment.
- Change and percentage change: derived from the last price and open price. Percentage change = (last price − open price) / open price × 100%.
- Market cap: typically circulating supply multiplied by the last price; the core metric for asset size.
- Market cap ranking: the asset’s position when all assets are sorted by market cap; it changes dynamically with price movement.
Validating against the sample data: change = 0.08879 − 0.08829 = 0.0005 (essentially matching the given 0.0004994, with the difference coming from precision truncation), and percentage change = 0.0005 / 0.08829 ≈ 0.566%. This confirms that the derived metrics in the record are self-consistent with the base fields. This kind of cross-validation is a necessary part of market data quality management.
2.2 Precision Cannot Be Ignored
Crypto asset prices often carry high precision (five or more decimal places). In most programming languages, floating-point arithmetic introduces precision errors. The correct approach is to use fixed-point or high-precision decimal types:
from decimal import Decimal, ROUND_HALF_UPlast = Decimal("0.08879")open_ = Decimal("0.08829")change = last - open_ # 0.00050change_pct = (change / open_ * 100).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP) # 0.5660
If the percentage change were computed with float, you might get results like 0.5659999999, which creates visible flaws in the presentation layer.
3. Two Mainstream Approaches to Data Collection
3.1 Polling (REST API)
Periodically call the market data endpoint to pull snapshot data. This approach is simple to implement and easy to debug, making it suitable for scenarios with low real-time requirements:
import time, requestsdef poll_market(symbol: str, interval: int = 10):while True:resp = requests.get(f"https://api.example-market.com/v1/ticker",params={"symbol": symbol}, timeout=5)data = resp.json()save_snapshot(data) # persist or push downstreamtime.sleep(interval)
The drawbacks of polling are obvious: long intervals miss price movement details, while short intervals generate excessive requests and may trigger API rate limits.
3.2 Push (WebSocket Subscription)
Subscribe to market data channels over a persistent connection, so the server pushes updates whenever trades occur or prices change. This approach delivers high real-time performance and efficient bandwidth usage, and is the mainstream choice in production. It requires additional engineering work:
- Reconnection: after a disconnect, reconnect with exponential backoff and request a full snapshot to fill the gap;
- Heartbeat: send pings periodically to detect dead connections promptly;
- Deduplication and ordering: pushed messages may arrive out of order and must be handled using timestamps or sequence numbers.
4. Market Cap and Ranking Logic
Market cap = circulating supply × last price. Note that supply itself is dynamic (e.g., token unlocks or burn mechanisms), so a market data system usually needs to maintain an independent supply data source rather than assuming it is constant.
Reverse-engineering the sample data: market cap of 88.8708 million USD ÷ last price of 0.08879 ≈ 1.001 billion in circulating supply—mathematically self-consistent. The market cap ranking is an asset’s position when all assets are sorted by market cap in descending order. Since prices across the market fluctuate in real time, rankings can shift frequently within short periods, so the presentation layer typically applies debouncing to prevent ranking numbers from “jumping” and hurting readability.
5. Data Validation and Engineering Best Practices
To build a reliable market data system, follow these practices:
- Unified conventions: clearly define the statistical window for percentage change (rolling 24 hours vs. since 00:00 UTC) and keep it consistent across the entire pipeline; otherwise, different modules will display conflicting values.
- Sanity checks: run anomaly detection on every record—for example, the last price deviating from the previous one beyond a threshold, the high being lower than the low, or the sign of the change contradicting the sign of the percentage change. Anomalies should trigger alerts rather than being written directly to storage.
- Timestamp management: store everything in UTC and convert to the user’s timezone at the presentation layer; also retain the data source’s update timestamp to help troubleshoot latency issues.
- Tiered storage: keep hot data (latest snapshots) in memory or cache, write time-series data (historical prices) to a time-series database, and archive long-term data to object storage—balancing query efficiency and cost.
- Multi-source redundancy: a single data source may fail or change its conventions unexpectedly. Production systems should ingest multiple sources, cross-compare them, and treat the majority-consistent result as the trusted value.
6. Conclusion
Behind a seemingly simple market record—last price, percentage change, market cap, ranking—lies a complete engineering system spanning data model design, collection channel construction, precision control, metric computation, and quality validation. For developers, mastering Decimal-based precision handling, the trade-offs between polling and push collection, and data self-consistency validation provides the core capability to build a trustworthy market data processing system. From there, layering on candlestick aggregation, indicator computation, and alert notifications evolves the system into a full-fledged digital asset market analysis platform.
