Skip to content

: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.

feat(coingecko): add tickers, market chart, ohlc and global tables (#103356)

Tom Owersed81b8c5c183
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.md
index dec3fabcd79a..ff3a77f64096 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
@@ -1859,15 +1859,15 @@ Note: docs.coinapi.io is behind a Cloudflare interstitial and returns 403 to cur
## CoinGecko — gaps
-Today (8): `asset_platforms`, `coins_categories`, `coins_categories_list`, `coins_list`, `coins_markets`, `exchanges`, `exchanges_list`, `insights`
+Today (12): `asset_platforms`, `coins_categories`, `coins_categories_list`, `coins_list`, `coins_market_chart`, `coins_markets`, `coins_ohlc`, `coins_tickers`, `exchanges`, `exchanges_list`, `global_market_data`, `insights`
Diffed against: <https://docs.coingecko.com/llms.txt>
-- [ ] `/coins/{id}/market_chart/range` — historical price, market cap and volume timeseries - the headline series; today only a current-price snapshot is synced (high)
-- [ ] `/coins/{id}/ohlc/range` — OHLC candles per coin over an arbitrary range, needed for any price analysis (high)
-- [ ] `/global` — total crypto market cap, active coins and BTC dominance - CoinGecko's flagship market-wide metric (high)
+- [x] `/coins/{id}/market_chart/range` — historical price, market cap and volume timeseries - the headline series; today only a current-price snapshot is synced (high)
+- [x] `/coins/{id}/ohlc/range` — OHLC candles per coin over an arbitrary range, needed for any price analysis (high)
+- [x] `/global` — total crypto market cap, active coins and BTC dominance - CoinGecko's flagship market-wide metric (high)
- [ ] `/global/market_cap_chart` — historical global market cap and volume, the time series behind the above (high)
-- [ ] `/coins/{id}/tickers` — market pairs per coin on CEX and DEX - the join that resolves coins_list against exchanges_list, which we sync but cannot currently link (high)
+- [x] `/coins/{id}/tickers` — market pairs per coin on CEX and DEX - the join that resolves coins_list against exchanges_list, which we sync but cannot currently link (high)
- [ ] `/exchanges/{id}/tickers` — trading pairs per exchange; the other half of the coin-to-exchange lookup (medium)
- [ ] `/exchanges/{id}/volume_chart/range` — historical exchange volume for ranking exchanges over time (medium)
- [ ] `/simple/supported_vs_currencies` — lookup of valid vs_currency codes that coins_markets is parameterised by (currently hardcoded to usd) (medium)
@@ -1875,7 +1875,7 @@ Diffed against: <https://docs.coingecko.com/llms.txt>
- [ ] `/exchange_rates` — BTC-to-currency rates, the standard normaliser for cross-currency reporting (medium)
- [ ] `/derivatives/exchanges and /derivatives/tickers` — derivatives venues and open interest, entirely absent from current coverage (medium)
- [ ] `/nfts/markets` — NFT collections with floor price, market cap and volume - a whole product surface with no table today (medium)
-- [ ] `/coins/{id}/supply_breakdown` — per-coin circulating/non-circulating supply split with non-circulating wallet detail (Pro, Analyst plan and above); needs per-coin fan-out over the full coin universe, which this top-level-only source has no plumbing for (medium)
+- [ ] `/coins/{id}/supply_breakdown` — per-coin circulating/non-circulating supply split with non-circulating wallet detail (Pro, Analyst plan and above); fans out per coin over the configured coin list, like the chart tables (medium)
Note: docs.coingecko.com/reference/\* pages are client-rendered and unparseable by curl, but llms.txt enumerates every reference page (Demo and Pro) with descriptions, and any single page can be fetched by appending .md. The onchain/GeckoTerminal family (networks, dexes, pools, token holders, pool trades) is a further ~35 endpoints with zero coverage; treated as a separate product rather than listed individually here.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/canonical_descriptions.py
index 751366523932..8cd2a38db975 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/canonical_descriptions.py
@@ -103,4 +103,69 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"posted_at": "Timestamp the insight was posted, in ISO 8601 format.",
},
},
+ "coins_tickers": {
+ "description": "Market pairs for each configured coin across centralized and decentralized exchanges, with last price, volume and spread.",
+ "docs_url": "https://docs.coingecko.com/reference/coins-id-tickers",
+ "columns": {
+ "coin_id": "CoinGecko id of the coin the pair was fetched for.",
+ "market_identifier": "CoinGecko exchange id of the venue the pair trades on (joins the exchanges table).",
+ "base": "Base currency of the pair. A contract address for decentralized exchange pairs.",
+ "target": "Target currency of the pair. A contract address for decentralized exchange pairs.",
+ "market": "Exchange the pair trades on: name, identifier, and whether it runs a trading incentive.",
+ "last": "Last traded price, in the pair's own target currency.",
+ "volume": "Trading volume of the pair over the last 24 hours.",
+ "converted_last": "Last traded price converted to BTC, ETH and USD.",
+ "converted_volume": "24-hour trading volume converted to BTC, ETH and USD.",
+ "trust_score": "CoinGecko liquidity rating for the pair (green, yellow, red, or null).",
+ "bid_ask_spread_percentage": "Spread between the best bid and ask, as a percentage.",
+ "timestamp": "Timestamp CoinGecko recorded the pair at.",
+ "last_traded_at": "Timestamp of the pair's last trade.",
+ "last_fetch_at": "Timestamp CoinGecko last fetched the pair from the exchange.",
+ "is_anomaly": "Whether CoinGecko flagged the price as an outlier.",
+ "is_stale": "Whether the exchange has stopped updating the pair.",
+ "trade_url": "Link to the pair on the exchange.",
+ "target_coin_id": "CoinGecko coin id of the target currency, when the target is a tracked coin.",
+ "coin_mcap_usd": "Market capitalization of the base coin in USD.",
+ },
+ },
+ "coins_market_chart": {
+ "description": "Daily price, market cap and trading volume history in USD for each configured coin.",
+ "docs_url": "https://docs.coingecko.com/reference/coins-id-market-chart-range",
+ "columns": {
+ "coin_id": "CoinGecko coin id the data point belongs to.",
+ "timestamp": "Time of the data point, at 00:00 UTC.",
+ "price": "Price in USD at that point.",
+ "market_cap": "Market capitalization in USD at that point.",
+ "total_volume": "Trading volume over the 24 hours to that point, in USD.",
+ },
+ },
+ "coins_ohlc": {
+ "description": "Daily open/high/low/close price candles in USD for each configured coin. Requires a Pro API key on the Analyst plan or above.",
+ "docs_url": "https://docs.coingecko.com/reference/coins-id-ohlc-range",
+ "columns": {
+ "coin_id": "CoinGecko coin id the candle belongs to.",
+ "timestamp": "Time the candle closed.",
+ "open": "Price in USD at the start of the candle.",
+ "high": "Highest price in USD during the candle.",
+ "low": "Lowest price in USD during the candle.",
+ "close": "Price in USD at the end of the candle.",
+ },
+ },
+ "global_market_data": {
+ "description": "Market-wide totals across every coin CoinGecko tracks: active coins, exchange count, total market cap and volume, and per-coin dominance.",
+ "docs_url": "https://docs.coingecko.com/reference/crypto-global",
+ "columns": {
+ "active_cryptocurrencies": "Number of coins with active market data.",
+ "upcoming_icos": "Number of upcoming ICOs.",
+ "ongoing_icos": "Number of ongoing ICOs.",
+ "ended_icos": "Number of ended ICOs.",
+ "markets": "Number of exchanges CoinGecko tracks.",
+ "total_market_cap": "Total market capitalization of all coins, keyed by currency.",
+ "total_volume": "Total 24-hour trading volume of all coins, keyed by currency.",
+ "market_cap_percentage": "Share of total market capitalization per coin, so `btc` is Bitcoin dominance.",
+ "market_cap_change_percentage_24h_usd": "Percentage change in total market capitalization over 24 hours, in USD.",
+ "volume_change_percentage_24h_usd": "Percentage change in total trading volume over 24 hours, in USD.",
+ "updated_at": "Timestamp CoinGecko last refreshed these totals, as a UNIX timestamp.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/coingecko.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/coingecko.py
index dcafe5bc2ae4..434a18aa7510 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/coingecko.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/coingecko.py
@@ -1,18 +1,39 @@
import dataclasses
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from requests import Response
+from structlog.types import FilteringBoundLogger
-from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import COINGECKO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import (
+ CHART_WINDOW_DAYS,
+ COINGECKO_ENDPOINTS,
+ DEFAULT_HISTORY_DAYS,
+ MARKET_CHART_ENDPOINT,
+ MAX_COINS,
+ MINIMUM_START_DATE,
+ OHLC_ENDPOINT,
+ CoinGeckoEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
+ RESTClient,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ create_auth,
+ create_response_hooks,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ ResponseAction,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -28,6 +49,12 @@ PLAN_PRO = "pro"
# /coins/markets allows up to 250 per page; other paginated endpoints accept it too.
PAGE_SIZE = 250
MAX_RETRY_ATTEMPTS = 6
+# Per-request (connect, read) ceiling. Left unset, a server that accepts the connection and then
+# never answers holds an import worker open for the whole run. The per-coin endpoints issue one
+# request per coin per page or per window, so one stalled request blocks every coin behind it.
+REQUEST_TIMEOUT_SECONDS = 60
+
+NO_COINS_ERROR = "No coin IDs configured"
# CoinGecko signals rate limiting via a 429 status (retried by the client on status alone) and, on the
# keyless/demo tier, via a 200/4xx body carrying ``{"status":{"error_code":429}}``. The client only
@@ -36,11 +63,26 @@ MAX_RETRY_ATTEMPTS = 6
# same way the old structural ``status.error_code == 429`` check was whitespace-agnostic.
RATE_LIMIT_BODY_MARKERS = ('"error_code":429', '"error_code": 429')
+_RATE_LIMIT_RESPONSE_ACTIONS: list[ResponseAction] = [
+ {"content": marker, "action": "retry"} for marker in RATE_LIMIT_BODY_MARKERS
+]
+
+# Column each of the three parallel series in a market chart response lands in.
+_MARKET_CHART_SERIES = {"prices": "price", "market_caps": "market_cap", "total_volumes": "total_volume"}
+
+_OHLC_COLUMNS = ("open", "high", "low", "close")
+
[email protected](frozen=True)
class CoinGeckoResumeConfig:
# Next page to fetch for paginated endpoints. Unused for single-response reference endpoints.
page: int = 1
+ # Index into the configured coin list of the coin the fan-out resumes at. Only the paginated
+ # per-coin endpoints checkpoint mid-list; the timeseries endpoints resume whole windows.
+ coin_index: int = 0
+ # ISO date (YYYY-MM-DD) of the first day the next window should fetch, for the timeseries
+ # endpoints. None for the endpoints that fetch no date range.
+ next_start: str | None = None
def _base_url(plan: str) -> str:
@@ -58,6 +100,37 @@ def _headers(plan: str, api_key: str) -> dict[str, str]:
return headers
+def _client_config(plan: str, api_key: str) -> ClientConfig:
+ return {
+ "base_url": _base_url(plan),
+ # Only non-secret headers here; the API key rides in the framework auth config so its
+ # value is redacted from logs and raised error messages.
+ "headers": {"Accept": "application/json"},
+ "auth": {
+ "type": "api_key",
+ "api_key": api_key,
+ "name": _api_key_header(plan),
+ "location": "header",
+ },
+ "max_retries": MAX_RETRY_ATTEMPTS,
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ }
+
+
+def _rest_client(plan: str, api_key: str) -> RESTClient:
+ """Client for the per-coin endpoints, whose fan-out over the configured coin list can't be
+ expressed declaratively. Read off the same config as the declarative path so the two can't
+ drift apart."""
+ config = _client_config(plan, api_key)
+ return RESTClient(
+ base_url=config["base_url"],
+ headers=config["headers"],
+ auth=create_auth(config["auth"]),
+ max_retry_attempts=config["max_retries"],
+ request_timeout=config["request_timeout"],
+ )
+
+
class CoinGeckoPagePaginator(PageNumberPaginator):
"""CoinGecko paginates with ``page``/``per_page``. A short page (fewer than ``per_page`` items) or
an empty page is the last one — stop without paying an extra empty-page request, since the free
@@ -77,51 +150,330 @@ class CoinGeckoPagePaginator(PageNumberPaginator):
self._has_next_page = False
-def coingecko_source(
+def _parse_coin_ids(coin_ids: Optional[str]) -> list[str]:
+ if not coin_ids:
+ return []
+ # Split one part further than the cap so the MAX_COINS check downstream can still see that the
+ # list overflowed, while a pathological string can never materialize more than that many parts.
+ coins: list[str] = []
+ seen: set[str] = set()
+ for raw in coin_ids.split(",", MAX_COINS + 1)[: MAX_COINS + 1]:
+ coin = raw.strip().lower()
+ if coin and coin not in seen:
+ seen.add(coin)
+ coins.append(coin)
+ return coins
+
+
+def _coins_for_fanout(coin_ids: Optional[str], logger: FilteringBoundLogger) -> list[str]:
+ coins = _parse_coin_ids(coin_ids)
+ if not coins:
+ raise ValueError(NO_COINS_ERROR)
+ if len(coins) > MAX_COINS:
+ logger.warning(f"CoinGecko: more than {MAX_COINS} coin IDs configured, syncing only the first {MAX_COINS}")
+ coins = coins[:MAX_COINS]
+ return coins
+
+
+def _coerce_date(value: Any) -> Optional[date]:
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str):
+ try:
+ return date.fromisoformat(value.strip())
+ except ValueError:
+ return None
+ return None
+
+
+def default_start_date() -> date:
+ return datetime.now(UTC).date() - timedelta(days=DEFAULT_HISTORY_DAYS)
+
+
+def start_date_error(start_date: Optional[str]) -> Optional[str]:
+ """Validation-time check for an unusable `start_date`.
+
+ A value earlier than `MINIMUM_START_DATE` is rejected here (credential validation) so a new
+ source can't be configured to run away, and re-checked in `_chart_pages` so a previously stored
+ configuration can't either. A value that doesn't parse is rejected too, because the sync falls
+ back to the default window and would otherwise sync a different range than the one asked for.
+ """
+ if not start_date or not start_date.strip():
+ return None
+
+ parsed = _coerce_date(start_date)
+ if parsed is None:
+ return f"Couldn't read '{start_date}' as a date. Use the format YYYY-MM-DD, for example 2025-01-01."
+ if parsed < MINIMUM_START_DATE:
+ return f"CoinGecko has no data before {MINIMUM_START_DATE.isoformat()}. Enter that date or a later one."
+ return None
+
+
+def _from_millis(value: Any) -> Optional[datetime]:
+ """Chart timestamps arrive as UNIX milliseconds. A non-numeric value means the point isn't
+ usable as a cursor or a key, so callers drop it rather than writing a column of mixed types."""
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ return datetime.fromtimestamp(value / 1000, tz=UTC)
+
+
+def _ticker_row(row: dict[str, Any], coin_id: str) -> dict[str, Any]:
+ """Pin the queried coin onto the row and lift the exchange id out of the nested ``market``
+ object, so every part of the primary key is a flat, always-present column."""
+ ticker = dict(row)
+ ticker["coin_id"] = coin_id
+ market = ticker.get("market")
+ ticker["market_identifier"] = market.get("identifier") if isinstance(market, dict) else None
+ return ticker
+
+
+def _market_chart_rows(page: list[Any], coin_id: str) -> list[dict[str, Any]]:
+ """Zip the three parallel ``[timestamp, value]`` series into one row per timestamp.
+
+ ``/coins/{id}/market_chart/range`` answers with a single object, which the client hands over as
+ a one-item page."""
+ body = page[0] if len(page) == 1 and isinstance(page[0], dict) else None
+ if body is None:
+ raise ValueError(
+ "Required a market chart object carrying price, market cap and volume series. "
+ "The API response shape may have changed."
+ )
+
+ rows: dict[datetime, dict[str, Any]] = {}
+ for key, column in _MARKET_CHART_SERIES.items():
+ for point in body.get(key) or []:
+ if not isinstance(point, list) or len(point) < 2:
+ continue
+ timestamp = _from_millis(point[0])
+ if timestamp is None:
+ continue
+ rows.setdefault(timestamp, {"coin_id": coin_id, "timestamp": timestamp})[column] = point[1]
+ return [rows[timestamp] for timestamp in sorted(rows)]
+
+
+def _ohlc_rows(page: list[Any], coin_id: str) -> list[dict[str, Any]]:
+ """Map each ``[timestamp, open, high, low, close]`` candle onto a row.
+
+ ``/coins/{id}/ohlc/range`` answers with a bare array of candles, which is the page itself."""
+ rows: list[dict[str, Any]] = []
+ for candle in page:
+ if not isinstance(candle, list) or len(candle) < 5:
+ continue
+ timestamp = _from_millis(candle[0])
+ if timestamp is None:
+ continue
+ rows.append({"coin_id": coin_id, "timestamp": timestamp, **dict(zip(_OHLC_COLUMNS, candle[1:5]))})
+ return rows
+
+
+_CHART_ROW_BUILDERS: dict[str, Callable[[list[Any], str], list[dict[str, Any]]]] = {
+ MARKET_CHART_ENDPOINT: _market_chart_rows,
+ OHLC_ENDPOINT: _ohlc_rows,
+}
+
+
+def _ticker_pages(
+ client: RESTClient,
+ config: CoinGeckoEndpointConfig,
+ coins: list[str],
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ hooks = create_response_hooks(_RATE_LIMIT_RESPONSE_ACTIONS, resource_name=config.name)
+ page_size = config.page_size or PAGE_SIZE
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_index = resume.coin_index if resume is not None else 0
+
+ for index in range(start_index, len(coins)):
+ coin_id = coins[index]
+ initial_paginator_state = {"page": resume.page} if resume is not None and index == start_index else None
+
+ def save_checkpoint(state: Optional[dict[str, Any]], coin_index: int = index) -> None:
+ # Persist AFTER a page is yielded so a crash re-yields the last page rather than
+ # skipping it. No next page means this coin is done, so the checkpoint moves on.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(
+ CoinGeckoResumeConfig(page=int(state["page"]), coin_index=coin_index)
+ )
+ else:
+ resumable_source_manager.save_state(CoinGeckoResumeConfig(coin_index=coin_index + 1))
+
+ for page in client.paginate(
+ path=config.path.format(coin_id=coin_id),
+ # The endpoint takes no per_page parameter, because its page size is fixed at 100,
+ # which only feeds the paginator's short-page check.
+ params=dict(config.extra_params),
+ paginator=CoinGeckoPagePaginator(page_size, config.max_pages),
+ data_selector=config.data_selector,
+ data_selector_required=True,
+ hooks=hooks,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ):
+ yield [_ticker_row(row, coin_id) for row in page]
+
+
+def _fetch_window(
+ client: RESTClient,
+ config: CoinGeckoEndpointConfig,
+ coin_id: str,
+ params: dict[str, Any],
+ hooks: Optional[dict[str, Any]],
+) -> list[Any]:
+ # A window is one request, so the paginator yields at most one page. Walked with a loop rather
+ # than next(): a StopIteration escaping into the calling generator surfaces as a RuntimeError.
+ for page in client.paginate(
+ path=config.path.format(coin_id=coin_id),
+ params=params,
+ paginator=SinglePagePaginator(),
+ data_selector=config.data_selector,
+ hooks=hooks,
+ ):
+ return page
+ return []
+
+
+def _chart_pages(
+ client: RESTClient,
+ config: CoinGeckoEndpointConfig,
+ coins: list[str],
+ start_date: Optional[str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ hooks = create_response_hooks(_RATE_LIMIT_RESPONSE_ACTIONS, resource_name=config.name)
+ build_rows = _CHART_ROW_BUILDERS[config.name]
+ window_days = config.window_days or CHART_WINDOW_DAYS
+
+ # Re-checked here (not just at credential validation) so a configuration stored before this
+ # floor existed can't schedule a runaway backfill either.
+ base_start = max(_coerce_date(start_date) or default_start_date(), MINIMUM_START_DATE)
+ if should_use_incremental_field:
+ last_value = _coerce_date(db_incremental_field_last_value)
+ if last_value is not None:
+ # Start at the last synced day rather than the day after: that day was still moving
+ # when it first landed, so re-reading it restates it and merge dedupes the overlap.
+ base_start = max(base_start, last_value)
+
+ end_boundary = datetime.now(UTC).date()
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = base_start
+ if resume is not None:
+ resumed_start = _coerce_date(resume.next_start)
+ if resumed_start is not None:
+ cursor = resumed_start
+ logger.debug(f"CoinGecko: resuming {config.name} from {cursor.isoformat()}")
+
+ while cursor <= end_boundary:
+ window_end = min(cursor + timedelta(days=window_days - 1), end_boundary)
+ params: dict[str, Any] = {**config.extra_params, "from": cursor.isoformat(), "to": window_end.isoformat()}
+
+ # One batch per window, holding every coin's rows for it. The pipeline commits the
+ # incremental watermark to the highest timestamp it has seen after each batch, so a batch
+ # must never carry one coin past a window another coin has not been fetched for: the next
+ # job starts from that watermark and would skip the coin left behind. Whole windows keep
+ # the watermark behind every coin, and make `sort_mode="asc"` true batch over batch.
+ # A window is one daily point per coin per day, so it stays small enough to hold.
+ window_rows: list[dict[str, Any]] = []
+ for coin_id in coins:
+ window_rows.extend(build_rows(_fetch_window(client, config, coin_id, params, hooks), coin_id))
+
+ if window_rows:
+ yield window_rows
+
+ cursor = window_end + timedelta(days=1)
+ # Saved AFTER yielding so a crash re-fetches the last window (merge dedupes it) instead of
+ # skipping it.
+ resumable_source_manager.save_state(CoinGeckoResumeConfig(next_start=cursor.isoformat()))
+
+
+def _per_coin_source(
plan: str,
api_key: str,
- endpoint: str,
+ config: CoinGeckoEndpointConfig,
+ coin_ids: Optional[str],
+ start_date: Optional[str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ client = _rest_client(plan, api_key)
+
+ if config.date_field is None:
+ return SourceResponse(
+ name=config.name,
+ items=lambda: _ticker_pages(
+ client=client,
+ config=config,
+ coins=_coins_for_fanout(coin_ids, logger),
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ # A market-pair snapshot carries no stable created_at to partition on.
+ partition_count=None,
+ partition_size=None,
+ )
+
+ return SourceResponse(
+ name=config.name,
+ items=lambda: _chart_pages(
+ client=client,
+ config=config,
+ coins=_coins_for_fanout(coin_ids, logger),
+ start_date=start_date,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.date_field],
+ sort_mode="asc",
+ )
+
+
+def _top_level_source(
+ plan: str,
+ api_key: str,
+ config: CoinGeckoEndpointConfig,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
- db_incremental_field_last_value: Optional[Any] = None,
+ db_incremental_field_last_value: Optional[Any],
) -> SourceResponse:
- config = COINGECKO_ENDPOINTS[endpoint]
-
page_size = config.page_size or PAGE_SIZE
params: dict[str, Any] = dict(config.extra_params)
if config.paginated:
params["per_page"] = page_size
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _base_url(plan),
- # Only non-secret headers here; the API key rides in the framework auth config below so
- # its value is redacted from logs and raised error messages.
- "headers": {"Accept": "application/json"},
- "auth": {
- "type": "api_key",
- "api_key": api_key,
- "name": _api_key_header(plan),
- "location": "header",
- },
- "max_retries": MAX_RETRY_ATTEMPTS,
- },
+ "client": _client_config(plan, api_key),
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
"path": config.path,
"params": params,
- # Bare-array bodies. A non-list body means the response shape changed (or an
- # unexpected error envelope) — fail loud rather than syncing a garbage row.
+ # Bare-array bodies, or the rows under the endpoint's envelope key. A body that
+ # carries neither means the response shape changed (or an unexpected error
+ # envelope) — fail loud rather than syncing a garbage row.
+ "data_selector": config.data_selector,
"data_selector_required": True,
"paginator": CoinGeckoPagePaginator(page_size, config.max_pages)
if config.paginated
else SinglePagePaginator(),
# The keyless/demo tier reports rate limiting inside a success-status body; the
# client retries on status only, so promote that in-body signal to a retry.
- "response_actions": [{"content": marker, "action": "retry"} for marker in RATE_LIMIT_BODY_MARKERS],
+ "response_actions": _RATE_LIMIT_RESPONSE_ACTIONS,
},
}
],
@@ -149,7 +501,7 @@ def coingecko_source(
)
return SourceResponse(
- name=endpoint,
+ name=config.name,
items=lambda: resource,
primary_keys=config.primary_keys,
# Snapshot/reference endpoints expose no stable created_at, so there's nothing to partition on.
@@ -159,6 +511,45 @@ def coingecko_source(
)
+def coingecko_source(
+ plan: str,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+ coin_ids: Optional[str] = None,
+ start_date: Optional[str] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = COINGECKO_ENDPOINTS[endpoint]
+
+ if config.per_coin:
+ return _per_coin_source(
+ plan=plan,
+ api_key=api_key,
+ config=config,
+ coin_ids=coin_ids,
+ start_date=start_date,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+ return _top_level_source(
+ plan=plan,
+ api_key=api_key,
+ config=config,
+ team_id=team_id,
+ job_id=job_id,
+ resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+
def validate_credentials(plan: str, api_key: str) -> bool:
"""Confirm the key is genuine by pinging with the plan's auth header. A valid key returns 200;
an invalid one returns 401. Transient/network failures also map to False (not validated)."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/settings.py
index 58db2936cd6f..22ed9e6874d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/settings.py
@@ -1,9 +1,39 @@
from dataclasses import field
+from datetime import date
from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
+# The endpoints that fan out over the configured coin list rather than being fetched once, named so
+# the fan-out and row-shaping paths reference them without repeating the string.
+TICKERS_ENDPOINT = "coins_tickers"
+MARKET_CHART_ENDPOINT = "coins_market_chart"
+OHLC_ENDPOINT = "coins_ohlc"
+
+# /coins/{id}/tickers is fixed at 100 items per page, unlike the 250 the other list endpoints take.
+TICKERS_PAGE_SIZE = 100
+
+# Days per request for the timeseries endpoints. /coins/{id}/ohlc/range caps a daily-interval
+# request at 180 candles; market_chart/range publishes no cap, so it reuses the same window rather
+# than guessing a larger one.
+CHART_WINDOW_DAYS = 180
+
+# Each coin costs a request per page (tickers) or per date window (timeseries), so an unbounded
+# coin list can burn a whole month of credits in one sync. CoinGecko lists far more coins than a
+# sync can walk, so the coin list is a deliberate pick rather than a slice of the whole catalog.
+MAX_COINS = 25
+
+# How far back the timeseries endpoints reach on a first sync when no start date is set. The Demo
+# plan only serves the past 365 days, so this default is the most history every plan can fetch.
+DEFAULT_HISTORY_DAYS = 365
+
+# Floor for any configured start date, including one stored before this floor existed. CoinGecko's
+# granular history begins in early 2018, so an earlier date buys no rows while fanning out into an
+# unbounded number of empty request windows and Redis checkpoints.
+MINIMUM_START_DATE = date(2018, 1, 1)
+
@frozen
class CoinGeckoEndpointConfig:
@@ -15,8 +45,10 @@ class CoinGeckoEndpointConfig:
# Whether the endpoint supports page/per_page pagination. Reference endpoints (e.g. /coins/list)
# return the whole collection in one response and ignore pagination params.
paginated: bool = False
- # per_page value to request. None means the source default (250). Some endpoints cap it lower
- # (e.g. /insights allows at most 20), so it is overridable per endpoint.
+ # Page size. None means the source default (250). Some endpoints cap it lower (e.g. /insights
+ # allows at most 20), so it is overridable per endpoint. Sent as `per_page` where the endpoint
+ # takes it; /coins/{id}/tickers has no such parameter, so there it only tells the paginator how
+ # wide a full page is.
page_size: int | None = None
# Hard cap on the page number to request, for endpoints the API refuses to page past
# (e.g. /insights rejects page > 20). None means walk until a short/empty page.
@@ -24,6 +56,16 @@ class CoinGeckoEndpointConfig:
# Extra static query params (e.g. vs_currency for /coins/markets).
extra_params: dict[str, str] = field(default_factory=dict)
should_sync_default: bool = True
+ # jsonpath to the rows inside the response envelope. None means the body is a bare array.
+ data_selector: str | None = None
+ # Whether ``path`` carries a ``{coin_id}`` placeholder, making the endpoint a fan-out over the
+ # configured coin list instead of a single top-level fetch.
+ per_coin: bool = False
+ # Date-range size per request for the timeseries endpoints, so a long backfill is split into
+ # windows the API accepts. None for the snapshot endpoints.
+ window_days: int | None = None
+ # Timestamp column the timeseries endpoints are keyed, partitioned and filtered on.
+ date_field: str | None = None
COINGECKO_ENDPOINTS: dict[str, CoinGeckoEndpointConfig] = {
@@ -77,11 +119,72 @@ COINGECKO_ENDPOINTS: dict[str, CoinGeckoEndpointConfig] = {
max_pages=20,
primary_keys=["title", "posted_at"],
),
+ # Market pairs for a coin across centralized and decentralized exchanges, which is the join
+ # between the coins and exchanges we already sync. Paginated at a fixed 100 per page, wrapped in a
+ # ``tickers`` envelope. A ticker carries no id, so key on the coin, the exchange and the pair.
+ TICKERS_ENDPOINT: CoinGeckoEndpointConfig(
+ name=TICKERS_ENDPOINT,
+ path="/coins/{coin_id}/tickers",
+ per_coin=True,
+ paginated=True,
+ page_size=TICKERS_PAGE_SIZE,
+ data_selector="tickers",
+ primary_keys=["coin_id", "market_identifier", "base", "target"],
+ should_sync_default=False,
+ ),
+ # Daily price, market cap and volume history per coin, in USD. Fetched in date windows, so the
+ # `from`/`to` filter makes this a genuinely incremental endpoint.
+ MARKET_CHART_ENDPOINT: CoinGeckoEndpointConfig(
+ name=MARKET_CHART_ENDPOINT,
+ path="/coins/{coin_id}/market_chart/range",
+ per_coin=True,
+ window_days=CHART_WINDOW_DAYS,
+ date_field="timestamp",
+ primary_keys=["coin_id", "timestamp"],
+ # Without `interval` the API picks granularity from the window length, so a shorter
+ # incremental window would return hourly points that don't line up with the daily ones
+ # already synced. Pin it so every window returns the same grain.
+ extra_params={"vs_currency": "usd", "interval": "daily"},
+ should_sync_default=False,
+ ),
+ # Daily OHLC candles per coin, in USD. Requires a Pro key on the Analyst plan or above.
+ OHLC_ENDPOINT: CoinGeckoEndpointConfig(
+ name=OHLC_ENDPOINT,
+ path="/coins/{coin_id}/ohlc/range",
+ per_coin=True,
+ window_days=CHART_WINDOW_DAYS,
+ date_field="timestamp",
+ primary_keys=["coin_id", "timestamp"],
+ # `interval` is required here, and `daily` is what the 180-day window above is sized for.
+ extra_params={"vs_currency": "usd", "interval": "daily"},
+ should_sync_default=False,
+ ),
+ # Market-wide totals: active coins, exchange count, total market cap and volume per currency,
+ # and per-coin market cap dominance. One object under a `data` envelope, so one row per sync.
+ "global_market_data": CoinGeckoEndpointConfig(
+ name="global_market_data",
+ path="/global",
+ data_selector="data",
+ primary_keys=["updated_at"],
+ ),
}
ENDPOINTS = tuple(COINGECKO_ENDPOINTS.keys())
-# CoinGecko's catalog/snapshot endpoints expose no server-side updated_after/since filter, so every
-# exposed endpoint is full refresh only. The map is kept (empty) to mirror the other sources' shape
-# and make adding a server-side-filterable endpoint later an additive change.
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in COINGECKO_ENDPOINTS}
+# Only the timeseries endpoints take a server-side date filter. Every catalog and snapshot endpoint
+# exposes no updated_after/since parameter, so those stay full refresh with an empty candidate list.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [incremental_field(config.date_field)] if config.date_field else []
+ for name, config in COINGECKO_ENDPOINTS.items()
+}
+
+# The timeseries endpoints re-read the window holding the last synced day, so the still-moving
+# current day is restated instead of frozen at whatever it was first imported as. Append would
+# write a second row for every day in that overlap, so merge is the only valid incremental mode.
+MERGE_ONLY_ENDPOINTS = tuple(name for name, config in COINGECKO_ENDPOINTS.items() if config.date_field)
+
+# The per-coin endpoints can only sync once coin IDs are configured, so they start disabled rather
+# than queueing a sync that can only fail.
+SHOULD_SYNC_DEFAULT = {name: config.should_sync_default for name, config in COINGECKO_ENDPOINTS.items()}
+
+PER_COIN_ENDPOINTS = tuple(name for name, config in COINGECKO_ENDPOINTS.items() if config.per_coin)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/source.py
index a0d013c26c22..804cf3a555f4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/source.py
@@ -10,15 +10,22 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldSelectConfigOption,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.coingecko import (
+ NO_COINS_ERROR,
PLAN_DEMO,
PLAN_PRO,
CoinGeckoResumeConfig,
+ _parse_coin_ids,
coingecko_source,
+ start_date_error,
validate_credentials as validate_coingecko_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ MAX_COINS,
+ MERGE_ONLY_ENDPOINTS,
+ PER_COIN_ENDPOINTS,
+ SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
@@ -58,7 +65,9 @@ class CoinGeckoSource(ResumableSource[CoinGeckoSourceConfig, CoinGeckoResumeConf
Create a key in your [CoinGecko developer dashboard](https://www.coingecko.com/en/developers/dashboard). Free **Demo** keys (`x-cg-demo-api-key`) and paid **Pro** keys (`x-cg-pro-api-key`) use different hosts — pick the plan that matches your key.
-CoinGecko enforces tight per-minute rate limits and monthly credit caps, especially on the Demo plan, so large tables may take a while to sync.""",
+CoinGecko enforces tight per-minute rate limits and monthly credit caps, especially on the Demo plan, so large tables may take a while to sync.
+
+The market pairs, historical chart and OHLC tables are per coin, so they only sync once you list the coins you want.""",
iconPath="/static/services/coingecko.png",
docsUrl="https://posthog.com/docs/cdp/sources/coingecko",
fields=cast(
@@ -82,6 +91,24 @@ CoinGecko enforces tight per-minute rate limits and monthly credit caps, especia
placeholder="CG-...",
secret=True,
),
+ SourceFieldInputConfig(
+ name="coin_ids",
+ label="Coin IDs",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="bitcoin, ethereum, solana",
+ secret=False,
+ caption=f"Comma-separated list of CoinGecko coin IDs, as they appear in the `coins_list` table. Up to {MAX_COINS} coins. The market pairs, historical chart and OHLC tables need this. The market-wide tables sync without it.",
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2025-01-01",
+ secret=False,
+ caption="Earliest day of history to sync for the chart tables (YYYY-MM-DD). Defaults to one year ago, which is as far back as the Demo plan serves.",
+ ),
],
),
)
@@ -100,6 +127,7 @@ CoinGecko enforces tight per-minute rate limits and monthly credit caps, especia
# not the per-request path/query.
"401 Client Error: Unauthorized for url: https://api.coingecko.com": "Your CoinGecko API key is invalid or has been revoked. Create a new Demo key in your CoinGecko dashboard, then reconnect.",
"401 Client Error: Unauthorized for url: https://pro-api.coingecko.com": "Your CoinGecko Pro API key is invalid or has been revoked. Create a new Pro key in your CoinGecko dashboard, then reconnect.",
+ NO_COINS_ERROR: "Add at least one coin ID in the source settings to sync this table.",
}
def get_schemas(
@@ -111,10 +139,13 @@ CoinGecko enforces tight per-minute rate limits and monthly credit caps, especia
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every exposed endpoint is a catalog/snapshot with no server-side timestamp filter, so all
- # are full refresh only — no endpoint carries incremental fields, so build_endpoint_schemas
- # leaves supports_incremental/supports_append False.
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ merge_only=MERGE_ONLY_ENDPOINTS,
+ should_sync_default=SHOULD_SYNC_DEFAULT,
+ )
def validate_credentials(
self,
@@ -123,6 +154,19 @@ CoinGecko enforces tight per-minute rate limits and monthly credit caps, especia
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
+ coins = _parse_coin_ids(config.coin_ids)
+ if len(coins) > MAX_COINS:
+ return False, f"Too many coin IDs. List at most {MAX_COINS}."
+
+ error = start_date_error(config.start_date)
+ if error is not None:
+ return False, error
+
+ # Coin IDs are only checked per schema: the market-wide tables sync without them, so a
+ # source that syncs only those must still connect.
+ if not coins and schema_name in PER_COIN_ENDPOINTS:
+ return False, "Add at least one coin ID to sync this table."
+
if validate_coingecko_credentials(config.plan, config.api_key):
return True, None
@@ -148,6 +192,12 @@ CoinGecko enforces tight per-minute rate limits and monthly credit caps, especia
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
+ logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
- db_incremental_field_last_value=None, # every CoinGecko endpoint is full refresh
+ coin_ids=config.coin_ids,
+ start_date=config.start_date,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko.py
index ac6473f2fb95..1529a4089e8b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko.py
@@ -1,4 +1,5 @@
import json
+from datetime import UTC, datetime, time, timedelta
from typing import Any
import pytest
@@ -10,6 +11,7 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.coingecko import (
DEMO_BASE_URL,
+ NO_COINS_ERROR,
PAGE_SIZE,
PLAN_DEMO,
PLAN_PRO,
@@ -18,7 +20,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.
coingecko_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import COINGECKO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import (
+ CHART_WINDOW_DAYS,
+ COINGECKO_ENDPOINTS,
+ DEFAULT_HISTORY_DAYS,
+ MAX_COINS,
+ TICKERS_PAGE_SIZE,
+)
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -76,17 +84,35 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return snapshots
-def _source(plan: str, api_key: str, endpoint: str, manager: mock.MagicMock):
+def _source(
+ plan: str,
+ api_key: str,
+ endpoint: str,
+ manager: mock.MagicMock,
+ coin_ids: str | None = None,
+ start_date: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+):
return coingecko_source(
plan=plan,
api_key=api_key,
endpoint=endpoint,
team_id=1,
job_id="j",
+ logger=mock.MagicMock(),
resumable_source_manager=manager,
+ coin_ids=coin_ids,
+ start_date=start_date,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
)
+def _today() -> Any:
+ return datetime.now(UTC).date()
+
+
def _rows(source_response) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
@@ -335,3 +361,372 @@ class TestSourceResponse:
response = _source(PLAN_DEMO, "key", endpoint, _manager())
assert response.name == endpoint
assert response.primary_keys == COINGECKO_ENDPOINTS[endpoint].primary_keys
+
+
+class TestGlobalMarketData:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unwraps_the_data_envelope_into_one_row(self, MockSession) -> None:
+ session = MockSession.return_value
+ # /global is the one endpoint whose rows sit under an envelope key rather than being a bare
+ # array, so a missing selector would sync zero rows or fail the shape check.
+ totals = {"active_cryptocurrencies": 17397, "markets": 1476, "updated_at": 1779878351}
+ _wire(session, [_response({"data": totals})])
+
+ assert _rows(_source(PLAN_DEMO, "key", "global_market_data", _manager())) == [totals]
+ assert session.send.call_count == 1
+
+
+class TestCoinTickers:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_over_configured_coins(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(
+ session,
+ [
+ _response(
+ {
+ "name": "Bitcoin",
+ "tickers": [{"base": "BTC", "target": "USDT", "market": {"identifier": "binance"}}],
+ }
+ ),
+ _response(
+ {
+ "name": "Ethereum",
+ "tickers": [{"base": "ETH", "target": "USDT", "market": {"identifier": "kraken"}}],
+ }
+ ),
+ ],
+ )
+
+ rows = _rows(_source(PLAN_DEMO, "key", "coins_tickers", _manager(), coin_ids="bitcoin, ethereum"))
+
+ assert [row["coin_id"] for row in rows] == ["bitcoin", "ethereum"]
+ # The exchange id is lifted out of the nested `market` object so every part of the primary
+ # key is a flat column.
+ assert [row["market_identifier"] for row in rows] == ["binance", "kraken"]
+ assert snaps[0]["url"].endswith("/coins/bitcoin/tickers")
+ assert snaps[1]["url"].endswith("/coins/ethereum/tickers")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_market_identifier_survives_a_missing_market(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response({"name": "Bitcoin", "tickers": [{"base": "BTC", "target": "USDT"}]})])
+
+ rows = _rows(_source(PLAN_DEMO, "key", "coins_tickers", _manager(), coin_ids="bitcoin"))
+ assert rows[0]["market_identifier"] is None
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pages_one_coin_then_moves_to_the_next(self, MockSession) -> None:
+ session = MockSession.return_value
+ full_page = [
+ {"base": f"B{i}", "target": "USDT", "market": {"identifier": "binance"}} for i in range(TICKERS_PAGE_SIZE)
+ ]
+ snaps = _wire(
+ session,
+ [
+ _response({"name": "Bitcoin", "tickers": full_page}),
+ _response(
+ {
+ "name": "Bitcoin",
+ "tickers": [{"base": "last", "target": "USDT", "market": {"identifier": "binance"}}],
+ }
+ ),
+ _response(
+ {
+ "name": "Ethereum",
+ "tickers": [{"base": "ETH", "target": "USDT", "market": {"identifier": "kraken"}}],
+ }
+ ),
+ ],
+ )
+
+ manager = _manager()
+ rows = _rows(_source(PLAN_DEMO, "key", "coins_tickers", manager, coin_ids="bitcoin,ethereum"))
+
+ assert len(rows) == TICKERS_PAGE_SIZE + 2
+ assert [snap["params"].get("page") for snap in snaps] == [1, 2, 1]
+ # The endpoint has no per_page parameter, so sending one would be rejected.
+ assert all("per_page" not in snap["params"] for snap in snaps)
+ assert manager.save_state.call_args_list == [
+ mock.call(CoinGeckoResumeConfig(page=2, coin_index=0)),
+ mock.call(CoinGeckoResumeConfig(coin_index=1)),
+ mock.call(CoinGeckoResumeConfig(coin_index=2)),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_at_the_saved_coin_and_page(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response({"name": "Solana", "tickers": [{"base": "SOL", "target": "USDT"}]})])
+
+ manager = _manager(CoinGeckoResumeConfig(page=4, coin_index=2))
+ rows = _rows(_source(PLAN_DEMO, "key", "coins_tickers", manager, coin_ids="bitcoin,ethereum,solana"))
+
+ assert session.send.call_count == 1
+ assert snaps[0]["url"].endswith("/coins/solana/tickers")
+ assert snaps[0]["params"]["page"] == 4
+ assert [row["coin_id"] for row in rows] == ["solana"]
+
+ @parameterized.expand([("blank", ""), ("unset", None), ("separators only", " , ")])
+ def test_no_coins_fails_with_the_curated_error(self, _name: str, coin_ids: str | None) -> None:
+ with pytest.raises(ValueError, match=NO_COINS_ERROR):
+ _rows(_source(PLAN_DEMO, "key", "coins_tickers", _manager(), coin_ids=coin_ids))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_coin_list_is_capped(self, MockSession) -> None:
+ session = MockSession.return_value
+ # A stored configuration can carry more coins than the cap, and each one costs a request.
+ _wire(session, [_response({"name": "c", "tickers": []}) for _ in range(MAX_COINS + 5)])
+
+ coin_ids = ",".join(f"coin-{i}" for i in range(MAX_COINS + 5))
+ _rows(_source(PLAN_DEMO, "key", "coins_tickers", _manager(), coin_ids=coin_ids))
+ assert session.send.call_count == MAX_COINS
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_duplicate_coins_are_fetched_once(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response({"name": "Bitcoin", "tickers": []})])
+
+ _rows(_source(PLAN_DEMO, "key", "coins_tickers", _manager(), coin_ids="bitcoin, BITCOIN , bitcoin"))
+ assert session.send.call_count == 1
+
+
+class TestMarketChart:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_zips_the_three_series_into_one_row_per_timestamp(self, MockSession) -> None:
+ session = MockSession.return_value
+ first, second = 1764547200000, 1764633600000
+ _wire(
+ session,
+ [
+ _response(
+ {
+ "prices": [[first, 90832.0], [second, 90360.0]],
+ "market_caps": [[first, 1.5e12], [second, 1.6e12]],
+ "total_volumes": [[first, 1.8e10], [second, 1.9e10]],
+ }
+ )
+ ],
+ )
+
+ start = (_today() - timedelta(days=5)).isoformat()
+ rows = _rows(_source(PLAN_PRO, "key", "coins_market_chart", _manager(), coin_ids="bitcoin", start_date=start))
+
+ assert rows == [
+ {
+ "coin_id": "bitcoin",
+ "timestamp": datetime.fromtimestamp(first / 1000, tz=UTC),
+ "price": 90832.0,
+ "market_cap": 1.5e12,
+ "total_volume": 1.8e10,
+ },
+ {
+ "coin_id": "bitcoin",
+ "timestamp": datetime.fromtimestamp(second / 1000, tz=UTC),
+ "price": 90360.0,
+ "market_cap": 1.6e12,
+ "total_volume": 1.9e10,
+ },
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_series_of_unequal_length_still_line_up(self, MockSession) -> None:
+ session = MockSession.return_value
+ first, second = 1764547200000, 1764633600000
+ # CoinGecko can return a volume point the price series has not caught up with yet.
+ _wire(session, [_response({"prices": [[first, 1.0]], "market_caps": [], "total_volumes": [[second, 2.0]]})])
+
+ start = (_today() - timedelta(days=5)).isoformat()
+ rows = _rows(_source(PLAN_PRO, "key", "coins_market_chart", _manager(), coin_ids="bitcoin", start_date=start))
+
+ assert [sorted(row.keys()) for row in rows] == [
+ ["coin_id", "price", "timestamp"],
+ ["coin_id", "timestamp", "total_volume"],
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_non_object_body_fails_loud(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response("unexpected")])
+
+ start = (_today() - timedelta(days=5)).isoformat()
+ with pytest.raises(ValueError, match="market chart object"):
+ _rows(_source(PLAN_PRO, "key", "coins_market_chart", _manager(), coin_ids="bitcoin", start_date=start))
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pins_daily_granularity_and_usd(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response({"prices": [], "market_caps": [], "total_volumes": []})])
+
+ start = (_today() - timedelta(days=5)).isoformat()
+ _rows(_source(PLAN_PRO, "key", "coins_market_chart", _manager(), coin_ids="bitcoin", start_date=start))
+
+ # Without an explicit interval the API picks granularity from the window length, so a short
+ # incremental window would return hourly points that don't line up with the synced daily ones.
+ assert snaps[0]["params"]["interval"] == "daily"
+ assert snaps[0]["params"]["vs_currency"] == "usd"
+
+
+class TestOhlc:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_maps_candles_onto_rows(self, MockSession) -> None:
+ session = MockSession.return_value
+ closed_at = 1764547200000
+ _wire(session, [_response([[closed_at, 90832.0, 91905.0, 90406.0, 90406.0]])])
+
+ start = (_today() - timedelta(days=5)).isoformat()
+ rows = _rows(_source(PLAN_PRO, "key", "coins_ohlc", _manager(), coin_ids="bitcoin", start_date=start))
+
+ assert rows == [
+ {
+ "coin_id": "bitcoin",
+ "timestamp": datetime.fromtimestamp(closed_at / 1000, tz=UTC),
+ "open": 90832.0,
+ "high": 91905.0,
+ "low": 90406.0,
+ "close": 90406.0,
+ }
+ ]
+
+ @parameterized.expand(
+ [("short candle", [[1764547200000, 1.0, 2.0]]), ("unparseable timestamp", [["nope", 1.0, 2.0, 3.0, 4.0]])]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unusable_candles_are_dropped(self, _name: str, body: list[Any], MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response(body)])
+
+ start = (_today() - timedelta(days=5)).isoformat()
+ assert _rows(_source(PLAN_PRO, "key", "coins_ohlc", _manager(), coin_ids="bitcoin", start_date=start)) == []
+
+
+class TestChartWindows:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_splits_a_long_backfill_into_windows_the_api_accepts(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = _today()
+ start = today - timedelta(days=CHART_WINDOW_DAYS + 10)
+ snaps = _wire(session, [_response([]) for _ in range(4)])
+ _rows(_source(PLAN_PRO, "key", "coins_ohlc", _manager(), coin_ids="bitcoin", start_date=start.isoformat()))
+
+ first_end = start + timedelta(days=CHART_WINDOW_DAYS - 1)
+ assert [(snap["params"]["from"], snap["params"]["to"]) for snap in snaps[:2]] == [
+ (start.isoformat(), first_end.isoformat()),
+ ((first_end + timedelta(days=1)).isoformat(), today.isoformat()),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_one_batch_holds_every_coin_for_a_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ today = _today()
+ start = today - timedelta(days=CHART_WINDOW_DAYS + 10)
+ first_candle, second_candle = 1764547200000, 1764633600000
+ snaps = _wire(
+ session,
+ [
+ _response([[first_candle, 1.0, 2.0, 3.0, 4.0]]),
+ _response([[first_candle, 5.0, 6.0, 7.0, 8.0]]),
+ _response([[second_candle, 1.0, 2.0, 3.0, 4.0]]),
+ _response([[second_candle, 5.0, 6.0, 7.0, 8.0]]),
+ ],
+ )
+
+ manager = _manager()
+ source = _source(
+ PLAN_PRO, "key", "coins_ohlc", manager, coin_ids="bitcoin,ethereum", start_date=start.isoformat()
+ )
+ batches = list(source.items())
+
+ # The pipeline commits the incremental watermark to the highest timestamp in each batch, so
+ # a batch carrying one coin past a window the other has not been fetched for would let the
+ # next job start beyond the coin left behind and skip it for good.
+ assert [[row["coin_id"] for row in batch] for batch in batches] == [
+ ["bitcoin", "ethereum"],
+ ["bitcoin", "ethereum"],
+ ]
+ # Both coins are fetched for one window before either moves on to the next.
+ windows = [snap["params"]["from"] for snap in snaps]
+ assert windows[0] == windows[1] and windows[2] == windows[3] and windows[0] != windows[2]
+ assert manager.save_state.call_args_list[-1] == mock.call(
+ CoinGeckoResumeConfig(next_start=(today + timedelta(days=1)).isoformat())
+ )
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_starts_at_the_default_history_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response([]) for _ in range(4)])
+
+ # No configured start date and no watermark: the first window must start at the furthest
+ # back every plan serves, not at the API's own earliest data.
+ _rows(
+ _source(
+ PLAN_PRO,
+ "key",
+ "coins_ohlc",
+ _manager(),
+ coin_ids="bitcoin",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2020-01-01",
+ )
+ )
+ assert snaps[0]["params"]["from"] == (_today() - timedelta(days=DEFAULT_HISTORY_DAYS)).isoformat()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_starts_at_the_last_synced_day(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response([]) for _ in range(4)])
+
+ # Relative to today, so the number of windows between the watermark and now stays fixed
+ # however far the real clock moves past this test.
+ last_synced_day = _today() - timedelta(days=10)
+ _rows(
+ _source(
+ PLAN_PRO,
+ "key",
+ "coins_ohlc",
+ _manager(),
+ coin_ids="bitcoin",
+ start_date=(last_synced_day - timedelta(days=400)).isoformat(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.combine(last_synced_day, time(9, 30), tzinfo=UTC),
+ )
+ )
+ # Re-reads the last synced day rather than starting after it: that day was still moving
+ # when it first landed, and merge dedupes the overlap.
+ assert snaps[0]["params"]["from"] == last_synced_day.isoformat()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_start_date_is_floored(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response([[1764547200000, 1.0, 2.0, 3.0, 4.0]])])
+
+ # A configuration stored before the floor existed must not schedule an unbounded backfill.
+ # Only the first window is pulled here; the rest would run all the way to today.
+ pages = _source(PLAN_PRO, "key", "coins_ohlc", _manager(), coin_ids="bitcoin", start_date="0001-01-01").items()
+ next(iter(pages))
+
+ assert snaps[0]["params"]["from"] == "2018-01-01"
+ assert session.send.call_count == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_at_the_saved_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response([]) for _ in range(4)])
+
+ resumed_from = (_today() - timedelta(days=3)).isoformat()
+ manager = _manager(CoinGeckoResumeConfig(next_start=resumed_from))
+ _rows(
+ _source(
+ PLAN_PRO,
+ "key",
+ "coins_ohlc",
+ manager,
+ coin_ids="bitcoin,ethereum",
+ start_date=(_today() - timedelta(days=300)).isoformat(),
+ )
+ )
+
+ # The saved window is re-fetched for every coin, so resuming cannot drop one of them.
+ assert session.send.call_count == 2
+ assert [snap["params"]["from"] for snap in snaps[:2]] == [resumed_from, resumed_from]
+ assert snaps[0]["url"].endswith("/coins/bitcoin/ohlc/range")
+ assert snaps[1]["url"].endswith("/coins/ethereum/ohlc/range")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py
index a7745b5021dd..0b35ffee8f67 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py
@@ -1,7 +1,12 @@
import pytest
from unittest import mock
-from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.settings import (
+ ENDPOINTS,
+ MAX_COINS,
+ MERGE_ONLY_ENDPOINTS,
+ PER_COIN_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.source import CoinGeckoSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.coingecko import (
CoinGeckoSourceConfig,
@@ -36,13 +41,17 @@ class TestCoinGeckoSource:
non_retryable_errors = self.source.get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable_errors)
- def test_get_schemas_covers_all_endpoints_full_refresh_only(self) -> None:
- schemas = self.source.get_schemas(self.config, self.team_id)
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
- assert {schema.name for schema in schemas} == set(ENDPOINTS)
- # CoinGecko's catalog/snapshot endpoints have no server-side timestamp filter.
- assert all(not schema.supports_incremental for schema in schemas)
- assert all(not schema.supports_append for schema in schemas)
+ assert set(schemas) == set(ENDPOINTS)
+ # Only the timeseries endpoints take a server-side date filter, and they re-read the window
+ # holding the last synced day, so append would duplicate every day in that overlap.
+ assert {name for name, schema in schemas.items() if schema.supports_incremental} == set(MERGE_ONLY_ENDPOINTS)
+ assert all(not schema.supports_append for schema in schemas.values())
+ # The per-coin endpoints can't sync until coin IDs are configured, so one-shot setup must
+ # not enable them.
+ assert {name for name, schema in schemas.items() if not schema.should_sync_default} == set(PER_COIN_ENDPOINTS)
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",
@@ -68,3 +77,53 @@ class TestCoinGeckoSource:
assert is_valid is expected_valid
assert error_message == expected_message
mock_validate.assert_called_once_with("demo", "CG-test")
+
+ @pytest.mark.parametrize("schema_name", PER_COIN_ENDPOINTS)
+ def test_per_coin_schema_needs_coin_ids(self, schema_name: str) -> None:
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name)
+
+ assert is_valid is False
+ assert error_message == "Add at least one coin ID to sync this table."
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.source.validate_coingecko_credentials"
+ )
+ def test_market_wide_schema_connects_without_coin_ids(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = True
+
+ assert self.source.validate_credentials(self.config, self.team_id, "coins_list") == (True, None)
+
+ @pytest.mark.parametrize("start_date", ["", " ", None])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.source.validate_coingecko_credentials"
+ )
+ def test_blank_start_date_falls_back_to_the_default_window(
+ self, mock_validate: mock.MagicMock, start_date: str | None
+ ) -> None:
+ mock_validate.return_value = True
+ config = CoinGeckoSourceConfig(api_key="CG-test", plan="demo", start_date=start_date)
+
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+
+ @pytest.mark.parametrize(
+ "config_kwargs, expected_message",
+ [
+ (
+ {"coin_ids": ",".join(f"coin-{i}" for i in range(MAX_COINS + 1))},
+ f"Too many coin IDs. List at most {MAX_COINS}.",
+ ),
+ ({"start_date": "1970-01-01"}, "CoinGecko has no data before 2018-01-01. Enter that date or a later one."),
+ (
+ # An unreadable date silently fell back to the default window, so the source synced
+ # a different range than the one that was configured.
+ {"start_date": "01/15/2025"},
+ "Couldn't read '01/15/2025' as a date. Use the format YYYY-MM-DD, for example 2025-01-01.",
+ ),
+ ],
+ )
+ def test_rejects_a_configuration_that_would_run_away(
+ self, config_kwargs: dict[str, str], expected_message: str
+ ) -> None:
+ config = CoinGeckoSourceConfig(api_key="CG-test", plan="demo", **config_kwargs)
+
+ assert self.source.validate_credentials(config, self.team_id) == (False, expected_message)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coingecko.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coingecko.py
index db62d522aab1..78fe93ec2776 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coingecko.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coingecko.py
@@ -10,3 +10,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
class CoinGeckoSourceConfig(config.Config):
api_key: str
plan: Literal["demo", "pro"] = config.value(default="demo")
+ coin_ids: str | None = None
+ start_date: str | None = None