This tutorial shows how to build autonomous prediction market agents using Swarms with the Kalshi API. You will build agents that discover markets, estimate probabilities, find edges against market odds, and execute trades programmatically.We cover a single-agent pattern for simple market analysis and a multi-agent swarm pattern with specialized research, analysis, risk, and execution agents.
Trading involves real financial risk. Always start with paper trading / demo mode before using real funds. The examples below include guardrails and dry-run mode — use them.
A single agent that discovers Kalshi markets, reasons about probability, and identifies edges.
from swarms import AgentKALSHI_ANALYST_PROMPT = """You are an expert Kalshi prediction market analyst.Your workflow:1. Use your tools to discover active markets on Kalshi2. Select the most interesting markets with high volume and liquidity3. For each selected market, research the event and estimate the TRUE probability4. Compare your estimated probability to the market's implied probability5. Identify edges: markets where your estimate differs from market odds by >10%When analyzing a market:- State the question clearly- List key factors that influence the outcome- Estimate the probability with reasoning- Compare to market price- Recommend: BET YES, BET NO, or NO EDGEAlways express probabilities as percentages and explain your reasoning.Never recommend betting more than 5% of bankroll on a single position."""analyst = Agent( agent_name="Kalshi-Analyst", agent_description="Analyzes Kalshi prediction markets and identifies edges", system_prompt=KALSHI_ANALYST_PROMPT, model_name="gpt-4o", max_loops=3, tools=[ discover_kalshi_events, get_kalshi_orderbook, ], output_type="str",)result = analyst.run( "Find the top 5 most active prediction markets on Kalshi. " "Analyze each one and identify any markets where you believe there is " "a significant edge (>10% probability difference between your estimate " "and the market price).")print(result)
For serious trading, use a multi-agent swarm with specialized roles. Each agent has a focused responsibility, and they work together in a sequential pipeline.
from swarms import Agent, SequentialWorkflow# --- Research Agent ---research_agent = Agent( agent_name="Kalshi-Researcher", agent_description="Discovers and summarizes Kalshi markets", system_prompt="""You are a Kalshi researcher. Your job:1. Use your tools to discover active markets on Kalshi2. Focus on markets with high volume and liquidity3. For each market, provide: the question, current odds, volume, and closing date4. Gather relevant context about each event from your knowledge5. Output a structured research brief for each marketFormat your output as a clear research report that an analyst can use.""", model_name="gpt-4o", max_loops=2, tools=[ discover_kalshi_events, get_kalshi_orderbook, ], output_type="str",)# --- Analyst Agent ---analyst_agent = Agent( agent_name="Probability-Analyst", agent_description="Estimates true probabilities and finds edges", system_prompt="""You are a quantitative analyst specializing in probability estimation.Given a research brief on Kalshi markets, you must:1. For each market, estimate the TRUE probability of each outcome2. Show your reasoning: list base rates, key factors, and analogies3. Compare your estimate to the market's implied probability4. Calculate the edge: (your estimate - market price) / market price5. Flag any market where the absolute edge exceeds 10%Output a structured analysis with:- Market ticker and question- Your probability estimate (with confidence interval)- Market implied probability- Edge percentage- Verdict: STRONG BUY YES, LEAN BUY YES, NO EDGE, LEAN BUY NO, STRONG BUY NO""", model_name="gpt-4o", max_loops=1, output_type="str",)# --- Risk Agent ---risk_agent = Agent( agent_name="Risk-Manager", agent_description="Enforces position sizing and risk limits", system_prompt="""You are a risk manager for a Kalshi trading operation.Given the analyst's recommendations, you must:1. Filter out any recommendations with edge < 10%2. Apply Kelly Criterion for position sizing (use half-Kelly for safety)3. Enforce these hard limits: - Max 5% of bankroll on any single position - Max 20% of bankroll in correlated positions - No positions in markets closing within 1 hour (too volatile) - Minimum liquidity: $10,000 in 24h volume4. For approved trades, output the exact order parameters: - Ticker - Side (yes/no) - Action (buy/sell) - Count (number of contracts) - Limit price in cents (1-99)5. For rejected trades, explain whyAssume a bankroll of $1,000 unless specified otherwise.""", model_name="gpt-4o", max_loops=1, output_type="str",)# --- Execution Agent ---execution_agent = Agent( agent_name="Trade-Executor", agent_description="Executes approved trades on Kalshi", system_prompt="""You are a Kalshi trade execution agent. Given approved trades from the risk manager:1. Parse each approved trade's parameters2. Use the place_kalshi_order tool to place the order3. Report the result of each order (confirmation or error)4. If an order fails, do NOT retry — report the failureAlways log every action. Never modify the risk manager's parameters.""", model_name="gpt-4o", max_loops=1, tools=[place_kalshi_order], output_type="str",)
swarm = SequentialWorkflow( agents=[research_agent, analyst_agent, risk_agent, execution_agent], max_loops=1,)result = swarm.run( "Scan Kalshi for the top active markets. " "Identify any edges and execute approved trades. " "Bankroll: $1,000.")print(result)
The sequential pipeline works as follows:
Research Agent discovers markets and gathers context
Analyst Agent estimates probabilities and identifies edges
Risk Agent filters, sizes positions, and enforces limits
Execution Agent places the approved orders (dry-run by default)
The DRY_RUN = True flag at the top of the execution tool prevents any real orders from being placed. Set it to False only when you are confident in the system.
Kalshi provides a full demo environment at https://demo-api.kalshi.co/trade-api/v2. Create a separate demo account, generate a demo API key, and change KALSHI_BASE to KALSHI_DEMO_BASE in your code to test end-to-end flow without risking real funds.