← Back to Dashboard

Polymarket Trading

Institutional-grade prediction market trading with 114+ tools across 10 skills — on-chain intelligence, social analysis, quantitative modeling, smart execution, counter-intelligence, trading optimization, and self-improving AI agents that learn from every trade.

Table of Contents

Overview

The Polymarket system gives AI agents the ability to trade prediction markets on Polymarket — the world's largest prediction market platform. It combines:

Everything goes through the standard enterprise permission pipeline — risk levels, side-effect checks, approval queues, guardrails, and audit logging.

Getting Started

1. Create a Polymarket Agent

Go to Agents → Create Agent and select the "Polymarket Trader" template from the Finance category. This pre-assigns all 9 skills (108 tools). Or assign skills individually:

SkillToolsPurpose
polymarket63Trading infrastructure, learning
polymarket-quant14Mathematical analysis engine
polymarket-onchain6Blockchain intelligence
polymarket-social5Social media sentiment
polymarket-feeds5Event calendar, news, odds
polymarket-analytics5Correlation, arbitrage, regime
polymarket-execution4Smart order execution
polymarket-counterintel3Manipulation detection
polymarket-portfolio3Portfolio optimization

2. Connect a Wallet

The agent needs an Ethereum wallet with USDC on Polygon. Two options:

3. Configure Risk Limits

Use the Config tab on the dashboard or poly_set_config. Set trading mode, max position, daily loss limit, drawdown threshold.

4. Fund & Start

Send USDC to the wallet on Polygon. Start with paper trading mode to test strategies risk-free.

Architecture (9 Skills)

┌─────────────────────────────────────────────────────────────────────┐
│                        POLYMARKET TRADING SYSTEM                     │
│                         108 tools · 9 skills                         │
├─────────────┬──────────────┬──────────────┬──────────────────────────┤
│  INTELLIGENCE               │   EXECUTION                 │ LEARNING │
│                             │                             │          │
│  On-Chain (6)               │  Trading (63)               │ Journal  │
│  · Whale tracking           │  · Orders, positions        │ Calibr.  │
│  · Orderbook depth          │  · Risk controls            │ Strategy │
│  · Net flow analysis        │  · Wallet management        │ Lessons  │
│  · Wallet profiling         │                             │ P&L Attr │
│  · Liquidity mapping        │  Execution Edge (4)         │          │
│  · TX decoding              │  · Sniper orders            │          │
│                             │  · TWAP/VWAP scale-in       │          │
│  Social (5)                 │  · Hedging                  │          │
│  · Twitter sentiment        │  · Exit strategies          │          │
│  · Reddit pulse             │                             │          │
│  · Telegram monitor         │  Portfolio (3)              │          │
│  · Polymarket comments      │  · Optimizer                │          │
│  · Velocity tracking        │  · Drawdown monitor         │          │
│                             │  · P&L attribution          │          │
│  Feeds (5)                  │                             │          │
│  · Event calendar           │  Counter-Intel (3)          │          │
│  · Official sources         │  · Manipulation detector    │          │
│  · Odds aggregator          │  · Resolution risk          │          │
│  · Breaking news            │  · Counterparty analysis    │          │
│  · Resolution tracking      │                             │          │
│                             │  Quant Engine (14)          │          │
│  Analytics (5)              │  · Kelly, Black-Scholes     │          │
│  · Correlation detection    │  · Monte Carlo, Bayesian    │          │
│  · Arbitrage scanning       │  · RSI, MACD, Bollinger     │          │
│  · Regime detection         │  · VaR, Entropy, Hurst      │          │
│  · Smart money index        │  · Signal generator         │          │
│  · Microstructure           │                             │          │
└─────────────┴──────────────┴──────────────┴──────────────────────────┘

Data Flow

Breaking News ──→ Social Velocity ──→ Sentiment Analysis ──→ ┐
Official Sources ──→ Event Calendar ──→ Resolution Track ──→ ├→ Smart Money Index ──→ Signal Generation
Whale Tracker ──→ Orderbook Depth ──→ On-Chain Flow ─────→ ┘        │
                                                                     ↓
