polymarket-mcp-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Polymarket MCP Server

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.
ara.so开发的Skill — MCP Skills合集。
一款AI驱动的MCP服务器,可让Claude在Polymarket预测市场中自主进行交易、分析和持仓管理。提供涵盖市场发现、分析、交易、投资组合管理以及基于WebSocket的实时监控在内的45款全面工具。

Installation

安装

Quick Start (DEMO Mode - No Wallet Required)

快速开始(演示模式 - 无需钱包)

bash
undefined
bash
undefined

Clone and install

Clone and install

git clone https://github.com/caiovicentino/polymarket-mcp-server.git cd polymarket-mcp-server ./quickstart.sh
git clone https://github.com/caiovicentino/polymarket-mcp-server.git cd polymarket-mcp-server ./quickstart.sh

Or automated one-liner

Or automated one-liner

Full Installation (Trading Enabled)

完整安装(启用交易功能)

bash
undefined
bash
undefined

Use automated installer

Use automated installer

./install.sh
./install.sh

Or manual installation

Or manual installation

python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -e .
undefined
python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -e .
undefined

Configuration

配置

Create
.env
file:
bash
cp .env.example .env
DEMO Mode (Read-Only):
env
DEMO_MODE=true
Full Trading Mode:
env
undefined
创建
.env
文件:
bash
cp .env.example .env
演示模式(只读):
env
DEMO_MODE=true
完整交易模式:
env
undefined

Required

必填项

POLYGON_PRIVATE_KEY=${POLYGON_PRIVATE_KEY} POLYGON_ADDRESS=${POLYGON_ADDRESS}
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
undefined
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
undefined

Claude Desktop Integration

Claude桌面端集成

Add to
claude_desktop_config.json
:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.json

Windows:
%APPDATA%\Claude\claude_desktop_config.json
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}"
      }
    }
  }
}
添加至
claude_desktop_config.json
macOS:
~/Library/Application Support/Claude/claude_desktop_config.json

Windows:
%APPDATA%\Claude\claude_desktop_config.json
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)

1. 市场发现(8款工具)

Search Markets

搜索市场

python
undefined
python
undefined

Tool: search_markets

Tool: search_markets

{ "query": "Trump election", "limit": 10, "offset": 0 }
undefined
{ "query": "Trump election", "limit": 10, "offset": 0 }
undefined

Get Trending Markets

获取热门市场

python
undefined
python
undefined

Tool: get_trending_markets

Tool: get_trending_markets

