Digital Asset Market Data: Collection, Storage, and Real-Time Push
This article presents a systematic design approach for digital asset market data services. Starting from a single market snapshot, it explains how to build a standardized data model with explicit field relationships and precision constraints, then walks through multi-source data collection, rolling statistical computation (24-hour window, market cap, and ranking), layered storage and caching, incremental real-time push, and fault tolerance, monitoring, and data quality governance. Readers will learn practical techniques for turning scattered raw market data into a unified, low-latency, and trustworthy data service, along with the common pitfalls to avoid. The numbers shown here only illustrate the data structure and do not constitute any investment advice.
Market data APIs for digital assets usually expose just a handful of fields: latest price, percentage change, open price, high/low, market cap, market cap rank, and update time. Many teams assume they can ship by simply polling on a schedule, parsing the response, and caching the result. But once this capability feeds into real-time dashboards, mobile pages, strategy signals, or risk-control workflows, problems surface all at once: upstream push latency, inconsistent statistical conventions, loss of decimal precision, data inconsistency across multiple instances, and corrupted state after reconnects.
The hard part of a market data service is not “fetching a number” — it is turning scattered raw data into a service with unified conventions, controllable latency, and full trustworthiness and traceability. Using a set of digital asset market snapshots as a sample, this article systematically walks through the design of a market data service across several layers: field semantics, data collection, statistical computation, storage and caching, real-time push, and fault tolerance and monitoring. The numbers used here only illustrate the data structure and do not constitute any investment advice.
From Raw Snapshots to a Standard Data Model
Reading a Raw Snapshot
Consider a typical market data snapshot:
- Symbol: GLM; Trading pair: GLMUSDT; Market type: CRYPTO
- Latest price: 0.08879 USD
- 24-hour change: +0.0004994; Percentage change: +0.566%
- Open price: 0.08829; High: 0.09268; Low: 0.08759
- Market cap: 88,870,800 USD; Market cap rank: 168
- Update time: 2026-11-24 11:58:39
At first glance this looks like an ordinary price query result. Digging deeper yields several conclusions:
The window interval is relatively complete. The open price falls between the low and the high, and the high is no lower than the low, indicating that the 24-hour statistical window is reasonably complete.
Price precision and computation precision differ.
- The change of 0.0004994 retains 7 decimal places, while the open and latest prices shown are only 5.
- From “latest price − change” you can derive the true window base price of about 0.0882906, truncated to 0.08829 for display.
- Computing 0.0004994 / 0.0882906 gives a percentage change of about 0.5657%, which rounds to exactly 0.566% at three decimals.
- This shows the upstream computes the percentage change on the untruncated base price, while the page only displays the truncated value.
Market cap implies a circulating supply assumption. Dividing the market cap of about 88,870,800 by the latest price of 0.08879 gives an implied circulating supply of about 100.09 million. If the circulating supply definition changes (for example, a future unlock), market cap changes in step, while the price may not.
These three points together show that market data fields cannot be treated as isolated numbers — there are clear derivation relationships and precision constraints among them. The first step in designing the data model is to make these relationships explicit.
The Four Field Layers
It helps to divide market data into four layers, each with a clear responsibility, so validation and maintenance stay manageable:
| Layer | Fields | Description |
|---|---|---|
| Identification | Symbol, quote currency, market type | Uniquely locates a market data record; the same asset has different prices in different markets, and these cannot be mixed |
| Price | Latest price, 24h open, high, low | Unified as fixed-point numbers (integer + decimal places) to avoid floating-point error accumulation |
| Derived | Change, percentage change, amplitude, market cap, market cap rank | Computed server-side under a unified convention, not dependent on upstream results |
| Metadata | Data time, collection time, source, version, freshness flag | Used to judge whether data is stale, whether it is traceable, and whether it can be overwritten by newer data |
The derived and metadata layers are the most easily overlooked, yet they determine whether the service can run stably over the long term:
- Derived fields are computed server-side: the same asset may yield a different change under different sources. Only by computing to a unified definition on the server do results stay consistent when switching between sources.
- Metadata makes problems traceable: when a question such as “why did the price jump suddenly” comes up, you need to know where the data came from, when it was produced, when it was collected, and whether it passed multi-source validation.
A Standardized Data Structure
The following sketch describes a unified market data model:
from dataclasses import dataclass, field@dataclass(frozen=True)class Quote:symbol: str # Symbol, e.g. GLMquote_ccy: str # Quote currency, e.g. USDmarket: str # Market type: spot / perpetual futures / delivery futureslast_px: int # Latest price (fixed-point integer)open24h: int # 24h open price (fixed-point integer)high24h: int # 24h high price (fixed-point integer)low24h: int # 24h low price (fixed-point integer)decimals: int # Number of decimal places for pricepub_ts: int # Data time (millisecond timestamp, UTC)recv_ts: int # Local collection timesource: str # Data source identifierseq: int = 0 # Server-side monotonically increasing version numberflags: set = field(default_factory=set) # e.g. stale, suspect
seq and flags are key:
- Both push and caching rely on
seqto judge old versus new. flagslet the “data is stale” state be explicitly perceived downstream, rather than silently returning an old number.
Data Collection: Multi-Source Ingestion and Robust Aggregation
Combining Pull and Push
Pure polling is simple to implement but has clear drawbacks:
- When there is no new market data between two polls, the request is wasted overhead.
- Real-time performance is capped by the polling interval.
Pure push has good real-time performance but requires you to handle reconnection, message ordering, connection limits, and more yourself.
A more robust engineering approach is “push-first, snapshot calibration”:
- Receive incremental market data over a long-lived connection for low-latency updates.
- Periodically (for example, every minute) pull a snapshot and compare it with the locally accumulated values.
- When the deviation exceeds a threshold, correct with the snapshot as the source of truth and record a data quality event.
Snapshot calibration also avoids a common pitfall: incremental push relies on “not losing any price point,” whereas a snapshot gives the complete window result and does not depend on message completeness.
Multi-Source Aggregation
It is recommended to connect at least two independent data sources:
- The primary source provides data externally.
- The backup source is collected synchronously but is not active; it is used only for comparison.
- When the primary has consecutive missing data or latency beyond a threshold, switch automatically; after recovery, go through a stabilization period before switching back, to avoid oscillation.
When multi-source prices disagree, there are three common strategies:
- Priority selection: take the first valid value in source order.
- Median method: take the median across multiple sources to reduce the impact of a single anomalous source.
- Weighted aggregation: dynamically assign weights based on each source’s historical latency, missing rate, and deviation.
Whichever strategy you use, record each data point’s source and aggregation method for traceability.
Idempotency, Deduplication, and Backpressure
Stream ingestion brings duplicate and out-of-order messages. Recommended practices:
- Use “symbol + market + data time” as the idempotency key; discard duplicate messages directly.
- Locally judge old versus new by timestamp; old messages must not overwrite new state.
- Add queue buffering and a drop policy at the entry point; when the queue backs up, drop intermediate price points and keep only the latest. Market data scenarios care about “what is the current price,” so losing intermediate points is usually acceptable.
- When the upstream rate-limits, use exponential backoff with jitter to avoid retry storms.
In addition, collection nodes should synchronize clocks using NTP, and uniformly record data time and collection time as millisecond UTC timestamps.
Derived Metrics: Rolling Statistics, Market Cap, and Ranking
24-Hour Rolling Window
The 24-hour statistic is the core derived computation of a market data service. Three things must be defined during design:
- Window convention: is it a “sliding window of the last 24 hours” or a fixed-period window (such as the calendar day)? The two yield different results and must be fixed in the documentation.
- Window open price: under the sliding window model, take the latest traded price at the window’s start, not the open of a fixed hour.
- Boundary inclusion rule: clarify whether the left and right boundaries are open or closed.
For each asset’s continuously arriving price series (t₁, p₁), (t₂, p₂), …, you need to answer at any moment:
- the latest price in the window pₙ;
- the window’s start price, used as the open;
- the highest and lowest prices in the window.
A naive approach traverses all data in the window each time, with a complexity of O(window length). Here, a “plain queue + two monotonic queues” reduces the amortized complexity per operation to O(1):
from collections import dequeclass RollingWindow:"""Slides by time, maintaining [open, high, low]"""def __init__(self, window_ms: int):self.window_ms = window_msself.data = deque() # (ts, price), ascending by timeself.max_q = deque() # prices monotonically decreasing, front is the maxself.min_q = deque() # prices monotonically increasing, front is the mindef push(self, ts: int, price: int):# For multiple records at the same instant, the first arrival wins to prevent out-of-order overwriteif self.data and ts < self.data[-1][0]:returnself.data.append((ts, price))while self.max_q and self.max_q[-1][1] <= price:self.max_q.pop()self.max_q.append((ts, price))while self.min_q and self.min_q[-1][1] >= price:self.min_q.pop()self.min_q.append((ts, price))self._evict(ts)def _evict(self, now: int):cutoff = now - self.window_mswhile self.data and self.data[0][0] < cutoff:self.data.popleft()if self.max_q and self.max_q[0][0] < cutoff:self.max_q.popleft()if self.min_q and self.min_q[0][0] < cutoff:self.min_q.popleft()def stats(self, last_px: int):if not self.data:return 0, last_px, last_pxopen_px = self.data[0][1]return open_px, self.max_q[0][1], self.min_q[0][1]
For each new data point, maintaining the monotonic queues pushes and pops each element at most once, and window eviction behaves similarly, so the amortized complexity is O(1). For a market data service handling tens of thousands of assets, this optimization directly determines whether the computation layer can keep up with the rate of data arrival.
Once you have the open, high, and low, you can further compute the change, percentage change, and amplitude:
class QuoteView:"""Converts internal quotes into the external display structure, unifying conventions and precision"""def __init__(self, win: RollingWindow, decimals: int):self.win = winself.decimals = decimalsself.scale = 10 ** decimalsdef view(self, q) -> dict:open_px, high, low = self.win.stats(q.last_px)change = q.last_px - open_px# Compute percentage change with integer arithmetic (unit: 1/10000) to avoid floating-point errorpct_bp = change * 10000 // open_px if open_px else 0return {"symbol": q.symbol,"pair": f"{q.symbol}{q.quote_ccy}","market": q.market,"last": f"{q.last_px / self.scale:.5f}","change": f"{change / self.scale:.7f}","change_pct": f"{pct_bp / 100:.3f}%","open24h": f"{open_px / self.scale:.5f}","high24h": f"{high / self.scale:.5f}","low24h": f"{low / self.scale:.5f}","seq": q.seq,"as_of": q.pub_ts,"flags": list(q.flags),}
Plugging in this article’s snapshot: with 0.0882906 as the base, the change is 0.0004994, the percentage change is about 0.566%, and the amplitude (high minus low, divided by the open) is about 5.77%. Clearly, the amplitude far exceeds the percentage change. This shows that long-tail digital assets fluctuate significantly within the statistical window; the “daily change” only reflects the difference between the window’s start and end, not the true volatility within the window. For downstream strategy and risk-control scenarios, the amplitude and the tick-by-tick series are often more valuable than the percentage change.
Market Cap and Market Cap Rank
Market cap is typically defined as “latest price × circulating supply,” so you need to independently maintain each asset’s circulating supply and the definition behind it (circulating market cap or fully diluted market cap), and record its source and update time. When the circulating supply is missing, the market cap field should be explicitly set to null, not 0, otherwise it pollutes the ranking.
Ranking is a “relative metric” with three details to clarify:
- Ranking scope: do all market assets participate, or only some? Do the exclusion rules change over time?
- Sort key: sort by market cap in descending order, and define a secondary sort key for ties (such as the symbol) to ensure stable, reproducible results.
- Update frequency: market cap changes slowly and does not need to refresh at the same frequency as price; recomputing in batches on a fixed cycle is enough, and the result should carry a “computed at” time.
By market cap rank, the example asset in this article ranks 168th, a long-tail asset. Such assets have weaker liquidity and uneven source quality, so data validation thresholds should be set more strictly.
Data Quality Validation
Before data enters statistics and external output, add three validations:
- Completeness validation: high ≥ low, and open lies between the low and the high.
- Spike validation: when a new price deviates from the previous valid price by more than a threshold (such as 30%), first mark it as suspect; it takes effect only after several consecutive confirmations, or the snapshot calibration result takes precedence.
- Freshness validation: when no new data arrives beyond the maximum update interval (such as 60 seconds), mark it as stale.
Storage and Caching: A Layered Design
Market data has very distinct access characteristics: hot assets are read at high frequency, while cold assets are accessed occasionally; recent data is queried intensively, while historical data is queried sparsely. Layered storage therefore fits well:
- Hot data: the full current market snapshot is kept in memory (in-process shared memory or a distributed memory cache), keyed by “market + symbol.” A “market snapshot set” is also maintained to support fetching a whole page in a single request.
- Warm data: minute-level and hour-level aggregates (open, high, low, close, volume) are written to a time-series or relational database partitioned by time, for drawing K-lines and curves.
- Cold data: older detail data is compressed in columnar format and archived to object storage, partitioned by date, and loaded on demand when needed.
Cache design has three key points:
- Write strategy: market data updates frequently, so “write-through” fits well — synchronously refresh the cache after data is persisted, ensuring the cache stays consistent with the data source.
- Multi-level cache and request collapsing: the query path goes through the in-process cache and then the distributed cache. When hot keys expire together, use a mutex or request collapsing (only one request per key is allowed to hit the source at the same moment) to prevent cache breakdown.
- Cache the metadata too: market cap, market cap rank, and circulating supply change slowly and can have longer cache times, while price data must refresh in real time; the two cannot be mixed in the same cache entry.
On Baidu AI Cloud, you can leverage general-purpose cloud components such as object storage, message queues, container platforms, log service, and monitoring/alerting to build the market data service architecture, focusing your energy on the data conventions and business logic itself.
Real-Time Push: From Polling to Incremental Delivery
For front-end real-time dashboards and mobile market pages, the value of a market data service depends largely on push quality. A push roughly involves four steps:
- The collection layer writes the latest market data and increments the version number.
- Change events are written to a message queue, partitioned by symbol to guarantee ordering for the same symbol.
- The push service consumes messages and routes changes to the long-lived connections subscribed to the corresponding symbol.
- The connection layer delivers the changes incrementally.
Incremental Push Example
def quote_stream(subscribe):sent_seq = {} # The most recently delivered version number per symbolfor ev in subscribe: # Blocking consumption of the message queuekey = (ev.market, ev.symbol)if ev.seq <= sent_seq.get(key, 0):continue # Old version or duplicate message, skip directlytry:channel.send_json(ev.payload) # Non-blocking send, returns immediately on failuresent_seq[key] = ev.seqexcept Backpressure:# Send congestion: skip intermediate versions, keep the latest for the next sendpending[key] = evcontinueif key in pending and pending[key].seq <= ev.seq:pending.pop(key)# When idle, prioritize resending the latest versions that backed up during congestionfor key, ev in pending.items():channel.send_json(ev.payload)
Key Design Points
- Incremental first: a single market update usually changes only a few fields; sending the whole object multiplies bandwidth usage.
- Forward-only: use the version number as the sole criterion for old versus new, so out-of-order or duplicate messages are naturally filtered out.
- Drop intermediate states: market data demands high real-time performance; when a connection is congested, keep the latest state and skip the intermediate price points.
- Snapshot + incremental recovery: after a client reconnects, it first requests a full snapshot, then receives subsequent increments, avoiding state gaps during the disconnection.
- Heartbeat and backoff: send periodic heartbeats to check connection liveness, and have clients reconnect with a jittered backoff strategy to prevent reconnection storms after a server restart.
Fault Tolerance, Monitoring, and Quality Governance
Fault Tolerance
- Upstream circuit breaking: after consecutive collection failures or timeouts, temporarily stop sending requests and tentatively resume after a cooldown.
- Explicit stale marking: when data is stale, the interface does not throw an error; it returns the latest valid value along with a
staleflag and anas_oftime, letting the caller decide the display strategy. - Scenario-based degradation: display scenarios can relax the refresh frequency, whereas trigger scenarios (such as price threshold alerts) should pause triggering to avoid false triggers based on outdated prices.
- Canary release: when a convention changes, first run the new logic and the old logic in parallel and compare their results (shadow mode), switching only after confirming the differences match expectations.
Monitoring Metrics
| Dimension | Key Metrics | Focus |
|---|---|---|
| Collection | Latency per source (collection time − data time), missing rate | Early signal of latency spikes or source outages |
| Computation | Window computation time, queue backlog | Whether it keeps up with the rate of data arrival |
| Storage | Cache hit rate, number of hot keys | Whether capacity and eviction policy are reasonable |
| Push | Connection count, send failure rate, reconnection count | Whether the connection layer is stable |
| Quality | Multi-source deviation, spike flag count, stale asset count | Data credibility and source quality |
Data Quality Governance
Establish a per-source data quality score that combines latency, missing rate, deviation, and spike rate, output reports periodically, and use them to drive collection strategy adjustments. When a source’s quality keeps declining, automatically lower its weight or even suspend the integration. For assets with large multi-source deviation, trigger a manual review.
Security and Compliance
- Credential management: market data interface credentials should be managed centrally through a key management service and rotated periodically, and must never be hard-coded in code or configuration files.
- Access control: authenticate and rate-limit external interfaces per caller to prevent a single caller from monopolizing resources.
- Log redaction: log only the necessary fields, avoiding the leakage of credentials and sensitive caller information.
- Compliant use: collecting and distributing market data must comply with the source’s terms of use, credit the data source and time when displaying, and include the necessary risk warnings.
Common Pitfalls and Best Practices
- Passing through raw fields directly: field definitions differ across sources, so standardize and convert them at the ingestion layer.
- Using floating point for price computation: switch to fixed-point integers and strictly unify the decimal places.
- Mixing display precision with computation precision: always keep full precision internally, and truncate only at the output layer.
- Simulating push with polling: both latency and overhead are unsatisfactory, so switch to long-lived push connections.
- Returning stale data without a flag: the caller must be able to perceive data freshness.
- Ignoring the market dimension: the same asset’s prices in different markets cannot substitute for one another.
- Switching data sources too frequently: switching should have a cooldown and a stabilization period to prevent oscillation.
Conclusion
A market data service may look like “reading a few numbers,” but it is in fact a systems engineering effort spanning data ingestion, convention definition, real-time computation, distributed storage, and real-time delivery. As the snapshot in this article shows, the derivation relationships among fields, the precision constraints, and the statistical window conventions are often the very details that determine service quality.
Build a market data service in the order “standard model → robust collection → unified computation → layered storage → incremental push → full-chain monitoring,” and drive continuous improvement through data quality governance, so that market data truly becomes trustworthy infrastructure for the business.
