Market Data Collection and Parsing for Digital Assets: A Practical Guide

    This article walks through the engineering practices for collecting, parsing, and storing digital asset market data. Starting from a sample spot market snapshot, it covers field semantics, separating atomic from derived fields, numeric precision, timezone handling, collection strategies such as push with polling fallback, backoff and rate limiting, idempotent writes, a layered processing architecture, data-level observability, and common pitfalls. The goal is a stable, reusable, and verifiable pipeline rather than a one-off parser.

    1. Starting With a Single Market Snapshot

    When building market monitoring, quantitative backtesting, or asset dashboard systems, the first step is usually not writing a strategy. It is fully understanding what a single market data record actually contains. Below is a typical spot market snapshot (data is for technical demonstration only and does not constitute any investment advice):

    1. {
    2. "symbol": "GLM",
    3. "pair": "GLMUSDT",
    4. "market_type": "CRYPTO",
    5. "name": "Golem",
    6. "last_price": 0.09359,
    7. "quote_currency": "USD",
    8. "change_24h_abs": 0.00009989,
    9. "change_24h_pct": 0.107,
    10. "open_price": 0.09349,
    11. "high_price": 0.09539,
    12. "low_price": 0.09119,
    13. "market_cap": 93733100,
    14. "rank": 164,
    15. "updated_at": "2026-12-01 19:50:38"
    16. }

    This record carries a lot of information: price dimensions (last, open, high, low), derived metrics (24-hour absolute and percentage change), global dimensions (market cap, rank), and metadata (pair, market type, quote currency, update time). The real engineering challenge is not reading it, but processing thousands of such records in a stable, reusable, and verifiable way.

    2. Field Semantics and Data Model Design

    2.1 Separate Atomic Fields From Derived Fields

    Derived fields such as percentage change should not be the single source of truth. The percentage change can be reconstructed from (last - open) / open, and the absolute change from last - open. The engineering recommendation is to persist only atomic fields and compute derived fields in the query or view layer. This avoids self-contradictory data when upstream conventions change.

    Example validation logic:

    1. def validate_snapshot(s: dict) -> bool:
    2. eps = 1e-6
    3. if not (s["low_price"] - eps <= s["last_price"] <= s["high_price"] + eps):
    4. return False
    5. if s["low_price"] > s["open_price"] or s["open_price"] > s["high_price"]:
    6. return False
    7. derived_pct = (s["last_price"] - s["open_price"]) / s["open_price"] * 100
    8. return abs(derived_pct - s["change_24h_pct"]) < 0.05

    This validation covers three common types of dirty data: last price out of range, inconsistent open/high/low relationships, and derived metrics that disagree with atomic fields.

    2.2 Numeric Precision and Type Selection

    Price fields must never be stored directly as binary floating point. A decimal like 0.09359 produces tail differences under floating point representation, and these accumulate and affect backtesting and reconciliation. Two approaches are recommended: use fixed-point types (Python’s Decimal, Java’s BigDecimal), or scale everything into integers (for example, multiply by 1e8 and store as int64), then scale back for display.

    1. from decimal import Decimal, ROUND_HALF_UP
    2. SCALE = Decimal("1e8")
    3. def to_scaled_int(price_str: str) -> int:
    4. return int((Decimal(price_str) * SCALE).quantize(Decimal("1"), ROUND_HALF_UP))

    2.3 Unifying the Time Dimension

    updated_at is a first-class citizen of market data. When persisting it, do three things: normalize to timezone-aware UTC storage; retain the original timezone information for auditing; and index time fields to support windowed aggregation. A bare timestamp string without timezone information should be flagged as low-confidence data rather than silently parsed in the local timezone.

    3. Collection Layer: Stability Over Real-Time

    3.1 Pulling vs. Pushing

    Market data ingestion usually has two paths: polling and long-lived connections. Polling is simple to implement and easy to scale horizontally, but has fixed latency. Long-lived connections offer low latency but require handling heartbeats, reconnection, and sequence gap filling. A common practice is “push primary, polling fallback”: the push path handles low latency, while scheduled polling handles alignment and gap filling.

    3.2 Backoff and Rate Limiting

    Every external data API has rate constraints. A robust retry must use exponential backoff with jitter, not a fixed-interval tight loop:

    1. import random, time
    2. def backoff_sleep(attempt: int, base: float = 0.5, cap: float = 30.0) -> None:
    3. delay = min(cap, base * (2 ** attempt))
    4. time.sleep(delay * (0.5 + random.random() / 2))

    You should also set a circuit breaker threshold: after N consecutive failures, pause pulling and trigger an alert to avoid cascading request storms.

    3.3 Idempotent Writes

    The same snapshot may be written multiple times due to retries. Using (symbol, market_type, updated_at) as a unique key for an idempotent upsert is the lowest-cost deduplication method.

    4. Processing Layer: Cleaning, Aggregation, and Features

    4.1 Layered Architecture

    A three-layer structure is recommended: a raw layer that keeps immutable original text (for traceability and replay); a detail layer that standardizes and validates fields; and a summary layer that produces minute-level and hour-level candles plus rolling metrics. The core value of layering is replayability: when strategies iterate, you can recompute from the raw layer instead of depending on historical conclusions.

    4.2 Handling Market Cap and Rank

    Market cap and rank are global aggregation results. They update less frequently than price, and different sources may use different conventions. Engineering-wise, treat them as slowly changing dimensions, store them separately, and annotate them with data timestamps. This avoids update amplification from mixing them with high-frequency prices in the same wide table.

    4.3 Anomaly Detection

    Beyond rule-based validation, you can add statistical methods: apply rolling median and median absolute deviation (MAD) checks on returns. Points that deviate beyond a threshold are flagged as suspicious rather than discarded outright, leaving the decision to humans or downstream strategies.

    5. Cloud Deployment: Assembling a Pipeline With Common Capabilities

    In a cloud environment, this pipeline can be assembled entirely from general product categories without binding to any proprietary interface:

    • Collection: a container platform hosts stateless collection services, with elastic scaling to handle traffic fluctuations;
    • Buffering: a message queue smooths peaks and decouples downstream consumption from upstream rates;
    • Storage: object storage holds raw snapshot files, while a relational database holds details and slowly changing dimensions;
    • Compute: batch jobs handle historical recomputation, and stream computing handles real-time aggregation;
    • Operations: a logging service collects runtime logs, and monitoring and alerting set thresholds for collection latency, failure rate, and data gaps.

    Baidu AI Cloud is typically used in such scenarios to host the combination of these general capabilities. For specific product selection and pricing, refer to the official documentation. This article does not cover any undisclosed parameters.

    6. Observability and Alerting

    Failures in a market data pipeline are often silent: the API does not error, but the data stops moving at some point. You must therefore monitor the data itself, not just the process:

    1. Freshness: alert when the gap between the latest updated_at and the current time exceeds a threshold;
    2. Gap rate: the ratio of expected records to actual records within a unit window;
    3. Consistency: the mismatch ratio between derived fields and atomic fields;
    4. Out-of-range rate: the ratio of last prices falling outside the high-low range.
    1. def freshness_lag_seconds(latest_utc, now_utc) -> float:
    2. return (now_utc - latest_utc).total_seconds()
    3. # More than 120 seconds without an update is considered anomalous
    4. ALERT_THRESHOLD = 120

    7. Common Pitfalls Checklist

    • Storing prices as floating point, accumulating tail differences over time;
    • Treating percentage change as authoritative, causing everything to shift after an upstream convention change;
    • Ignoring timezones, producing an 8-hour offset in cross-day aggregation;
    • Monitoring only process liveness, not data freshness;
    • Retrying without backoff, dragging downstream systems down too;
    • Mixing slowly changing dimensions with high-frequency data, causing write amplification;
    • Discarding anomalies outright, breaking replayability.

    8. Summary

    A seemingly simple market snapshot expands into five engineering topics: type precision, time semantics, idempotent writes, layered replayability, and data-level observability. Separating atomic fields from derived fields, separating the raw layer from the summary layer, and upgrading from “monitoring the process” to “monitoring the data” are the three highest-value practices. All numbers in this article are for technical demonstration only. Market data carries volatility risk, and any decision should be based on independent judgment.