{ "period": "24h", # "24h", "7d", or "30d" "limit": 20 }
undefined
{ "period": "24h", # "24h", "7d", or "30d" "limit": 20 }
undefined

Markets Closing Soon

即将结束的市场

python
undefined
python
undefined

Tool: get_markets_closing_soon

Tool: get_markets_closing_soon

{ "hours": 24, "limit": 10 }
undefined
{ "hours": 24, "limit": 10 }
undefined

Category-Specific Markets

特定分类市场

python
undefined
python
undefined

Tool: get_markets_by_category

Tool: get_markets_by_category

{ "category": "Politics", # Politics, Sports, Crypto, Pop Culture "limit": 20 }
undefined
{ "category": "Politics", # Politics, Sports, Crypto, Pop Culture "limit": 20 }
undefined

2. Market Analysis (10 Tools)

2. 市场分析(10款工具)

Get Market Details

获取市场详情

python
undefined
python
undefined

Tool: get_market_details

Tool: get_market_details

{ "market_id": "0x1234..." }
undefined
{ "market_id": "0x1234..." }
undefined

Analyze Market Opportunity (AI-Powered)

AI驱动的市场机会分析

python
undefined
python
undefined

Tool: analyze_market_opportunity

Tool: analyze_market_opportunity

{ "market_id": "0x1234...", "analysis_depth": "deep" # "quick" or "deep" }
{ "market_id": "0x1234...", "analysis_depth": "deep" # "quick" or "deep" }

Returns: BUY/SELL/HOLD recommendation with reasoning

返回:包含理由的买入/卖出/持有建议

undefined
undefined

Get Orderbook Depth

获取订单簿深度

python
undefined
python
undefined

Tool: get_orderbook_depth

Tool: get_orderbook_depth

{ "token_id": "0x5678..." }
undefined
{ "token_id": "0x5678..." }
undefined

Compare Markets

对比市场

python
undefined
python
undefined

Tool: compare_markets

Tool: compare_markets

{ "market_ids": ["0x1234...", "0x5678...", "0x9abc..."] }
undefined
{ "market_ids": ["0x1234...", "0x5678...", "0x9abc..."] }
undefined

Calculate Spread

计算点差

python
undefined
python
undefined

Tool: calculate_spread

Tool: calculate_spread

{ "token_id": "0x5678..." }
undefined
{ "token_id": "0x5678..." }
undefined

3. Trading (12 Tools)

3. 交易功能(12款工具)

Place Limit Order

挂限价单

python
undefined
python
undefined

Tool: place_limit_order

Tool: place_limit_order

{ "token_id": "0x5678...", "side": "BUY", # or "SELL" "price": 0.65, "size": 100, "time_in_force": "GTC" # GTC, GTD, FOK, FAK }
undefined
{ "token_id": "0x5678...", "side": "BUY", # or "SELL" "price": 0.65, "size": 100, "time_in_force": "GTC" # GTC, GTD, FOK, FAK }
undefined

Place Market Order

挂市价单

python
undefined
python
undefined

Tool: place_market_order

Tool: place_market_order

{ "token_id": "0x5678...", "side": "BUY", "amount": 50 }
undefined
{ "token_id": "0x5678...", "side": "BUY", "amount": 50 }
undefined

Smart Trade (AI-Powered)

AI智能交易

python
undefined
python
undefined

Tool: smart_trade

Tool: smart_trade

{ "instruction": "Buy $200 worth of Yes on Trump 2024 election if price below 0.60", "strategy": "passive" # aggressive, passive, or mid }
{ "instruction": "Buy $200 worth of Yes on Trump 2024 election if price below 0.60", "strategy": "passive" # aggressive, passive, or mid }

Automatically parses instruction and executes optimal trade

自动解析指令并执行最优交易

undefined
undefined

Get AI Suggested Prices

获取AI建议价格

python
undefined
python
undefined

Tool: get_ai_suggested_prices

Tool: get_ai_suggested_prices

{ "token_id": "0x5678...", "side": "BUY", "strategy": "mid" # aggressive, passive, or mid }
undefined
{ "token_id": "0x5678...", "side": "BUY", "strategy": "mid" # aggressive, passive, or mid }
undefined

Cancel Order

取消订单

python
undefined
python
undefined

Tool: cancel_order

Tool: cancel_order

{ "order_id": "0xabcd..." }
undefined
{ "order_id": "0xabcd..." }
undefined

Get Open Orders

获取未成交订单

python
undefined
python
undefined

Tool: get_open_orders

Tool: get_open_orders

{ "market_id": "0x1234..." # Optional filter }
undefined
{ "market_id": "0x1234..." # 可选过滤条件 }
undefined

4. Portfolio Management (8 Tools)

4. 投资组合管理(8款工具)

Get Portfolio Summary

获取投资组合摘要

python
undefined
python
undefined

Tool: get_portfolio_summary

Tool: get_portfolio_summary

{}
{}

Returns: total value, positions, P&L, risk metrics

返回:总价值、持仓、盈亏、风险指标

undefined
undefined

Get Active Positions

获取活跃持仓

python
undefined
python
undefined

Tool: get_active_positions

Tool: get_active_positions

{ "market_id": "0x1234..." # Optional filter }
undefined
{ "market_id": "0x1234..." # 可选过滤条件 }
undefined

Calculate P&L

计算盈亏

python
undefined
python
undefined

Tool: calculate_pnl

Tool: calculate_pnl

{ "position_id": "0x5678...", "include_unrealized": true }
undefined
{ "position_id": "0x5678...", "include_unrealized": true }
undefined

Analyze Portfolio Risk

分析投资组合风险

python
undefined
python
undefined

Tool: analyze_portfolio_risk

Tool: analyze_portfolio_risk

{}
{}

Returns: concentration risk, liquidity risk, diversification score

返回:集中度风险、流动性风险、分散度评分

undefined
undefined

Optimize Portfolio (AI-Powered)

AI驱动的投资组合优化

python
undefined
python
undefined

Tool: optimize_portfolio

Tool: optimize_portfolio

{ "risk_profile": "balanced", # conservative, balanced, or aggressive "target_allocation": { "Politics": 0.4, "Sports": 0.3, "Crypto": 0.3 } }
{ "risk_profile": "balanced", # conservative, balanced, or aggressive "target_allocation": { "Politics": 0.4, "Sports": 0.3, "Crypto": 0.3 } }

Returns: rebalancing suggestions with rationale

返回:包含理由的再平衡建议

undefined
undefined

Get Trade History

获取交易历史

python
undefined
python
undefined

Tool: get_trade_history

Tool: get_trade_history

{ "start_date": "2024-01-01", "end_date": "2024-12-31", "market_id": "0x1234..." # Optional }
undefined
{ "start_date": "2024-01-01", "end_date": "2024-12-31", "market_id": "0x1234..." # 可选过滤条件 }
undefined

5. Real-Time Monitoring (7 Tools)

5. 实时监控(7款工具)

Subscribe to Market Updates

订阅市场更新

python
undefined
python
undefined

Tool: subscribe_to_market

Tool: subscribe_to_market

{ "market_id": "0x1234...", "channels": ["price", "orderbook", "trades"] }
undefined
{ "market_id": "0x1234...", "channels": ["price", "orderbook", "trades"] }
undefined

Subscribe to User Orders

订阅用户订单状态

python
undefined
python
undefined

Tool: subscribe_to_user_orders

Tool: subscribe_to_user_orders

{}
{}

Monitors all your order status changes

监控所有订单状态变化

undefined
undefined

Get WebSocket Status

获取WebSocket状态

python
undefined
python
undefined

Tool: get_websocket_status

Tool: get_websocket_status

{}
{}

Returns: connection state, subscriptions, message counts

返回:连接状态、订阅列表、消息计数

undefined
undefined

Unsubscribe from Market

取消市场订阅

python
undefined
python
undefined

Tool: unsubscribe_from_market

Tool: unsubscribe_from_market

{ "market_id": "0x1234..." }
undefined
{ "market_id": "0x1234..." }
undefined

Python API Usage

Python API 使用

Direct Python Integration

直接Python集成

python
from polymarket_mcp.client import PolymarketClient
from decimal import Decimal
import os
python
from polymarket_mcp.client import PolymarketClient
from decimal import Decimal
import os

Initialize client

Initialize client

client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )
client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )

Search markets

Search markets

markets = client.search_markets(query="election", limit=5) for market in markets: print(f"{market['question']} - Volume: ${market['volume24h']}")
markets = client.search_markets(query="election", limit=5) for market in markets: print(f"{market['question']} - Volume: ${market['volume24h']}")

Get market analysis

Get market analysis

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']}")
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']}")

Place order with safety checks

Place order with safety checks

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']}")
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']}")

Monitor portfolio

Monitor portfolio

portfolio = client.get_portfolio_summary() print(f"Total Value: ${portfolio['total_value_usd']}") print(f"Unrealized P&L: ${portfolio['unrealized_pnl']}")
portfolio = client.get_portfolio_summary() print(f"Total Value: ${portfolio['total_value_usd']}") print(f"Unrealized P&L: ${portfolio['unrealized_pnl']}")

Get real-time updates via WebSocket

Get real-time updates via WebSocket

client.subscribe_to_market( market_id=market_id, channels=["price", "orderbook"] )
undefined
client.subscribe_to_market( market_id=market_id, channels=["price", "orderbook"] )
undefined

Trading Strategies Example

交易策略示例

python
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")  # 5% minimum spread
    
    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=lambda x: x['spread'], reverse=True)
    
    def execute_trade(self, opportunity):
        """Execute trade on identified opportunity"""
        # Get AI-suggested optimal price
        suggested = self.client.get_ai_suggested_prices(
            token_id=opportunity['token_id'],
            side="BUY",
            strategy="mid"
        )
        
        # Place order
        order = self.client.place_limit_order(
            token_id=opportunity['token_id'],
            side="BUY",
            price=Decimal(str(suggested['suggested_price'])),
            size=100,
            time_in_force="GTC"
        )
        
        return order
python
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")  # 5% minimum spread
    
    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=lambda x: x['spread'], reverse=True)
    
    def execute_trade(self, opportunity):
        """Execute trade on identified opportunity"""
        # Get AI-suggested optimal price
        suggested = self.client.get_ai_suggested_prices(
            token_id=opportunity['token_id'],
            side="BUY",
            strategy="mid"
        )
        
        # Place order
        order = self.client.place_limit_order(
            token_id=opportunity['token_id'],
            side="BUY",
            price=Decimal(str(suggested['suggested_price'])),
            size=100,
            time_in_force="GTC"
        )
        
        return order

Usage

Usage

client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )
bot = SimpleArbitrageBot(client) opportunities = bot.find_arbitrage_opportunities()
for opp in opportunities[:3]: print(f"Opportunity: {opp['market']}") print(f"Spread: {opp['spread']:.2%}") order = bot.execute_trade(opp) print(f"Order placed: {order['id']}\n")
undefined
client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )
bot = SimpleArbitrageBot(client) opportunities = bot.find_arbitrage_opportunities()
for opp in opportunities[:3]: print(f"Opportunity: {opp['market']}") print(f"Spread: {opp['spread']:.2%}") order = bot.execute_trade(opp) print(f"Order placed: {order['id']}\n")
undefined

Risk Management Example

风险管理示例

python
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  # 40%
    
    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()
        
        # Check total exposure
        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}"
            }
        
        # Check position size
        if trade_value_usd > self.max_position_size:
            return {
                "allowed": False,
                "reason": f"Trade size ${trade_value_usd} exceeds max position ${self.max_position_size}"
            }
        
        # Check category concentration
        category_exposure = risk_analysis.get('category_concentration', {}).get(market_category, 0)
        new_category_allocation = (category_exposure + trade_value_usd) / new_exposure
        
        if new_category_allocation > self.max_category_allocation:
            return {
                "allowed": False,
                "reason": f"Would exceed {market_category} allocation: {new_category_allocation:.1%}"
            }
        
        return {"allowed": True, "reason": "All risk checks passed"}
    
    def suggest_position_size(self, market_id: str) -> float:
        """Suggest optimal position size based on risk"""
        portfolio = self.client.get_portfolio_summary()
        market = self.client.get_market_details(market_id)
        
        # Kelly Criterion simplified
        win_rate = 0.55  # Estimate from market analysis
        odds = market['tokens'][0]['price']
        
        kelly_fraction = (win_rate - (1 - win_rate) / odds) / odds
        suggested_size = portfolio['total_value_usd'] * kelly_fraction * 0.5  # Half Kelly
        
        return min(suggested_size, self.max_position_size)
python
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  # 40%
    
    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()
        
        # Check total exposure
        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}"
            }
        
        # Check position size
        if trade_value_usd > self.max_position_size:
            return {
                "allowed": False,
                "reason": f"Trade size ${trade_value_usd} exceeds max position ${self.max_position_size}"
            }
        
        # Check category concentration
        category_exposure = risk_analysis.get('category_concentration', {}).get(market_category, 0)
        new_category_allocation = (category_exposure + trade_value_usd) / new_exposure
        
        if new_category_allocation > self.max_category_allocation:
            return {
                "allowed": False,
                "reason": f"Would exceed {market_category} allocation: {new_category_allocation:.1%}"
            }
        
        return {"allowed": True, "reason": "All risk checks passed"}
    
    def suggest_position_size(self, market_id: str) -> float:
        """Suggest optimal position size based on risk"""
        portfolio = self.client.get_portfolio_summary()
        market = self.client.get_market_details(market_id)
        
        # Kelly Criterion simplified
        win_rate = 0.55  # Estimate from market analysis
        odds = market['tokens'][0]['price']
        
        kelly_fraction = (win_rate - (1 - win_rate) / odds) / odds
        suggested_size = portfolio['total_value_usd'] * kelly_fraction * 0.5  # Half Kelly
        
        return min(suggested_size, self.max_position_size)

Usage

Usage

client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )
risk_mgr = RiskManager(client)
client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )
risk_mgr = RiskManager(client)

Check if trade is allowed

Check if trade is allowed

trade_check = risk_mgr.check_trade_allowed( trade_value_usd=500, market_category="Politics" )
if trade_check['allowed']: suggested_size = risk_mgr.suggest_position_size(market_id="0x1234...") print(f"Suggested position size: ${suggested_size:.2f}") else: print(f"Trade blocked: {trade_check['reason']}")
undefined
trade_check = risk_mgr.check_trade_allowed( trade_value_usd=500, market_category="Politics" )
if trade_check['allowed']: suggested_size = risk_mgr.suggest_position_size(market_id="0x1234...") print(f"Suggested position size: ${suggested_size:.2f}") else: print(f"Trade blocked: {trade_check['reason']}")
undefined

Common Patterns

常见模式

Pattern 1: Market Research Pipeline

模式1:市场研究流程

python
undefined
python
undefined

1. Find trending markets

1. 查找热门市场

trending = client.get_trending_markets(period="24h", limit=20)
trending = client.get_trending_markets(period="24h", limit=20)

2. Analyze each market

2. 分析每个市场

for market in trending[:5]: analysis = client.analyze_market_opportunity( market_id=market['id'], analysis_depth="deep" )
if analysis['recommendation'] == 'BUY':
    # 3. Get orderbook depth
    orderbook = client.get_orderbook_depth(market['tokens'][0]['id'])
    
    # 4. Check liquidity
    if orderbook['total_liquidity'] > 10000:
        print(f"Good opportunity: {market['question']}")
        print(f"Reason: {analysis['reasoning']}")
undefined
for market in trending[:5]: analysis = client.analyze_market_opportunity( market_id=market['id'], analysis_depth="deep" )
if analysis['recommendation'] == 'BUY':
    # 3. 获取订单簿深度
    orderbook = client.get_orderbook_depth(market['tokens'][0]['id'])
    
    # 4. 检查流动性
    if orderbook['total_liquidity'] > 10000:
        print(f"Good opportunity: {market['question']}")
        print(f"Reason: {analysis['reasoning']}")
undefined

Pattern 2: Automated Portfolio Rebalancing

模式2:自动化投资组合再平衡

python
undefined
python
undefined

1. Get portfolio risk analysis

1. 获取投资组合风险分析

risk = client.analyze_portfolio_risk()
risk = client.analyze_portfolio_risk()

2. If risk is high, get optimization suggestions

2. 如果风险较高,获取优化建议

if risk['overall_risk_score'] > 70: optimization = client.optimize_portfolio( risk_profile="balanced", target_allocation={ "Politics": 0.35, "Sports": 0.30, "Crypto": 0.35 } )
# 3. Execute suggested trades
for suggestion in optimization['suggestions']:
    if suggestion['action'] == 'REDUCE':
        client.place_market_order(
            token_id=suggestion['token_id'],
            side="SELL",
            amount=suggestion['amount']
        )
undefined
if risk['overall_risk_score'] > 70: optimization = client.optimize_portfolio( risk_profile="balanced", target_allocation={ "Politics": 0.35, "Sports": 0.30, "Crypto": 0.35 } )
# 3. 执行建议交易
for suggestion in optimization['suggestions']:
    if suggestion['action'] == 'REDUCE':
        client.place_market_order(
            token_id=suggestion['token_id'],
            side="SELL",
            amount=suggestion['amount']
        )
undefined

Pattern 3: Real-Time Monitoring with Alerts

模式3:带告警的实时监控

python
import asyncio

async def monitor_positions():
    # Subscribe to user orders
    client.subscribe_to_user_orders()
    
    # Monitor portfolio value
    while True:
        portfolio = client.get_portfolio_summary()
        
        # Alert on significant P&L change
        if abs(portfolio['unrealized_pnl']) > 500:
            print(f"⚠️ Large P&L movement: ${portfolio['unrealized_pnl']}")
            
            # Analyze if should close positions
            risk = client.analyze_portfolio_risk()
            if risk['liquidity_risk'] > 80:
                print("🚨 High liquidity risk - consider closing positions")
        
        await asyncio.sleep(60)  # Check every minute
python
import asyncio

async def monitor_positions():
    # Subscribe to user orders
    client.subscribe_to_user_orders()
    
    # Monitor portfolio value
    while True:
        portfolio = client.get_portfolio_summary()
        
        # Alert on significant P&L change
        if abs(portfolio['unrealized_pnl']) > 500:
            print(f"⚠️ Large P&L movement: ${portfolio['unrealized_pnl']}")
            
            # Analyze if should close positions
            risk = client.analyze_portfolio_risk()
            if risk['liquidity_risk'] > 80:
                print("🚨 High liquidity risk - consider closing positions")
        
        await asyncio.sleep(60)  # Check every minute

Run monitoring

Run monitoring

asyncio.run(monitor_positions())
undefined
asyncio.run(monitor_positions())
undefined

Web Dashboard

Web控制台

Start the visual web interface:
bash
polymarket-web
启动可视化Web界面:
bash
polymarket-web

Or: ./start_web_dashboard.sh

Or: ./start_web_dashboard.sh


Dashboard features:
- Real-time market monitoring
- Configuration management with visual controls
- AI-powered market analysis
- System statistics and performance charts
- Live WebSocket status

控制台功能:
- 实时市场监控
- 可视化配置管理
- AI驱动的市场分析
- 系统统计与性能图表
- 实时WebSocket状态

Configuration Options

配置选项

Safety Limits

安全限制

env
undefined
env
undefined

Order Limits

订单限制

MAX_ORDER_SIZE_USD=1000 MAX_POSITION_SIZE_PER_MARKET=2000 MAX_TOTAL_EXPOSURE_USD=5000
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
MIN_LIQUIDITY_REQUIRED=10000 MAX_SPREAD_TOLERANCE=0.05

Confirmations

确认机制

REQUIRE_CONFIRMATION_ABOVE_USD=500 ENABLE_AUTONOMOUS_TRADING=true
undefined
REQUIRE_CONFIRMATION_ABOVE_USD=500 ENABLE_AUTONOMOUS_TRADING=true
undefined

Rate Limiting

速率限制

env
undefined
env
undefined

API Rate Limits (per minute)

API速率限制(每分钟)

RATE_LIMIT_READ_PER_MIN=100 RATE_LIMIT_WRITE_PER_MIN=20 RATE_LIMIT_BURST_SIZE=5
undefined
RATE_LIMIT_READ_PER_MIN=100 RATE_LIMIT_WRITE_PER_MIN=20 RATE_LIMIT_BURST_SIZE=5
undefined

WebSocket Configuration

WebSocket配置

env
WEBSOCKET_RECONNECT_DELAY=5
WEBSOCKET_MAX_RETRIES=10
WEBSOCKET_PING_INTERVAL=30
env
WEBSOCKET_RECONNECT_DELAY=5
WEBSOCKET_MAX_RETRIES=10
WEBSOCKET_PING_INTERVAL=30

Troubleshooting

故障排查

Connection Issues

连接问题

bash
undefined
bash
undefined

Test API connectivity

测试API连通性

python -m polymarket_mcp.test_connection
python -m polymarket_mcp.test_connection

Check WebSocket status

检查WebSocket状态

python -c "from polymarket_mcp.client import PolymarketClient;
c = PolymarketClient();
print(c.get_websocket_status())"
undefined
python -c "from polymarket_mcp.client import PolymarketClient;
c = PolymarketClient();
print(c.get_websocket_status())"
undefined

Authentication Errors

认证错误

python
undefined
python
undefined

Verify wallet configuration

验证钱包配置

from polymarket_mcp.client import PolymarketClient import os
client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )
from polymarket_mcp.client import PolymarketClient import os
client = PolymarketClient( private_key=os.getenv("POLYGON_PRIVATE_KEY"), polygon_address=os.getenv("POLYGON_ADDRESS") )

Test authentication

测试认证

try: portfolio = client.get_portfolio_summary() print("✓ Authentication successful") except Exception as e: print(f"✗ Auth failed: {e}")
undefined
try: portfolio = client.get_portfolio_summary() print("✓ Authentication successful") except Exception as e: print(f"✗ Auth failed: {e}")
undefined

Rate Limit Handling

速率限制处理

python
from polymarket_mcp.client import PolymarketClient
from time import sleep

client = PolymarketClient()
python
from polymarket_mcp.client import PolymarketClient
from time import sleep

client = PolymarketClient()

Built-in rate limiting

Built-in rate limiting

for i in range(100): try: markets = client.search_markets(query=f"test {i}", limit=1) # Rate limiter automatically throttles requests except Exception as e: if "rate limit" in str(e).lower(): print("Rate limit hit, waiting...") sleep(60)
undefined
for i in range(100): try: markets = client.search_markets(query=f"test {i}", limit=1) # Rate limiter automatically throttles requests except Exception as e: if "rate limit" in str(e).lower(): print("Rate limit hit, waiting...") sleep(60)
undefined

Order Validation Failures

订单验证失败

python
undefined
python
undefined

Check order validation before placing

下单前检查订单有效性

from polymarket_mcp.client import PolymarketClient from decimal import Decimal
client = PolymarketClient()
from polymarket_mcp.client import PolymarketClient from decimal import Decimal
client = PolymarketClient()

Validate market liquidity

Validate market liquidity

orderbook = client.get_orderbook_depth(token_id="0x5678...") if orderbook['total_liquidity'] < 10000: print("⚠️ Low liquidity - consider smaller order size")
orderbook = client.get_orderbook_depth(token_id="0x5678...") if orderbook['total_liquidity'] < 10000: print("⚠️ Low liquidity - consider smaller order size")

Calculate expected slippage

Calculate expected slippage

spread = client.calculate_spread(token_id="0x5678...") if spread['spread_percentage'] > 0.05: print(f"⚠️ High spread: {spread['spread_percentage']:.2%}")
undefined
spread = client.calculate_spread(token_id="0x5678...") if spread['spread_percentage'] > 0.05: print(f"⚠️ High spread: {spread['spread_percentage']:.2%}")
undefined

DEMO Mode Limitations

演示模式限制

If you see "Trading disabled in DEMO mode":
bash
undefined
如果看到"Trading disabled in DEMO mode":
bash
undefined

Switch to full mode

切换到完整模式

1. Get Polygon wallet private key

1. 获取Polygon钱包私钥

2. Update .env:

2. 更新.env:

DEMO_MODE=false POLYGON_PRIVATE_KEY=your_actual_key POLYGON_ADDRESS=0xYourAddress
DEMO_MODE=false POLYGON_PRIVATE_KEY=your_actual_key POLYGON_ADDRESS=0xYourAddress

3. Restart MCP server

3. 重启MCP服务器

undefined
undefined

Testing

测试

bash
undefined
bash
undefined

Run all tests

运行所有测试

pytest
pytest

Test specific tool

测试特定工具

pytest tests/test_trading.py::test_place_limit_order
pytest tests/test_trading.py::test_place_limit_order

Test with real API (caution)

测试真实API(谨慎操作)

pytest tests/test_integration.py --run-live
undefined
pytest tests/test_integration.py --run-live
undefined

Resources

资源