Manipulation Check ──→ Resolution Risk ──→ Counterparty ──→ Risk Gate
                                                                     ↓
Kelly Criterion ──→ Position Sizing ──→ Execution (Sniper/TWAP) ──→ Trade
                                                                     ↓
Exit Strategy ──→ Drawdown Monitor ──→ Portfolio Optimizer       Record Prediction
                                                                     ↓
                            Resolve → Review → Lesson → Calibrate → Improve

Performance

Trading Modes

ModeHow It WorksBest For
ApprovalAgent queues trades → humans approve/reject on dashboard. Auto-approve rules for small trades.Production, compliance, learning the system
AutonomousAgent trades within risk limits. Circuit breakers auto-pause on loss limits.Proven strategies, experienced users
PaperSimulated trading with real data. All logged for strategy evaluation.Testing, new agents, strategy development

On-Chain Intelligence (6 tools)

ToolWhat It Does
poly_whale_trackerMonitor large trades, detect whale wallets, track accumulation/distribution. Actions: scan, list_whales, add_whale, remove_whale
poly_orderbook_depthL2 orderbook analysis — bid/ask walls, liquidity depth, imbalance ratio, spoofing indicators
poly_onchain_flowNet buy/sell flow over 5m/1h/4h/24h windows. Separates whale flow from retail
poly_wallet_profilerProfile any wallet — trade count, volume, win rate, markets traded. Evaluate if a whale is worth following
poly_liquidity_mapMap liquidity across multiple tokens. Ranks tradability, identifies thin markets
poly_transaction_decoderDecode Polygon transactions — CTF minting, redeeming, splitting, merging

Social Intelligence (5 tools)

ToolWhat It Does
poly_twitter_sentimentTwitter/X sentiment via Google News proxy. Keyword-based scoring with spike detection
poly_polymarket_commentsScrape market comment sections — often contains insider-tier info before price moves
poly_reddit_pulseMonitor r/polymarket, r/politics, r/sports, custom subs. Reddit surfaces info 6-12h before MSM
poly_telegram_monitorScrape public Telegram channels for prediction market alpha
poly_social_velocityCross-platform mention velocity — detects spikes from 10→1000 mentions/hour

Event & Data Feeds (5 tools)

ToolWhat It Does
poly_calendar_eventsStructured event calendar — elections, courts, fed, earnings, sports. Actions: list, add, remove, upcoming, auto_discover
poly_official_sourcesFirst-party data from White House, SCOTUS, SEC, Fed, ESPN, NOAA, Congress. RSS/Atom feeds
poly_odds_aggregatorCompare Polymarket prices vs betting odds from other platforms. Divergence = opportunity
poly_resolution_trackerTrack how markets resolve. Monitor resolution sources directly for early signals
poly_breaking_newsAP, Reuters, BBC, CNN via RSS. Flags headlines most likely to move prediction markets

Advanced Analytics (5 tools)

ToolWhat It DoesMath
poly_market_correlationPearson correlation between token price historiesr = Σ(x-x̄)(y-ȳ) / √(Σ(x-x̄)²·Σ(y-ȳ)²)
poly_arbitrage_scannerYES+NO≠$1, multi-outcome sums, cross-market divergencePrice sum deviation analysis
poly_regime_detectorTrending (H>0.55), mean-reverting (H<0.45), random walkHurst exponent via R/S analysis
poly_smart_money_indexComposite: orderbook imbalance + flow + momentum + newsWeighted signal aggregation (-1 to 1)
poly_market_microstructureSpread, fill probability, slippage simulation at various sizesOrderbook walk simulation

Execution Edge (4 tools)

ToolWhat It Does
poly_sniperTrailing limit order — auto-adjusts to trail best bid/ask. Actions: create, list, cancel, status
poly_scale_inTWAP/VWAP execution — split large orders into time-weighted slices. Minimizes market impact
poly_hedgeCreate hedges in correlated markets. Actions: create, list, close, analyze
poly_exit_strategyTake-profit, stop-loss, trailing stop, time-based exit. Actions: create, list, remove, check

Counter-Intelligence (3 tools)

