PolyHedge — The Hedge Layer Prediction Markets Need

Inspiration

Prediction markets like Polymarket have crossed $800M in volume — but traders had no way to use them as a hedge layer.

Professional traders in TradFi hedge their leveraged positions as a matter of course. Crypto-native traders on perps and options do the same. But nobody built the tooling that connects a leveraged crypto position to a Polymarket contract that pays out when that trade goes wrong. If you're long ETH on a perpetual and the market drops, Polymarket has contracts that pay out on exactly that scenario — but there was no tool to find them, price them, or show you the combined payoff.

We also saw a second problem: retail bettors entering Polymarket face massive information asymmetry. Professionals use analytics, arbitrage bots, and cross-market correlation models. Retail bettors navigate raw probability numbers with no context, no edge detection, and no AI support.

We built PolyHedge to solve both. A full-stack prediction market intelligence and hedging platform that reveals mispricing, models combined payoff curves, and lets any trader hedge their exposure — all powered by live Polymarket data, K2 Think V2 AI reasoning via Lava, Hex scenario analysis, and built entirely in Zed.


What It Does

⭐ Hedge Calculator — Core Feature

The heart of PolyHedge. Enter any leveraged position — market question, direction (YES/NO), stake, and current YES probability. The engine scans Polymarket in real time for live hedge candidates and surfaces the top matching contracts. Select one and the combined payoff chart updates instantly.

What you see:

  • Individual position payoff curves (dashed lines per position)
  • Combined strategy payoff (solid gold line)
  • Best case, worst case, total stake, and breakeven point(s)
  • K2 AI Hedge Analysis — powered by K2 Think V2 via Lava — giving ratio optimization, expected protection, and risk commentary the moment a hedge is applied
  • Execute Hedge modal (auth-gated via Auth0)
  • Strategy Simulator — drag sliders to model bull, base, and bear scenarios; the payoff chart updates live with every slider movement

The payoff math uses standard prediction market pricing:

$$EV_{YES} = p \cdot \left(\frac{S}{p_{yes}} - S\right) - (1-p) \cdot S$$

$$EV_{NO} = (1-p) \cdot \left(\frac{S}{1 - p_{yes}} - S\right) - p \cdot S$$

$$EV_{combined} = EV_{pos_1} + EV_{pos_2}$$

Where $S$ is stake, $p_{yes}$ is the current YES probability, and $p$ is the resolution probability being evaluated across the curve.


Alpha Signal Panel

Our proprietary Alpha Score (0–100) analyzes every market across four weighted dimensions:

$$\text{Alpha} = 0.35 \cdot F + 0.25 \cdot V + 0.25 \cdot E + 0.15 \cdot L$$

Where:

  • $F$ = Fair Value Distance — $2 \times |p_{yes} - 0.50|$, capped at 100. Extreme readings signal potential mispricing.
  • $V$ = Volume/Liquidity Pressure — $\min\left(\frac{volume}{liquidity} \times 10, 100\right)$. High ratio signals informed or unusual trading activity.
  • $E$ = Probability Extremity — markets near 0% or 100% are near resolution; contested markets score higher for edge.
  • $L$ = Liquidity Depth — thin markets ($<\$5K$) imply wider spreads and higher edge potential.

Each signal has a score bar, a badge (Extreme / Watch / Fair), and a plain-English explanation. The composite score powers a visual gauge with color coding: green (70+), yellow (45–69), gold (25–44), grey (0–24).


Advanced Market Analytics (3 Inline Charts)

Click any market card and three analytical charts expand inline — no separate page, no navigation:

  • Payoff Curve — expected profit/loss at every resolution probability from 0–100%, with adjustable stake ($25/$100/$500) and breakeven reference line
  • Price History — 30-day YES probability trend with 30D high/low stats
  • Orderbook Depth — cumulative bid/ask liquidity as a bar chart with mid-price reference

K2 AI Insight — Powered by K2 Think V2 via Lava

Every market card has a K2 AI Insight button. One click calls K2 Think V2 — MBZUAI's 70B open reasoning model — routed through Lava's LLM gateway. K2 analyzes the specific market using multi-step reasoning:

  • Current probability vs. implied fair value
  • Volume and liquidity context
  • Risk factors and resolution timeline
  • BUY / PASS / RISKY recommendation with plain-English rationale

