PREDICTION MARKETS API

AI Agent Prediction Markets API

Give your autonomous agents access to 200+ prediction markets across Polymarket, Manifold, Augur, Gnosis, and UMA. Real-time odds, Kelly criterion sizing, and automated resolution webhooks.

Get API Key → Read the Docs
200+
Active Markets
$50M+
Daily Volume
8
Protocols Supported
<200ms
Odds Latency

// API REFERENCE

Prediction Market Endpoints

Four core endpoints cover the full lifecycle: market discovery, position management, resolution tracking, and liquidity provision.

GET
/v1/prediction-markets/markets
List all active markets with current probability, volume, liquidity depth, and resolution date. Supports filtering by protocol, category, and probability range.
POST
/v1/prediction-markets/positions/open
Open a YES or NO position on any supported market. Optionally pass kelly_fraction to auto-size using the Kelly criterion formula against your wallet balance.
GET
/v1/prediction-markets/resolution
Fetch resolution status and final outcome for settled markets. Includes oracle source, resolution timestamp, and payout amounts per share.
POST
/v1/prediction-markets/liquidity/add
Provide liquidity to AMM-based markets (Augur, Gnosis). Earn market-maker fees automatically distributed on resolution.

// SUPPORTED PROTOCOLS

8 Prediction Market Protocols

Purple Flea abstracts the complexity of each protocol behind a unified REST interface. One API key, all markets.

Protocol Type Chain Markets Avg Volume/Day Status
Polymarket CLOB Order Book Polygon 80+ $30M LIVE
Manifold AMM (CFMM) Off-chain 50+ $2M LIVE
Augur v2 AMM + Reporting Ethereum 30+ $5M LIVE
Gnosis Conditional Conditional Tokens Gnosis Chain 20+ $3M LIVE
UMA Protocol Optimistic Oracle Ethereum 15+ $4M LIVE
Zeitgeist Prediction Market Polkadot 10+ $1.5M LIVE
Omen AMM (Gnosis CTF) Gnosis Chain 8+ $800K BETA
PlotX Non-custodial AMM Polygon 5+ $500K BETA

// MARKET INTELLIGENCE

Probability Curves & Kelly Sizing

The API returns real-time probability distributions for each market outcome. Use the built-in Kelly criterion calculator to size positions optimally given your edge and bankroll.

Kelly Criterion Formula
f* = (p × b - q) / b

Where f* = fraction of bankroll to wager, p = probability of winning, q = 1-p, and b = net odds received on the bet (payout per unit staked). Pass kelly_fraction: 0.5 to use half-Kelly for more conservative sizing.

// Live Probability Feed — BTC $100K by June 2026

Polymarket
62%
Manifold
58%
Augur
65%
Gnosis
60%
UMA
63%
Consensus: 61.6% • Arbitrage spread: 7% • Updated: live

// AGENT EXAMPLE

Python Agent with Kelly Sizing

A complete agent that monitors markets, estimates edge, and places optimal positions using the Kelly criterion.

kelly_prediction_agent.py
"""
Purple Flea Prediction Markets Agent
Uses Kelly criterion to size bets optimally.
Runs as a daemon, polling every 60 seconds.
"""

import requests
import time
import json
from typing import Optional
from dataclasses import dataclass

API_KEY = "pf_live_your_key_here"
BASE_URL = "https://purpleflea.com/v1/prediction-markets"
BANKROLL_USDC = 1000.0   # Total bankroll in USDC
MAX_KELLY_FRACTION = 0.25   # Cap at 25% of Kelly to be conservative

@dataclass
class Market:
    id: str
    question: str
    protocol: str
    yes_price: float    # current probability [0,1]
    liquidity: float
    volume_24h: float
    resolution_date: str

def get_headers() -> dict:
    return {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }

def fetch_markets(min_liquidity: float = 10000) -> list[Market]:
    """Fetch all active markets above a liquidity threshold."""
    resp = requests.get(
        f"{BASE_URL}/markets",
        params={"min_liquidity": min_liquidity, "status": "active"},
        headers=get_headers(),
        timeout=10,
    )
    resp.raise_for_status()
    data = resp.json()
    return [Market(**m) for m in data["markets"]]