ToolWhat It Does
poly_manipulation_detectorDetect wash trading, spoofing, layering, volume concentration, rapid-fire bot activity
poly_resolution_riskScore ambiguity risk — vague language, subjective resolution, missing sources, no end date
poly_counterparty_analysisWho's on the other side? Whale vs retail distribution. Shows if you're trading against smart money

Portfolio Management (3 tools)

ToolWhat It Does
poly_portfolio_optimizerMean-variance optimization across positions. Optimal weights for max Sharpe ratio
poly_drawdown_monitorReal-time drawdown tracking with circuit breaker. Daily P&L tracking. Actions: check, history
poly_pnl_attributionP&L by strategy, category, and signal source. Kill losers, double winners. Actions: analyze, record, summary

Quant Engine (14 tools)

ToolWhat It DoesMath
poly_kelly_criterionOptimal position sizingf* = (bp - q) / b
poly_binary_pricingFair value estimationBlack-Scholes adapted for binary options
poly_bayesian_updateUpdate beliefs with evidenceP(H|E) = P(E|H)P(H) / P(E)
poly_monte_carloSimulate 10,000 price pathsOrnstein-Uhlenbeck process
poly_technical_indicatorsRSI, MACD, Bollinger, VWAP, EMAStandard TA formulas
poly_volatilityRealized vol, EWMA, HurstR/S analysis, Cornish-Fisher VaR
poly_stat_arbPairs trading signalsEngle-Granger cointegration
poly_value_at_riskDownside riskHistorical, Parametric, MC VaR
poly_entropyInformation theoryShannon entropy, KL divergence
poly_generate_signalMaster signal combinerWeighted aggregation + Kelly sizing
poly_correlation_matrixPortfolio diversificationPairwise correlation + PCA

Learning System (8 tools)

The Learning Loop

  1. Recall: poly_recall_lessons — check past lessons for this market type
  2. Predict: poly_record_prediction — journal prediction with reasoning BEFORE trading
  3. Execute: poly_place_order + poly_exit_strategy
  4. Resolve: poly_resolve_prediction — log outcome → auto-updates calibration
  5. Review: poly_trade_reviewpoly_record_lesson — extract insights
  6. Calibrate: poly_calibration — "Am I overconfident at 80%?"
  7. Rank: poly_strategy_performance — which signals make money?
  8. Attribute: poly_pnl_attribution — P&L by strategy/category/signal

Risk Management

Every trade goes through a 9-step permission pipeline, plus Polymarket-specific risk checks:

  1. Sandbox → Working hours → IP check → Tool blocks → Skill membership → Risk level → Side effects → Approval → Guardrails

Plus: circuit breaker, daily trade/loss limits, position size caps, category restrictions, manipulation screening, resolution risk check, liquidity verification, slippage estimation.

Wallet Security & Transfers

The wallet system implements a 7-layer security model for managing funds. All features are accessible from the Wallet tab on the dashboard.

Wallet Management

FeatureDescriptionAccess
View BalancesLive USDC + MATIC balances from Polygon RPC. Auto-refreshes every 15s.Admin
DepositCopy wallet address to send USDC on Polygon. Supports bridging from other chains via polymarket.com.Admin
Export Private KeyReveal the private key for import into MetaMask/Rabby. Requires confirmation. Audit-logged.Owner only
View on PolygonScanDirect link to the wallet's transaction history on the block explorer.Admin

Withdrawal Whitelist

Agents can only transfer funds to pre-registered addresses. This is the primary defense against prompt injection, hallucination, and social engineering attacks.

Security LayerWhat It Does
Whitelist-onlyAgent cannot send to arbitrary addresses. The poly_transfer_funds tool validates against the whitelist.
Cooling periodConfigurable delay (default 24h, min 0) after adding an address before transfers are allowed. Prevents "add + drain" attacks.
Per-transaction limitMax dollar amount per single transfer (default $100). Set per address.
Daily limitMax total dollars per day per address (default $500). Resets at midnight.
Owner-only managementOnly owner role users can add/remove/modify whitelisted addresses.
Always approval-gatedEvery transfer creates a pending request. Cannot be auto-approved regardless of trading mode.
4-hour expiryPending transfers expire after 4 hours. No stale approvals sitting around.
Full audit trailEvery action logged: add/remove address, approve/reject/fail transfer, export key.