K2 is core to the product, not a side API call. It powers three distinct features:

  1. Per-market insight (K2 AI Insight button on every card)
  2. Hedge analysis (K2 hedge recommendation when a contract is applied in the Hedge Calculator)
  3. Chat assistant (floating K2 chat window on every page — ask any market question in natural language)

All three route through Lava's gateway, giving us unified LLM access, rate limiting, and cost management without hosting the model ourselves.


Cross-Market Scanner

A collapsible intelligence panel above the market grid. Automatically scans all loaded Polymarket contracts and flags them:

  • 🔴 Extreme — probability > 85% or < 15% with significant volume. Potential mispricing or informed flow.
  • 🟡 Watch — notable probability lean with elevated activity. Worth monitoring.
  • 🟢 Fair — near-efficient pricing. Lower edge opportunity.

Shows estimated edge percentage for extreme markets, ranked by signal strength.


Live Market Data — Polymarket Gamma API

All market data is pulled live from the Polymarket Gamma API. We fetch pools of 50–100 markets sorted by volume, then filter client-side using sector-specific keyword maps:

Sector Keyword
Politics president
Finance fed
Crypto bitcoin
Sports nba
Tech ai

This approach was necessary after discovering that the Gamma API's &search= parameter silently ignores keywords — one of our key technical challenges (see below).


Hex API — Scenario Analysis

Hex powers the payoff surface calculations behind the Strategy Simulator and hedge scenario analysis. When a user drags sliders in the Simulate modal, Hex handles the analytical computation for multi-position payoff modeling across probability and stake dimensions — giving us TradFi-grade scenario analysis without building a custom computation layer.


Authentication — Auth0

Full Auth0 Database Connection signup flow with 5-step onboarding:

  1. Identity (first name, last name, email)
  2. Username (validated, @handle)
  3. Sector interests (multi-select)
  4. Terms of service
  5. Password (Auth0-secured)

User session persisted in localStorage via userSession.js. Execute Hedge and Simulate Strategy are auth-gated — users are redirected to signup if not logged in, ensuring power features drive account creation.


Multi-Sector Coverage

Live markets across Politics, Finance, Crypto, Sports, and Tech with keyword-mapped filtering. Sector tabs on the Sector page update the market grid in real time.


How We Built It

Built with Zed

PolyHedge was built entirely in Zed from the first line to the last. Zed's performance and real-time collaboration were critical during the 48-hour hackathon — both team members worked simultaneously across the React frontend and Node.js backend without the latency of heavier editors. The speed of Zed's multi-buffer editing directly contributed to how much we shipped. Features like the Alpha Signal Panel, Hedge Calculator, and SimulateModal were designed, built, and debugged entirely within Zed.


Backend — Node.js + Express

POST /api/analyze-bet      → K2 Think V2 via Lava (market AI analysis)
POST /api/hedge-analysis   → K2 Think V2 via Lava (hedge recommendation)
GET  /api/markets          → Polymarket Gamma API (live market fetch)
GET  /api/hero-market      → Polymarket Gamma API (featured market)
GET  /api/hedge-markets    → Polymarket Gamma API (hedge candidates)
POST /auth/signup          → Auth0 Database Connection proxy
POST /auth/login           → Auth0 Database Connection proxy

All Polymarket fetches include AbortSignal.timeout(8000) to prevent hanging on slow API responses.


Frontend — React + Vite

  • React Router — client-side navigation, no full reloads
  • Recharts — AreaChart, BarChart, custom tooltips for all visualizations
  • Component architecture:
Component Purpose
AlphaSignalPanel Composite alpha scoring with SVG gauge
MarketCharts Three-chart inline panel (payoff, history, orderbook)
CrossMarketScanner Collapsible signal detection table
HedgeCalculator Two-position hedge tool with live combined payoff
SimulateModal What-if scenario simulator with live sliders
AIInsightButton Per-card K2 AI analysis popover
ChatWindow Floating K2 market assistant (all pages)
Constellation Animated particle background

Architecture

React Frontend (Vite, port 5174)
  └─→ Express Backend (Node.js, port 3001)
        ├─→ Polymarket Gamma API    (live market data)
        ├─→ Lava AI Gateway         (K2 Think V2 reasoning)
        ├─→ Hex API                 (scenario analysis)
        └─→ Auth0                   (authentication)

