| name | polymarket-mcp-server |
| description | Enable Claude to trade, analyze, and manage Polymarket prediction markets with 45 AI-powered tools, real-time monitoring, and enterprise-grade safety features |
| triggers | ["help me trade on Polymarket","analyze prediction markets","set up Polymarket trading bot","monitor my Polymarket positions","find trending prediction markets","execute trades on Polymarket with Claude","manage my Polymarket portfolio","get real-time Polymarket market data"] |
Polymarket MCP Server
Skill by ara.so — MCP Skills collection.
AI-powered MCP server that enables Claude to autonomously trade, analyze, and manage positions on Polymarket prediction markets. Provides 45 comprehensive tools across market discovery, analysis, trading, portfolio management, and real-time monitoring with WebSocket support.
Installation
Quick Start (DEMO Mode - No Wallet Required)
git clone https://github.com/caiovicentino/polymarket-mcp-server.git
cd polymarket-mcp-server
./quickstart.sh
curl -sSL https://raw.githubusercontent.com/caiovicentino/polymarket-mcp-server/main/quickstart.sh | bash
Full Installation (Trading Enabled)
./install.sh
python -m venv venv
source venv/bin/activate
pip install -e .
Configuration
Create .env file:
cp .env.example .env
DEMO Mode (Read-Only):
DEMO_MODE=true
Full Trading Mode:
# Required
POLYGON_PRIVATE_KEY=${POLYGON_PRIVATE_KEY}
POLYGON_ADDRESS=${POLYGON_ADDRESS}
# Optional Safety Limits
MAX_ORDER_SIZE_USD=1000
MAX_TOTAL_EXPOSURE_USD=5000
MAX_POSITION_SIZE_PER_MARKET=2000
MIN_LIQUIDITY_REQUIRED=10000
MAX_SPREAD_TOLERANCE=0.05
REQUIRE_CONFIRMATION_ABOVE_USD=500
ENABLE_AUTONOMOUS_TRADING=true
Claude Desktop Integration
Add to claude_desktop_config.json:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"polymarket": {
"command": "/absolute/path/to/venv/bin/python",
"args": ["-m", "polymarket_mcp.server"],
"cwd": "/absolute/path/to/polymarket-mcp-server",
"env": {
"POLYGON_PRIVATE_KEY": "${POLYGON_PRIVATE_KEY}",
"POLYGON_ADDRESS": "${POLYGON_ADDRESS}"
}
}
}
}
Tool Categories
1. Market Discovery (8 Tools)
Search Markets
{
"query": "Trump election",
"limit": 10,
"offset": 0
}
Get Trending Markets
{
"period": "24h",
"limit": 20
}
Markets Closing Soon
{
"hours": 24,
"limit": 10
}
Category-Specific Markets
{
"category": "Politics",
"limit": 20
}
2. Market Analysis (10 Tools)
Get Market Details
{
"market_id": "0x1234..."
}
Analyze Market Opportunity (AI-Powered)
{
"market_id": "0x1234...",
"analysis_depth": "deep"
}
Get Orderbook Depth
{
"token_id": "0x5678..."
}
Compare Markets
{
"market_ids": ["0x1234...", "0x5678...", "0x9abc..."]
}
Calculate Spread
{
"token_id": "0x5678..."
}
3. Trading (12 Tools)
Place Limit Order
{
"token_id": "0x5678...",
"side": "BUY",
"price": 0.65,
"size": 100,
"time_in_force": "GTC"
}
Place Market Order
{
"token_id": "0x5678...",
"side": "BUY",
"amount": 50
}
Smart Trade (AI-Powered)
{
"instruction": "Buy $200 worth of Yes on Trump 2024 election if price below 0.60",
"strategy": "passive"
}
Get AI Suggested Prices
{
"token_id": "0x5678...",
"side": "BUY",
"strategy": "mid"
}
Cancel Order
{
"order_id": "0xabcd..."
}
Get Open Orders
{
"market_id": "0x1234..."
}
4. Portfolio Management (8 Tools)
Get Portfolio Summary
{}
Get Active Positions
{
"market_id": "0x1234..."
}
Calculate P&L
{
"position_id": "0x5678...",
"include_unrealized": true
}
Analyze Portfolio Risk
{}
Optimize Portfolio (AI-Powered)
{
"risk_profile": "balanced",
"target_allocation": {
"Politics": 0.4,
"Sports": 0.3,
"Crypto": 0.3
}
}
Get Trade History
{
"start_date": "2024-01-01",
"end_date": "2024-12-31",
"market_id": "0x1234..."
}
5. Real-Time Monitoring (7 Tools)
Subscribe to Market Updates
{
"market_id": "0x1234...",
"channels": ["price", "orderbook", "trades"]
}
Subscribe to User Orders
{}
Get WebSocket Status
{}
Unsubscribe from Market
{
"market_id": "0x1234..."
}
Python API Usage
Direct Python Integration
from polymarket_mcp.client import PolymarketClient
from decimal import Decimal
import os
client = PolymarketClient(
private_key=os.getenv("POLYGON_PRIVATE_KEY"),
polygon_address=os.getenv("POLYGON_ADDRESS")
)
markets = client.search_markets(query="election", limit=5)
for market in markets:
print(f"{market['question']} - Volume: ${market['volume24h']}")
market_id = markets[0]['id']
analysis = client.analyze_market_opportunity(
market_id=market_id,
analysis_depth="deep"
)
print(f"Recommendation: {analysis['recommendation']}")
print(f"Reasoning: {analysis['reasoning']}")
token_id = markets[0]['tokens'][0]['id']
order = client.place_limit_order(
token_id=token_id,
side="BUY",
price=Decimal("0.55"),
size=100,
time_in_force="GTC"
)
print(f"Order placed: {order['id']}")
portfolio = client.get_portfolio_summary()
print(f"Total Value: $")
()
client.subscribe_to_market(
market_id=market_id,
channels=[, ]
)
Trading Strategies Example
from polymarket_mcp.client import PolymarketClient
from decimal import Decimal
class SimpleArbitrageBot:
def __init__(self, client: PolymarketClient):
self.client = client
self.min_spread = Decimal("0.05")
def find_arbitrage_opportunities(self):
"""Find markets with high spreads"""
trending = self.client.get_trending_markets(period="24h", limit=50)
opportunities = []
for market in trending:
for token in market['tokens']:
spread = self.client.calculate_spread(token['id'])
if spread['spread_percentage'] > float(self.min_spread):
opportunities.append({
'market': market['question'],
'token_id': token['id'],
'spread': spread['spread_percentage'],
'best_bid': spread['best_bid'],
'best_ask': spread['best_ask']
})
return sorted(opportunities, key= x: x[], reverse=)
():
suggested = .client.get_ai_suggested_prices(
token_id=opportunity[],
side=,
strategy=
)
order = .client.place_limit_order(
token_id=opportunity[],
side=,
price=Decimal((suggested[])),
size=,
time_in_force=
)
order
client = PolymarketClient(
private_key=os.getenv(),
polygon_address=os.getenv()
)
bot = SimpleArbitrageBot(client)
opportunities = bot.find_arbitrage_opportunities()
opp opportunities[:]:
()
()
order = bot.execute_trade(opp)
()
Risk Management Example
from polymarket_mcp.client import PolymarketClient
class RiskManager:
def __init__(self, client: PolymarketClient):
self.client = client
self.max_exposure_usd = 5000
self.max_position_size = 2000
self.max_category_allocation = 0.4
def check_trade_allowed(self, trade_value_usd: float, market_category: str) -> dict:
"""Validate if trade passes risk checks"""
portfolio = self.client.get_portfolio_summary()
risk_analysis = self.client.analyze_portfolio_risk()
new_exposure = portfolio['total_value_usd'] + trade_value_usd
if new_exposure > self.max_exposure_usd:
return {
"allowed": False,
"reason": f"Would exceed max exposure: ${new_exposure} > ${self.max_exposure_usd}"
}
if trade_value_usd > self.max_position_size:
return {
"allowed": False,
"reason": f"Trade size $ exceeds max position $"
}
category_exposure = risk_analysis.get(, {}).get(market_category, )
new_category_allocation = (category_exposure + trade_value_usd) / new_exposure
new_category_allocation > .max_category_allocation:
{
: ,
:
}
{: , : }
() -> :
portfolio = .client.get_portfolio_summary()
market = .client.get_market_details(market_id)
win_rate =
odds = market[][][]
kelly_fraction = (win_rate - ( - win_rate) / odds) / odds
suggested_size = portfolio[] * kelly_fraction *
(suggested_size, .max_position_size)
client = PolymarketClient(
private_key=os.getenv(),
polygon_address=os.getenv()
)
risk_mgr = RiskManager(client)
trade_check = risk_mgr.check_trade_allowed(
trade_value_usd=,
market_category=
)
trade_check[]:
suggested_size = risk_mgr.suggest_position_size(market_id=)
()
:
()
Common Patterns
Pattern 1: Market Research Pipeline
trending = client.get_trending_markets(period="24h", limit=20)
for market in trending[:5]:
analysis = client.analyze_market_opportunity(
market_id=market['id'],
analysis_depth="deep"
)
if analysis['recommendation'] == 'BUY':
orderbook = client.get_orderbook_depth(market['tokens'][0]['id'])
if orderbook['total_liquidity'] > 10000:
print(f"Good opportunity: {market['question']}")
print(f"Reason: {analysis['reasoning']}")
Pattern 2: Automated Portfolio Rebalancing
risk = client.analyze_portfolio_risk()
if risk['overall_risk_score'] > 70:
optimization = client.optimize_portfolio(
risk_profile="balanced",
target_allocation={
"Politics": 0.35,
"Sports": 0.30,
"Crypto": 0.35
}
)
for suggestion in optimization['suggestions']:
if suggestion['action'] == 'REDUCE':
client.place_market_order(
token_id=suggestion['token_id'],
side="SELL",
amount=suggestion['amount']
)
Pattern 3: Real-Time Monitoring with Alerts
import asyncio
async def monitor_positions():
client.subscribe_to_user_orders()
while True:
portfolio = client.get_portfolio_summary()
if abs(portfolio['unrealized_pnl']) > 500:
print(f"⚠️ Large P&L movement: ${portfolio['unrealized_pnl']}")
risk = client.analyze_portfolio_risk()
if risk['liquidity_risk'] > 80:
print("🚨 High liquidity risk - consider closing positions")
await asyncio.sleep(60)
asyncio.run(monitor_positions())
Web Dashboard
Start the visual web interface:
polymarket-web
Dashboard features:
- Real-time market monitoring
- Configuration management with visual controls
- AI-powered market analysis
- System statistics and performance charts
- Live WebSocket status
Configuration Options
Safety Limits
# Order Limits
MAX_ORDER_SIZE_USD=1000
MAX_POSITION_SIZE_PER_MARKET=2000
MAX_TOTAL_EXPOSURE_USD=5000
# Liquidity Checks
MIN_LIQUIDITY_REQUIRED=10000
MAX_SPREAD_TOLERANCE=0.05
# Confirmations
REQUIRE_CONFIRMATION_ABOVE_USD=500
ENABLE_AUTONOMOUS_TRADING=true
Rate Limiting
# API Rate Limits (per minute)
RATE_LIMIT_READ_PER_MIN=100
RATE_LIMIT_WRITE_PER_MIN=20
RATE_LIMIT_BURST_SIZE=5
WebSocket Configuration
WEBSOCKET_RECONNECT_DELAY=5
WEBSOCKET_MAX_RETRIES=10
WEBSOCKET_PING_INTERVAL=30
Troubleshooting
Connection Issues
python -m polymarket_mcp.test_connection
python -c "from polymarket_mcp.client import PolymarketClient; \
c = PolymarketClient(); \
print(c.get_websocket_status())"
Authentication Errors
from polymarket_mcp.client import PolymarketClient
import os
client = PolymarketClient(
private_key=os.getenv("POLYGON_PRIVATE_KEY"),
polygon_address=os.getenv("POLYGON_ADDRESS")
)
try:
portfolio = client.get_portfolio_summary()
print("✓ Authentication successful")
except Exception as e:
print(f"✗ Auth failed: {e}")
Rate Limit Handling
from polymarket_mcp.client import PolymarketClient
from time import sleep
client = PolymarketClient()
for i in range(100):
try:
markets = client.search_markets(query=f"test {i}", limit=1)
except Exception as e:
if "rate limit" in str(e).lower():
print("Rate limit hit, waiting...")
sleep(60)
Order Validation Failures
from polymarket_mcp.client import PolymarketClient
from decimal import Decimal
client = PolymarketClient()
orderbook = client.get_orderbook_depth(token_id="0x5678...")
if orderbook['total_liquidity'] < 10000:
print("⚠️ Low liquidity - consider smaller order size")
spread = client.calculate_spread(token_id="0x5678...")
if spread['spread_percentage'] > 0.05:
print(f"⚠️ High spread: {spread['spread_percentage']:.2%}")
DEMO Mode Limitations
If you see "Trading disabled in DEMO mode":
DEMO_MODE=false
POLYGON_PRIVATE_KEY=your_actual_key
POLYGON_ADDRESS=0xYourAddress
Testing
pytest
pytest tests/test_trading.py::test_place_limit_order
pytest tests/test_integration.py --run-live
Resources