Collecting and Parsing Crypto Market Data: A Practical Guide

    This article walks through the practical engineering work behind crypto market data collection and parsing, using a sample ticker record as the starting point. It covers field semantics and type modeling with fixed-point decimals, a four-stage cleaning pipeline of tokenize, normalize, validate, and persist, incremental fetching with cursor plus overlap windows and idempotent writes, layered storage from raw to detail to aggregate, and observability metrics for latency, completeness, and quality. Readers will find Python examples, a troubleshooting table, and guidance on defining field, time, and failure semantics to build a reliable data pipeline.

    1. Starting from a Single Ticker Record

    In crypto engineering practice, the most basic and most error-prone part is often not the strategy itself, but the collection and parsing of market data. Below is a typical market data sample (field names have been generalized):

    1. Code: GLM
    2. Pair: GLMUSDT
    3. Market Type: CRYPTO
    4. Name: Golem
    5. Last Price: 0.09359
    6. Quote Currency: USD
    7. 24h Change Amount: 0.0001998
    8. 24h Change Percent: 0.214%
    9. Open Price: 0.09339
    10. High Price: 0.09539
    11. Low Price: 0.09119
    12. Market Cap: 93.7331 million
    13. Market Cap Rank: 164
    14. Updated At: 2026-12-01 19:59:41

    This record carries a lot of information, but ingesting it directly introduces a series of hidden risks: numbers are given as strings, the change percent carries a percent sign, the market cap carries a unit, and the timestamp has no time zone. What engineering actually needs to do is convert this kind of “human-readable” display data into “machine-computable” structured data.

    2. Field Semantics and Type Modeling

    The first step is to build a field dictionary that makes the semantics, dimension, and value range of each field explicit.

    • Price fields (last, open, high, low) are essentially fixed-point decimals. Binary floating point should not be used for direct equality comparison; it is better to accept strings as input and store fixed-point numbers or integers in the smallest unit.
    • The change amount and change percent are redundant with each other: change amount ≈ last price - price 24h ago, and change percent ≈ change amount / price 24h ago. The two can be used for cross-validation.
    • The high and low prices form the intraday range, and the last price must fall within it; otherwise the data has most likely expired or the fields are misaligned.
    • Market cap and market cap rank are aggregate metrics, usually computed upstream and pushed down; consumers should not derive them on their own.
    • The update time must carry time zone semantics; otherwise cross-region deployments will run into offset problems that are hard to pin down.

    A workable type definition:

    1. from dataclasses import dataclass
    2. from decimal import Decimal
    3. @dataclass(frozen=True)
    4. class TickerSnapshot:
    5. symbol: str # trading pair, e.g. GLMUSDT
    6. market_type: str # market type, e.g. CRYPTO
    7. last: Decimal # last price
    8. open24h: Decimal # open price 24h ago
    9. high24h: Decimal
    10. low24h: Decimal
    11. change_amount: Decimal
    12. change_pct: Decimal # percent sign removed; 0.214 means 0.214%
    13. market_cap: Decimal | None
    14. rank: int | None
    15. event_time: str # ISO8601 string with time zone

    3. Cleaning and Validation Pipeline

    The parsing layer should be split into four stages — tokenize → normalize → validate → persist — with each stage doing one thing only, which makes problems easier to locate.

    1. import re
    2. from decimal import Decimal, InvalidOperation
    3. PCT = re.compile(r"^(-?\d+(?:\.\d+)?)%$")
    4. CN_UNIT = {"万": 10**4, "亿": 10**8}
    5. def to_decimal(raw: str) -> Decimal:
    6. try:
    7. return Decimal(raw.strip())
    8. except InvalidOperation as exc:
    9. raise ValueError(f"invalid number: {raw!r}") from exc
    10. def parse_pct(raw: str) -> Decimal:
    11. m = PCT.match(raw.strip())
    12. if not m:
    13. raise ValueError(f"invalid percentage: {raw!r}")
    14. return Decimal(m.group(1))
    15. def parse_cap(raw: str) -> Decimal | None:
    16. s = raw.strip()
    17. for unit, scale in CN_UNIT.items():
    18. if s.endswith(unit):
    19. return Decimal(s[:-1]) * scale
    20. return to_decimal(s) if s else None
    21. def validate(t: TickerSnapshot) -> list[str]:
    22. errs = []
    23. if not (t.low24h <= t.last <= t.high24h):
    24. errs.append("last price out of range")
    25. if t.high24h < t.low24h:
    26. errs.append("high price below low price")
    27. if t.last > 0:
    28. derived = (t.change_amount / t.last) * 100
    29. if abs(derived - t.change_pct) > Decimal("0.05"):
    30. errs.append("change percent inconsistent with change amount")
    31. return errs

    It is worth stressing that validation is not as simple as “discarding dirty data.” A safer approach in production is to write records that fail validation into a separate quarantine collection, along with the failure reason and the original payload, and then review them with an offline job. This avoids silent data loss that would leave hard-to-notice gaps in downstream metrics.

    4. Incremental Fetching and Idempotent Writes

    Market data is typically high-frequency and repeatable. Full overwrites waste bandwidth and introduce jitter; pure incremental fetching, on the other hand, tends to miss segments after a service restart. A common engineering approach combines a cursor with overlapping time windows:

    1. Persist a cursor that records the event time of the last successfully processed record;
    2. On each fetch, go back by a fixed window (for example, 5 minutes) to form an overlap region;
    3. Use (symbol, event_time) as the business primary key for idempotent writes, so duplicate data is naturally overwritten;
    4. Periodically run a full alignment to repair cursor drift.

    Illustrative logic:

    1. def next_window(cursor, overlap=300, step=60):
    2. start = cursor - overlap
    3. return start, start + step

    The design of the idempotency key is the core of this scheme. As long as the primary key is stable, retries, backfills, and concurrent consumption will not produce duplicate records, which is far more reliable than depending on an upstream “exactly once” promise.

    5. Layered Storage and Computation

    Data landing should be layered so that parsing logic and query logic do not pollute each other.

    • Raw layer: stores unprocessed payloads for traceability and re-parsing;
    • Detail layer: structured per-record snapshots, partitioned by time;
    • Aggregate layer: derived metrics such as minute-level, hour-level, and day-level open, high, low, last, and volume.

    On the cloud, this can be implemented by combining only generic capabilities: object storage holds raw payloads and cold data, a message queue buffers between collection and parsing to smooth out peaks, a container platform runs parsing and aggregation jobs, a logging service collects runtime logs, and monitoring and alerting set thresholds for “data latency” and “validation failure rate.” Each layer can then scale independently and be replayed separately.

    6. Observability and Common Failures

    Failures in a market data pipeline are often not crashes but “quietly getting slower.” At a minimum, monitor three kinds of metrics:

    • Latency: the difference between the current time and the event time of the latest data;
    • Completeness: deviation of record counts within a unit window from the baseline;
    • Quality: validation failure rate and field missing rate.

    Common failures and where to look:

    Symptom Possible cause How to investigate
    Last price unchanged for a long time Collection thread blocked or cursor stalled Check consumer lag and thread stacks
    Change percent abnormally amplified Denominator close to zero or unit conversion error Review the normalization function
    Missing market cap Upstream aggregation job produced nothing Check aggregate layer partitions
    Overall time offset Missing time zone annotation Unify to time-zone-aware timestamps

    7. Conclusion

    A seemingly simple ticker record unfolds into a complete chain: type modeling, normalization, cross-validation, idempotent writes, layered storage, and observability. Making this chain solid is what gives later metric computation, backtesting, and visualization a trustworthy foundation. For developers, what is truly worth investing in is not piling up complex components, but defining three things clearly — field semantics, time semantics, and failure semantics. They are the entire source of data pipeline reliability.