def kelly_fraction(p_edge: float, current_price: float) -> float:
    """
    Calculate Kelly fraction given agent's estimated probability (p_edge)
    and current market price.

    f* = (p*b - q) / b  where b = (1/price - 1)
    """
    if current_price <= 0 or current_price >= 1:
        return 0.0

    b = (1.0 / current_price) - 1.0   # Net odds
    q = 1.0 - p_edge               # Probability of losing
    f_star = (p_edge * b - q) / b
    return max(0.0, min(f_star, MAX_KELLY_FRACTION))

def estimate_edge(market: Market) -> Optional[float]:
    """
    Agent's edge estimation model.
    In production: use ML model, news sentiment, or fundamental analysis.
    Returns agent's own probability estimate, or None if no edge found.
    """
    # Example: simple mean-reversion from consensus
    # Real agents would use much more sophisticated models here
    consensus = market.yes_price
    agent_estimate = consensus  # placeholder — replace with your model

    edge = abs(agent_estimate - consensus)
    if edge < 0.03:   # Less than 3% edge, skip
        return None
    return agent_estimate

def open_position(market_id: str, direction: str, usdc_amount: float) -> dict:
    """Open a YES or NO position on a market."""
    payload = {
        "market_id": market_id,
        "direction": direction,       # "YES" or "NO"
        "amount_usdc": round(usdc_amount, 2),
        "slippage_tolerance": 0.02,   # 2% max slippage
    }
    resp = requests.post(
        f"{BASE_URL}/positions/open",
        json=payload,
        headers=get_headers(),
        timeout=15,
    )
    resp.raise_for_status()
    return resp.json()

def run_agent(poll_interval: int = 60):
    """Main agent loop."""
    print("[PurpleFlea] Prediction Markets Agent started.")
    print(f"[PurpleFlea] Bankroll: ${BANKROLL_USDC} USDC | Poll: {poll_interval}s")

    while True:
        try:
            markets = fetch_markets(min_liquidity=50000)
            print(f"[PurpleFlea] Scanning {len(markets)} markets...")

            for market in markets:
                p_agent = estimate_edge(market)
                if p_agent is None:
                    continue

                direction = "YES" if p_agent > market.yes_price else "NO"
                f = kelly_fraction(p_agent, market.yes_price)
                bet_size = BANKROLL_USDC * f

                if bet_size < 5.0:   # Minimum $5 position
                    continue

                print(f"  >> Edge found: {market.question[:50]}...")
                print(f"     Market: {market.yes_price:.1%} | Agent: {p_agent:.1%} | Kelly: {f:.1%}")
                print(f"     Placing {direction} ${bet_size:.2f} on {market.protocol}")

                result = open_position(market.id, direction, bet_size)
                print(f"     Position opened: {result['position_id']}")

        except Exception as e:
            print(f"[PurpleFlea] Error: {e}")

        time.sleep(poll_interval)

if __name__ == "__main__":
    run_agent()

// KEY FEATURES

Built for Autonomous Agents

Every feature is designed around the needs of autonomous trading agents: zero UI dependency, webhook-first, and composable with the full Purple Flea suite.

📈
Real-Time Odds Feed

WebSocket and REST endpoints with sub-200ms latency. Receive probability updates as order books fill and new trades execute across all supported protocols simultaneously.

Resolution Webhooks

Register a callback URL per market. When a market resolves, Purple Flea fires a signed webhook with the final outcome, oracle source, and USDC payout amount — no polling required.

🎯
Kelly Criterion Engine

Pass your own probability estimate alongside a position request and the API will calculate the optimal bet fraction, apply your kelly_fraction multiplier, and size accordingly.

🔗
Cross-Market Arbitrage

Unified market IDs across protocols let agents detect and exploit probability discrepancies between Polymarket, Augur, and Gnosis within a single API response.

💰
Liquidity Provision

Agents can act as market makers on AMM-based protocols. Deposit USDC to earn maker fees on both sides of each market, with automatic withdrawal on resolution.

🔐
Free Faucet Entry

New agents can claim free USDC from the Purple Flea faucet to try prediction market positions with zero capital risk. Visit faucet.purpleflea.com to get started.


// GET STARTED

Start Trading Prediction Markets Today

Register your agent in under 60 seconds. Connect to 200+ markets across 8 protocols with a single API key.

Register Your Agent → Get Free USDC