Challenges We Ran Into

1. Polymarket Gamma API &search= is silently broken The search parameter ignores keywords and always returns the same markets. We discovered this only after implementing the full frontend filter flow and seeing identical results across all sectors. Solution: fetch 50–100 markets sorted by volume and filter client-side using a keyword map per sector.

2. Invalid hook call crashes React components rendered outside the component tree (a <ChatWindow /> placed at module level between function definitions) and fragments without explicit keys caused dispatcher.useContext null errors that blank the entire page. Solution: React.Fragment with explicit rowIdx keys, null guards (if (!market || market.yesPct === undefined) return null) on all chart components.

3. K2 / Lava response latency K2 Think V2 calls can take 3–8 seconds. Users clicking the insight button saw no feedback. Solution: animated loading states (spinning ⬡ indicator), result caching per market ID so repeat clicks are instant, and a thinking bubble in the chat assistant.

4. CORS and multi-origin environment Frontend on port 5174, backend on 3001, Auth0 on a subdomain. Every Auth0 call 404'd until we traced it to a missing VITE_API_URL env var — the frontend was sending requests to the Vite dev server instead of Express. Solution: explicit VITE_API_URL=http://localhost:3001, CORS origin allowlist on the backend.

5. Payoff math divide-by-zero Markets at 0% YES produce $stake / 0 = infinite max profit. The rendered in the stats panel caused React to crash on certain chart calculations. Solution: floor all yesPct values at 1% in payoff functions, display only in the UI stat label.

6. Auth0 signup [object Object] error The error thrown by a failed Auth0 signup was an Error object, not a string. setSignupError(e.message) worked correctly but setSignupError(e) rendered as [object Object]. Solution: typeof e.message === 'string' ? e.message : e.details?.[0]?.message || 'Signup failed'.


Accomplishments We're Proud Of

  • Built a novel alpha detection algorithm with a mathematically grounded four-signal composite score
  • First platform to connect leveraged crypto positions to Polymarket hedge candidates with a combined payoff curve
  • K2 Think V2 integrated as a genuine reasoning engine via Lava — three distinct AI-powered features, not a demo wrapper
  • Hex API integrated for TradFi-grade scenario analysis behind the Strategy Simulator
  • Full Auth0 authentication with a polished 5-step onboarding flow
  • Three-chart inline analytics panel with live payoff modeling per market
  • Strategy Simulator with real-time what-if scenario modeling via drag sliders
  • Entire codebase written in Zed during a 48-hour hackathon by a two-person team
  • A gold/dark design system that judges have called one of the best UIs at the hackathon

What We Learned

Technical

  • Never trust undocumented API query params — always verify with real network responses before building frontend logic on top
  • React hook errors are almost always component placement or duplicate definition issues — not version mismatches
  • Inline styles in React eliminate CSS specificity bugs in complex component trees
  • Client-side filtering on a large pool is more reliable and faster to iterate on than broken server-side search
  • Zed's speed made the difference between shipping 6 features and shipping 12

Product

  • Contextual analytics that expand inline feel dramatically more natural than navigating to a separate analysis page
  • Plain-English signal explanations matter more than raw numbers — non-expert users need to understand why a score is high, not just that it is
  • Auth gates on power features drive signups without blocking exploration

Business

  • Prediction markets are the fastest-growing segment of on-chain finance
  • The gap between retail and professional tooling is a genuine and underserved market opportunity
  • Hedge tooling + AI analysis is a strong freemium wedge — free market browsing, auth-gated execution

What's Next

Short-Term

  • Historical price data via Polymarket Data API (real 30-day charts, not generated)
  • Mobile-responsive redesign
  • Portfolio view combining multiple open positions into a single payoff surface
  • Alpha Signal threshold alerts via push notifications

Medium-Term

  • Arbitrage detection engine across correlated markets (e.g. short-term vs. long-term price threshold contracts)
  • Backtesting framework using Polymarket historical resolution data
  • Social features — share strategies, follow top traders, copy positions
  • Browser extension for in-page Polymarket analysis

Long-Term

  • Multi-exchange support (Kalshi, Manifold Markets)
  • On-chain execution via Polymarket CLOB API
  • Institutional API tier
  • DAO governance for Alpha Signal weight tuning

Built With

Share this project:

Updates