:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(coinmarketcap): add exchange and historical ranking tables (#103457)
Tom Owersa645fc6798b7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex aa7bec3c3ccf..1fcf99b20372 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -1883,7 +1883,7 @@ Note: docs.coingecko.com/reference/\* pages are client-rendered and unparseable## CoinMarketCap — gaps-Today (9): `categories`, `cryptocurrency_info`, `cryptocurrency_map`, `exchange_map`, `fiat_map`, `global_metrics_quotes_historical`, `listings_latest`, `ohlcv_historical`, `quotes_historical`+Today (13): `categories`, `cryptocurrency_info`, `cryptocurrency_map`, `exchange_info`, `exchange_listings_latest`, `exchange_map`, `exchange_quotes_historical`, `fiat_map`, `global_metrics_quotes_historical`, `listings_historical`, `listings_latest`, `ohlcv_historical`, `quotes_historical`Diffed against: <https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency.md>@@ -1891,16 +1891,16 @@ Diffed against: <https://pro.coinmarketcap.com/api/documentation/pro-api-referen- [x] `GET /v2/cryptocurrency/ohlcv/historical` — daily OHLCV candles, required for any price or return analysis (high)- [x] `GET /v1/global-metrics/quotes/historical` — total market cap, BTC dominance and altcoin market cap over time - CMC's headline market metric (high)- [x] `GET /v2/cryptocurrency/info` — coin metadata (tags, platform, category, urls) that resolves the ids in the cryptocurrency_map we already sync (high)-- [ ] `GET /v1/exchange/listings/latest` — ranked exchanges with volume and liquidity; exchange_map alone carries no metrics (high)-- [ ] `GET /v1/exchange/info` — exchange metadata lookup resolving the ids in the synced exchange_map (medium)-- [ ] `GET /v1/cryptocurrency/listings/historical` — historical ranked snapshots, letting you reconstruct rank changes without polling listings/latest (medium)+- [x] `GET /v1/exchange/listings/latest` — ranked exchanges with volume and liquidity; exchange_map alone carries no metrics (high)+- [x] `GET /v1/exchange/info` — exchange metadata lookup resolving the ids in the synced exchange_map (medium)+- [x] `GET /v1/cryptocurrency/listings/historical` — historical ranked snapshots, letting you reconstruct rank changes without polling listings/latest (medium)- [ ] `GET /v2/cryptocurrency/market-pairs/latest` — per-coin market pairs and where volume actually trades (medium)- [ ] `GET /v1/exchange/market-pairs/latest` — per-exchange market pairs; joins exchanges to cryptocurrencies (medium)-- [ ] `GET /v1/exchange/quotes/historical` — historical exchange volume for venue share analysis (medium)+- [x] `GET /v1/exchange/quotes/historical` — historical exchange volume for venue share analysis (medium)- [ ] `GET /v1/cryptocurrency/category` — coin membership per category - the categories table we sync lists categories but not their constituents (medium)- [ ] `GET /v3/fear-and-greed/historical` — CMC's proprietary sentiment index over time, a commonly requested signal (medium)-Note: coinmarketcap.com/api/documentation is a client-rendered zudoku app, but every page is served as markdown by appending .md, and pro.coinmarketcap.com/llms.txt indexes the whole reference by family (Cryptocurrency 19, Exchange 7, Global Metrics 6, DEX/Token 16, Holder 5, Derivatives 3, RWA 7, CMC Index 4...). The cryptocurrency and global-metrics historical families are now covered; the exchange historical family is not. The DEX (Token/Pool/Holder/OHLCV) and Real World Assets families are also entirely uncovered but are treated as separate products rather than enumerated here.+Note: coinmarketcap.com/api/documentation is a client-rendered zudoku app, but every page is served as markdown by appending .md, and pro.coinmarketcap.com/llms.txt indexes the whole reference by family (Cryptocurrency 19, Exchange 7, Global Metrics 6, DEX/Token 16, Holder 5, Derivatives 3, RWA 7, CMC Index 4...). The cryptocurrency and global-metrics historical families are now covered, as is the exchange family apart from market pairs, assets and proof-of-reserves. The DEX (Token/Pool/Holder/OHLCV) and Real World Assets families are also entirely uncovered but are treated as separate products rather than enumerated here.## Commercetools — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.pyindex a2ecf98210dd..88461ab8e95c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py@@ -80,6 +80,72 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_historical_data": "Timestamp (ISO 8601) of the latest market data record available for this exchange.",},},+ "exchange_listings_latest": {+ "description": "Latest aggregate market data per exchange: traded volume, liquidity, ranking and market pair count.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/exchange/listings-latest-2.md",+ "columns": {+ "id": "The unique CoinMarketCap ID for this exchange.",+ "name": "The name of this exchange.",+ "slug": "The web URL friendly shorthand version of this exchange name.",+ "num_market_pairs": "The number of trading pairs actively tracked on this exchange.",+ "date_launched": "Timestamp (ISO 8601) of the date this exchange launched.",+ "exchange_score": "The exchange score. Deprecated by CoinMarketCap on 4 November 2024 and now always null.",+ "liquidity_score": "The liquidity score.",+ "rank": "The exchange rank.",+ "traffic_score": "The traffic score.",+ "last_updated": "Timestamp (ISO 8601) of the last time this record was updated.",+ "quote": "Market quote by currency conversion (default USD): volume_24h, volume_24h_adjusted, volume_7d, volume_30d, the matching percent changes, effective_liquidity_24h, derivative_volume, open_interest and spot_volume_usd.",+ },+ },+ "exchange_info": {+ "description": "Static metadata for each exchange: launch date, logo, description and resource URLs.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/exchange/metadata-2.md",+ "columns": {+ "id": "The unique CoinMarketCap ID for this exchange.",+ "name": "The name of this exchange.",+ "slug": "The web URL friendly shorthand version of this exchange name.",+ "logo": "Link to a CoinMarketCap hosted logo png for this exchange.",+ "description": "A CoinMarketCap supplied brief description of this exchange.",+ "date_launched": "Timestamp (ISO 8601) of the launch date for this exchange.",+ "notice": "A Markdown formatted message outlining a condition affecting the availability of this exchange's market data, otherwise null.",+ "weekly_visits": "The number of weekly visitors.",+ "spot_volume_usd": "Reported all time spot volume in USD.",+ "urls": "Resource URLs for this exchange: website, blog, chat, fee and twitter.",+ },+ },+ "exchange_quotes_historical": {+ "description": "Historical daily traded volume for the highest-volume exchanges. One row per exchange per interval.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/exchange/quotes-historical-2.md",+ "columns": {+ "id": "The CoinMarketCap exchange ID this quote belongs to.",+ "name": "The exchange name.",+ "slug": "The exchange slug.",+ "timestamp": "Timestamp (ISO 8601) of when this historical quote was recorded.",+ "num_market_pairs": "Number of market pairs available at this historical interval.",+ "quote": "Market details for this interval by currency conversion (default USD): volume_24h and the conversion timestamp.",+ },+ },+ "listings_historical": {+ "description": "Daily ranked snapshot of the market, taken at the end of each UTC day. One row per cryptocurrency per day, covering the top of the CoinMarketCap ranking.",+ "docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency/listings-historical.md",+ "columns": {+ "snapshot_date": "The UTC day this snapshot was requested for. Added by PostHog, because the response identifies the day only through last_updated.",+ "id": "The unique CoinMarketCap ID for this cryptocurrency.",+ "name": "The name of this cryptocurrency.",+ "symbol": "The ticker symbol for this cryptocurrency.",+ "slug": "The web URL friendly shorthand version of this cryptocurrency name.",+ "cmc_rank": "The cryptocurrency's CoinMarketCap rank at the end of this UTC day.",+ "num_market_pairs": "The number of active trading pairs available for this cryptocurrency across supported exchanges.",+ "circulating_supply": "The approximate number of coins circulating at the end of this UTC day.",+ "total_supply": "The approximate total amount of coins in existence at the end of this UTC day (minus any coins verifiably burned).",+ "max_supply": "The expected maximum limit of coins ever to be available for this cryptocurrency.",+ "last_updated": "Timestamp (ISO 8601) of the last market data update available during this UTC day.",+ "date_added": "Timestamp (ISO 8601) of when this cryptocurrency was added to CoinMarketCap.",+ "tags": "Tags associated with this cryptocurrency.",+ "platform": "Metadata about the parent cryptocurrency platform this is a token on, if any.",+ "quote": "Market quote by currency conversion (default USD) at the end of this UTC day: price, volume_24h, market_cap, the percent changes and the conversion timestamp.",+ },+ },"cryptocurrency_info": {"description": "Static metadata for each cryptocurrency: category, tags, platform, description and resource URLs.","docs_url": "https://pro.coinmarketcap.com/api/documentation/pro-api-reference/cryptocurrency/metadata.md",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.pyindex ba6d184a4e64..523d8992187e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py@@ -10,10 +10,13 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.settings import (COINMARKETCAP_BATCH_ENDPOINTS,COINMARKETCAP_ENDPOINTS,+ COINMARKETCAP_SNAPSHOT_ENDPOINTS,HISTORICAL_BACKFILL_DAYS,HISTORICAL_COIN_LIMIT,+ HISTORICAL_EXCHANGE_LIMIT,PAGE_SIZE,CoinMarketCapBatchEndpointConfig,+ CoinUniverse,RowShape,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -45,6 +48,8 @@ class CoinMarketCapResumeConfig:# boundary is an id rather than a batch position because the coin universe changes between# attempts: a coin that leaves it would shift later ids into a skipped prefix.last_coin_id: int = 0+ # Last UTC day (ISO date) already yielded by a day-walking snapshot endpoint.+ last_snapshot_date: str = ""class CoinMarketCapPaginator(OffsetPaginator):@@ -108,11 +113,11 @@ def _get(session: requests.Session, path: str, params: dict[str, Any]) -> dict[sreturn body if isinstance(body, dict) else {}-def _coin_ids_from_map(session: requests.Session) -> list[int]:+def _ids_from_map(session: requests.Session, path: str) -> list[int]:ids: list[int] = []start = 1while True:- page = _get(session, "/v1/cryptocurrency/map", {"start": start, "limit": PAGE_SIZE, "sort": "id"})+ page = _get(session, path, {"start": start, "limit": PAGE_SIZE, "sort": "id"})rows = page.get("data") or []ids.extend(int(row["id"]) for row in rows if isinstance(row, dict) and row.get("id") is not None)# Counted before filtering: an unusable row on a full page must not end the walk.@@ -121,20 +126,26 @@ def _coin_ids_from_map(session: requests.Session) -> list[int]:start += PAGE_SIZE-def _top_coin_ids_by_market_cap(session: requests.Session, limit: int) -> list[int]:- page = _get(- session,- "/v1/cryptocurrency/listings/latest",- {"start": 1, "limit": limit, "sort": "market_cap", "sort_dir": "desc"},- )+def _top_ids_by_rank(session: requests.Session, path: str, sort: str, limit: int) -> list[int]:+ page = _get(session, path, {"start": 1, "limit": limit, "sort": sort, "sort_dir": "desc"})rows = [row for row in (page.get("data") or []) if isinstance(row, dict) and row.get("id") is not None]- # Sorted by id rather than left in rank order, so a resumed run batches the same coins in the+ # Sorted by id rather than left in rank order, so a resumed run batches the same ids in the# same order as the run it picks up from even though the ranking itself moves between syncs.return sorted(int(row["id"]) for row in rows)+def _universe_ids(session: requests.Session, universe: CoinUniverse) -> list[int]:+ if universe == "map":+ return _ids_from_map(session, "/v1/cryptocurrency/map")+ if universe == "exchange_map":+ return _ids_from_map(session, "/v1/exchange/map")+ if universe == "top_by_market_cap":+ return _top_ids_by_rank(session, "/v1/cryptocurrency/listings/latest", "market_cap", HISTORICAL_COIN_LIMIT)+ return _top_ids_by_rank(session, "/v1/exchange/listings/latest", "volume_24h", HISTORICAL_EXCHANGE_LIMIT)++def _coin_entries(data: Any) -> Iterator[dict[str, Any]]:- """Yield each cryptocurrency object out of a CoinMarketCap `data` payload.+ """Yield each cryptocurrency or exchange object out of a CoinMarketCap `data` payload.Requesting several ids returns a map keyed by id, a single id returns the object on its own,and requesting by symbol wraps each value in a list.@@ -194,11 +205,7 @@ def get_batch_rows(yield rowsreturn- coin_ids = (- _coin_ids_from_map(session)- if config.universe == "map"- else _top_coin_ids_by_market_cap(session, HISTORICAL_COIN_LIMIT)- )+ coin_ids = _universe_ids(session, config.universe)resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonelast_coin_id = resume_config.last_coin_id if resume_config is not None else 0if last_coin_id:@@ -247,6 +254,97 @@ def _batch_source()+def _last_published_snapshot_date(now: datetime.datetime) -> datetime.date:+ """Most recent UTC day whose ranked snapshot CoinMarketCap has published.++ A completed day's snapshot lands about 30 minutes after midnight, so for the first hour of a+ new day the newest day on offer is the one before yesterday. Asking for a day CoinMarketCap+ has not published yet would fail the sync once a day, on the hour it rolls over.+ """+ yesterday = now.date() - datetime.timedelta(days=1)+ return yesterday if now.hour >= 1 else yesterday - datetime.timedelta(days=1)+++def _snapshot_start_date(db_incremental_field_last_value: Optional[Any]) -> datetime.date:+ if isinstance(db_incremental_field_last_value, datetime.datetime):+ return db_incremental_field_last_value.date()+ if isinstance(db_incremental_field_last_value, datetime.date):+ return db_incremental_field_last_value+ if isinstance(db_incremental_field_last_value, str) and db_incremental_field_last_value:+ try:+ return datetime.date.fromisoformat(db_incremental_field_last_value[:10])+ except ValueError:+ pass+ backfill_start = datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=HISTORICAL_BACKFILL_DAYS)+ return backfill_start.date()+++def get_snapshot_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = COINMARKETCAP_SNAPSHOT_ENDPOINTS[endpoint]+ session = _api_session(api_key)++ # The watermark day is re-requested rather than stepped over: a run cut short part-way through+ # a day would otherwise leave the rest of that day's ranking missing for good. One day costs a+ # single credit and the merge de-duplicates the overlap.+ day = _snapshot_start_date(db_incremental_field_last_value)+ last_day = _last_published_snapshot_date(datetime.datetime.now(datetime.UTC))++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None and resume_config.last_snapshot_date:+ logger.debug(f"CoinMarketCap: resuming {endpoint} after {resume_config.last_snapshot_date}")+ resumed_day = datetime.date.fromisoformat(resume_config.last_snapshot_date) + datetime.timedelta(days=1)+ day = max(day, resumed_day)++ while day <= last_day:+ body = _get(+ session,+ config.path,+ {**config.extra_params, "date": day.isoformat(), "start": 1, "limit": config.limit},+ )+ rows = [row for row in (body.get("data") or []) if isinstance(row, dict)]+ if rows:+ yield [{**row, config.date_field: day.isoformat()} for row in rows]++ # Saved after the day is yielded, so a crash re-yields that day rather than skipping it.+ resumable_source_manager.save_state(CoinMarketCapResumeConfig(last_snapshot_date=day.isoformat()))+ day += datetime.timedelta(days=1)+++def _snapshot_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ config = COINMARKETCAP_SNAPSHOT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_snapshot_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # One request per day, walked oldest day first.+ sort_mode="asc",+ )++def coinmarketcap_source(api_key: str,endpoint: str,@@ -256,6 +354,15 @@ def coinmarketcap_source(resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:+ if endpoint in COINMARKETCAP_SNAPSHOT_ENDPOINTS:+ return _snapshot_source(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+if endpoint in COINMARKETCAP_BATCH_ENDPOINTS:return _batch_source(api_key=api_key,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.pyindex 1255e8773890..d96870fdc92c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/settings.py@@ -22,6 +22,14 @@ HISTORICAL_BATCH_SIZE = 20# The highest-ranked coins by market cap are what these tables get used for.HISTORICAL_COIN_LIMIT = 100+# Same bound for the per-exchange history, taken from the top of the volume ranking. There are far+# fewer exchanges than coins, so this covers most of the venues anyone reports on.+HISTORICAL_EXCHANGE_LIMIT = 100++# How deep the daily ranked snapshot goes. listings/historical bills per 100 cryptocurrencies per+# day requested, so the rank depth and the day window together set what a sync costs.+LISTINGS_HISTORICAL_RANK_LIMIT = 100+# How far back a historical request reaches when there is no watermark to start from. One year# of daily points is the longest window every paid plan tier serves, so a first sync doesn't# fail outright on the entry plans.@@ -88,6 +96,18 @@ COINMARKETCAP_ENDPOINTS: dict[str, CoinMarketCapEndpointConfig] = {path="/v1/exchange/map",extra_params={"sort": "id"},),+ # Latest volume, liquidity and ranking per exchange. exchange_map carries no metrics.+ "exchange_listings_latest": CoinMarketCapEndpointConfig(+ name="exchange_listings_latest",+ path="/v1/exchange/listings/latest",+ # This endpoint's `sort` enum has no id option, and every other choice except `name` is a+ # metric that reorders mid-sync and would make offset pages skip or repeat exchanges.+ extra_params={+ "sort": "name",+ "sort_dir": "asc",+ "aux": "num_market_pairs,traffic_score,rank,exchange_score,effective_liquidity_24h,date_launched,fiats",+ },+ ),}# How a response body turns into rows.@@ -100,7 +120,10 @@ RowShape = Literal["object_map", "per_coin_quotes", "quote_list"]# Where the ids for an `id=` param come from.# "map": every id in /v1/cryptocurrency/map.# "top_by_market_cap": the HISTORICAL_COIN_LIMIT highest-ranked coins in listings/latest.-CoinUniverse = Literal["map", "top_by_market_cap"]+# "exchange_map": every id in /v1/exchange/map.+# "top_exchanges_by_volume": the HISTORICAL_EXCHANGE_LIMIT highest-volume exchanges in+# exchange/listings/latest.+CoinUniverse = Literal["map", "top_by_market_cap", "exchange_map", "top_exchanges_by_volume"]@frozen@@ -176,6 +199,30 @@ COINMARKETCAP_BATCH_ENDPOINTS: dict[str, CoinMarketCapBatchEndpointConfig] = {"skip_invalid": "true",},),+ # Static metadata (launch date, logo, urls, fee docs) resolving the ids in exchange_map.+ "exchange_info": CoinMarketCapBatchEndpointConfig(+ name="exchange_info",+ path="/v1/exchange/info",+ primary_keys=["id"],+ row_shape="object_map",+ universe="exchange_map",+ extra_params={"aux": "urls,logo,description,date_launched,notice,status"},+ ),+ # Daily traded volume and market pair count per exchange.+ "exchange_quotes_historical": CoinMarketCapBatchEndpointConfig(+ name="exchange_quotes_historical",+ path="/v1/exchange/quotes/historical",+ primary_keys=["id", "timestamp"],+ row_shape="per_coin_quotes",+ universe="top_exchanges_by_volume",+ batch_size=HISTORICAL_BATCH_SIZE,+ windowed=True,+ partition_key="timestamp",+ extra_params={+ "interval": "daily",+ "count": str(HISTORICAL_MAX_COUNT),+ },+ ),# Total market cap, BTC/ETH dominance and altcoin market cap over time."global_metrics_quotes_historical": CoinMarketCapBatchEndpointConfig(name="global_metrics_quotes_historical",@@ -196,16 +243,59 @@ COINMARKETCAP_BATCH_ENDPOINTS: dict[str, CoinMarketCapBatchEndpointConfig] = {),}-ENDPOINTS = (*COINMARKETCAP_ENDPOINTS.keys(), *COINMARKETCAP_BATCH_ENDPOINTS.keys())-# Only global metrics syncs incrementally. Its `time_start` filter drives a single global series,-# so the one watermark the pipeline hands a source is exactly the right lower bound.+@frozen+class CoinMarketCapSnapshotEndpointConfig:+ """An endpoint returning one ranked snapshot per UTC day, addressed by a `date` param.++ The source walks the days itself, one request each, and pages the ranking down to `limit`.+ """++ name: str+ path: str+ primary_keys: list[str]+ # Field stamped onto every row with the UTC day the snapshot was requested for. The response+ # carries no such field, and `last_updated` repeats across days for a coin that has stopped+ # trading, so two days of rows would otherwise collapse into one on merge.+ date_field: str+ limit: int+ partition_key: Optional[str] = None+ extra_params: dict[str, str] = field(default_factory=dict)+++COINMARKETCAP_SNAPSHOT_ENDPOINTS: dict[str, CoinMarketCapSnapshotEndpointConfig] = {+ # Daily ranked snapshot of the market, so rank changes can be read back without polling+ # listings/latest.+ "listings_historical": CoinMarketCapSnapshotEndpointConfig(+ name="listings_historical",+ path="/v1/cryptocurrency/listings/historical",+ primary_keys=["id", "snapshot_date"],+ date_field="snapshot_date",+ limit=LISTINGS_HISTORICAL_RANK_LIMIT,+ partition_key="snapshot_date",+ extra_params={+ "sort": "cmc_rank",+ "sort_dir": "asc",+ "aux": "platform,tags,date_added,circulating_supply,total_supply,max_supply,cmc_rank,num_market_pairs",+ },+ ),+}++ENDPOINTS = (+ *COINMARKETCAP_ENDPOINTS.keys(),+ *COINMARKETCAP_BATCH_ENDPOINTS.keys(),+ *COINMARKETCAP_SNAPSHOT_ENDPOINTS.keys(),+)++# Only the two tables whose rows form one global series over time sync incrementally, because the+# single watermark the pipeline hands a source is exactly the right lower bound for both: global+# metrics filters on `time_start`, and the daily ranked snapshot walks days from the watermark.## The "latest"/"map" endpoints reflect current state with no `since`-style filter, so an-# "incremental" sync would re-fetch every page anyway. The per-coin historical endpoints do take-# `time_start`, but the coin universe is the top coins by market cap and that ranking churns:-# driving `time_start` off a watermark shared by every coin would give a coin that enters the-# universe later only the history since that watermark, and nothing would ever fill the gap.+# "incremental" sync would re-fetch every page anyway. The per-coin and per-exchange historical+# endpoints do take `time_start`, but their universe is the top of a ranking and that ranking+# churns: driving `time_start` off a watermark shared by every entity would give one that enters+# the universe later only the history since that watermark, and nothing would ever fill the gap.INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"global_metrics_quotes_historical": [{@@ -215,4 +305,12 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"field_type": IncrementalFieldType.DateTime,}],+ "listings_historical": [+ {+ "label": "snapshot_date",+ "type": IncrementalFieldType.Date,+ "field": "snapshot_date",+ "field_type": IncrementalFieldType.Date,+ }+ ],}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.pyindex f6f8c3591159..63d3b1b1ed26 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py@@ -1,4 +1,5 @@import json+import datetimefrom collections.abc import Iterablefrom typing import Any, cast@@ -12,10 +13,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketCoinMarketCapPaginator,CoinMarketCapResumeConfig,_history_start,+ _last_published_snapshot_date,_rows_from,+ _snapshot_start_date,coinmarketcap_source,get_batch_rows,get_resource,+ get_snapshot_rows,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.settings import (@@ -24,6 +28,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketHISTORICAL_BACKFILL_DAYS,HISTORICAL_BATCH_SIZE,HISTORICAL_COIN_LIMIT,+ HISTORICAL_EXCHANGE_LIMIT,+ LISTINGS_HISTORICAL_RANK_LIMIT,METADATA_BATCH_SIZE,PAGE_SIZE,)@@ -109,7 +115,10 @@ class TestGetResource:assert endpoint_def["path"].startswith("/v1/")assert endpoint_def["data_selector"] == "data"- @pytest.mark.parametrize("endpoint", ["cryptocurrency_map", "listings_latest", "fiat_map", "exchange_map"])+ @pytest.mark.parametrize(+ "endpoint",+ ["cryptocurrency_map", "listings_latest", "fiat_map", "exchange_map", "exchange_listings_latest"],+ )def test_paginated_endpoints_pass_a_stable_sort(self, endpoint: str) -> None:# A stable `sort` keeps offset pagination from skipping/duplicating rows mid-sync.endpoint_def = cast(dict[str, Any], get_resource(endpoint)["endpoint"])@@ -524,6 +533,185 @@ class TestGetBatchRows:assert first_batch[1]["time_start"] == _history_start(None)assert first_batch[0].endswith(COINMARKETCAP_BATCH_ENDPOINTS[endpoint].path)+ def test_exchange_info_batches_every_id_in_the_exchange_map(self) -> None:+ manager = self._manager()+ rows, session = self._run(+ "exchange_info",+ [+ _make_batch_response({"data": [{"id": 16}, {"id": 24}]}),+ _make_batch_response({"data": {"16": {"id": 16}, "24": {"id": 24}}}),+ ],+ manager,+ )++ map_call, info_call = session.calls+ # The ids come from the exchange map, not the cryptocurrency map.+ assert map_call[0].endswith("/v1/exchange/map")+ assert info_call[0].endswith("/v1/exchange/info")+ assert info_call[1]["id"] == "16,24"+ assert [row["id"] for row in rows] == [16, 24]++ def test_exchange_history_ranks_the_exchange_universe_by_volume(self) -> None:+ listings = {"data": [{"id": exchange_id} for exchange_id in range(HISTORICAL_BATCH_SIZE + 1, 0, -1)]}+ manager = self._manager()+ _, session = self._run(+ "exchange_quotes_historical",+ [_make_batch_response(listings), _make_batch_response({"data": {}}), _make_batch_response({"data": {}})],+ manager,+ )++ universe_call, first_batch, _ = session.calls+ # `market_cap` is not in this endpoint's sort enum — exchanges rank by traded volume.+ assert universe_call[0].endswith("/v1/exchange/listings/latest")+ assert universe_call[1]["sort"] == "volume_24h"+ assert universe_call[1]["sort_dir"] == "desc"+ assert universe_call[1]["limit"] == HISTORICAL_EXCHANGE_LIMIT++ assert first_batch[0].endswith("/v1/exchange/quotes/historical")+ assert first_batch[1]["id"] == ",".join(str(i) for i in range(1, HISTORICAL_BATCH_SIZE + 1))+ assert first_batch[1]["time_start"] == _history_start(None)+++class TestLastPublishedSnapshotDate:+ @pytest.mark.parametrize(+ ("hour", "expected_day"),+ [+ # A completed day's snapshot lands ~30 minutes after midnight UTC, so before 01:00+ # yesterday is not there yet and asking for it would fail the sync.+ (0, 8),+ (1, 9),+ (23, 9),+ ],+ )+ def test_waits_for_the_snapshot_to_publish(self, hour: int, expected_day: int) -> None:+ now = datetime.datetime(2026, 3, 10, hour, 15, tzinfo=datetime.UTC)+ assert _last_published_snapshot_date(now) == datetime.date(2026, 3, expected_day)+++class TestSnapshotStartDate:+ def test_falls_back_to_the_backfill_window(self) -> None:+ expected = (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=HISTORICAL_BACKFILL_DAYS)).date()+ assert _snapshot_start_date(None) == expected++ @pytest.mark.parametrize(+ "watermark",+ [+ "2026-03-01",+ "2026-03-01T00:00:00.000Z",+ datetime.date(2026, 3, 1),+ datetime.datetime(2026, 3, 1, 18, 0, tzinfo=datetime.UTC),+ ],+ )+ def test_reads_the_day_out_of_every_watermark_shape(self, watermark: Any) -> None:+ assert _snapshot_start_date(watermark) == datetime.date(2026, 3, 1)++ def test_unparseable_watermark_falls_back_rather_than_raising(self) -> None:+ expected = (datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=HISTORICAL_BACKFILL_DAYS)).date()+ assert _snapshot_start_date("not-a-date") == expected+++class TestGetSnapshotRows:+ def _manager(self, resume_config: CoinMarketCapResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_config is not None+ manager.load_state.return_value = resume_config+ return manager++ def _run(+ self,+ responses: list[Response],+ manager: MagicMock,+ now: Any,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict[str, Any]], _FakeSession]:+ patcher, session = _patch_session(responses)+ with (+ patcher,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.coinmarketcap.coinmarketcap._last_published_snapshot_date",+ return_value=now,+ ),+ ):+ batches = list(+ get_snapshot_rows(+ api_key="test-key",+ endpoint="listings_historical",+ logger=MagicMock(),+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ return [row for batch in batches for row in batch], session++ def test_walks_one_request_per_day_from_the_watermark(self) -> None:+ manager = self._manager()+ rows, session = self._run(+ [+ _make_batch_response({"data": [{"id": 1, "cmc_rank": 1}]}),+ _make_batch_response({"data": [{"id": 1, "cmc_rank": 2}]}),+ ],+ manager,+ now=datetime.date(2026, 3, 2),+ db_incremental_field_last_value="2026-03-01",+ )++ assert [params["date"] for _, params in session.calls] == ["2026-03-01", "2026-03-02"]+ assert all(url.endswith("/v1/cryptocurrency/listings/historical") for url, _ in session.calls)+ assert session.calls[0][1]["limit"] == LISTINGS_HISTORICAL_RANK_LIMIT+ assert session.calls[0][1]["sort"] == "cmc_rank"++ # The response identifies its day only through last_updated, which repeats for a coin that+ # stopped trading, so the requested day is stamped on to keep the two days distinct.+ assert [row["snapshot_date"] for row in rows] == ["2026-03-01", "2026-03-02"]+ assert [row["cmc_rank"] for row in rows] == [1, 2]++ def test_re_requests_the_watermark_day(self) -> None:+ # A run cut short part-way through a day would otherwise leave the rest of that day's+ # ranking missing for good.+ _, session = self._run(+ [_make_batch_response({"data": []})],+ self._manager(),+ now=datetime.date(2026, 3, 1),+ db_incremental_field_last_value="2026-03-01",+ )+ assert [params["date"] for _, params in session.calls] == ["2026-03-01"]++ def test_checkpoints_each_day_after_yielding_it(self) -> None:+ manager = self._manager()+ self._run(+ [+ _make_batch_response({"data": [{"id": 1}]}),+ _make_batch_response({"data": [{"id": 1}]}),+ ],+ manager,+ now=datetime.date(2026, 3, 2),+ db_incremental_field_last_value="2026-03-01",+ )++ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ CoinMarketCapResumeConfig(last_snapshot_date="2026-03-01"),+ CoinMarketCapResumeConfig(last_snapshot_date="2026-03-02"),+ ]++ def test_resume_picks_up_the_day_after_the_checkpoint(self) -> None:+ manager = self._manager(CoinMarketCapResumeConfig(last_snapshot_date="2026-03-02"))+ _, session = self._run(+ [_make_batch_response({"data": [{"id": 1}]})],+ manager,+ now=datetime.date(2026, 3, 3),+ db_incremental_field_last_value="2026-03-01",+ )+ assert [params["date"] for _, params in session.calls] == ["2026-03-03"]++ def test_makes_no_request_when_the_watermark_is_already_current(self) -> None:+ _, session = self._run(+ [],+ self._manager(),+ now=datetime.date(2026, 3, 1),+ db_incremental_field_last_value="2026-03-02",+ )+ assert session.calls == []+class TestBatchEndpointErrors:def test_a_plan_refusal_matches_a_non_retryable_error(self) -> None: