Skip to content
Shell
13.9 KB
Raw Blame

DeepStack Prediction Markets Integration Plan

Vision: State-of-the-Art Prediction Market Research Tool

Build a comprehensive prediction market integration that enables:

  • Real-time market discovery across Kalshi + Polymarket
  • AI-powered analysis (inefficiencies, contrarian signals, thesis correlation)
  • Deep thesis system integration
  • Multi-surface presence (dashboard widget, dedicated page, thesis embedding)

Phase 1: Backend Foundation

1.1 Create Prediction Markets Python Module

File: /core/data/prediction_markets.py

# Data models (Pydantic)
- PredictionMarket: Unified market model (id, platform, title, category, yes_price, no_price, volume, etc.)
- MarketPrice: Current price snapshot
- PriceHistory: Historical OHLC for probability

# API Clients
- KalshiClient: Async client for api.elections.kalshi.com/trade-api/v2
  - get_markets(status, limit, category)
  - get_market(ticker)
  - get_market_history(ticker, limit)
  - get_orderbook(ticker)
  - search_markets(query)

- PolymarketClient: Async client for gamma-api.polymarket.com
  - get_markets(limit, active)
  - get_market(condition_id)
  - get_prices_history(token_id)
  - search_markets(query)

# Unified Manager
- PredictionMarketManager: Single interface for both platforms
  - get_trending_markets(limit)
  - search(query)
  - get_market_detail(platform, market_id)
  - get_price_history(platform, market_id, timeframe)

1.2 Create Backend API Router

File: /core/api/prediction_markets_router.py

# Register router in api_server.py: app.include_router(prediction_markets_router)

Endpoints:
GET  /api/predictions/trending?limit=20&category=economics
GET  /api/predictions/search?q=fed+rate
GET  /api/predictions/market/{platform}/{market_id}
GET  /api/predictions/market/{platform}/{market_id}/history?timeframe=1d
GET  /api/predictions/categories
POST /api/predictions/analyze  # AI analysis endpoint

1.3 Caching Layer

  • In-memory cache with TTL (LRU cache)
  • Market list: 5 min TTL
  • Individual prices: 30 sec TTL
  • Search results: 1 min TTL

Phase 2: Database Schema

2.1 Supabase Migration

File: /web/supabase/migrations/008_prediction_markets.sql

-- User watchlists for prediction markets
CREATE TABLE prediction_market_watchlists (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  platform TEXT NOT NULL CHECK (platform IN ('kalshi', 'polymarket')),
  external_market_id TEXT NOT NULL,
  market_title TEXT NOT NULL,
  notes TEXT,
  alert_threshold_high NUMERIC,
  alert_threshold_low NUMERIC,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(user_id, platform, external_market_id)
);

-- Link prediction markets to theses
CREATE TABLE thesis_prediction_market_links (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  thesis_id UUID REFERENCES thesis(id) ON DELETE CASCADE,
  platform TEXT NOT NULL,
  external_market_id TEXT NOT NULL,
  market_title TEXT NOT NULL,
  relationship TEXT CHECK (relationship IN ('supports', 'contradicts', 'correlates', 'hedges')),
  ai_analysis TEXT,
  price_at_link NUMERIC,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(thesis_id, platform, external_market_id)
);

-- RLS policies for user-owned data

Phase 3: Frontend - Core Components

3.1 Types & Store

File: /web/src/types/prediction-markets.ts

interface PredictionMarket {
  id: string;
  platform: 'kalshi' | 'polymarket';
  title: string;
  category: string;
  yesPrice: number;  // 0-1 (probability)
  noPrice: number;
  volume: number;
  volume24h?: number;
  endDate?: string;
  status: 'active' | 'closed' | 'settled';
  url: string;
  description?: string;
}

File: /web/src/lib/stores/prediction-markets-store.ts

- markets: PredictionMarket[]
- watchlist: WatchlistItem[]
- filters: { source, category, search, sort }
- selectedMarket: PredictionMarket | null
- Actions: fetchMarkets, search, addToWatchlist, removeFromWatchlist

3.2 API Routes (Next.js)

File: /web/src/app/api/prediction-markets/route.ts

  • Proxy to backend with authentication
  • Add mock fallback for development

3.3 Components

Location: /web/src/components/prediction-markets/

MarketCard.tsx        - Single market display (probability bar, volume, platform badge)
MarketList.tsx        - Filterable/sortable list of markets
MarketDetailPanel.tsx - Full detail view with chart, orderbook, AI analysis
MarketPriceChart.tsx  - Probability chart using lightweight-charts
MarketSearch.tsx      - Search input with AI suggestions
MarketFilters.tsx     - Source/category/status filters
WatchlistPanel.tsx    - User's watched markets

3.4 Dedicated Page

File: /web/src/app/prediction-markets/page.tsx

Layout: 3-column responsive

  • Left: Filters & categories
  • Center: Market list/grid
  • Right: Detail panel (selected market)

Features:

  • Grid/list view toggle
  • Real-time price polling (30s interval)
  • Keyboard navigation
  • Deep linking (/prediction-markets?market=KALSHI:FED-JAN-25)

Phase 4: Dashboard Integration

4.1 Dashboard Widget

File: /web/src/components/prediction-markets/PredictionMarketsWidget.tsx

Compact widget showing:

  • Top 3 trending markets (by volume change)
  • User's watchlist highlights (if any)
  • 1 AI opportunity (if detected)
  • "See all" link to full page

Add to dashboard layout alongside existing widgets.


Phase 5: Thesis Integration

5.1 ThesisRelatedMarkets Component

File: /web/src/components/thesis/ThesisRelatedMarkets.tsx

Shows in ThesisDashboard:

  • AI-suggested markets based on thesis symbol/hypothesis
  • User-linked markets with relationship type
  • Quick probability display + mini chart
  • "Link Market" action button

5.2 ThesisMarketLinker Component

File: /web/src/components/prediction-markets/ThesisMarketLinker.tsx

Modal/dialog for linking a market to a thesis:

  • Search prediction markets
  • Select relationship type (supports/contradicts/correlates/hedges)
  • Optional notes
  • Save to thesis_prediction_market_links table

Phase 6: AI Integration

6.1 New AI Tools

File: /web/src/lib/llm/prediction-market-tools.ts

// Market Discovery
search_prediction_markets: tool({
  description: 'Search prediction markets by topic or keyword',
  inputSchema: z.object({
    query: z.string(),
    source: z.enum(['all', 'kalshi', 'polymarket']).optional(),
    limit: z.number().default(10),
  }),
  execute: async ({ query, source, limit }) => {
    // Fetch from /api/prediction-markets/search
    return { success: true, data: { markets, query } };
  },
})

get_prediction_market: tool({
  description: 'Get detailed info about a specific prediction market',
  inputSchema: z.object({
    platform: z.enum(['kalshi', 'polymarket']),
    market_id: z.string(),
  }),
  execute: async ({ platform, market_id }) => {
    // Fetch market detail + recent price history
    return { success: true, data: { market, history } };
  },
})

// Analysis
analyze_prediction_market: tool({
  description: 'AI analysis of market for opportunities/insights',
  inputSchema: z.object({
    platform: z.enum(['kalshi', 'polymarket']),
    market_id: z.string(),
    analysis_types: z.array(z.enum(['inefficiency', 'momentum', 'contrarian'])).optional(),
  }),
  execute: async ({ platform, market_id, analysis_types }) => {
    // Call backend /api/predictions/analyze
    return { success: true, data: { analyses, summary } };
  },
})

find_markets_for_thesis: tool({
  description: 'Find prediction markets related to a trading thesis',
  inputSchema: z.object({
    thesis_id: z.string().optional(),
    symbol: z.string().optional(),
    hypothesis: z.string().optional(),
  }),
  execute: async (params) => {
    // AI-powered matching based on thesis content
    return { success: true, data: { relatedMarkets } };
  },
})

// UI Control
show_prediction_markets: tool({
  description: 'Show prediction markets panel or page',
  inputSchema: z.object({
    market_id: z.string().optional(),
    filter: z.object({ category: z.string().optional() }).optional(),
  }),
  execute: async ({ market_id, filter }) => ({
    success: true,
    action: 'show_panel',
    panel: 'prediction-markets',
    market_id,
    filter,
  }),
})

6.2 Context Enhancement

Add prediction market context to TradingContext in chat route:

  • User's watchlist (top 5 by recent price change)
  • Active opportunities (if any)
  • Thesis-linked markets

6.3 System Prompt Update

Add prediction market awareness to system prompt:

You have access to real-time prediction market data from Kalshi and Polymarket.
When discussing market outlook or thesis validation, reference relevant prediction markets.
You can analyze markets for inefficiencies, contrarian opportunities, and thesis correlation.

Phase 7: AI Analysis Engine

7.1 Backend Analysis Endpoint

File: /core/analysis/prediction_market_analyzer.py

Analysis types:

  1. Inefficiency Detection: Compare market probability to fundamentals/news
  2. Momentum Analysis: Price trend + volume patterns
  3. Contrarian Signal: Crowd sentiment vs historical accuracy
  4. Thesis Correlation: How market outcomes affect thesis

Returns structured analysis with confidence scores.


Critical Files to Modify

Backend (Python)

  • /core/api_server.py - Add include_router(prediction_markets_router)
  • NEW: /core/data/prediction_markets.py - API clients
  • NEW: /core/api/prediction_markets_router.py - FastAPI router
  • NEW: /core/analysis/prediction_market_analyzer.py - AI analysis

Frontend (TypeScript)

  • NEW: /web/src/types/prediction-markets.ts - Types
  • NEW: /web/src/lib/stores/prediction-markets-store.ts - Zustand store
  • NEW: /web/src/app/api/prediction-markets/route.ts - API route
  • NEW: /web/src/app/prediction-markets/page.tsx - Dedicated page
  • NEW: /web/src/components/prediction-markets/*.tsx - Components
  • /web/src/lib/llm/tools.ts - Add prediction market tools
  • /web/src/lib/llm/system-prompt.ts - Add PM context
  • /web/src/components/thesis/ThesisDashboard.tsx - Add related markets section

Database

  • NEW: /web/supabase/migrations/008_prediction_markets.sql

Implementation Order

Week 1: Foundation
├── Day 1-2: Backend API clients (Kalshi + Polymarket)
├── Day 3: Backend router + caching
└── Day 4-5: Database schema + Supabase migration

Week 2: Frontend Core
├── Day 1: Types, store, API route
├── Day 2-3: MarketCard, MarketList components
├── Day 4: MarketPriceChart, MarketDetailPanel
└── Day 5: Dedicated page layout

Week 3: Integration
├── Day 1-2: Dashboard widget
├── Day 3: Thesis integration (ThesisRelatedMarkets)
├── Day 4: AI tools (search, get, show)
└── Day 5: System prompt + context enhancement

Week 4: AI Analysis
├── Day 1-2: Backend analyzer (inefficiency, momentum)
├── Day 3: analyze_prediction_market tool
├── Day 4: find_markets_for_thesis tool
└── Day 5: Polish, testing, edge cases

Success Metrics

  • Both Kalshi and Polymarket APIs returning data
  • Search returns relevant results across platforms
  • Dashboard widget shows trending + watchlist
  • Dedicated page has working filters, search, detail panel
  • Charts display probability history correctly
  • Thesis can link to prediction markets
  • AI can search, analyze, and cite prediction markets
  • AI proactively suggests related markets for theses

Agent Orchestration Strategy

Phase 1: Backend Foundation → backend-architect + fullstack-developer

Task: Create Python prediction market clients and FastAPI router

  • backend-architect: Design API client structure, caching strategy
  • fullstack-developer: Implement KalshiClient, PolymarketClient, router

Phase 2: Database Schema → supabase-toolkit:data-engineer

Task: Create Supabase migration for watchlists and thesis links

  • Use mcp__supabase__apply_migration for schema changes
  • Design RLS policies for user data isolation

Phase 3: Frontend Core → frontend-developer + ui-builder skill

Task: Build types, store, API routes, components

  • frontend-developer: Zustand store, API routes, page layout
  • ui-builder skill: Component styling with Tailwind/shadcn

Phase 4: Dashboard Widget → frontend-developer

Task: Create compact prediction markets widget for dashboard

Phase 5: Thesis Integration → fullstack-developer

Task: Add ThesisRelatedMarkets component, linking functionality

Phase 6: AI Tools → ai-engineer

Task: Create prediction market tools for chat

  • search_prediction_markets, get_prediction_market, analyze_prediction_market
  • show_prediction_markets, find_markets_for_thesis

Phase 7: AI Analysis Engine → ai-engineer

Task: Build backend analyzer for inefficiency/momentum/contrarian detection

Quality Gates

  • After Phase 1: testing-suite:test-engineer → Backend unit tests
  • After Phase 3: pr-review-toolkit:code-reviewer → Frontend review
  • After Phase 6: pr-review-toolkit:code-reviewer → AI tools review
  • Final: security-pro:security-auditor → Security review of API keys/data handling

MCP Tools to Leverage

  • mcp__supabase__* → Database operations
  • mcp__playwright-server__* → UI testing during development
  • mcp__firecrawl__* → Research Kalshi/Polymarket API docs if needed
  • mcp__perplexity__* → Research best practices for prediction market APIs

Design Decisions

Q: Real-time vs polling? A: Start with polling (30s for prices, 5min for market lists). WebSocket upgrade can come later based on usage.

Q: Store market data in Supabase? A: Only store user-specific data (watchlists, thesis links). Market data stays fresh from APIs.

Q: How to handle rate limits? A: Aggressive caching + request deduplication. Kalshi has reasonable limits; Polymarket is 1000/hour free.

Q: Navigation placement? A: Top-level nav item "Predictions" alongside Chat, Journal, Thesis. Dashboard widget provides quick access.