Transfer Flow

  1. Owner adds address — Dashboard → Wallet tab → "Add Address" → set label, address, limits, cooling period
  2. Cooling period elapses — address badge changes from "Cooling: Xh left" to "Active"
  3. User instructs agent — Chat: "Transfer $50 USDC to My MetaMask"
  4. Agent calls poly_transfer_funds — validates whitelist, cooling, limits → creates pending request
  5. Owner approves — Dashboard → Wallet tab → Pending Transfers → Approve button
  6. On-chain execution — Backend sends USDC/MATIC via ethers.js on Polygon → TX hash logged
Edge Cases Handled: Unknown address → rejected with available labels shown. Cooling active → blocked with hours remaining. Over per-tx limit → blocked. Daily limit exceeded → blocked with today's total. Pending transfers to removed address → must reject first. Expired → auto-marked.

AI-Powered Market Monitors

The watcher engine provides continuous market surveillance using a configurable background LLM for real-time analysis. It runs a demand-driven architecture — zero CPU/network when idle.

Engine Architecture

Watcher Types

TypeWhat It DoesAI?
price_levelAlert when price crosses a thresholdNo
price_changeAlert on % change over time windowNo
volume_surgeDetect unusual volume spikesNo
resolution_watchMonitor markets near resolutionNo
portfolio_driftAlert on portfolio allocation driftNo
arbitrage_scanContinuous arbitrage opportunity scanningNo
crypto_priceMonitor crypto prices (BTC, ETH, etc.)No
market_scanScan for markets matching criteriaNo
news_intelligenceMulti-source news + LLM impact assessmentYes
geopoliticalCIA-analyst-style pattern detection connecting world events to marketsYes
cross_signalCorrelates signals from buffer when 3+ convergeYes
sentiment_shiftTracks sentiment over time, alerts on directional changesYes

AI Configuration

Background AI analysis uses a separate, configurable LLM (not the main agent model). Configure via the Monitors tab → "Configure" button:

Database Tables

TablePurpose
poly_watchersWatcher definitions with type, config, interval, status
poly_watcher_eventsGenerated signals/alerts with severity, routing status
poly_watcher_configPer-agent AI model config, budget, spawn limits
poly_analysis_cache1h TTL cache to avoid duplicate LLM calls
poly_sentiment_historySentiment trend data for shift detection
poly_signal_bufferCross-signal correlation buffer with expiry

Dashboard (22 Tabs)

Layout

Two-column layout: vertical navigation sidebar (280px) on the left with grouped tabs, content pane on the right. The P&L line chart is sticky at the top and always visible regardless of scroll position.

GroupTabs
TradingOverview · Wallet · Pending Trades · Trade History · Paper
AutomationMonitors (engine status + AI config) · Signals (events + acknowledge)
OrdersOrders (snipers + scale-in) · Hedges · Exit Rules
IntelligenceOn-Chain · Social · Events · Alerts
AnalyticsAnalytics · Drawdown · Attribution · Calibration
JournalJournal · Strategies · Lessons

Key UI Features

All data loads in parallel via Promise.all (23+ API calls batched). SSE streams provide real-time price and dashboard updates.

Organization Support

The Polymarket page is fully organization-aware:

System Prompt

Agents with Polymarket skills get an injected system prompt (buildPolymarketPrompt()) containing:

All 108 Tools

polymarket (64 tools)

Market Discovery (11) · Wallet & Account (6) · Funds (2) · Fund Transfers (1) · Portfolio (4) · Order Management (8) · Analytics (6) · Config (4) · Alerts (3) · Approval Queue (4) · Social (3) · Paper (2) · System (2) · Learning (8)

polymarket-quant (14 tools)

Kelly · Black-Scholes · Bayesian · Monte Carlo · RSI/MACD/Bollinger · Volatility/Hurst · Stat Arb · VaR · Entropy · News Feed · Sentiment · Signal Generator · Correlation Matrix

polymarket-onchain (6 tools)

