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(warehouse-sources): add coinapi quotes, metrics and rate history (#103347)

Tom Owersa5ae35f409ce
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 929a42f19617..04254c147a0b 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
@@ -1840,14 +1840,14 @@ Note: Cohere's API is overwhelmingly POST inference (chat, embed, rerank, classi
## CoinApi — gaps
-Today (6): `assets`, `exchange_rates`, `exchanges`, `ohlcv_history`, `symbols`, `trades_history`
+Today (10): `assets`, `exchange_rates`, `exchange_rates_history`, `exchanges`, `metrics_listing`, `metrics_symbol_history`, `ohlcv_history`, `quotes_history`, `symbols`, `trades_history`
Diffed against: <https://raw.githubusercontent.com/api-bricks/api-bricks-sdk/master/coinapi/market-data-api-rest/spec/openapi.json>
-- [ ] `/v1/quotes/{symbol_id}/history` — historical bid/ask quote timeseries - the main analytical series alongside trades and OHLCV (high)
-- [ ] `/v1/metrics/listing` — catalogue of every metric id CoinAPI supports; the lookup table needed to make any metrics sync interpretable (high)
-- [ ] `/v1/metrics/symbol/history` — funding rate, open interest and other derivative metrics per symbol - resolves ids from the symbols table we already sync (high)
-- [ ] `/v1/exchangerate/{asset_id_base}/{asset_id_quote}/history` — historical FX timeseries; today only the current-rate snapshot is synced (high)
+- [x] `/v1/quotes/{symbol_id}/history` — historical bid/ask quote timeseries - the main analytical series alongside trades and OHLCV (high)
+- [x] `/v1/metrics/listing` — catalogue of every metric id CoinAPI supports; the lookup table needed to make any metrics sync interpretable (high)
+- [x] `/v1/metrics/symbol/history` — funding rate, open interest and other derivative metrics per symbol - resolves ids from the symbols table we already sync (high)
+- [x] `/v1/exchangerate/{asset_id_base}/{asset_id_quote}/history` — historical FX timeseries; today only the current-rate snapshot is synced (high)
- [ ] `/v1/orderbooks/{symbol_id}/history` — historical order book snapshots for liquidity and spread analysis (medium)
- [ ] `/v1/metrics/exchange/history` — per-exchange metric history joining to the exchanges table already synced (medium)
- [ ] `/v1/metrics/asset/history` — per-asset metric history joining to the assets table already synced (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.py
index 7a59ed80a287..68fafcbfaae5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.py
@@ -58,6 +58,14 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"volume_1mth_usd": "Trading volume over the last month, in USD.",
},
},
+ "metrics_listing": {
+ "description": "Every metric CoinAPI supports, with its description. The lookup table behind the metric history tables.",
+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/metrics",
+ "columns": {
+ "metric_id": "CoinAPI identifier of the metric (e.g. FUNDING_RATE, DERIVATIVES_OPEN_INTEREST).",
+ "description": "What the metric measures.",
+ },
+ },
"exchange_rates": {
"description": "Current exchange rate from the configured base asset to every other asset, one row per quote asset.",
"docs_url": "https://docs.coinapi.io/market-data/rest-api/exchange-rates",
@@ -99,4 +107,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"taker_side": "Aggressor side of the trade: BUY, SELL, or UNKNOWN.",
},
},
+ "exchange_rates_history": {
+ "description": "Historical exchange rates between the configured base and quote assets, aggregated into the configured period.",
+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/exchange-rates#timeseries-data-get",
+ "columns": {
+ "asset_id_base": "Base asset of the rate (injected from the source configuration).",
+ "asset_id_quote": "Quote asset of the rate (injected from the source configuration).",
+ "period_id": "Aggregation period of the row (injected from the source configuration), e.g. 1DAY.",
+ "time_period_start": "Start time of the period (inclusive).",
+ "time_period_end": "End time of the period (exclusive).",
+ "time_open": "Timestamp of the first rate in the period.",
+ "time_close": "Timestamp of the last rate in the period.",
+ "rate_open": "First rate in the period.",
+ "rate_high": "Highest rate in the period.",
+ "rate_low": "Lowest rate in the period.",
+ "rate_close": "Last rate in the period.",
+ },
+ },
+ "metrics_symbol_history": {
+ "description": "History of one metric (funding rate, open interest and the rest of the metrics listing) for the configured symbol.",
+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/metrics#historical-metrics-for-symbol-get",
+ "columns": {
+ "symbol_id": "Symbol the metric belongs to (injected from the source configuration).",
+ "metric_id": "Metric the row measures (injected from the source configuration).",
+ "period_id": "Aggregation period of the row (injected from the source configuration), e.g. 1DAY.",
+ "time_period_start": "Start time of the period (inclusive).",
+ "time_period_end": "End time of the period (exclusive).",
+ "time_open": "Timestamp of the first observation in the period.",
+ "time_close": "Timestamp of the last observation in the period.",
+ "first": "First metric value observed in the period.",
+ "last": "Last metric value observed in the period.",
+ "min": "Lowest metric value observed in the period.",
+ "max": "Highest metric value observed in the period.",
+ "count": "Number of observations in the period.",
+ "sum": "Sum of the metric values observed in the period.",
+ },
+ },
+ "quotes_history": {
+ "description": "Historical best bid and ask updates (top of book) for the configured symbol.",
+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/quotes#historical-data-get",
+ "columns": {
+ "symbol_id": "Symbol the quote belongs to.",
+ "time_exchange": "Timestamp the exchange reported for the quote.",
+ "time_coinapi": "Timestamp CoinAPI received the quote.",
+ "ask_price": "Best asking price.",
+ "ask_size": "Volume resting on the best ask. Zero means the size is unknown.",
+ "bid_price": "Best bidding price.",
+ "bid_size": "Volume resting on the best bid. Zero means the size is unknown.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.py
index cec33be5d28b..2a4082a6a65c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.py
@@ -8,6 +8,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.settings import (
COIN_API_ENDPOINTS,
CoinApiEndpointConfig,
@@ -110,12 +112,57 @@ def _initial_time_start(
return _format_time(datetime.now(UTC) - timedelta(days=DEFAULT_LOOKBACK_DAYS))
+@frozen
+class CoinApiTimeseriesRequest:
+ path: str
+ # Query params constant across every page of the sync.
+ params: dict[str, Any]
+ # Columns injected into each row because the response omits them.
+ row_defaults: dict[str, Any]
+
+
+def _resolve_timeseries_request(
+ config: CoinApiEndpointConfig,
+ symbol_id: str,
+ period_id: str,
+ metric_id: str,
+ exchange_rate_base_asset: str,
+ exchange_rate_quote_asset: str,
+ time_end: str,
+) -> CoinApiTimeseriesRequest:
+ path = config.path
+ params: dict[str, Any] = {}
+ row_defaults: dict[str, Any] = {}
+
+ if config.requires_symbol:
+ if "{symbol_id}" in path:
+ path = path.replace("{symbol_id}", symbol_id)
+ else:
+ params["symbol_id"] = symbol_id
+ row_defaults["symbol_id"] = symbol_id
+ if config.requires_metric:
+ params["metric_id"] = metric_id
+ row_defaults["metric_id"] = metric_id
+ if config.requires_quote_asset:
+ path = path.replace("{base}", exchange_rate_base_asset).replace("{quote}", exchange_rate_quote_asset)
+ row_defaults["asset_id_base"] = exchange_rate_base_asset
+ row_defaults["asset_id_quote"] = exchange_rate_quote_asset
+ if config.needs_period:
+ params["period_id"] = period_id
+ row_defaults["period_id"] = period_id
+ if config.needs_time_end:
+ params["time_end"] = time_end
+
+ return CoinApiTimeseriesRequest(path=path, params=params, row_defaults=row_defaults)
+
+
def _get_timeseries_rows(
config: CoinApiEndpointConfig,
logger: FilteringBoundLogger,
fetch: Any,
- symbol_id: str,
- period_id: str,
+ path: str,
+ extra_params: dict[str, Any],
+ row_defaults: dict[str, Any],
incremental_field: str,
initial_time_start: str,
resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],
@@ -125,23 +172,17 @@ def _get_timeseries_rows(
if resume is not None and resume.time_start:
logger.debug(f"CoinAPI: resuming {config.name} from time_start={time_start}")
- path = config.path.replace("{symbol_id}", symbol_id)
-
while True:
- params: dict[str, Any] = {"time_start": time_start, "limit": PAGE_LIMIT}
- if config.needs_period:
- params["period_id"] = period_id
+ params: dict[str, Any] = {**extra_params, "time_start": time_start, "limit": PAGE_LIMIT}
data = fetch(_build_url(path, params))
if not isinstance(data, list) or not data:
break
- # OHLCV rows omit the symbol/period they belong to; injecting them keeps the primary key
- # columns present and the table self-describing.
+ # Aggregated history rows omit the symbol / period / metric / assets they belong to; injecting
+ # them keeps the primary key columns present and the table self-describing.
for row in data:
- row["symbol_id"] = symbol_id
- if config.needs_period:
- row["period_id"] = period_id
+ row.update(row_defaults)
yield data
@@ -172,7 +213,9 @@ def get_rows(
resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],
symbol_id: str = "",
period_id: str = "1DAY",
+ metric_id: str = "",
exchange_rate_base_asset: str = "USD",
+ exchange_rate_quote_asset: str = "",
start_date: str = "",
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
@@ -208,11 +251,33 @@ def get_rows(
return
# Time-series endpoint.
- if not symbol_id:
+ if config.requires_symbol and not symbol_id:
raise ValueError(
f"CoinAPI endpoint '{endpoint}' requires a symbol_id. Set the Symbol ID field on the source "
f"(e.g. BITSTAMP_SPOT_BTC_USD) to sync this table."
)
+ if config.requires_metric and not metric_id:
+ raise ValueError(
+ f"CoinAPI endpoint '{endpoint}' requires a metric_id. Set the Metric ID field on the source "
+ f"(e.g. FUNDING_RATE, from the metrics_listing table) to sync this table."
+ )
+ if config.requires_quote_asset and not exchange_rate_quote_asset:
+ raise ValueError(
+ f"CoinAPI endpoint '{endpoint}' requires a quote asset. Set the Exchange rate quote asset field "
+ f"on the source (e.g. BTC) to sync this table."
+ )
+
+ request = _resolve_timeseries_request(
+ config=config,
+ symbol_id=symbol_id,
+ period_id=period_id or "1DAY",
+ metric_id=metric_id,
+ exchange_rate_base_asset=exchange_rate_base_asset or "USD",
+ exchange_rate_quote_asset=exchange_rate_quote_asset,
+ # Bounded once per sync. Rows arriving after this point are picked up by the next sync,
+ # which starts from the watermark this one leaves behind.
+ time_end=_format_time(datetime.now(UTC)),
+ )
cursor = incremental_field or config.incremental_fields[0]["field"]
initial_time_start = _initial_time_start(should_use_incremental_field, db_incremental_field_last_value, start_date)
@@ -221,8 +286,9 @@ def get_rows(
config=config,
logger=logger,
fetch=fetch,
- symbol_id=symbol_id,
- period_id=period_id or "1DAY",
+ path=request.path,
+ extra_params=request.params,
+ row_defaults=request.row_defaults,
incremental_field=cursor,
initial_time_start=initial_time_start,
resumable_source_manager=resumable_source_manager,
@@ -236,7 +302,9 @@ def coin_api_source(
resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],
symbol_id: str = "",
period_id: str = "1DAY",
+ metric_id: str = "",
exchange_rate_base_asset: str = "USD",
+ exchange_rate_quote_asset: str = "",
start_date: str = "",
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
@@ -253,7 +321,9 @@ def coin_api_source(
resumable_source_manager=resumable_source_manager,
symbol_id=symbol_id,
period_id=period_id,
+ metric_id=metric_id,
exchange_rate_base_asset=exchange_rate_base_asset,
+ exchange_rate_quote_asset=exchange_rate_quote_asset,
start_date=start_date,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.py
index 2747c64508e2..00cea5b13ec2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.py
@@ -10,7 +10,7 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
EndpointKind = Literal["reference", "exchange_rate", "timeseries"]
-@dataclass
+@dataclass(frozen=True)
class CoinApiEndpointConfig:
name: str
path: str # may contain `{symbol_id}` / `{base}` placeholders, resolved from config
@@ -19,11 +19,20 @@ class CoinApiEndpointConfig:
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Stable time field rows are partitioned by (timeseries only). Never an updated_at-style field.
partition_key: Optional[str] = None
- # Time-series endpoints are scoped to a single symbol passed in the path, so they only sync when
- # the user has configured a `symbol_id`. They're off by default to avoid surprising credit spend.
+ # Time-series endpoints are scoped to a single market or metric the user configures on the source,
+ # so they only sync once those fields are set. They're off by default to avoid surprising credit
+ # spend. The symbol rides in the path where the endpoint has a `{symbol_id}` placeholder and in the
+ # query string otherwise.
requires_symbol: bool = False
- # OHLCV history additionally needs a `period_id` aggregation param (e.g. 1DAY).
+ # Whether the endpoint needs a `metric_id` (from the metrics_listing table) to select a series.
+ requires_metric: bool = False
+ # Whether the endpoint needs a quote asset to pair with the configured exchange rate base asset.
+ requires_quote_asset: bool = False
+ # Aggregated history endpoints additionally need a `period_id` param (e.g. 1DAY).
needs_period: bool = False
+ # CoinAPI documents `time_end` as required on some history endpoints, and rejects the request
+ # without it. The transport bounds those at the sync's start time.
+ needs_time_end: bool = False
should_sync_default: bool = True
@@ -57,6 +66,14 @@ COIN_API_ENDPOINTS: dict[str, CoinApiEndpointConfig] = {
kind="reference",
primary_keys=["symbol_id"],
),
+ # Every metric id CoinAPI supports, with its description. The lookup that makes the metric history
+ # tables readable, and where a user finds the `metric_id` those tables are configured with.
+ "metrics_listing": CoinApiEndpointConfig(
+ name="metrics_listing",
+ path="/v1/metrics/listing",
+ kind="reference",
+ primary_keys=["metric_id"],
+ ),
# Current exchange rates from the configured base asset to every other asset. A point-in-time
# snapshot — full refresh only. `asset_id_base` is injected per row from the configured base.
"exchange_rates": CoinApiEndpointConfig(
@@ -91,6 +108,57 @@ COIN_API_ENDPOINTS: dict[str, CoinApiEndpointConfig] = {
requires_symbol=True,
should_sync_default=False,
),
+ # Historical exchange rates between the configured base and quote assets, aggregated into the
+ # configured period. Rows carry neither the assets nor the period, so all three are injected to
+ # keep the primary key columns present.
+ "exchange_rates_history": CoinApiEndpointConfig(
+ name="exchange_rates_history",
+ path="/v1/exchangerate/{base}/{quote}/history",
+ kind="timeseries",
+ primary_keys=["asset_id_base", "asset_id_quote", "period_id", "time_period_start"],
+ incremental_fields=[_datetime_field("time_period_start")],
+ partition_key="time_period_start",
+ requires_quote_asset=True,
+ needs_period=True,
+ needs_time_end=True,
+ should_sync_default=False,
+ ),
+ # Per-symbol derivative metrics (funding rate, open interest and the rest of the metrics_listing
+ # catalogue) for the configured symbol. `period_id` is always sent: left off, CoinAPI returns raw
+ # ticks in a different row shape, and the period-aggregated shape is what this primary key assumes.
+ "metrics_symbol_history": CoinApiEndpointConfig(
+ name="metrics_symbol_history",
+ path="/v1/metrics/symbol/history",
+ kind="timeseries",
+ primary_keys=["symbol_id", "metric_id", "period_id", "time_period_start"],
+ incremental_fields=[_datetime_field("time_period_start")],
+ partition_key="time_period_start",
+ requires_symbol=True,
+ requires_metric=True,
+ needs_period=True,
+ should_sync_default=False,
+ ),
+ # Historical best bid/ask updates for the configured symbol. CoinAPI documents no unique id on a
+ # quote, and its own example response repeats a row verbatim, so the whole row is the key —
+ # identical updates carry no extra information and collapsing them keeps the merge key unique.
+ "quotes_history": CoinApiEndpointConfig(
+ name="quotes_history",
+ path="/v1/quotes/{symbol_id}/history",
+ kind="timeseries",
+ primary_keys=[
+ "symbol_id",
+ "time_exchange",
+ "time_coinapi",
+ "ask_price",
+ "ask_size",
+ "bid_price",
+ "bid_size",
+ ],
+ incremental_fields=[_datetime_field("time_exchange"), _datetime_field("time_coinapi")],
+ partition_key="time_exchange",
+ requires_symbol=True,
+ should_sync_default=False,
+ ),
}
ENDPOINTS = tuple(COIN_API_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py
index f44677333e67..9612f6ccde34 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py
@@ -51,7 +51,9 @@ class CoinApiSource(ResumableSource[CoinApiSourceConfig, CoinApiResumeConfig]):
Create a key in the [CoinAPI customer portal](https://customer.coinapi.io/). CoinAPI uses a credit/quota-based (pay-as-you-go) model with a daily credit limit, so large time-series tables can consume significant credits.
-The **reference** tables (assets, exchanges, symbols) and **exchange rates** sync with just an API key. The **OHLCV** and **trades** history tables are scoped to a single market, so set the **Symbol ID** field (and, for OHLCV, the **Period ID**) to enable them.""",
+The **reference** tables (assets, exchanges, symbols, metrics listing) and **exchange rates** sync with just an API key.
+
+The history tables each cover one series, so they need a bit more setup. Set the **Symbol ID** field (and the **Period ID**) for OHLCV, trades, quotes and symbol metrics history. Symbol metrics history also needs a **Metric ID**, which you can pick from the metrics listing table. Exchange rates history needs an **Exchange rate quote asset** to pair with the base asset.""",
iconPath="/static/services/coin_api.png",
docsUrl="https://posthog.com/docs/cdp/sources/coin-api",
fields=cast(
@@ -73,6 +75,14 @@ The **reference** tables (assets, exchanges, symbols) and **exchange rates** syn
placeholder="USD",
secret=False,
),
+ SourceFieldInputConfig(
+ name="exchange_rate_quote_asset",
+ label="Exchange rate quote asset",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="BTC",
+ secret=False,
+ ),
SourceFieldInputConfig(
name="symbol_id",
label="Symbol ID",
@@ -89,6 +99,14 @@ The **reference** tables (assets, exchanges, symbols) and **exchange rates** syn
placeholder="1DAY",
secret=False,
),
+ SourceFieldInputConfig(
+ name="metric_id",
+ label="Metric ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="FUNDING_RATE",
+ secret=False,
+ ),
SourceFieldInputConfig(
name="start_date",
label="Start date",
@@ -129,9 +147,16 @@ The **reference** tables (assets, exchanges, symbols) and **exchange rates** syn
def _build_schema(endpoint: str) -> SourceSchema:
endpoint_config = COIN_API_ENDPOINTS[endpoint]
is_timeseries = endpoint_config.kind == "timeseries"
- description = None
+ requirements = []
if endpoint_config.requires_symbol:
- description = "Requires a Symbol ID on the source. Only syncs the configured symbol."
+ requirements.append("a Symbol ID")
+ if endpoint_config.requires_metric:
+ requirements.append("a Metric ID")
+ if endpoint_config.requires_quote_asset:
+ requirements.append("an Exchange rate quote asset")
+ description = None
+ if requirements:
+ description = f"Requires {' and '.join(requirements)} on the source. Only syncs the configured series."
# CoinAPI's time-series endpoints filter server-side on `time_start`, so they're genuinely
# incremental. Reference/snapshot endpoints expose no such filter — full refresh only.
return SourceSchema(
@@ -182,7 +207,9 @@ The **reference** tables (assets, exchanges, symbols) and **exchange rates** syn
resumable_source_manager=resumable_source_manager,
symbol_id=config.symbol_id or "",
period_id=config.period_id or "1DAY",
+ metric_id=config.metric_id or "",
exchange_rate_base_asset=config.exchange_rate_base_asset or "USD",
+ exchange_rate_quote_asset=config.exchange_rate_quote_asset or "",
start_date=config.start_date or "",
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py
index 4d71e17b5c78..28ca179b6f4b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py
@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.c
_format_time,
_headers,
_initial_time_start,
+ _resolve_timeseries_request,
coin_api_source,
get_rows,
validate_credentials,
@@ -204,11 +205,116 @@ class TestExchangeRateEndpoint:
assert session.requested_urls[0] == f"{BASE_URL}/v1/exchangerate/EUR"
+class TestResolveTimeseriesRequest:
+ @parameterized.expand(
+ [
+ (
+ "symbol_in_path",
+ "ohlcv_history",
+ "/v1/ohlcv/SYM/history",
+ {"period_id": "1DAY"},
+ {"symbol_id": "SYM", "period_id": "1DAY"},
+ ),
+ (
+ "symbol_in_query",
+ "metrics_symbol_history",
+ "/v1/metrics/symbol/history",
+ {"symbol_id": "SYM", "metric_id": "FUNDING_RATE", "period_id": "1DAY"},
+ {"symbol_id": "SYM", "metric_id": "FUNDING_RATE", "period_id": "1DAY"},
+ ),
+ (
+ "assets_in_path",
+ "exchange_rates_history",
+ "/v1/exchangerate/USD/BTC/history",
+ {"period_id": "1DAY", "time_end": "2024-06-01T00:00:00Z"},
+ {"asset_id_base": "USD", "asset_id_quote": "BTC", "period_id": "1DAY"},
+ ),
+ (
+ "no_period",
+ "quotes_history",
+ "/v1/quotes/SYM/history",
+ {},
+ {"symbol_id": "SYM"},
+ ),
+ ]
+ )
+ def test_resolves_path_params_and_row_defaults(
+ self, _name: str, endpoint: str, path: str, params: dict, row_defaults: dict
+ ) -> None:
+ request = _resolve_timeseries_request(
+ config=COIN_API_ENDPOINTS[endpoint],
+ symbol_id="SYM",
+ period_id="1DAY",
+ metric_id="FUNDING_RATE",
+ exchange_rate_base_asset="USD",
+ exchange_rate_quote_asset="BTC",
+ time_end="2024-06-01T00:00:00Z",
+ )
+ assert (request.path, request.params, request.row_defaults) == (path, params, row_defaults)
+
+
class TestTimeseriesEndpoint:
def test_requires_symbol_id(self) -> None:
with pytest.raises(ValueError, match="requires a symbol_id"):
_run("ohlcv_history", [], _manager(), symbol_id="")
+ def test_requires_metric_id(self) -> None:
+ with pytest.raises(ValueError, match="requires a metric_id"):
+ _run("metrics_symbol_history", [], _manager(), symbol_id="SYM", metric_id="")
+
+ def test_requires_quote_asset(self) -> None:
+ with pytest.raises(ValueError, match="requires a quote asset"):
+ _run("exchange_rates_history", [], _manager(), exchange_rate_quote_asset="")
+
+ def test_metrics_symbol_history_sends_symbol_and_metric_as_query_params(self) -> None:
+ with mock.patch.object(coin_api, "PAGE_LIMIT", 5):
+ rows = [{"time_period_start": "2024-01-01T00:00:00.0000000Z", "sum": 1.5}]
+ batches, session = _run(
+ "metrics_symbol_history",
+ [_FakeResponse(json_data=rows)],
+ _manager(),
+ symbol_id="SYM",
+ metric_id="FUNDING_RATE",
+ )
+ url = session.requested_urls[0]
+ assert url.startswith(f"{BASE_URL}/v1/metrics/symbol/history?")
+ assert "symbol_id=SYM" in url
+ assert "metric_id=FUNDING_RATE" in url
+ assert "period_id=1DAY" in url
+ assert batches[0][0]["symbol_id"] == "SYM"
+ assert batches[0][0]["metric_id"] == "FUNDING_RATE"
+ assert batches[0][0]["period_id"] == "1DAY"
+
+ def test_exchange_rates_history_injects_both_assets(self) -> None:
+ with mock.patch.object(coin_api, "PAGE_LIMIT", 5):
+ rows = [{"time_period_start": "2024-01-01T00:00:00.0000000Z", "rate_close": 1.0}]
+ batches, session = _run(
+ "exchange_rates_history",
+ [_FakeResponse(json_data=rows)],
+ _manager(),
+ exchange_rate_base_asset="EUR",
+ exchange_rate_quote_asset="BTC",
+ )
+ assert session.requested_urls[0].startswith(f"{BASE_URL}/v1/exchangerate/EUR/BTC/history?")
+ # CoinAPI rejects this endpoint without time_end, so every page must carry one.
+ assert "time_end=" in session.requested_urls[0]
+ assert batches[0][0]["asset_id_base"] == "EUR"
+ assert batches[0][0]["asset_id_quote"] == "BTC"
+
+ def test_quotes_history_walks_forward_on_time_exchange(self) -> None:
+ with mock.patch.object(coin_api, "PAGE_LIMIT", 1):
+ page1 = [{"symbol_id": "SYM", "time_exchange": "2024-01-01T00:00:00.0000000Z", "bid_price": 1}]
+ page2: list[dict] = []
+ _, session = _run(
+ "quotes_history",
+ [_FakeResponse(json_data=page1), _FakeResponse(json_data=page2)],
+ _manager(),
+ symbol_id="SYM",
+ start_date="2023-01-01T00:00:00",
+ )
+ assert session.requested_urls[0].startswith(f"{BASE_URL}/v1/quotes/SYM/history?")
+ assert "time_start=2024-01-01T00%3A00%3A00.0000000Z" in session.requested_urls[1]
+
def test_injects_symbol_and_period_for_ohlcv(self) -> None:
with mock.patch.object(coin_api, "PAGE_LIMIT", 5):
rows = [{"time_period_start": "2024-01-01T00:00:00.0000000Z", "price_close": 1}]
@@ -290,6 +396,18 @@ class TestCoinApiSourceResponse:
("exchange_rates", ["asset_id_base", "asset_id_quote"], False),
("ohlcv_history", ["symbol_id", "period_id", "time_period_start"], True),
("trades_history", ["uuid"], True),
+ ("metrics_listing", ["metric_id"], False),
+ (
+ "exchange_rates_history",
+ ["asset_id_base", "asset_id_quote", "period_id", "time_period_start"],
+ True,
+ ),
+ ("metrics_symbol_history", ["symbol_id", "metric_id", "period_id", "time_period_start"], True),
+ (
+ "quotes_history",
+ ["symbol_id", "time_exchange", "time_coinapi", "ask_price", "ask_size", "bid_price", "bid_size"],
+ True,
+ ),
]
)
def test_primary_keys_and_partitioning(self, endpoint: str, expected_keys: list[str], partitioned: bool) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.py
index b610d6c4fa5e..9109d3260e29 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.py
@@ -43,18 +43,35 @@ class TestCoinApiSource:
def test_get_schemas_marks_only_timeseries_incremental(self) -> None:
schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
assert set(schemas) == set(ENDPOINTS)
- for name in ("assets", "exchanges", "symbols", "exchange_rates"):
+ for name in ("assets", "exchanges", "symbols", "exchange_rates", "metrics_listing"):
assert schemas[name].supports_incremental is False
assert schemas[name].supports_append is False
- for name in ("ohlcv_history", "trades_history"):
+ for name in (
+ "ohlcv_history",
+ "trades_history",
+ "exchange_rates_history",
+ "metrics_symbol_history",
+ "quotes_history",
+ ):
assert schemas[name].supports_incremental is True
assert schemas[name].supports_append is True
def test_timeseries_endpoints_off_by_default(self) -> None:
schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
assert schemas["assets"].should_sync_default is True
- assert schemas["ohlcv_history"].should_sync_default is False
- assert schemas["trades_history"].should_sync_default is False
+ assert schemas["metrics_listing"].should_sync_default is True
+ for name in ("ohlcv_history", "trades_history", "exchange_rates_history", "quotes_history"):
+ assert schemas[name].should_sync_default is False
+
+ def test_get_schemas_describes_every_field_an_endpoint_needs(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["metrics_symbol_history"].description == (
+ "Requires a Symbol ID and a Metric ID on the source. Only syncs the configured series."
+ )
+ assert schemas["exchange_rates_history"].description == (
+ "Requires an Exchange rate quote asset on the source. Only syncs the configured series."
+ )
+ assert schemas["assets"].description is None
def test_get_schemas_filtered_by_names(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id, names=["ohlcv_history"])
@@ -114,7 +131,9 @@ class TestCoinApiSource:
kwargs = mock_source.call_args.kwargs
assert kwargs["symbol_id"] == ""
assert kwargs["period_id"] == "1DAY"
+ assert kwargs["metric_id"] == ""
assert kwargs["exchange_rate_base_asset"] == "USD"
+ assert kwargs["exchange_rate_quote_asset"] == ""
assert kwargs["start_date"] == ""
def test_documented_tables_render_for_public_docs(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coinapi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coinapi.py
index 01cf892d4c3f..d8b65d36e507 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coinapi.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coinapi.py
@@ -8,6 +8,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
class CoinApiSourceConfig(config.Config):
api_key: str
exchange_rate_base_asset: str | None = None
+ exchange_rate_quote_asset: str | None = None
symbol_id: str | None = None
period_id: str | None = None
+ metric_id: str | None = None
start_date: str | None = None