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 global chart, rates, derivatives and NFT tables (#103460)

Tom Owersefc32840dc03
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 b1ddab356e24..1eed14fc6392 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
@@ -1861,22 +1861,22 @@ Note: docs.coinapi.io is behind a Cloudflare interstitial and returns 403 to cur
## CoinGecko — gaps
-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`
+Today (17): `asset_platforms`, `coins_categories`, `coins_categories_list`, `coins_list`, `coins_market_chart`, `coins_markets`, `coins_ohlc`, `coins_tickers`, `derivatives_exchanges`, `derivatives_tickers`, `exchange_rates`, `exchanges`, `exchanges_list`, `global_market_cap_chart`, `global_market_data`, `insights`, `nfts_markets`
Diffed against: <https://docs.coingecko.com/llms.txt>
- [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)
+- [x] `/global/market_cap_chart` — historical global market cap and volume, the time series behind the above (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)
- [ ] `/coins/{id}/history` — single-day historical snapshot per coin, cheap way to build a daily fact table (medium)
-- [ ] `/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)
+- [x] `/exchange_rates` — BTC-to-currency rates, the standard normaliser for cross-currency reporting (medium)
+- [x] `/derivatives/exchanges and /derivatives/tickers` — derivatives venues and open interest, entirely absent from current coverage (medium)
+- [x] `/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); 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 8cd2a38db975..e29c2e4310e3 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
@@ -168,4 +168,91 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Timestamp CoinGecko last refreshed these totals, as a UNIX timestamp.",
},
},
+ "global_market_cap_chart": {
+ "description": "Daily history of the total crypto market capitalization and trading volume in USD, which is the timeseries behind global_market_data. Requires a Pro API key on the Analyst plan or above.",
+ "docs_url": "https://docs.coingecko.com/reference/global-market-cap-chart",
+ "columns": {
+ "timestamp": "Time of the data point, at 00:00 UTC.",
+ "market_cap": "Total market capitalization of all coins in USD at that point.",
+ "volume": "Total trading volume over the 24 hours to that point, in USD.",
+ },
+ },
+ "exchange_rates": {
+ "description": "Exchange rate of 1 BTC against every currency CoinGecko tracks, covering fiat, commodities and other crypto. Use it to convert the BTC-denominated columns on the derivatives and exchange tables into another currency.",
+ "docs_url": "https://docs.coingecko.com/reference/exchange-rates",
+ "columns": {
+ "id": "Currency code the rate is for, for example `usd` or `eth`.",
+ "name": "Display name of the currency.",
+ "unit": "Symbol or ticker the currency is quoted in.",
+ "value": "How many units of the currency 1 BTC is worth.",
+ "type": "Kind of currency: `fiat`, `crypto`, or `commodity`.",
+ },
+ },
+ "derivatives_exchanges": {
+ "description": "Derivatives venues CoinGecko tracks, with open interest, 24-hour volume and how many contracts each lists.",
+ "docs_url": "https://docs.coingecko.com/reference/derivatives-exchanges",
+ "columns": {
+ "id": "CoinGecko derivatives exchange id (joins the market column on derivatives_tickers by name).",
+ "name": "Display name of the venue.",
+ "open_interest_btc": "Total open interest across the venue's contracts, denominated in BTC.",
+ "trade_volume_24h_btc": "Trading volume over the last 24 hours, denominated in BTC.",
+ "number_of_perpetual_pairs": "Count of perpetual contracts listed on the venue.",
+ "number_of_futures_pairs": "Count of dated futures contracts listed on the venue.",
+ "image": "Logo URL for the venue.",
+ "year_established": "Year the venue launched (null when unknown).",
+ "country": "Country the venue is registered in.",
+ "description": "Free-text description of the venue.",
+ "url": "Link to the venue's website.",
+ },
+ },
+ "derivatives_tickers": {
+ "description": "Every perpetual and futures contract across the derivatives venues, with price, funding rate, open interest and 24-hour volume.",
+ "docs_url": "https://docs.coingecko.com/reference/derivatives-tickers",
+ "columns": {
+ "market": "Display name of the venue the contract trades on.",
+ "symbol": "Contract symbol as the venue lists it.",
+ "index_id": "Ticker of the underlying asset the contract tracks.",
+ "price": "Last traded price of the contract.",
+ "price_percentage_change_24h": "Percentage change in the contract price over the last 24 hours.",
+ "contract_type": "Kind of contract: `perpetual` or `futures`.",
+ "index": "Value of the underlying index the contract settles against.",
+ "basis": "Difference between the contract price and the index, as a percentage.",
+ "spread": "Spread between the best bid and ask, as a percentage.",
+ "funding_rate": "Current funding rate, for perpetual contracts.",
+ "open_interest": "Value of all open positions in the contract, in USD.",
+ "volume_24h": "Trading volume over the last 24 hours, in USD.",
+ "last_traded_at": "Timestamp of the contract's last trade, as a UNIX timestamp.",
+ "expired_at": "Expiry of a dated futures contract (null for perpetuals).",
+ },
+ },
+ "nfts_markets": {
+ "description": "NFT collections CoinGecko tracks, with floor price, market cap, volume and holder counts. Requires a Pro API key on the Analyst plan or above.",
+ "docs_url": "https://docs.coingecko.com/reference/nfts-markets",
+ "columns": {
+ "id": "CoinGecko NFT collection id.",
+ "contract_address": "Address of the collection's contract on its asset platform.",
+ "asset_platform_id": "Blockchain the collection lives on (joins the asset_platforms table).",
+ "name": "Display name of the collection.",
+ "symbol": "Ticker symbol of the collection.",
+ "image": "Logo URLs for the collection, at each available size.",
+ "description": "Free-text description of the collection.",
+ "native_currency": "CoinGecko coin id of the currency the collection trades in.",
+ "native_currency_symbol": "Ticker symbol of that currency.",
+ "floor_price": "Lowest listed price in the collection, in its native currency and in USD.",
+ "market_cap": "Floor price times total supply, in the native currency and in USD.",
+ "volume_24h": "Trading volume over the last 24 hours, in the native currency and in USD.",
+ "floor_price_in_usd_24h_percentage_change": "Percentage change in the USD floor price over 24 hours.",
+ "floor_price_24h_percentage_change": "Percentage change in the floor price over 24 hours, per currency.",
+ "market_cap_24h_percentage_change": "Percentage change in market cap over 24 hours, per currency.",
+ "volume_24h_percentage_change": "Percentage change in trading volume over 24 hours, per currency.",
+ "number_of_unique_addresses": "Count of addresses holding at least one item from the collection.",
+ "number_of_unique_addresses_24h_percentage_change": "Percentage change in holder count over 24 hours.",
+ "volume_in_usd_24h_percentage_change": "Percentage change in USD trading volume over 24 hours.",
+ "total_supply": "Number of items in the collection.",
+ "one_day_sales": "Count of sales over the last day.",
+ "one_day_sales_24h_percentage_change": "Percentage change in daily sales count over 24 hours.",
+ "one_day_average_sale_price": "Average sale price over the last day, in the native currency.",
+ "one_day_average_sale_price_24h_percentage_change": "Percentage change in average sale price over 24 hours.",
+ },
+ },
}
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 434a18aa7510..e9586ecfdf77 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
@@ -10,6 +10,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.
CHART_WINDOW_DAYS,
COINGECKO_ENDPOINTS,
DEFAULT_HISTORY_DAYS,
+ EXCHANGE_RATES_ENDPOINT,
+ GLOBAL_CHART_DAYS_OPTIONS,
+ GLOBAL_MARKET_CAP_CHART_ENDPOINT,
MARKET_CHART_ENDPOINT,
MAX_COINS,
MINIMUM_START_DATE,
@@ -70,6 +73,9 @@ _RATE_LIMIT_RESPONSE_ACTIONS: list[ResponseAction] = [
# 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"}
+# The global market cap chart answers with two parallel series already named as we want the columns.
+_GLOBAL_CHART_SERIES = {"market_cap": "market_cap", "volume": "volume"}
+
_OHLC_COLUMNS = ("open", "high", "low", "close")
@@ -229,30 +235,63 @@ def _ticker_row(row: dict[str, Any], coin_id: str) -> dict[str, Any]:
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."
- )
+def _single_object_body(page: list[Any], expected: str) -> dict[str, Any]:
+ """These endpoints answer with a single object, which the client hands over as a one-item page.
+ Anything else is a changed response shape rather than a row."""
+ if len(page) == 1 and isinstance(page[0], dict):
+ return page[0]
+ raise ValueError(f"Required {expected}. The API response shape may have changed.")
+
+def _zip_series(body: dict[str, Any], series: dict[str, str], base: dict[str, Any]) -> list[dict[str, Any]]:
+ """Zip parallel ``[timestamp, value]`` series into one row per timestamp, ordered ascending."""
rows: dict[datetime, dict[str, Any]] = {}
- for key, column in _MARKET_CHART_SERIES.items():
+ for key, column in 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]
+ rows.setdefault(timestamp, {**base, "timestamp": timestamp})[column] = point[1]
return [rows[timestamp] for timestamp in sorted(rows)]
+def _market_chart_rows(page: list[Any], coin_id: str) -> list[dict[str, Any]]:
+ body = _single_object_body(page, "a market chart object carrying price, market cap and volume series")
+ return _zip_series(body, _MARKET_CHART_SERIES, {"coin_id": coin_id})
+
+
+def _global_market_cap_chart_rows(page: list[Any]) -> list[dict[str, Any]]:
+ body = _single_object_body(page, "a global market cap chart object carrying market cap and volume series")
+ return _zip_series(body, _GLOBAL_CHART_SERIES, {})
+
+
+def _exchange_rate_rows(page: list[Any]) -> list[dict[str, Any]]:
+ """Flatten the ``rates`` object, which is keyed by currency code rather than being a row list,
+ into a row per currency with the code as its id."""
+ body = _single_object_body(page, "an exchange rates object keyed by currency code")
+ return [{"id": code, **rate} for code, rate in body.items() if isinstance(rate, dict)]
+
+
+def _global_chart_days(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> str:
+ """Pick the smallest `days` window that still covers everything since the watermark.
+
+ The endpoint takes no from/to range, so the window is how far back an incremental run reads.
+ The day holding the watermark is re-read rather than skipped: it was still moving when it first
+ landed, and merge dedupes the overlap.
+ """
+ last_value = _coerce_date(db_incremental_field_last_value) if should_use_incremental_field else None
+ if last_value is None:
+ return "max"
+
+ days_since = (datetime.now(UTC).date() - last_value).days + 1
+ for option in GLOBAL_CHART_DAYS_OPTIONS:
+ if option != "max" and days_since <= int(option):
+ return option
+ return "max"
+
+
def _ohlc_rows(page: list[Any], coin_id: str) -> list[dict[str, Any]]:
"""Map each ``[timestamp, open, high, low, close]`` candle onto a row.
@@ -273,6 +312,13 @@ _CHART_ROW_BUILDERS: dict[str, Callable[[list[Any], str], list[dict[str, Any]]]]
OHLC_ENDPOINT: _ohlc_rows,
}
+# Top-level endpoints whose body is a single object rather than a row list, keyed to the builder
+# that reshapes it. Membership also routes them away from the declarative top-level path.
+_TOP_LEVEL_ROW_BUILDERS: dict[str, Callable[[list[Any]], list[dict[str, Any]]]] = {
+ GLOBAL_MARKET_CAP_CHART_ENDPOINT: _global_market_cap_chart_rows,
+ EXCHANGE_RATES_ENDPOINT: _exchange_rate_rows,
+}
+
def _ticker_pages(
client: RESTClient,
@@ -314,20 +360,22 @@ def _ticker_pages(
yield [_ticker_row(row, coin_id) for row in page]
-def _fetch_window(
+def _fetch_single_page(
client: RESTClient,
- config: CoinGeckoEndpointConfig,
- coin_id: str,
+ path: str,
params: dict[str, Any],
+ data_selector: Optional[str],
hooks: Optional[dict[str, Any]],
+ data_selector_required: bool = False,
) -> 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.
+ # 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),
+ path=path,
params=params,
paginator=SinglePagePaginator(),
- data_selector=config.data_selector,
+ data_selector=data_selector,
+ data_selector_required=data_selector_required,
hooks=hooks,
):
return page
@@ -380,7 +428,8 @@ def _chart_pages(
# 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))
+ page = _fetch_single_page(client, config.path.format(coin_id=coin_id), params, config.data_selector, hooks)
+ window_rows.extend(build_rows(page, coin_id))
if window_rows:
yield window_rows
@@ -441,6 +490,56 @@ def _per_coin_source(
)
+def _reshaped_pages(
+ client: RESTClient,
+ config: CoinGeckoEndpointConfig,
+ params: dict[str, Any],
+ build_rows: Callable[[list[Any]], list[dict[str, Any]]],
+) -> Iterator[list[dict[str, Any]]]:
+ hooks = create_response_hooks(_RATE_LIMIT_RESPONSE_ACTIONS, resource_name=config.name)
+ page = _fetch_single_page(client, config.path, params, config.data_selector, hooks, data_selector_required=True)
+ rows = build_rows(page)
+ if rows:
+ yield rows
+
+
+def _reshaped_top_level_source(
+ plan: str,
+ api_key: str,
+ config: CoinGeckoEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ client = _rest_client(plan, api_key)
+ build_rows = _TOP_LEVEL_ROW_BUILDERS[config.name]
+ params: dict[str, Any] = dict(config.extra_params)
+
+ if config.date_field is None:
+ return SourceResponse(
+ name=config.name,
+ items=lambda: _reshaped_pages(client, config, params, build_rows),
+ primary_keys=config.primary_keys,
+ # A rate snapshot carries no stable created_at to partition on.
+ partition_count=None,
+ partition_size=None,
+ )
+
+ # The endpoint takes a relative `days` window instead of a from/to range, so an incremental run
+ # narrows that window rather than moving a cursor.
+ params["days"] = _global_chart_days(should_use_incremental_field, db_incremental_field_last_value)
+ return SourceResponse(
+ name=config.name,
+ items=lambda: _reshaped_pages(client, config, params, build_rows),
+ 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,
@@ -526,6 +625,15 @@ def coingecko_source(
) -> SourceResponse:
config = COINGECKO_ENDPOINTS[endpoint]
+ if config.name in _TOP_LEVEL_ROW_BUILDERS:
+ return _reshaped_top_level_source(
+ plan=plan,
+ api_key=api_key,
+ config=config,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
if config.per_coin:
return _per_coin_source(
plan=plan,
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 22ed9e6874d9..0438e843aa39 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
@@ -12,6 +12,17 @@ TICKERS_ENDPOINT = "coins_tickers"
MARKET_CHART_ENDPOINT = "coins_market_chart"
OHLC_ENDPOINT = "coins_ohlc"
+# Top-level endpoints whose body has to be reshaped into rows rather than being a row list already,
+# named so the row builders and the routing in coingecko.py reference them without repeating the
+# string.
+EXCHANGE_RATES_ENDPOINT = "exchange_rates"
+GLOBAL_MARKET_CAP_CHART_ENDPOINT = "global_market_cap_chart"
+
+# /global/market_cap_chart takes a relative `days` window from a fixed enum rather than a from/to
+# range. `days=1` is served at hourly granularity and every larger value at daily, so 1 is left out:
+# a shorter window would return hourly points that don't line up with the daily rows already synced.
+GLOBAL_CHART_DAYS_OPTIONS = ("7", "14", "30", "90", "180", "365", "max")
+
# /coins/{id}/tickers is fixed at 100 items per page, unlike the 250 the other list endpoints take.
TICKERS_PAGE_SIZE = 100
@@ -66,6 +77,9 @@ class CoinGeckoEndpointConfig:
window_days: int | None = None
# Timestamp column the timeseries endpoints are keyed, partitioned and filtered on.
date_field: str | None = None
+ # Whether CoinGecko serves the endpoint only to paid plans. A Demo key gets a 401 back, so these
+ # endpoints are gated on the configured plan rather than offered to everyone.
+ pro_only: bool = False
COINGECKO_ENDPOINTS: dict[str, CoinGeckoEndpointConfig] = {
@@ -167,6 +181,48 @@ COINGECKO_ENDPOINTS: dict[str, CoinGeckoEndpointConfig] = {
data_selector="data",
primary_keys=["updated_at"],
),
+ # Historical market-wide market cap and volume, which is the timeseries behind global_market_data.
+ # Two parallel [timestamp, value] series under a `market_cap_chart` envelope, zipped into one row
+ # per timestamp. Requires a Pro key on the Analyst plan or above.
+ GLOBAL_MARKET_CAP_CHART_ENDPOINT: CoinGeckoEndpointConfig(
+ name=GLOBAL_MARKET_CAP_CHART_ENDPOINT,
+ path="/global/market_cap_chart",
+ data_selector="market_cap_chart",
+ date_field="timestamp",
+ primary_keys=["timestamp"],
+ extra_params={"vs_currency": "usd"},
+ pro_only=True,
+ ),
+ # BTC-to-currency rates, which normalise the BTC-denominated columns on the derivatives and
+ # exchanges tables into any other currency. One object keyed by currency code under a `rates`
+ # envelope, flattened into a row per currency.
+ EXCHANGE_RATES_ENDPOINT: CoinGeckoEndpointConfig(
+ name=EXCHANGE_RATES_ENDPOINT,
+ path="/exchange_rates",
+ data_selector="rates",
+ ),
+ # Derivatives venues with open interest, 24h volume and contract counts. Paginated.
+ "derivatives_exchanges": CoinGeckoEndpointConfig(
+ name="derivatives_exchanges",
+ path="/derivatives/exchanges",
+ paginated=True,
+ ),
+ # Every perpetual and futures contract across those venues, with price, funding rate, open
+ # interest and 24h volume. One bare array with no pagination params. A ticker carries no id, so
+ # key on the venue and the contract symbol.
+ "derivatives_tickers": CoinGeckoEndpointConfig(
+ name="derivatives_tickers",
+ path="/derivatives",
+ primary_keys=["market", "symbol"],
+ ),
+ # NFT collections with floor price, market cap and 24h volume. Paginated. Requires a Pro key on
+ # the Analyst plan or above.
+ "nfts_markets": CoinGeckoEndpointConfig(
+ name="nfts_markets",
+ path="/nfts/markets",
+ paginated=True,
+ pro_only=True,
+ ),
}
ENDPOINTS = tuple(COINGECKO_ENDPOINTS.keys())
@@ -188,3 +244,7 @@ MERGE_ONLY_ENDPOINTS = tuple(name for name, config in COINGECKO_ENDPOINTS.items(
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)
+
+# Endpoints a Demo key can't reach at all, so they are offered only to a source configured with a
+# Pro key rather than queueing a sync that can only 401.
+PRO_ONLY_ENDPOINTS = tuple(name for name, config in COINGECKO_ENDPOINTS.items() if config.pro_only)
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 804cf3a555f4..b5db6c432a63 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
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.
MAX_COINS,
MERGE_ONLY_ENDPOINTS,
PER_COIN_ENDPOINTS,
+ PRO_ONLY_ENDPOINTS,
SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
@@ -67,7 +68,9 @@ Create a key in your [CoinGecko developer dashboard](https://www.coingecko.com/e
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.""",
+The market pairs, historical chart and OHLC tables are per coin, so they only sync once you list the coins you want.
+
+The global market cap chart and NFT market tables need a Pro key on the Analyst plan or above.""",
iconPath="/static/services/coingecko.png",
docsUrl="https://posthog.com/docs/cdp/sources/coingecko",
fields=cast(
@@ -139,12 +142,18 @@ The market pairs, historical chart and OHLC tables are per coin, so they only sy
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ should_sync_default = dict(SHOULD_SYNC_DEFAULT)
+ if config.plan != PLAN_PRO:
+ # A Demo key is refused outright by the Pro-only endpoints, so one-shot setup must not
+ # enable a table that can only 401.
+ should_sync_default.update(dict.fromkeys(PRO_ONLY_ENDPOINTS, False))
+
return build_endpoint_schemas(
ENDPOINTS,
INCREMENTAL_FIELDS,
names,
merge_only=MERGE_ONLY_ENDPOINTS,
- should_sync_default=SHOULD_SYNC_DEFAULT,
+ should_sync_default=should_sync_default,
)
def validate_credentials(
@@ -167,6 +176,9 @@ The market pairs, historical chart and OHLC tables are per coin, so they only sy
if not coins and schema_name in PER_COIN_ENDPOINTS:
return False, "Add at least one coin ID to sync this table."
+ if config.plan != PLAN_PRO and schema_name in PRO_ONLY_ENDPOINTS:
+ return False, "This table needs a CoinGecko Pro key on the Analyst plan or above."
+
if validate_coingecko_credentials(config.plan, config.api_key):
return True, 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 1529a4089e8b..3b655ae11c32 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
@@ -730,3 +730,137 @@ class TestChartWindows:
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")
+
+
+class TestExchangeRates:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_flattens_the_rates_object_into_a_row_per_currency(self, MockSession) -> None:
+ session = MockSession.return_value
+ # The body is keyed by currency code rather than being a row list, so without the flattening
+ # the whole object would land as one unusable row.
+ _wire(
+ session,
+ [
+ _response(
+ {
+ "rates": {
+ "btc": {"name": "Bitcoin", "unit": "BTC", "value": 1.0, "type": "crypto"},
+ "usd": {"name": "US Dollar", "unit": "$", "value": 80443.4, "type": "fiat"},
+ }
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source(PLAN_DEMO, "key", "exchange_rates", _manager()))
+
+ assert rows == [
+ {"id": "btc", "name": "Bitcoin", "unit": "BTC", "value": 1.0, "type": "crypto"},
+ {"id": "usd", "name": "US Dollar", "unit": "$", "value": 80443.4, "type": "fiat"},
+ ]
+ assert session.send.call_count == 1
+
+
+class TestGlobalMarketCapChart:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_zips_the_two_series_into_one_row_per_timestamp(self, MockSession) -> None:
+ session = MockSession.return_value
+ first, second = 1764547200000, 1764633600000
+ _wire(
+ session,
+ [
+ _response(
+ {
+ "market_cap_chart": {
+ "market_cap": [[first, 2.6e12], [second, 2.7e12]],
+ "volume": [[first, 7.2e10], [second, 7.3e10]],
+ }
+ }
+ )
+ ],
+ )
+
+ rows = _rows(_source(PLAN_PRO, "key", "global_market_cap_chart", _manager()))
+
+ assert rows == [
+ {"timestamp": datetime.fromtimestamp(first / 1000, tz=UTC), "market_cap": 2.6e12, "volume": 7.2e10},
+ {"timestamp": datetime.fromtimestamp(second / 1000, tz=UTC), "market_cap": 2.7e12, "volume": 7.3e10},
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_asks_for_the_whole_history(self, MockSession) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response({"market_cap_chart": {"market_cap": [], "volume": []}})])
+
+ _rows(
+ _source(
+ PLAN_PRO,
+ "key",
+ "global_market_cap_chart",
+ _manager(),
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime.now(UTC),
+ )
+ )
+ # A full refresh must ignore the stored watermark, or it would resync a narrow window and
+ # leave the rest of the table behind.
+ assert snaps[0]["params"]["days"] == "max"
+
+ @parameterized.expand(
+ [
+ # The endpoint takes a relative window from a fixed enum, so a gap picks the smallest
+ # option that still covers it. A gap of one day still asks for 7: `days=1` is served
+ # hourly and would not line up with the daily rows already synced.
+ ("one day behind", 1, "7"),
+ ("a week behind", 7, "14"),
+ ("a month behind", 40, "90"),
+ ("beyond the largest window", 400, "max"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_narrows_the_window_to_the_watermark(
+ self, _name: str, days_behind: int, expected_days: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ snaps = _wire(session, [_response({"market_cap_chart": {"market_cap": [], "volume": []}})])
+
+ _rows(
+ _source(
+ PLAN_PRO,
+ "key",
+ "global_market_cap_chart",
+ _manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime.combine(
+ _today() - timedelta(days=days_behind), time(9, 30), tzinfo=UTC
+ ),
+ )
+ )
+ assert snaps[0]["params"]["days"] == expected_days
+
+
+class TestReshapedEndpointsFailLoud:
+ @parameterized.expand(
+ [
+ ("exchange rates, no envelope", "exchange_rates", {"unexpected": "object"}, "data_selector"),
+ ("exchange rates, wrong inner type", "exchange_rates", {"rates": []}, "exchange rates object"),
+ ("global chart, no envelope", "global_market_cap_chart", {"unexpected": "object"}, "data_selector"),
+ (
+ "global chart, wrong inner type",
+ "global_market_cap_chart",
+ {"market_cap_chart": []},
+ "global market cap chart object",
+ ),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unexpected_shape_fails_loud(
+ self, _name: str, endpoint: str, body: Any, expected_message: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ # These bodies are reshaped rather than yielded as rows, so a changed shape must fail rather
+ # than silently syncing zero rows or one garbage row.
+ _wire(session, [_response(body)])
+
+ with pytest.raises(ValueError, match=expected_message):
+ _rows(_source(PLAN_PRO, "key", endpoint, _manager()))
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 0b35ffee8f67..20d749333e4a 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
@@ -6,6 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.
MAX_COINS,
MERGE_ONLY_ENDPOINTS,
PER_COIN_ENDPOINTS,
+ PRO_ONLY_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 (
@@ -49,9 +50,18 @@ class TestCoinGeckoSource:
# 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)
+ # On a Demo key the per-coin endpoints can't sync until coin IDs are configured and the
+ # Pro-only ones can't sync at all, so one-shot setup must not enable either.
+ assert {name for name, schema in schemas.items() if not schema.should_sync_default} == set(
+ PER_COIN_ENDPOINTS
+ ) | set(PRO_ONLY_ENDPOINTS)
+
+ def test_pro_plan_enables_the_pro_only_endpoints(self) -> None:
+ config = CoinGeckoSourceConfig(api_key="CG-test", plan="pro")
+
+ schemas = {schema.name: schema for schema in self.source.get_schemas(config, self.team_id)}
+
+ assert all(schemas[name].should_sync_default for name in PRO_ONLY_ENDPOINTS)
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",
@@ -85,6 +95,23 @@ class TestCoinGeckoSource:
assert is_valid is False
assert error_message == "Add at least one coin ID to sync this table."
+ @pytest.mark.parametrize("schema_name", PRO_ONLY_ENDPOINTS)
+ def test_pro_only_schema_is_refused_on_a_demo_key(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 == "This table needs a CoinGecko Pro key on the Analyst plan or above."
+
+ @pytest.mark.parametrize("schema_name", PRO_ONLY_ENDPOINTS)
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.source.validate_coingecko_credentials"
+ )
+ def test_pro_only_schema_connects_on_a_pro_key(self, mock_validate: mock.MagicMock, schema_name: str) -> None:
+ mock_validate.return_value = True
+ config = CoinGeckoSourceConfig(api_key="CG-test", plan="pro")
+
+ assert self.source.validate_credentials(config, self.team_id, schema_name) == (True, None)
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.coingecko.source.validate_coingecko_credentials"
)