Whale Tracker · Orderbook Depth · On-Chain Flow · Wallet Profiler · Liquidity Map · Transaction Decoder

polymarket-social (5 tools)

Twitter Sentiment · Polymarket Comments · Reddit Pulse · Telegram Monitor · Social Velocity

polymarket-feeds (5 tools)

Event Calendar · Official Sources · Odds Aggregator · Resolution Tracker · Breaking News

polymarket-analytics (5 tools)

Market Correlation · Arbitrage Scanner · Regime Detector · Smart Money Index · Market Microstructure

polymarket-execution (4 tools)

Sniper Order · Scale In (TWAP/VWAP) · Hedge Position · Exit Strategy

polymarket-counterintel (3 tools)

Manipulation Detector · Resolution Risk · Counterparty Analysis

polymarket-portfolio (3 tools)

Portfolio Optimizer · Drawdown Monitor · P&L Attribution

polymarket-watcher (4 tools)

Setup Monitors · List Monitors · Manage Monitor · AI Watcher Config

API Reference

Dashboard & Data

MethodEndpointDescription
GET/polymarket/dashboardGlobal dashboard stats (daily counters, wallets)
GET/polymarket/:agentId/tradesTrade history for an agent
GET/polymarket/:agentId/pendingPending trades awaiting approval
POST/polymarket/trades/:id/decideApprove/reject a pending trade
GET/polymarket/:agentId/configTrading configuration
PUT/polymarket/:agentId/configUpdate trading configuration

Wallet & Transfers

MethodEndpointRoleDescription
GET/polymarket/:agentId/walletadminWallet address and status
GET/polymarket/:agentId/wallet/balanceadminLive USDC + MATIC balances from Polygon
POST/polymarket/:agentId/wallet/exportownerExport private key (requires {confirm:"EXPORT"})
GET/polymarket/:agentId/wallet/whitelistadminList whitelisted withdrawal addresses
POST/polymarket/:agentId/wallet/whitelistownerAdd whitelisted address (24h cooling default)
PUT/polymarket/:agentId/wallet/whitelist/:idownerUpdate address limits or label
DELETE/polymarket/:agentId/wallet/whitelist/:idownerRemove whitelisted address
GET/polymarket/:agentId/transfersadminTransfer request history
POST/polymarket/:agentId/transfers/:id/approveownerApprove and execute transfer on-chain
POST/polymarket/:agentId/transfers/:id/rejectownerReject a pending transfer

Watchers & AI

MethodEndpointDescription
GET/polymarket/:agentId/watchersList market monitors
POST/polymarket/watchers/:id/togglePause/resume a watcher
DELETE/polymarket/watchers/:idDelete a watcher
GET/polymarket/:agentId/watcher-eventsList watcher signals/events
POST/polymarket/:agentId/watcher-events/acknowledge-allAcknowledge all unread signals
GET/polymarket/:agentId/watcher-configAI analysis model configuration
POST/polymarket/:agentId/watcher-configUpdate AI config (provider, model, budget)
GET/polymarket/engine/statusWatcher engine status (running, ticks, events)
POST/polymarket/engine/controlStart/stop watcher engine

SSE Streams

EndpointDescription
/polymarket/stream?agentId=XDashboard update events (trade completed, config changed)
/polymarket/prices/stream?agentId=XLive CLOB midpoint prices for open positions (3s interval)

Best Practices

Proactive Trading Engine

The watcher engine includes a proactive trading loop that automatically wakes the trading agent when it's behind on daily trade goals. This ensures consistent market engagement without manual intervention.

