### GET /api-reference/market/get-markets Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves a list of all available markets, with optional filtering and pagination ```APIDOC ## GET /api-reference/market/get-markets ### Description Retrieves a paginated list of all available markets with optional filtering criteria ### Method GET ### Endpoint /api-reference/market/get-markets ### Parameters #### Query Parameters - **status** (string) - Optional - Filter by market status (active, closed, etc.) - **category** (string) - Optional - Filter by market category - **page** (integer) - Optional - Page number for pagination (default: 1) - **limit** (integer) - Optional - Number of markets per page (default: 100) - **sort_by** (string) - Optional - Field to sort by (e.g., 'created_at', 'volume') ### Request Example { "status": "active", "category": "politics", "page": 1, "limit": 50 } ### Response #### Success Response (200) - **markets** (array) - Array of market objects - **pagination** (object) - Pagination information - **total** (integer) - Total number of markets matching criteria - **page** (integer) - Current page number - **limit** (integer) - Number of markets per page #### Response Example { "markets": [ { "market_id": "KALS样-2023-XYZ", "name": "Will Event X occur?", "category": "politics", "status": "active", "current_price": 45.8, "volume": 15000 } ], "pagination": { "total": 250, "page": 1, "limit": 50 } } ``` -------------------------------- ### GET /api-reference/live_data/get-live-data Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves real-time market data including current prices, volumes, and market status ```APIDOC ## GET /api-reference/live_data/get-live-data ### Description Retrieves real-time market data including current prices, volumes, spreads, and market status for all active markets ### Method GET ### Endpoint /api-reference/live_data/get-live-data ### Parameters #### Query Parameters - **market_ids** (array) - Optional - Array of specific market IDs to retrieve data for - **categories** (array) - Optional - Filter by market categories - **limit** (integer) - Optional - Maximum number of markets to return ### Request Example { "market_ids": ["KALS样-2023-XYZ", "KALS样-2023-ABC"], "categories": ["politics", "sports"], "limit": 50 } ### Response #### Success Response (200) - **markets** (array) - Array of live market data - **market_id** (string) - Unique identifier for the market - **current_price** (number) - Current market price - **bid** (number) - Current bid price - **ask** (number) - Current ask price - **volume** (number) - Trading volume - **change_24h** (number) - 24-hour price change - **last_update** (string) - Timestamp of last update - **status** (string) - Market status #### Response Example { "markets": [ { "market_id": "KALS样-2023-XYZ", "current_price": 45.8, "bid": 45.5, "ask": 46.1, "volume": 15000, "change_24h": 2.3, "last_update": "2023-06-01T12:30:00Z", "status": "active" } ] } ``` -------------------------------- ### GET /api-reference/events/get-events Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves a list of all events, with filtering and pagination options ```APIDOC ## GET /api-reference/events/get-events ### Description Retrieves a list of all available events with optional filtering and pagination ### Method GET ### Endpoint /api-reference/events/get-events ### Parameters #### Query Parameters - **category** (string) - Optional - Filter by event category - **status** (string) - Optional - Filter by event status - **page** (integer) - Optional - Page number for pagination (default: 1) - **limit** (integer) - Optional - Number of events per page (default: 100) - **search** (string) - Optional - Search term for event names/descriptions ### Request Example { "category": "sports", "status": "upcoming", "page": 1, "limit": 20 } ### Response #### Success Response (200) - **events** (array) - Array of event objects - **event_id** (string) - Unique identifier for the event - **name** (string) - Event name - **description** (string) - Event description - **category** (string) - Event category - **start_time** (string) - Event start time - **status** (string) - Current status - **pagination** (object) - Pagination information #### Response Example { "events": [ { "event_id": "event_12345", "name": "2023 World Cup Final", "description": "Final match of the 2023 FIFA World Cup", "category": "sports", "start_time": "2023-12-18T16:00:00Z", "status": "upcoming" } ], "pagination": { "total": 500, "page": 1, "limit": 20 } } ``` -------------------------------- ### GET /series Source: https://context7.com/disler/beyond-mcp/llms.txt Lists all available series, which are templates for creating markets. Options to filter by category, tags, and include product metadata. ```APIDOC ## GET /series ### Description List all series (~6900 market templates) ### Method GET ### Endpoint /series ### Parameters #### Query Parameters - **category** (string) - Optional - Filter series by category. - **tags** (string) - Optional - Filter series by tags. - **include_product_metadata** (boolean) - Optional - Whether to include detailed product metadata (default: false). ### Request Example ```json { "category": "politics", "include_product_metadata": true } ``` ### Response #### Success Response (200) - **series** (array) - A list of series objects. #### Response Example ```json { "series": [ { "ticker": "2024_us_election", "name": "2024 US Election Series", "category": "politics", "tags": ["election", "usa", "2024"] } ] } ``` ``` -------------------------------- ### Use Kalshi Search Cache Source: https://context7.com/disler/beyond-mcp/llms.txt Example usage of the KalshiSearchCache for performing keyword searches. First run builds the cache (2-5 minutes), subsequent runs use the cached data for instant results. ```python # Usage in CLI cache = KalshiSearchCache() results = cache.search(client, "bitcoin", limit=10, quiet=False) # First run: 2-5 minutes to build cache # Subsequent runs: Instant! ``` -------------------------------- ### Execute end-to-end Kalshi workflow via Bash commands Source: https://context7.com/disler/beyond-mcp/llms.txt Provides a Bash script that walks through four integration approaches (MCP server, CLI, file‑system scripts, and skill‑based usage). Shows installation steps, command invocations, and notes on context usage and performance trade‑offs. Requires UV toolchain and appropriate repository layout. ```bash # 1. MCP SERVER APPROACH # Install server cd apps/1_mcp_server uv run mcp install server.py --name "Kalshi Markets" # Use in Claude Desktop # User: "What's the Kalshi exchange status?" # Claude: [Calls get_exchange_status tool via MCP] # User: "Search for Bitcoin markets" # Claude: [Calls search_markets tool with keyword="Bitcoin"] # # Characteristics: # - Every tool call loses context # - Standardized protocol # - Works with any MCP client # 2. CLI APPROACH cd apps/2_cli uv sync # By hand uv run kalshi status uv run kalshi search "bitcoin" --json | jq # By agent via bash tool # User: "Check Kalshi exchange status using the CLI" # Claude: [Runs bash command: cd apps/2_cli && uv run kalshi status --json] # Claude: [Parses JSON output, presents to user] # # With prime prompt (.claude/commands/prime_kalshi_cli_tools.md): # User: "/prime_kalshi_cli_tools" # Claude: [Loads CLI documentation into context] # User: "Get exchange status" # Claude: [Knows to use CLI, executes command] # # Characteristics: # - Subprocess overhead # - Context preserved via prime prompt # - Dual human/agent usage # 3. FILE SYSTEM SCRIPTS APPROACH cd apps/3_file_system_scripts # By hand uv run scripts/status.py --json uv run scripts/search.py "election" --json # By agent # User: "Check Kalshi status using the scripts in apps/3_file_system_scripts" # Claude: [Lists scripts directory, finds status.py] # Claude: [Reads status.py (158 lines) to understand it] # Claude: [Executes: uv run scripts/status.py --json] # Claude: [Processes output] # # With prime prompt: # User: "/prime_file_system_scripts" # Claude: [Loads script overview into context] # User: "Search for Bitcoin markets" # Claude: [Executes: uv run scripts/search.py "bitcoin" --json] # # Characteristics: # - Progressive disclosure (only load needed script) # - Zero shared dependencies # - Maximum portability # 4. SKILL APPROACH (Claude Code only) cd apps/4_skill claude # Natural language usage - automatic skill detection # User: "What are the top Bitcoin prediction markets?" # Claude: [Detects "prediction markets" keyword] # Claude: [Auto-loads kalshi-markets skill] # Claude: [Reads SKILL.md for instructions] # Claude: [Executes: uv run scripts/search.py "bitcoin" --json --limit 10] # Claude: [Analyzes results, responds naturally] # User: "Show me the orderbook for KXBTCD-25NOV0612-T102499.99" # Claude: [Skill already loaded] # Claude: [Executes: uv run scripts/orderbook.py KXBTCD-25NOV0612-T102499.99 --json] # Claude: [Formats orderbook data for display] # # Characteristics: # - Automatic discovery and invocation # - Same progressive disclosure as scripts # - Team sharing via git # - Claude Code ecosystem only # Performance comparison: # MCP: High context usage every call (full tool definitions) # CLI: Medium context (prime prompt + command output) # Scripts: Low context (only scripts used + output) # Skills: Low context (SKILL.md + scripts used + output) ``` -------------------------------- ### GET /api-reference/search/get-tags-for-series-categories Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves available tags and categories for filtering series and markets ```APIDOC ## GET /api-reference/search/get-tags-for-series-categories ### Description Retrieves all available tags and categories that can be used to filter and search for series and markets ### Method GET ### Endpoint /api-reference/search/get-tags-for-series-categories ### Parameters #### Query Parameters - **type** (string) - Optional - Type of tags to retrieve (series, markets, events) ### Request Example { "type": "series" } ### Response #### Success Response (200) - **tags** (array) - Array of tag objects - **tag_id** (string) - Unique identifier for the tag - **name** (string) - Tag name - **category** (string) - Tag category - **description** (string) - Tag description - **usage_count** (integer) - Number of times this tag is used #### Response Example { "tags": [ { "tag_id": "tag_12345", "name": "politics", "category": "category", "description": "Political events and outcomes", "usage_count": 150 }, { "tag_id": "tag_67890", "name": "sports", "category": "category", "description": "Sports-related events", "usage_count": 200 } ] } ``` -------------------------------- ### GET /api-reference/events/get-event Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves detailed information about a specific event ```APIDOC ## GET /api-reference/events/get-event ### Description Retrieves comprehensive information about a specific event including metadata and related data ### Method GET ### Endpoint /api-reference/events/get-event ### Parameters #### Path Parameters - **event_id** (string) - Required - Unique identifier for the event #### Query Parameters - **include_markets** (boolean) - Optional - Whether to include associated markets - **include_metadata** (boolean) - Optional - Whether to include event metadata ### Request Example { "event_id": "event_12345", "include_markets": true, "include_metadata": true } ### Response #### Success Response (200) - **event_id** (string) - Unique identifier for the event - **name** (string) - Event name - **description** (string) - Event description - **category** (string) - Event category - **start_time** (string) - Event start time - **end_time** (string) - Event end time - **status** (string) - Current status - **metadata** (object) - Additional event metadata - **markets** (array) - Associated markets (if requested) #### Response Example { "event_id": "event_12345", "name": "2023 World Cup Final", "description": "Final match of the 2023 FIFA World Cup", "category": "sports", "start_time": "2023-12-18T16:00:00Z", "end_time": "2023-12-18T18:00:00Z", "status": "upcoming", "metadata": { "location": "Qatar", "teams": ["Team A", "Team B"] } } ``` -------------------------------- ### GET /api-reference/market/get-market-orderbook Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves the current orderbook for a market, showing bid and ask prices with quantities ```APIDOC ## GET /api-reference/market/get-market-orderbook ### Description Retrieves the current orderbook state for a specific market, showing active buy and sell orders ### Method GET ### Endpoint /api-reference/market/get-market-orderbook ### Parameters #### Path Parameters - **market_id** (string) - Required - Unique identifier for the market #### Query Parameters - **depth** (integer) - Optional - Number of price levels to show (default: 10) ### Request Example { "market_id": "KALS样-2023-XYZ", "depth": 5 } ### Response #### Success Response (200) - **bids** (array) - Array of buy orders - **asks** (array) - Array of sell orders - **price** (number) - Order price - **quantity** (number) - Available quantity at this price - **timestamp** (string) - Last update time #### Response Example { "bids": [ { "price": 45.2, "quantity": 25 }, { "price": 44.8, "quantity": 40 } ], "asks": [ { "price": 45.6, "quantity": 30 }, { "price": 46.0, "quantity": 15 } ] } ``` -------------------------------- ### GET /api-reference/market/get-series Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves information about a specific trading series, including its associated markets ```APIDOC ## GET /api-reference/market/get-series ### Description Retrieves detailed information about a specific trading series and its associated markets ### Method GET ### Endpoint /api-reference/market/get-series ### Parameters #### Path Parameters - **series_id** (string) - Required - Unique identifier for the trading series #### Query Parameters - **include_markets** (boolean) - Optional - Whether to include associated markets in response ### Request Example { "series_id": "series_2023_Q2", "include_markets": true } ### Response #### Success Response (200) - **series_id** (string) - Unique identifier for the series - **name** (string) - Human-readable name of the series - **description** (string) - Description of the series - **start_date** (string) - Series start date - **end_date** (string) - Series end date - **markets** (array) - Array of associated markets (if include_markets=true) #### Response Example { "series_id": "series_2023_Q2", "name": "Q2 2023 Events", "description": "Binary contracts for Q2 2023 events", "start_date": "2023-04-01", "end_date": "2023-06-30", "markets": [ { "market_id": "KALS样-2023-XYZ", "name": "Will Event X occur?", "status": "active" } ] } ``` -------------------------------- ### GET /api-reference/market/get-market-candlesticks Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Retrieves candlestick data for a specific market, including opening, closing, high, and low prices over time intervals ```APIDOC ## GET /api-reference/market/get-market-candlesticks ### Description Retrieves candlestick data for a specific market with time-series OHLC (Open, High, Low, Close) data ### Method GET ### Endpoint /api-reference/market/get-market-candlesticks ### Parameters #### Path Parameters - **market_id** (string) - Required - Unique identifier for the market #### Query Parameters - **start_time** (string) - Optional - Start timestamp for data range - **end_time** (string) - Optional - End timestamp for data range - **interval** (string) - Optional - Time interval for candlesticks (e.g., '1h', '1d') ### Request Example { "market_id": "KALS样-2023-XYZ", "start_time": "2023-01-01T00:00:00Z", "end_time": "2023-12-31T23:59:59Z", "interval": "1h" } ### Response #### Success Response (200) - **data** (array) - Array of candlestick data points - **timestamp** (string) - Time of the data point - **open** (number) - Opening price - **high** (number) - Highest price in interval - **low** (number) - Lowest price in interval - **close** (number) - Closing price - **volume** (number) - Trading volume #### Response Example { "data": [ { "timestamp": "2023-06-01T00:00:00Z", "open": 45.2, "high": 47.8, "low": 44.5, "close": 46.3, "volume": 1250 } ] } ``` -------------------------------- ### GET /markets Source: https://context7.com/disler/beyond-mcp/llms.txt Lists available markets with options to filter by status, series ticker, event ticker, and pagination. ```APIDOC ## GET /markets ### Description List markets with filters. ### Method GET ### Endpoint /markets ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of markets to return (default: 100). - **status** (string) - Optional - Filter markets by their status (e.g., 'open', 'closed', 'upcoming'). - **series_ticker** (string) - Optional - Filter markets belonging to a specific series. - **event_ticker** (string) - Optional - Filter markets belonging to a specific event. - **cursor** (string) - Optional - Cursor for pagination to retrieve the next set of results. ### Request Example ```json { "limit": 50, "status": "open" } ``` ### Response #### Success Response (200) - **markets** (array) - A list of market objects. - **cursor** (string) - A cursor for paginating through results. #### Response Example ```json { "markets": [ { "ticker": "2024_us_pres_trump_wins", "name": "Will Donald Trump win the 2024 US Presidency?", "event_ticker": "2024_us_pres", "series_ticker": "2024_us_election", "status": "open", "last_price": "0.55", "volume": "12345", "bid": "0.54", "ask": "0.56" } ], "cursor": "some_cursor_string" } ``` ``` -------------------------------- ### GET /api-reference/market/get-trades Source: https://github.com/disler/beyond-mcp/blob/main/ai_docs/README.md Fetches recent trading activity and trade executions for a specific market ```APIDOC ## GET /api-reference/market/get-trades ### Description Retrieves recent trade executions and trading activity for a specific market ### Method GET ### Endpoint /api-reference/market/get-trades ### Parameters #### Path Parameters - **market_id** (string) - Required - Unique identifier for the market #### Query Parameters - **limit** (integer) - Optional - Maximum number of trades to return (default: 100) - **start_time** (string) - Optional - Start timestamp for trade history - **end_time** (string) - Optional - End timestamp for trade history ### Request Example { "market_id": "KALS样-2023-XYZ", "limit": 50, "start_time": "2023-06-01T00:00:00Z" } ### Response #### Success Response (200) - **trades** (array) - Array of trade objects - **trade_id** (string) - Unique identifier for the trade - **price** (number) - Price at which trade was executed - **quantity** (number) - Number of contracts traded - **timestamp** (string) - Time of trade execution - **side** (string) - Trade direction (buy/sell) #### Response Example { "trades": [ { "trade_id": "trade_12345", "price": 45.8, "quantity": 10, "timestamp": "2023-06-01T12:30:00Z", "side": "buy" } ] } ``` -------------------------------- ### GET /markets/{ticker} Source: https://context7.com/disler/beyond-mcp/llms.txt Retrieves detailed information for a specific market identified by its ticker. ```APIDOC ## GET /markets/{ticker} ### Description Get detailed market information ### Method GET ### Endpoint /markets/{ticker} ### Parameters #### Path Parameters - **ticker** (string) - Required - The unique ticker symbol of the market. ### Request Example ```json { "ticker": "2024_us_pres_trump_wins" } ``` ### Response #### Success Response (200) - **ticker** (string) - The market ticker. - **name** (string) - The full name of the market. - **event_ticker** (string) - The ticker of the event this market belongs to. - **series_ticker** (string) - The ticker of the series this market belongs to. - **status** (string) - The current status of the market. - **last_price** (string) - The last traded price for the market. - **volume** (string) - The total volume traded for the market. - **bid** (string) - The current highest bid price. - **ask** (string) - The current lowest ask price. - **open_interest** (string) - The number of open contracts. - **contract_size** (string) - The size of a single contract. - **strike_price** (string) - The strike price for the market. - **expiration_date** (string) - The expiration date of the market. #### Response Example ```json { "ticker": "2024_us_pres_trump_wins", "name": "Will Donald Trump win the 2024 US Presidency?", "event_ticker": "2024_us_pres", "series_ticker": "2024_us_election", "status": "open", "last_price": "0.55", "volume": "12345", "bid": "0.54", "ask": "0.56", "open_interest": "5000", "contract_size": "1", "strike_price": "1.00", "expiration_date": "2024-11-05T23:59:59Z" } ``` ``` -------------------------------- ### GET /markets/trades Source: https://context7.com/disler/beyond-mcp/llms.txt Fetches recent trades across all markets or for a specific market, with options for time range and pagination. ```APIDOC ## GET /markets/trades ### Description Get recent trades across markets or for specific market ### Method GET ### Endpoint /markets/trades ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of trades to return (default: 100). - **ticker** (string) - Optional - Filter trades for a specific market ticker. - **min_ts** (integer) - Optional - Filter trades that occurred after this timestamp (Unix epoch seconds). - **max_ts** (integer) - Optional - Filter trades that occurred before this timestamp (Unix epoch seconds). - **cursor** (string) - Optional - Cursor for pagination to retrieve the next set of results. ### Request Example ```json { "ticker": "2024_us_pres_trump_wins", "min_ts": 1678886400 } ``` ### Response #### Success Response (200) - **trades** (array) - A list of trade objects, each with 'price', 'quantity', 'timestamp', and 'ticker'. - **cursor** (string) - A cursor for paginating through results. #### Response Example ```json { "trades": [ {"price": "0.55", "quantity": "10", "timestamp": 1678886500, "ticker": "2024_us_pres_trump_wins"}, {"price": "0.54", "quantity": "5", "timestamp": 1678886450, "ticker": "2024_us_pres_trump_wins"} ], "cursor": "another_cursor_string" } ``` ``` -------------------------------- ### GET /series/{series_ticker} Source: https://context7.com/disler/beyond-mcp/llms.txt Retrieves detailed information for a specific series identified by its ticker. ```APIDOC ## GET /series/{series_ticker} ### Description Get specific series information ### Method GET ### Endpoint /series/{series_ticker} ### Parameters #### Path Parameters - **series_ticker** (string) - Required - The unique ticker symbol of the series. ### Request Example ```json { "series_ticker": "2024_us_election" } ``` ### Response #### Success Response (200) - **ticker** (string) - The series ticker. - **name** (string) - The name of the series. - **category** (string) - The category the series belongs to. - **tags** (array) - A list of tags associated with the series. - **product_metadata** (object) - Optional - Detailed metadata about the products within this series if requested. #### Response Example ```json { "ticker": "2024_us_election", "name": "2024 US Election Series", "category": "politics", "tags": ["election", "usa", "2024"], "product_metadata": { "markets_per_event": 2, "resolution_format": "binary" } } ``` ``` -------------------------------- ### GET /events Source: https://context7.com/disler/beyond-mcp/llms.txt Lists events, which are collections of related markets, with options for filtering and pagination. Can also include nested market data. ```APIDOC ## GET /events ### Description List events (collections of related markets) ### Method GET ### Endpoint /events ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of events to return (default: 200). - **status** (string) - Optional - Filter events by their status (e.g., 'active', 'completed'). - **series_ticker** (string) - Optional - Filter events belonging to a specific series. - **with_nested_markets** (boolean) - Optional - Whether to include markets nested within each event (default: false). - **cursor** (string) - Optional - Cursor for pagination to retrieve the next set of results. ### Request Example ```json { "status": "active", "with_nested_markets": true } ``` ### Response #### Success Response (200) - **events** (array) - A list of event objects. - **cursor** (string) - A cursor for paginating through results. #### Response Example ```json { "events": [ { "ticker": "2024_us_pres", "name": "2024 US Presidential Election", "status": "active", "markets": [ { "ticker": "2024_us_pres_trump_wins", "name": "Will Donald Trump win the 2024 US Presidency?", "last_price": "0.55" } ] } ], "cursor": "event_cursor_string" } ``` ``` -------------------------------- ### GET /markets/{ticker}/orderbook Source: https://context7.com/disler/beyond-mcp/llms.txt Retrieves the order book for a specific market, allowing for a specified depth. ```APIDOC ## GET /markets/{ticker}/orderbook ### Description Get orderbook (0 = all levels, 1-100 = specific depth) ### Method GET ### Endpoint /markets/{ticker}/orderbook ### Parameters #### Path Parameters - **ticker** (string) - Required - The unique ticker symbol of the market. #### Query Parameters - **depth** (integer) - Optional - The number of order book levels to retrieve. 0 for all levels, 1-100 for a specific depth (default: 0). ### Request Example ```json { "ticker": "2024_us_pres_trump_wins", "depth": 10 } ``` ### Response #### Success Response (200) - **bids** (array) - A list of bid orders, each with 'price' and 'quantity'. - **asks** (array) - A list of ask orders, each with 'price' and 'quantity'. #### Response Example ```json { "bids": [ {"price": "0.54", "quantity": "100"}, {"price": "0.53", "quantity": "50"} ], "asks": [ {"price": "0.56", "quantity": "120"}, {"price": "0.57", "quantity": "75"} ] } ``` ``` -------------------------------- ### GET /exchange/status Source: https://context7.com/disler/beyond-mcp/llms.txt Retrieves the current status of the exchange, including information about trading hours and any ongoing maintenance. ```APIDOC ## GET /exchange/status ### Description Get exchange status (trading hours, maintenance) ### Method GET ### Endpoint /exchange/status ### Parameters No parameters required. ### Request Example ```json {} ``` ### Response #### Success Response (200) - **trading_hours** (object) - Details about the exchange's trading hours. - **maintenance_status** (string) - The current maintenance status of the exchange. #### Response Example ```json { "trading_hours": { "opens_at": "09:00:00", "closes_at": "17:00:00", "time_zone": "UTC" }, "maintenance_status": "operational" } ``` ``` -------------------------------- ### Get Exchange Status - Python Source: https://context7.com/disler/beyond-mcp/llms.txt Retrieves the current exchange status from the Kalshi API. It utilizes the `httpx` library for making HTTP requests and the `click` library for command-line interface functionality. The output can be displayed in JSON format or a human-readable format. ```python #!/usr/bin/env python3 import click import httpx import json from typing import Dict, Any class KalshiClient: """Direct HTTP client for Kalshi API""" def __init__(self): self.client = httpx.Client( base_url="https://api.elections.kalshi.com/trade-api/v2", timeout=30.0, follow_redirects=True ) def get_exchange_status(self) -> Dict[str, Any]: """Get exchange status""" response = self.client.get("/exchange/status") response.raise_for_status() return response.json() @click.group() @click.pass_context def cli(ctx): """Kalshi Prediction Markets CLI""" ctx.obj['client'] = KalshiClient() @cli.command() @click.option('--json', 'output_json', is_flag=True) @click.pass_context def status(ctx, output_json): """Get exchange status""" result = ctx.obj['client'].get_exchange_status() if output_json: click.echo(json.dumps(result, indent=2)) else: click.echo(f"Exchange Active: {result['exchange_active']}") click.echo(f"Trading Active: {result['trading_active']}") ``` -------------------------------- ### GET /events/{event_ticker} Source: https://context7.com/disler/beyond-mcp/llms.txt Retrieves details for a specific event identified by its ticker. Can optionally include nested market data. ```APIDOC ## GET /events/{event_ticker} ### Description Get specific event details ### Method GET ### Endpoint /events/{event_ticker} ### Parameters #### Path Parameters - **event_ticker** (string) - Required - The unique ticker symbol of the event. #### Query Parameters - **with_nested_markets** (boolean) - Optional - Whether to include markets nested within the event (default: false). ### Request Example ```json { "event_ticker": "2024_us_pres", "with_nested_markets": true } ``` ### Response #### Success Response (200) - **ticker** (string) - The event ticker. - **name** (string) - The name of the event. - **status** (string) - The status of the event. - **markets** (array) - Optional - A list of market objects related to the event if `with_nested_markets` is true. #### Response Example ```json { "ticker": "2024_us_pres", "name": "2024 US Presidential Election", "status": "active", "markets": [ { "ticker": "2024_us_pres_trump_wins", "name": "Will Donald Trump win the 2024 US Presidency?", "last_price": "0.55" }, { "ticker": "2024_us_pres_biden_wins", "name": "Will Joe Biden win the 2024 US Presidency?", "last_price": "0.40" } ] } ``` ``` -------------------------------- ### Get Current Cache File Source: https://context7.com/disler/beyond-mcp/llms.txt Locates the most recent valid cache file in the cache directory. Validates file freshness against TTL and returns the path if still valid, otherwise returns None. ```python def _get_current_cache_file(self) -> Optional[Path]: """Find most recent valid cache file""" cache_files = list(self.cache_dir.glob("kalshi_markets_*.csv")) if not cache_files: return None cache_files.sort(reverse=True) latest = cache_files[0] # Check TTL timestamp_str = latest.stem.replace("kalshi_markets_", "") cache_time = datetime.strptime(timestamp_str, "%Y%m%d_%H%M") if datetime.now() - cache_time < timedelta(hours=self.ttl_hours): return latest return None ``` -------------------------------- ### Initialize Kalshi Search Cache Source: https://context7.com/disler/beyond-mcp/llms.txt Instantiates the KalshiSearchCache class with configurable cache directory and TTL. Automatically creates cache directory if missing and supports customizing the cache expiration time. ```python import pandas as pd import time from pathlib import Path from datetime import datetime, timedelta class KalshiSearchCache: """ Intelligent market search cache with pandas. Strategy: 1. First search: Fetch ALL open markets (~6900), save CSV 2. Load CSV into pandas DataFrame 3. Search with string matching (instant) 4. Auto-refresh after 6 hours """ def __init__(self, cache_dir=None, ttl_hours=6): if cache_dir is None: project_root = Path(__file__).resolve().parents[4] cache_dir = project_root / ".kalshi_cache" self.cache_dir = Path(cache_dir) self.cache_dir.mkdir(parents=True, exist_ok=True) self.ttl_hours = ttl_hours ``` -------------------------------- ### Retrieve Kalshi market data using KalshiClient (Python) Source: https://context7.com/disler/beyond-mcp/llms.txt Demonstrates how to use the KalshiClient library to query exchange status, list open markets, fetch a specific market, obtain its orderbook, and list recent trades. Requires the KalshiClient package and network access to the Kalshi API. Outputs are printed to the console; adapt as needed for further processing. ```python response = self.client.get(f"/series/{series_ticker}") response.raise_for_status() return response.json() client = KalshiClient() # Check if exchange is active status = client.get_exchange_status() print(f"Trading: {status['trading_active']}") # List open markets markets = client.get_markets(limit=10, status="open") for m in markets['markets']: print(f"{m['ticker']}: {m['title']}") # Get specific market market = client.get_market("KXBTCD-25NOV0612-T102499.99") print(f"Yes price: {market['market']['yes_bid']}¢") # Get orderbook orderbook = client.get_market_orderbook("KXBTCD-25NOV0612-T102499.99", depth=5) print(f"Top bid: {orderbook['orderbook']['yes'][0]}") # Recent trades trades = client.get_trades(limit=5, ticker="KXBTCD-25NOV0612-T102499.99") for t in trades['trades']: print(f"Price: {t['yes_price']}¢, Count: {t['count']}") ``` -------------------------------- ### Directory structure for Kalshi Markets Skill in Bash Source: https://context7.com/disler/beyond-mcp/llms.txt This Bash snippet shows the directory structure for the Kalshi Markets skill, which includes a skill description file and a scripts directory containing the same scripts as the file system approach. ```bash # Directory structure: # .claude/skills/kalshi-markets/ # ├── SKILL.md (skill description above) # └── scripts/ # ├── status.py (same as file system scripts) # ├── markets.py # ├── market.py # └── ... (10 total scripts) ``` -------------------------------- ### List Markets - Python Source: https://context7.com/disler/beyond-mcp/llms.txt Lists markets from the Kalshi API, allowing filtering by limit and status. It uses the `httpx` library for HTTP requests and `click` for command-line features. Supports both JSON and human-readable output. ```python @cli.command() @click.option('--limit', default=10) @click.option('--status', default='open') @click.option('--json', 'output_json', is_flag=True) @click.pass_context def markets(ctx, limit, status, output_json): """List markets""" result = ctx.obj['client'].get_markets(limit, status) if output_json: click.echo(json.dumps(result, indent=2)) else: for i, market in enumerate(result['markets'], 1): click.echo(f"{i}. {market['ticker']}") click.echo(f" {market['title']}") ``` -------------------------------- ### Build Market Cache Source: https://context7.com/disler/beyond-mcp/llms.txt Fetches all open markets from Kalshi API by iterating through series, aggregates data in a DataFrame, and saves to timestamped CSV. Implements rate limiting and progress tracking for large datasets. ```python def build_cache(self, kalshi_client, quiet=False) -> pd.DataFrame: """Build complete market cache (2-5 minutes first run)""" if not quiet: print("[CACHE] Building market cache...") print("[CACHE] Fetching all series...") start = time.time() # Get all series series_response = kalshi_client.get_series_list() all_series = series_response['series'] if not quiet: print(f"[CACHE] Found {len(all_series)} series") print("[CACHE] Fetching OPEN markets from each series...") all_markets = [] # Fetch open markets from each series for i, series in enumerate(all_series): if (i + 1) % 100 == 0 and not quiet: print(f"[CACHE] Progress: {i+1}/{len(all_series)}") try: result = kalshi_client.get_markets( series_ticker=series['ticker'], limit=100, status="open" ) for market in result.get('markets', []): market['series_title'] = series['title'] market['series_category'] = series['category'] all_markets.append(market) # Rate limiting if i % 50 == 0: time.sleep(0.5) except: continue # Save to CSV df = pd.DataFrame(all_markets) timestamp = datetime.now().strftime("%Y%m%d_%H%M") cache_file = self.cache_dir / f"kalshi_markets_{timestamp}.csv" df.to_csv(cache_file, index=False) elapsed = time.time() - start if not quiet: print(f"[CACHE] Complete! {len(all_markets)} markets") print(f"[CACHE] Time: {elapsed:.1f}s ({elapsed/60:.1f}m)") print(f"[CACHE] Saved: {cache_file.name}") return df ``` -------------------------------- ### Search Cached Markets Source: https://context7.com/disler/beyond-mcp/llms.txt Performs instant keyword search across cached market data using pandas string matching. Searches in title, subtitle, series title, and series ticker fields with case-insensitive matching. ```python def search(self, kalshi_client, keyword: str, limit=20, quiet=False): """Search cached markets instantly""" df = self.load_cache(kalshi_client, quiet) if df.empty: return [] keyword_lower = keyword.lower() # Search across multiple fields mask = ( df['title'].str.lower().str.contains(keyword_lower, na=False) | df['subtitle'].str.lower().str.contains(keyword_lower, na=False) | df['series_title'].str.lower().str.contains(keyword_lower, na=False) | df['series_ticker'].str.lower().str.contains(keyword_lower, na=False) ) results = df[mask].head(limit) if not quiet: print(f"[CACHE] Found {len(results)} matches for '{keyword}'") return results.to_dict('records') ``` -------------------------------- ### Python MCP Server for Kalshi Prediction Markets Source: https://context7.com/disler/beyond-mcp/llms.txt This Python script implements an MCP server using the FastMCP library to expose tools for accessing Kalshi prediction market data. It wraps a CLI tool via subprocess, making each tool call stateless. Dependencies include `mcp`, `subprocess`, `json`, and `pathlib`. It takes tool-specific arguments and returns JSON output. ```python #!/usr/bin/env python3 from mcp.server.fastmcp import FastMCP import subprocess import json from pathlib import Path mcp = FastMCP("Kalshi Prediction Markets") CLI_PATH = Path(__file__).parent.parent / "2_cli" def run_kalshi_cli(*args) -> dict: """Execute kalshi CLI and return parsed JSON""" cmd = ["uv", "run", "kalshi", *args, "--json"] result = subprocess.run( cmd, cwd=CLI_PATH, capture_output=True, text=True, check=True ) return json.loads(result.stdout) @mcp.tool() def get_exchange_status() -> dict: """Get current Kalshi exchange and trading status""" return run_kalshi_cli("status") @mcp.tool() def search_markets(keyword: str, limit: int = 10) -> dict: """ Search markets by keyword using cached data. First search builds cache (~2-5 min), subsequent instant. """ return run_kalshi_cli("search", keyword, "--limit", str(limit)) @mcp.tool() def list_markets( limit: int = 10, status: str = "open", series_ticker: Optional[str] = None ) -> dict: """List markets with filters""" args = ["markets", "--limit", str(limit), "--status", status] if series_ticker: args.extend(["--series-ticker", series_ticker]) return run_kalshi_cli(*args) # Install in Claude Desktop # uv run mcp install server.py --name "Kalshi Markets" # Usage from Claude: # "What's the Kalshi exchange status?" # "Search for Bitcoin markets" # "Show me 5 open markets" ```