Skip to content
cd ..

Building a Prediction Market Trading System Inside an Agent Platform

// · 5 min read

I built a full prediction market trading system into AgenticMail Enterprise. 126 tools across 10 skill modules. Three trading modes. Quantitative analysis. On chain intelligence. Risk management with circuit breakers. It’s the most technically dense feature in the platform, and it started because I wanted to see what happens when you give an AI agent real market access with proper guardrails.

10 Skill Modules, 126 Tools

The trading system is organized into skill modules that can be mixed and matched depending on the agent’s role:

Market Discovery handles finding and filtering markets. Search by category, volume, expiration date, or custom criteria. The agent can scan hundreds of markets and surface the ones matching its trading thesis.

Position Management covers opening, closing, and adjusting positions. Limit orders, market orders, and conditional orders. Portfolio rebalancing across multiple markets.

Quantitative Analysis is where it gets interesting. Kelly criterion for optimal position sizing, Black Scholes pricing adapted for binary prediction markets, Bayesian updating for incorporating new information into probability estimates, and Monte Carlo simulation for scenario analysis. These aren’t toy implementations. The Kelly calculator accounts for edge estimation uncertainty, and the Monte Carlo engine runs thousands of paths with configurable correlation structures.

Technical Analysis provides RSI, MACD, and Bollinger Band calculations adapted for prediction market price series. Prediction markets have different dynamics than equities (prices are bounded between 0 and 1, mean reversion is stronger near extremes), so the indicator parameters are tuned accordingly.

Risk Management calculates Value at Risk (VaR) across the portfolio, monitors exposure limits, and enforces position sizing rules. The circuit breaker system automatically halts trading when predefined thresholds are hit: maximum daily loss, maximum position concentration, unusual volatility, or rapid drawdown.

On Chain Intelligence monitors blockchain activity for the markets the agent is trading. Large position changes, whale movements, smart contract events, and liquidity shifts. This gives the agent information that isn’t visible in the order book alone.

News and Sentiment ingests relevant news feeds and social media signals, scoring them for market impact. The agent can factor breaking news into probability estimates before the market fully prices it in.

Execution Optimization handles slippage estimation, optimal order splitting, and timing. Prediction markets can be thin, and a large order that moves the market against you is a real concern.

Backtesting lets you run strategies against historical market data before deploying them live. The backtester accounts for realistic execution assumptions including slippage and fees.

Reporting generates performance attribution, win/loss analysis, and strategy effectiveness reports.

Three Trading Modes

The mode system is crucial for managing risk:

Approval Mode requires human approval for every trade. The agent does all the analysis, identifies opportunities, sizes positions, and presents a fully formed trade recommendation. A human reviews and approves or rejects. This is the starting point for any new strategy.

Autonomous Mode lets the agent trade independently within predefined risk parameters. Maximum position size, maximum daily volume, allowed market categories, and loss limits are all configured upfront. The agent operates freely within those boundaries. If it hits a boundary, it stops and escalates.

Paper Mode executes everything against simulated balances. Full analysis, full execution logic, but no real money at risk. The paper trading engine uses real market prices so the simulation is realistic, but it doesn’t account for market impact since paper orders don’t move prices.

Circuit Breakers

The circuit breaker system deserves its own section because it’s the feature that lets me sleep at night when an agent is trading autonomously.

Five types of circuit breakers are active simultaneously:

  1. Daily loss limit. If the agent’s losses exceed a configured percentage of its portfolio in a single day, all trading halts.
  2. Position concentration. No single market position can exceed a percentage of the total portfolio.
  3. Volatility circuit breaker. If a market’s implied volatility spikes beyond the configured threshold, the agent pauses trading in that market.
  4. Drawdown halt. If the portfolio drops below a high water mark by more than the configured percentage, everything stops.
  5. Correlation circuit breaker. If portfolio exposure to correlated markets exceeds the limit, new positions in correlated markets are blocked.

When a circuit breaker triggers, the agent logs the event, sends a notification to the configured alert channel, and enters a cooldown period. It can resume automatically after the cooldown or require manual re activation, depending on your configuration.

Why Build This

Prediction markets are one of the best testbeds for autonomous agent decision making. The outcomes are binary and verifiable. The feedback loop is fast. The stakes are real. Building this pushed me to solve problems in risk management, real time decision making, and human oversight that apply far beyond trading. The patterns here directly informed the approval workflows, circuit breakers, and monitoring used throughout Enterprise.

Source Code

The fullAnalysis function orchestrates all quantitative modules in parallel, gathering regime detection, smart money signals, microstructure data, orderbook depth, whale activity, flow analysis, and manipulation checks into a single result:

export async function fullAnalysis(params: {
  tokenId: string; marketSlug?: string;
  bankroll?: number; estimatedTrueProb?: number;
}): Promise<FullAnalysisResult> {
  const [regimeResult, smartMoneyResult, microResult,
         orderbookResult, whaleResult, flowResult, manipulationResult] =
    await Promise.all([
      detectRegime(tokenId).catch(() => null),
      calculateSmartMoneyIndex(tokenId).catch(() => null),
      analyzeMicrostructure(tokenId).catch(() => null),
      analyzeOrderbookDepth(tokenId).catch(() => null),
      scanWhaleTrades(tokenId).catch(() => null),
      analyzeFlow(tokenId).catch(() => null),
      detectManipulation(tokenId).catch(() => null),
    ]);
}

View the full source on GitHub

// share

// subscribe

New posts and updates straight to your inbox. No noise.

cd ..