How It Works

  1. Every 15 minutes, the watcher checks today's trade count vs the min_trades_daily goal
  2. Balance gate — before waking the agent, checks USDC balance on-chain. If < $5, the wake is skipped entirely (prevents burning API tokens when there's nothing to trade with)
  3. Spawn cooldown — 5-minute minimum between agent wakes to prevent spam
  4. Mandatory analysis sequence — the wake message forces the agent through an 8-step analysis before placing any trades

Mandatory Pre-Trade Sequence

Every proactive wake requires the agent to complete these steps in order before placing any trades:

StepToolPurpose
1poly_watcher_events action=checkCheck for unread market signals
2poly_goals action=checkReview performance targets
3poly_drawdown_monitor action=checkPortfolio-level risk check (halt if >15%)
4poly_calibrationAm I over/under-confident?
5poly_pnl_attributionWhich strategies are making/losing money?
6poly_strategy_performanceWhich signals are actually profitable?
7poly_get_positionsReview open positions and P&L drift
8poly_exit_strategy action=checkCheck if exit conditions triggered

Only after completing all 8 steps does the agent proceed to market screening and trade placement. This ensures quality over quantity — no blind trading.

Smart Execution Requirements

Token Efficiency

AI trading sessions can be expensive — a single proactive wake can consume 100K+ input tokens ($3-5) if not optimized. The system implements several token-saving measures:

Response Trimming

Tool responses are automatically trimmed to reduce token consumption while preserving essential information:

ToolBeforeAfterWhat's Trimmed
poly_get_positions17-22K chars3-5K charsRaw API fields stripped to: asset, size, avgPrice, currentPrice, title, outcome, pnl, resolved, redeemable
poly_screen_markets19-38K chars4-6K charsFull market objects stripped to: id, question, slug, outcomes, prices, volume, liquidity. Max 8 results.
poly_twitter_sentiment15K chars2-3K charsItems capped at 5 per query, only title+sentiment+source kept
poly_search_markets5-7K chars3-4K charsDefault limit reduced from 20→8, clobTokenIds stripped (agent can fetch via poly_get_market)

Agent Behavioral Rules

The system prompt enforces strict token efficiency rules:

Expected Savings

These optimizations reduce proactive session cost from $3-5 per wake to $0.50-1.50 per wake — a 60-75% reduction in token usage.

Monitoring: Check agent token usage in the budget sync logs. Each LLM call logs input/output tokens and cost. If sessions are still ballooning past 50K input tokens, review tool call patterns for redundant searches.

Troubleshooting

IssueSolution
SDK not installingRun poly_check_sdk. Check npm connectivity and disk space.
Trades failingpoly_wallet_status — may need USDC or MATIC for gas.
No dashboard dataTables auto-create on first tool use. Run any poly_ tool to initialize.
Circuit breaker stuckpoly_circuit_breaker action=reset_daily or Pause/Resume button.
Rate limitedBuilt-in rate limiter (30 req/min/domain). Wait 60 seconds.
Stale data on dashboardClick Refresh. SSE stream auto-updates on changes.
Config not taking effectConfig reads from DB on every call — changes are instant. No restart needed.
Manipulation detector false positiveSingle-wallet concentration is normal in low-volume markets. Check volume.
Transfer "Not whitelisted"Add the address in Dashboard → Wallet → Add Address. Only owner role can add.
Transfer "Cooling period"Wait for the configured cooling period to elapse. Check badge on the address card.
Transfer failed on-chainCheck MATIC balance for gas. Verify USDC balance is sufficient. Check PolygonScan for details.
Agent wakes but can't tradeBalance gate skips wakes when USDC < $5. Fund the wallet with more USDC on Polygon.
Sessions burning 100K+ tokensCheck for duplicate tool calls in logs. Agent should follow token efficiency rules — max 2 screens, no retry on rate limit.
Agent keeps calling rate-limited toolsSystem prompt instructs: skip on first "Rate limited" error. If still happening, check if agent is using latest system prompt (restart PM2).
"not enough balance / allowance"Run poly_set_allowances to approve USDC + CTF tokens for exchange contracts. Also check USDC balance.
"invalid price (undefined)"Auto-trade fired without resolving token price. System now auto-fetches midpoint — verify token_id is valid.
Neg-risk market auto-sell won't fillNeg-risk orderbooks have inverted structure. Limit sells at midpoint won't fill when best bid is 0.001. Use market order or sell at best bid.
Can't see Polymarket pageClient org users need access granted: Organizations → Org → Visible Pages → toggle Polymarket.
AI watchers not runningConfigure AI model in Monitors tab → Configure button. Check daily budget isn't exhausted.
Watcher engine stoppedEngine auto-starts when active watchers exist. Check Monitors tab → Start Engine button.