:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 3 missing tables to the Kalshi source (#117467)
Tom Owersa6f87eded4ca
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 4355717c77ee..888189a85e02 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@@ -6711,9 +6711,9 @@ Today (5): `events`, `markets`, `milestones`, `series`, `trades`Diffed against: <https://docs.kalshi.com/openapi.yaml>-- [ ] `Market candlesticks (GET /trade-api/v2/markets/candlesticks)` — analyze price, volume, and liquidity trends using historical time buckets (high)-- [ ] `Historical markets (GET /trade-api/v2/historical/markets)` — retain archived contracts needed to interpret older trades and long-term market outcomes (high)-- [ ] `Historical trades (GET /trade-api/v2/historical/trades)` — recover trades before the historical cutoff for complete volume and price history (high)+- [x] `Market candlesticks (GET /trade-api/v2/markets/candlesticks)` — analyze price, volume, and liquidity trends using historical time buckets (high)+- [x] `Historical markets (GET /trade-api/v2/historical/markets)` — retain archived contracts needed to interpret older trades and long-term market outcomes (high)+- [x] `Historical trades (GET /trade-api/v2/historical/trades)` — recover trades before the historical cutoff for complete volume and price history (high)- [ ] `Positions (GET /trade-api/v2/portfolio/positions; GET /trade-api/v2/historical/positions)` — measure account exposure, realized profit, and trading fees for current and archived positions (high)- [ ] `Fills (GET /trade-api/v2/portfolio/fills; GET /trade-api/v2/historical/fills)` — analyze account execution prices, fees, and trading volume across current and archived fills (high)- [ ] `Settlements (GET /trade-api/v2/portfolio/settlements)` — reconcile settled contracts with payouts and account trading results (high)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.pyindex c83f8e1562cf..ed782ecf2bc9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/canonical_descriptions.py@@ -2,39 +2,54 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)+_MARKET_COLUMNS = {+ "ticker": "Unique identifier for the market.",+ "event_ticker": "Identifier of the event this market belongs to.",+ "market_type": "Structure of the contract, for example binary or scalar.",+ "title": "Human-readable question the market resolves.",+ "status": "Lifecycle state of the market, for example active, closed, or settled.",+ "created_time": "When the market was created.",+ "updated_time": "When the market was last modified.",+ "open_time": "When the market opened for trading.",+ "close_time": "When the market stops accepting trades.",+ "expiration_time": "When the market expires.",+ "expected_expiration_time": "Currently expected expiration time, which can move before settlement.",+ "result": "Settlement outcome once the market has resolved.",+ "rules_primary": "Primary resolution rules for the market.",+ "rules_secondary": "Additional resolution detail and edge cases.",+ "strike_type": "How the strike is expressed, for example greater than or between.",+ "yes_bid_dollars": "Best bid price for the yes side, in dollars.",+ "yes_ask_dollars": "Best ask price for the yes side, in dollars.",+ "no_bid_dollars": "Best bid price for the no side, in dollars.",+ "no_ask_dollars": "Best ask price for the no side, in dollars.",+ "last_price_dollars": "Price of the most recent trade, in dollars.",+ "previous_price_dollars": "Price at the previous close, in dollars.",+ "volume_fp": "Total contracts traded over the market's life.",+ "volume_24h_fp": "Contracts traded in the last 24 hours.",+ "open_interest_fp": "Contracts currently outstanding.",+ "liquidity_dollars": "Resting liquidity in the order book, in dollars.",+ "notional_value_dollars": "Payout of a single contract at settlement, in dollars.",+ "can_close_early": "Whether the market may close before its scheduled close time.",+}++_TRADE_COLUMNS = {+ "trade_id": "Unique identifier for the trade.",+ "ticker": "Market the trade executed in.",+ "created_time": "When the trade executed.",+ "count_fp": "Number of contracts traded.",+ "yes_price_dollars": "Price paid for the yes side, in dollars.",+ "no_price_dollars": "Price paid for the no side, in dollars.",+ "taker_side": "Side the taker traded, yes or no.",+ "taker_outcome_side": "Outcome the taker bought.",+ "taker_book_side": "Book side the taker executed against, bid or ask.",+ "is_block_trade": "Whether the trade was negotiated as a block rather than matched on the book.",+}+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"markets": {"description": "One row per tradeable event contract, carrying its rules, current quotes, and settlement outcome.","docs_url": "https://docs.kalshi.com/api-reference/market/get-markets",- "columns": {- "ticker": "Unique identifier for the market.",- "event_ticker": "Identifier of the event this market belongs to.",- "market_type": "Structure of the contract, for example binary or scalar.",- "title": "Human-readable question the market resolves.",- "status": "Lifecycle state of the market, for example active, closed, or settled.",- "created_time": "When the market was created.",- "updated_time": "When the market was last modified.",- "open_time": "When the market opened for trading.",- "close_time": "When the market stops accepting trades.",- "expiration_time": "When the market expires.",- "expected_expiration_time": "Currently expected expiration time, which can move before settlement.",- "result": "Settlement outcome once the market has resolved.",- "rules_primary": "Primary resolution rules for the market.",- "rules_secondary": "Additional resolution detail and edge cases.",- "strike_type": "How the strike is expressed, for example greater than or between.",- "yes_bid_dollars": "Best bid price for the yes side, in dollars.",- "yes_ask_dollars": "Best ask price for the yes side, in dollars.",- "no_bid_dollars": "Best bid price for the no side, in dollars.",- "no_ask_dollars": "Best ask price for the no side, in dollars.",- "last_price_dollars": "Price of the most recent trade, in dollars.",- "previous_price_dollars": "Price at the previous close, in dollars.",- "volume_fp": "Total contracts traded over the market's life.",- "volume_24h_fp": "Contracts traded in the last 24 hours.",- "open_interest_fp": "Contracts currently outstanding.",- "liquidity_dollars": "Resting liquidity in the order book, in dollars.",- "notional_value_dollars": "Payout of a single contract at settlement, in dollars.",- "can_close_early": "Whether the market may close before its scheduled close time.",- },+ "columns": _MARKET_COLUMNS,},"events": {"description": "Groups the markets that resolve the same real-world question, such as one election or one game.",@@ -74,18 +89,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"trades": {"description": "Every public trade printed on the exchange, append-only, one row per execution.","docs_url": "https://docs.kalshi.com/api-reference/market/get-trades",- "columns": {- "trade_id": "Unique identifier for the trade.",- "ticker": "Market the trade executed in.",- "created_time": "When the trade executed.",- "count_fp": "Number of contracts traded.",- "yes_price_dollars": "Price paid for the yes side, in dollars.",- "no_price_dollars": "Price paid for the no side, in dollars.",- "taker_side": "Side the taker traded, yes or no.",- "taker_outcome_side": "Outcome the taker bought.",- "taker_book_side": "Book side the taker executed against, bid or ask.",- "is_block_trade": "Whether the trade was negotiated as a block rather than matched on the book.",- },+ "columns": _TRADE_COLUMNS,},"milestones": {"description": "Scheduled real-world happenings, such as a court date or a data release, that Kalshi ties markets to.",@@ -105,4 +109,27 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_updated_ts": "When the milestone was last modified.",},},+ "historical_markets": {+ "description": "Markets that settled before Kalshi's historical cutoff and moved out of the live markets list into the archive.",+ "docs_url": "https://docs.kalshi.com/api-reference/historical/get-historical-markets",+ "columns": _MARKET_COLUMNS,+ },+ "historical_trades": {+ "description": "Public trades filled before Kalshi's historical cutoff, one row per execution.",+ "docs_url": "https://docs.kalshi.com/api-reference/historical/get-historical-trades",+ "columns": _TRADE_COLUMNS,+ },+ "market_candlesticks": {+ "description": "Daily open, high, low, and close prices, volume, and open interest for each live market.",+ "docs_url": "https://docs.kalshi.com/api-reference/market/batch-get-market-candlesticks",+ "columns": {+ "market_ticker": "Market the candlestick describes.",+ "end_period_ts": "Unix timestamp, in seconds, of the inclusive end of the daily period.",+ "price": "Open, high, low, close, mean, and previous traded yes prices in the period, in dollars. Null fields mean no trade.",+ "yes_bid": "Open, high, low, and close of the best yes bid in the period, in dollars.",+ "yes_ask": "Open, high, low, and close of the best yes ask in the period, in dollars.",+ "volume_fp": "Contracts traded in the period.",+ "open_interest_fp": "Contracts outstanding at the end of the period.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.pyindex a373845636d3..6b004d631dd1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/kalshi.py@@ -1,3 +1,4 @@+from collections.abc import Iterable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional@@ -12,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resJSONResponseCursorPaginator,SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpointfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe@@ -23,6 +25,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.setKALSHI_BASE_URL = "https://api.elections.kalshi.com/trade-api/v2"+CANDLESTICK_PERIOD_MINUTES = 1440+_CANDLESTICK_PERIOD_SECONDS = CANDLESTICK_PERIOD_MINUTES * 60+# The batch candlestick endpoint takes at most 100 tickers and returns at most 10,000 candlesticks+# per request, with no pagination, so a batch that could exceed the cap is split before it is sent.+_MAX_TICKERS_PER_REQUEST = 100+_MAX_CANDLESTICKS_PER_REQUEST = 10_000+@frozenclass KalshiResumeConfig:@@ -46,6 +55,143 @@ def _to_epoch_seconds(value: Any) -> Optional[int]:return None+@frozen+class _CandlestickMarket:+ ticker: str+ start_ts: int+ end_ts: int++ @property+ def expected_candlesticks(self) -> int:+ # One candlestick per period, plus the partial periods at each end of the window.+ return (self.end_ts - self.start_ts) // _CANDLESTICK_PERIOD_SECONDS + 2+++def _candlestick_market(market: dict[str, Any], window_start: Optional[int], now: int) -> Optional[_CandlestickMarket]:+ ticker = market.get("ticker")+ opened = _to_epoch_seconds(market.get("open_time"))+ if not ticker or opened is None:+ return None+ start = opened if window_start is None else max(opened, window_start)+ closed = _to_epoch_seconds(market.get("close_time"))+ end = now if closed is None else min(closed, now)+ if start >= end:+ return None+ return _CandlestickMarket(ticker=str(ticker), start_ts=start, end_ts=end)+++def _batch_markets(markets: Iterable[_CandlestickMarket]) -> Iterator[list[_CandlestickMarket]]:+ batch: list[_CandlestickMarket] = []+ expected = 0+ for market in markets:+ cost = market.expected_candlesticks+ if batch and (len(batch) >= _MAX_TICKERS_PER_REQUEST or expected + cost > _MAX_CANDLESTICKS_PER_REQUEST):+ yield batch+ batch, expected = [], 0+ batch.append(market)+ expected += cost+ if batch:+ yield batch+++def _fetch_candlesticks(client: RESTClient, batch: list[_CandlestickMarket], now: int) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for page in client.paginate(+ path="/markets/candlesticks",+ params={+ "market_tickers": ",".join(market.ticker for market in batch),+ "start_ts": min(market.start_ts for market in batch),+ "end_ts": now,+ "period_interval": CANDLESTICK_PERIOD_MINUTES,+ },+ paginator=SinglePagePaginator(),+ data_selector="markets",+ data_selector_required=True,+ ):+ for market in page:+ for candlestick in market.get("candlesticks") or []:+ rows.append({"market_ticker": market.get("market_ticker"), **candlestick})+ return rows+++def _candlestick_rows(+ client: RESTClient,+ resumable_source_manager: ResumableSourceManager[KalshiResumeConfig],+ window_start: Optional[int],+ now: int,+) -> Iterator[list[dict[str, Any]]]:+ params: dict[str, Any] = {"limit": 1000, "mve_filter": "exclude"}+ if window_start is not None:+ # A market that closed before the window has no candlesticks in it.+ params["min_close_ts"] = window_start++ page_cursor: Optional[str] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ page_cursor = resume.cursor++ next_cursor: list[Optional[str]] = [None]++ def remember_next_cursor(state: Optional[dict[str, Any]], has_next_page: bool) -> None:+ next_cursor[0] = str(state["cursor"]) if has_next_page and state and state.get("cursor") else None++ for markets in client.paginate(+ path="/markets",+ params=params,+ paginator=JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor"),+ data_selector="markets",+ data_selector_required=True,+ initial_paginator_state={"cursor": page_cursor} if page_cursor else None,+ page_state_hook=remember_next_cursor,+ ):+ # Every row of the earlier market pages is already yielded, so resuming from the cursor that+ # fetched this page loses nothing.+ if page_cursor:+ resumable_source_manager.save_state(KalshiResumeConfig(cursor=page_cursor))+ resumable_source_manager.safe_point()++ candidates = (_candlestick_market(market, window_start, now) for market in markets)+ pending = list(_batch_markets(market for market in candidates if market is not None))+ pending.reverse()+ while pending:+ batch = pending.pop()+ rows = _fetch_candlesticks(client, batch, now)+ if len(rows) >= _MAX_CANDLESTICKS_PER_REQUEST and len(batch) > 1:+ # The response may be truncated at the cap; refetch the batch in halves.+ middle = len(batch) // 2+ pending.extend([batch[middle:], batch[:middle]])+ resumable_source_manager.safe_point()+ continue+ if rows:+ yield rows+ else:+ resumable_source_manager.safe_point()++ page_cursor = next_cursor[0]+++def _candlestick_source(+ config: KalshiEndpointConfig,+ resumable_source_manager: ResumableSourceManager[KalshiResumeConfig],+ last_value: Optional[Any],+) -> SourceResponse:+ client = RESTClient(base_url=KALSHI_BASE_URL, headers={"Accept": "application/json"})+ last_period_end = _to_epoch_seconds(last_value)+ # Start one period back so the latest, possibly partial, candlestick is fetched again.+ window_start = None if last_period_end is None else last_period_end - _CANDLESTICK_PERIOD_SECONDS+ now = int(datetime.now(UTC).timestamp())++ return SourceResponse(+ name=config.name,+ items=lambda: _candlestick_rows(client, resumable_source_manager, window_start, now),+ primary_keys=config.primary_keys,+ # Rows arrive grouped by market, not by time, so the watermark can only advance once the+ # walk completes.+ sort_mode="desc",+ )++def _build_endpoint(config: KalshiEndpointConfig, should_use_incremental_field: bool) -> Endpoint:endpoint: Endpoint = {"path": config.path,@@ -81,6 +227,10 @@ def kalshi_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = KALSHI_ENDPOINTS[endpoint]+ last_value = db_incremental_field_last_value if should_use_incremental_field else None++ if config.market_fan_out:+ return _candlestick_source(config, resumable_source_manager, last_value)# Kalshi's market-data endpoints are public and take no credential, so no `auth` is configured.rest_config: RESTAPIConfig = {@@ -109,8 +259,6 @@ def kalshi_source(if state and state.get("cursor"):resumable_source_manager.save_state(KalshiResumeConfig(cursor=str(state["cursor"])))- last_value = db_incremental_field_last_value if should_use_incremental_field else None-resource = rest_api_resource(rest_config,team_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.pyindex 8f6f5c33e5ef..c89a2727f53c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/settings.py@@ -14,13 +14,16 @@ class KalshiEndpointConfig:primary_keys: list[str] = field(default_factory=lambda: ["ticker"])partition_key: Optional[str] = None # stable creation-time field for datetime partitioningincremental_fields: list[IncrementalField] = field(default_factory=list)- # Only trades exposes a server-side time filter (`min_ts`). Everything else accepts the param- # and silently ignores it, so those endpoints are full-refresh only.+ # Only the trade endpoints expose a server-side time filter (`min_ts`), and candlesticks take an+ # explicit time window. Everything else accepts the param and silently ignores it, so those+ # endpoints are full-refresh only.supports_incremental: bool = False# Trades come back newest-first; every other endpoint is treated as ascending.newest_first: bool = False# `/series` returns the whole collection in one response with no `cursor` key.paginated: bool = True+ # Candlesticks are fetched per batch of markets, so rows arrive in no global time order.+ market_fan_out: bool = Falsepage_size: int = 200@@ -35,6 +38,17 @@ def _created_time_field() -> list[IncrementalField]:]+def _end_period_ts_field() -> list[IncrementalField]:+ return [+ {+ "label": "end_period_ts",+ "type": IncrementalFieldType.Integer,+ "field": "end_period_ts",+ "field_type": IncrementalFieldType.Integer,+ }+ ]++KALSHI_ENDPOINTS: dict[str, KalshiEndpointConfig] = {# Every market ever listed, one row per contract. `updated_time` moves but there is no filter# for it, so this is a full refresh; partition on the stable `created_time`.@@ -85,6 +99,39 @@ KALSHI_ENDPOINTS: dict[str, KalshiEndpointConfig] = {primary_keys=["id"],page_size=200,),+ # Markets that settled before the historical cutoff move out of `/markets` into this archive.+ "historical_markets": KalshiEndpointConfig(+ name="historical_markets",+ path="/historical/markets",+ data_key="markets",+ primary_keys=["ticker"],+ partition_key="created_time",+ page_size=1000,+ ),+ # Trades filled before the historical cutoff. Like `/markets/trades`, it honours `min_ts` and+ # returns newest-first.+ "historical_trades": KalshiEndpointConfig(+ name="historical_trades",+ path="/historical/trades",+ data_key="trades",+ primary_keys=["trade_id"],+ partition_key="created_time",+ incremental_fields=_created_time_field(),+ supports_incremental=True,+ newest_first=True,+ page_size=1000,+ ),+ # Daily candlesticks for every live non-combo market, fetched in batches of tickers.+ "market_candlesticks": KalshiEndpointConfig(+ name="market_candlesticks",+ path="/markets/candlesticks",+ data_key="markets",+ primary_keys=["market_ticker", "end_period_ts"],+ incremental_fields=_end_period_ts_field(),+ supports_incremental=True,+ market_fan_out=True,+ page_size=1000,+ ),}ENDPOINTS = tuple(KALSHI_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.pyindex acfb250b6972..97f466063e31 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/source.py@@ -56,7 +56,7 @@ class KalshiSource(ResumableSource[KalshiSourceConfig, KalshiResumeConfig]):releaseStatus=ReleaseStatus.ALPHA,caption="""Kalshi's market data endpoints are public, so this source needs no API key.-It syncs markets, events, series, trades, and milestones. Portfolio data (your own orders, fills, and positions) needs a signed API key and is not supported yet.""",+It syncs markets, events, series, trades, milestones, and daily market candlesticks. It also syncs the historical archive of markets and trades. Portfolio data (your own orders, fills, and positions) needs a signed API key and is not supported yet.""",iconPath="/static/services/kalshi.png",docsUrl="https://posthog.com/docs/cdp/sources/kalshi",keywords=["prediction market", "event contracts", "trading"],@@ -86,8 +86,8 @@ It syncs markets, events, series, trades, and milestones. Portfolio data (your oforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Only `trades` carries incremental fields, so build_endpoint_schemas marks it (and only it)- # incremental and leaves the rest full-refresh.+ # Only the trade and candlestick endpoints carry incremental fields, so build_endpoint_schemas+ # marks them incremental and leaves the rest full-refresh.return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)def validate_credentials(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.pyindex 521f2ebc3556..028b7d950321 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi.py@@ -1,4 +1,4 @@-from datetime import UTC, date, datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Anyfrom parameterized import parameterized@@ -7,11 +7,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesScriptedResponse,SourceDriver,always,+ route,scripted_network,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kalshi import KalshiSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.kalshi.kalshi import (KalshiResumeConfig,+ _batch_markets,+ _candlestick_market,+ _CandlestickMarket,_to_epoch_seconds,validate_credentials,)@@ -30,6 +34,25 @@ def _page(data_key: str, items: list[dict[str, Any]], *, cursor: str | None = Noreturn ScriptedResponse(json=body)+def _epoch(moment: datetime) -> int:+ return int(moment.timestamp())+++def _market(ticker: str, opened: datetime, closes: datetime) -> dict[str, Any]:+ return {"ticker": ticker, "open_time": opened.isoformat(), "close_time": closes.isoformat()}+++def _candlesticks(*markets: tuple[str, list[int]]) -> ScriptedResponse:+ return ScriptedResponse(+ json={+ "markets": [+ {"market_ticker": ticker, "candlesticks": [{"end_period_ts": ts, "volume_fp": "1.00"} for ts in ends]}+ for ticker, ends in markets+ ]+ }+ )++class TestKalshiTransport:@parameterized.expand([@@ -47,19 +70,26 @@ class TestKalshiTransport:# API and quietly turn every incremental sync into a full scan.assert _to_epoch_seconds(value) == expected- def test_trades_incremental_sends_min_ts(self) -> None:+ @parameterized.expand(+ [+ ("trades", "/trade-api/v2/markets/trades"),+ ("historical_trades", "/trade-api/v2/historical/trades"),+ ]+ )+ def test_trades_incremental_sends_min_ts(self, endpoint: str, path: str) -> None:result = _driver().run(- "trades",+ endpoint,[_page("trades", [{"trade_id": "t1"}])],incremental_field="created_time",db_incremental_field_last_value=datetime(2021, 1, 1, tzinfo=UTC),)assert result.raised is None+ assert result.paths == [path]assert result.requests[0].param("min_ts") == "1609459200"- assert result.requests[0].param("limit") == str(KALSHI_ENDPOINTS["trades"].page_size)+ assert result.requests[0].param("limit") == str(KALSHI_ENDPOINTS[endpoint].page_size)- @parameterized.expand(["markets", "events", "milestones"])+ @parameterized.expand(["markets", "events", "milestones", "historical_markets"])def test_non_incremental_endpoints_never_send_min_ts(self, endpoint: str) -> None:# Kalshi answers 200 and ignores params it doesn't recognise, so a filter wired onto an# endpoint that has none would look like it worked while syncing everything every run.@@ -102,6 +132,7 @@ class TestKalshiTransport:@parameterized.expand([("trades", "desc"),+ ("historical_trades", "desc"),("markets", "asc"),("series", "asc"),]@@ -155,3 +186,184 @@ class TestKalshiTransport:assert validate_credentials() is expectedassert network.requests_log[0].path == "/trade-api/v2/exchange/status"+++class TestKalshiCandlesticks:+ def test_walks_market_pages_and_batches_candlestick_requests(self) -> None:+ now = datetime.now(UTC)+ opened_a, opened_b = now - timedelta(days=3), now - timedelta(days=10)+ closes = now + timedelta(days=30)+ result = _driver().run(+ "market_candlesticks",+ route(+ {+ "/markets": [+ _page(+ "markets",+ [+ _market("A", opened_a, closes),+ _market("B", opened_b, closes),+ # Not open yet, so it has no candlesticks to fetch.+ _market("LATER", now + timedelta(days=1), closes),+ ],+ cursor="c1",+ ),+ _page("markets", [_market("C", opened_a, closes)]),+ ],+ "/candlesticks": [+ _candlesticks(("A", [100, 200]), ("B", [300])),+ _candlesticks(("C", [])),+ ],+ }+ ),+ should_use_incremental_field=False,+ )++ assert result.raised is None+ assert result.paths == [+ "/trade-api/v2/markets",+ "/trade-api/v2/markets/candlesticks",+ "/trade-api/v2/markets",+ "/trade-api/v2/markets/candlesticks",+ ]+ assert result.params("cursor") == [None, None, "c1", None]+ assert result.params("mve_filter") == ["exclude", None, "exclude", None]+ assert result.params("min_close_ts") == [None, None, None, None]+ assert result.params("market_tickers") == [None, "A,B", None, "C"]+ assert result.params("start_ts") == [None, str(_epoch(opened_b)), None, str(_epoch(opened_a))]+ assert result.params("period_interval") == [None, "1440", None, "1440"]+ assert result.rows == [+ {"market_ticker": "A", "end_period_ts": 100, "volume_fp": "1.00"},+ {"market_ticker": "A", "end_period_ts": 200, "volume_fp": "1.00"},+ {"market_ticker": "B", "end_period_ts": 300, "volume_fp": "1.00"},+ ]+ assert result.response is not None+ assert result.response.sort_mode == "desc"++ @parameterized.expand(+ [+ ("watermark_after_open", 5, 3),+ ("watermark_before_open", 30, 3),+ ]+ )+ def test_incremental_sync_windows_markets_and_candlesticks(+ self, _name: str, opened_days_ago: int, watermark_days_ago: int+ ) -> None:+ now = datetime.now(UTC)+ opened = now - timedelta(days=opened_days_ago)+ watermark = _epoch(now - timedelta(days=watermark_days_ago))+ window_start = watermark - 86400+ result = _driver().run(+ "market_candlesticks",+ route(+ {+ "/markets": [_page("markets", [_market("A", opened, now + timedelta(days=1))])],+ "/candlesticks": [_candlesticks(("A", [watermark + 86400]))],+ }+ ),+ incremental_field="end_period_ts",+ db_incremental_field_last_value=watermark,+ )++ assert result.raised is None+ assert result.params("min_close_ts") == [str(window_start), None]+ assert result.params("start_ts") == [None, str(max(_epoch(opened), window_start))]+ assert result.rows == [{"market_ticker": "A", "end_period_ts": watermark + 86400, "volume_fp": "1.00"}]++ def test_refetches_a_batch_in_halves_when_the_response_hits_the_cap(self) -> None:+ now = datetime.now(UTC)+ opened, closes = now - timedelta(days=2), now + timedelta(days=1)+ result = _driver().run(+ "market_candlesticks",+ route(+ {+ "/markets": [_page("markets", [_market("A", opened, closes), _market("B", opened, closes)])],+ "/candlesticks": [+ _candlesticks(("A", list(range(5_000))), ("B", list(range(5_000)))),+ _candlesticks(("A", [1])),+ _candlesticks(("B", [2])),+ ],+ }+ ),+ should_use_incremental_field=False,+ )++ assert result.raised is None+ assert result.params("market_tickers") == [None, "A,B", "A", "B"]+ assert [(row["market_ticker"], row["end_period_ts"]) for row in result.rows] == [("A", 1), ("B", 2)]++ def test_resumes_from_the_saved_market_page_and_stages_each_page_cursor(self) -> None:+ now = datetime.now(UTC)+ opened, closes = now - timedelta(days=2), now + timedelta(days=1)+ result = _driver().run(+ "market_candlesticks",+ route(+ {+ "/markets": [+ _page("markets", [_market("A", opened, closes)], cursor="c2"),+ _page("markets", [_market("B", opened, closes)]),+ ],+ "/candlesticks": [_candlesticks(("A", [1])), _candlesticks(("B", [2]))],+ }+ ),+ should_use_incremental_field=False,+ resume_state=KalshiResumeConfig(cursor="saved"),+ )++ assert result.raised is None+ assert result.params("cursor") == ["saved", None, "c2", None]+ # Each cursor is staged before the rows of the page it fetched, so a resume rereads that page.+ assert result.saved_states == [KalshiResumeConfig(cursor="saved"), KalshiResumeConfig(cursor="c2")]+ assert KalshiResumeConfig(cursor="c2") in result.committed_states++ @parameterized.expand(+ [+ ("open_market", 10, 5, None, (-10, 0)),+ ("closed_market_ends_at_close", 10, -2, None, (-10, -2)),+ ("window_after_open", 10, 5, -3, (-3, 0)),+ ("not_open_yet", -1, 5, None, None),+ ("closed_before_window", 10, -5, -3, None),+ ]+ )+ def test_candlestick_market_window(+ self,+ _name: str,+ opened_days_ago: int,+ closes_in_days: int,+ window_days: int | None,+ expected_days: tuple[int, int] | None,+ ) -> None:+ now = 1_800_000_000+ day = 86400+ market = {+ "ticker": "A",+ "open_time": datetime.fromtimestamp(now - opened_days_ago * day, UTC).isoformat(),+ "close_time": datetime.fromtimestamp(now + closes_in_days * day, UTC).isoformat(),+ }+ window_start = None if window_days is None else now + window_days * day++ result = _candlestick_market(market, window_start, now)++ if expected_days is None:+ assert result is None+ else:+ assert result == _CandlestickMarket(+ ticker="A", start_ts=now + expected_days[0] * day, end_ts=now + expected_days[1] * day+ )++ @parameterized.expand(+ [+ # 150 short-lived markets split on the 100-ticker limit.+ ("ticker_limit", 150, 1, [100, 50]),+ # Each market can return about 1,002 candlesticks, so 9 fit under the 10,000 cap.+ ("candlestick_cap", 20, 1000, [9, 9, 2]),+ # One market alone over the cap still gets a request of its own.+ ("single_oversized_market", 2, 20_000, [1, 1]),+ ]+ )+ def test_batches_respect_ticker_and_candlestick_limits(+ self, _name: str, count: int, days: int, expected_sizes: list[int]+ ) -> None:+ markets = [_CandlestickMarket(ticker=str(i), start_ts=0, end_ts=days * 86400) for i in range(count)]++ assert [len(batch) for batch in _batch_markets(markets)] == expected_sizesdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.pyindex a8dd8d7d4568..de010ce49849 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kalshi/tests/test_kalshi_source.py@@ -13,15 +13,18 @@ class TestKalshiSource:@parameterized.expand([("trades_is_incremental", "trades", True),+ ("historical_trades_is_incremental", "historical_trades", True),+ ("market_candlesticks_is_incremental", "market_candlesticks", True),("markets_is_not", "markets", False),+ ("historical_markets_is_not", "historical_markets", False),("events_is_not", "events", False),("series_is_not", "series", False),("milestones_is_not", "milestones", False),])- def test_only_trades_supports_incremental(self, _name: str, endpoint: str, expected: bool) -> None:- # Only /markets/trades honours a server-side time filter. Advertising incremental anywhere- # else would promise a cheap sync that still walks the whole collection.+ def test_only_time_filtered_endpoints_support_incremental(self, _name: str, endpoint: str, expected: bool) -> None:+ # Only the trade and candlestick endpoints honour a server-side time filter. Advertising+ # incremental anywhere else would promise a cheap sync that still walks the whole collection.schemas = {s.name: s for s in KalshiSource().get_schemas(None, 1)} # type: ignore[arg-type]assert schemas[endpoint].supports_incremental is expected