Build an AI Trading Bot with OpenClaw

Complete guide to building automated Polymarket trading bots using OpenClaw (Clawdbot). Learn AI-powered trading strategies, cron scheduling, risk management, and Telegram control for prediction market automation.

Build AI-Powered Trading Bots with OpenClaw

OpenClaw (Clawdbot) is a multi-channel AI gateway that lets you build sophisticated prediction market trading bots without complex infrastructure. Run scheduled jobs, execute trades via API, and make AI-powered decisions—all controlled through Telegram, Discord, or the command line.

This guide walks you through building a complete Polymarket trading bot using OpenClaw, from basic price monitoring to AI-driven trading strategies.

What is OpenClaw?

OpenClaw is an open-source AI agent framework that provides:

  • Scheduled Cron Jobs — Run trading strategies on any schedule (every minute, hourly, daily)
  • Shell Command Execution — Execute scripts, API calls, and trading logic
  • AI Decision Making — Leverage Claude or other LLMs to analyze markets and make trading decisions
  • Multi-Channel Control — Monitor and control your bot via Telegram, Discord, or CLI
  • Web Scraping & APIs — Fetch market data, news, and external signals
# Install OpenClaw globally
npm install -g openclaw

# Initialize in your project
openclaw init

# Start the gateway
openclaw gateway start

Bot Architecture with OpenClaw

┌─────────────────────────────────────────────────────────┐
│                      OpenClaw Gateway                    │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐   │
│  │  Cron Jobs   │  │  AI Engine   │  │   Channels   │   │
│  │  (scheduled) │  │  (Claude)    │  │  (Telegram)  │   │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘   │
│         │                 │                  │           │
│         ▼                 ▼                  ▼           │
│  ┌─────────────────────────────────────────────────┐    │
│  │              Your Trading Scripts                │    │
│  │   • Price monitoring    • Order execution        │    │
│  │   • Strategy logic      • Risk management        │    │
│  └─────────────────────────────────────────────────┘    │
│                          │                               │
└──────────────────────────┼───────────────────────────────┘
                           ▼
                    ┌──────────────┐
                    │  Polymarket  │
                    │     API      │
                    └──────────────┘

OpenClaw acts as the orchestration layer—scheduling your scripts, providing AI analysis, and sending alerts to your preferred channel.

Prerequisites

  • Node.js 18+ installed
  • An Anthropic API key (for AI-powered decisions)
  • Polymarket account with API credentials
  • A Telegram bot token (optional, for mobile alerts)
  • Basic familiarity with JavaScript/TypeScript

Step 1: Project Setup

Create a new directory and initialize OpenClaw:

mkdir polymarket-bot && cd polymarket-bot

# Initialize npm and install dependencies
npm init -y
npm install openclaw @polymarket/client dotenv

# Create environment file
cat > .env << 'EOF'
ANTHROPIC_API_KEY=sk-ant-...
POLYMARKET_API_KEY=your-api-key
POLYMARKET_API_SECRET=your-api-secret
TELEGRAM_BOT_TOKEN=your-telegram-token
EOF

# Initialize OpenClaw
npx openclaw init

This creates the basic project structure with OpenClaw configuration files.

Step 2: Basic Price Monitoring Bot

Let's create a simple script that monitors Polymarket prices and sends alerts:

// scripts/monitor-prices.ts
import { fetchMarketData } from './polymarket-api';

interface WatchedMarket {
  id: string;
  name: string;
  alertBelow?: number;
  alertAbove?: number;
}

const WATCHED_MARKETS: WatchedMarket[] = [
  {
    id: '0x1234...', // Polymarket condition ID
    name: 'Bitcoin above $100k by Dec 2025',
    alertBelow: 0.30,
    alertAbove: 0.70,
  },
  // Add more markets to watch
];

async function checkPrices() {
  const alerts: string[] = [];
  
  for (const market of WATCHED_MARKETS) {
    const data = await fetchMarketData(market.id);
    const yesPrice = data.outcomes[0].price;
    
    if (market.alertBelow && yesPrice < market.alertBelow) {
      alerts.push(`📉 ${market.name}\nYES price dropped to ${(yesPrice * 100).toFixed(1)}%`);
    }
    if (market.alertAbove && yesPrice > market.alertAbove) {
      alerts.push(`📈 ${market.name}\nYES price rose to ${(yesPrice * 100).toFixed(1)}%`);
    }
  }
  
  if (alerts.length > 0) {
    console.log('ALERTS:\n' + alerts.join('\n\n'));
  } else {
    console.log('No price alerts triggered');
  }
}

checkPrices();

Schedule this to run every 5 minutes using OpenClaw's cron system:

# In your Telegram chat with the bot, or via CLI:
/cron add price-monitor "*/5 * * * *" "cd ~/polymarket-bot && npx ts-node scripts/monitor-prices.ts"

# List active cron jobs
/cron list

# Check job logs
/cron logs price-monitor

Step 3: AI-Powered Trading Strategy

The real power of OpenClaw is combining scheduled execution with AI decision-making. Here's a strategy that uses Claude to analyze markets and suggest trades:

// scripts/ai-strategy.ts
import Anthropic from '@anthropic-ai/sdk';
import { fetchMarketData, getRecentNews } from './polymarket-api';

const anthropic = new Anthropic();

interface TradeSignal {
  marketId: string;
  action: 'BUY_YES' | 'BUY_NO' | 'HOLD' | 'SELL';
  confidence: number;
  reasoning: string;
}

async function analyzeMarket(marketId: string): Promise<TradeSignal> {
  // Fetch current market data
  const market = await fetchMarketData(marketId);
  const news = await getRecentNews(market.question);
  
  const prompt = `You are a prediction market analyst. Analyze this market and provide a trading signal.

Market: ${market.question}
Current YES price: ${(market.outcomes[0].price * 100).toFixed(1)}%
Current NO price: ${(market.outcomes[1].price * 100).toFixed(1)}%
24h volume: $${market.volume24h.toLocaleString()}
Liquidity: $${market.liquidity.toLocaleString()}

Recent relevant news:
${news.map(n => `- ${n.headline}`).join('\n')}

Based on this information:
1. What is your estimated probability for YES?
2. Is there an edge vs the current price?
3. What action would you recommend?

Respond in JSON format:
{
  "estimatedProbability": 0.XX,
  "edge": 0.XX,
  "action": "BUY_YES" | "BUY_NO" | "HOLD",
  "confidence": 0.XX,
  "reasoning": "..."
}`;

  const response = await anthropic.messages.create({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 1024,
    messages: [{ role: 'user', content: prompt }],
  });

  const content = response.content[0];
  if (content.type === 'text') {
    const analysis = JSON.parse(content.text);
    return {
      marketId,
      action: analysis.action,
      confidence: analysis.confidence,
      reasoning: analysis.reasoning,
    };
  }
  
  return { marketId, action: 'HOLD', confidence: 0, reasoning: 'Failed to parse' };
}

async function main() {
  const MARKETS_TO_ANALYZE = ['0x1234...', '0x5678...'];
  
  for (const marketId of MARKETS_TO_ANALYZE) {
    const signal = await analyzeMarket(marketId);
    
    // Only act on high-confidence signals
    if (signal.confidence > 0.7 && signal.action !== 'HOLD') {
      console.log(`🎯 TRADE SIGNAL: ${signal.action}`);
      console.log(`Confidence: ${(signal.confidence * 100).toFixed(0)}%`);
      console.log(`Reasoning: ${signal.reasoning}`);
      
      // Execute trade (implement with your risk parameters)
      // await executeTrade(signal);
    } else {
      console.log(`Market ${marketId}: HOLD (confidence: ${signal.confidence})`);
    }
  }
}

main();

Step 4: Executing Trades

Here's how to execute trades on Polymarket using their CLOB API:

// scripts/execute-trade.ts
import { ClobClient } from '@polymarket/clob-client';

const client = new ClobClient(
  'https://clob.polymarket.com',
  process.env.POLYMARKET_API_KEY!,
  process.env.POLYMARKET_API_SECRET!
);

interface TradeParams {
  marketId: string;
  side: 'BUY' | 'SELL';
  outcome: 'YES' | 'NO';
  amount: number; // in USDC
  maxPrice: number; // max price willing to pay (0-1)
}

async function executeTrade(params: TradeParams) {
  try {
    // Get current orderbook
    const orderbook = await client.getOrderbook(params.marketId);
    
    // Check if price is acceptable
    const bestAsk = orderbook.asks[0]?.price;
    if (bestAsk && bestAsk > params.maxPrice) {
      console.log(`Price ${bestAsk} exceeds max ${params.maxPrice}, skipping`);
      return null;
    }

    // Place market order
    const order = await client.createOrder({
      tokenId: params.marketId,
      side: params.side,
      amount: params.amount,
      price: params.maxPrice,
      type: 'GTC', // Good til cancelled
    });

    console.log(`✅ Order placed: ${order.id}`);
    console.log(`   Side: ${params.side} ${params.outcome}`);
    console.log(`   Amount: $${params.amount}`);
    console.log(`   Price: ${(params.maxPrice * 100).toFixed(1)}%`);

    return order;
  } catch (error) {
    console.error('Trade execution failed:', error);
    throw error;
  }
}

// Example usage
executeTrade({
  marketId: '0x1234...',
  side: 'BUY',
  outcome: 'YES',
  amount: 10, // $10 USDC
  maxPrice: 0.45, // Max 45 cents
});

Step 5: Scheduling with Cron

OpenClaw's cron system lets you schedule any script. Here are common patterns for trading bots:

# Price monitoring every 5 minutes
/cron add price-alerts "*/5 * * * *" "cd ~/polymarket-bot && npm run monitor"

# AI analysis every hour
/cron add hourly-analysis "0 * * * *" "cd ~/polymarket-bot && npm run analyze"

# Portfolio rebalancing daily at 9 AM
/cron add daily-rebalance "0 9 * * *" "cd ~/polymarket-bot && npm run rebalance"

# Check for arbitrage opportunities every minute
/cron add arb-scanner "* * * * *" "cd ~/polymarket-bot && npm run scan-arb"

# Generate daily P&L report
/cron add daily-report "0 18 * * *" "cd ~/polymarket-bot && npm run daily-report"

All cron job output is sent to your configured channel (Telegram, Discord), so you get real-time notifications of trades, alerts, and errors.

Step 6: Risk Management (Critical)

Automated trading is risky. Implement these safeguards:

// scripts/risk-manager.ts
interface RiskLimits {
  maxPositionSize: number;      // Max $ per position
  maxDailyLoss: number;         // Stop trading if daily loss exceeds
  maxOpenPositions: number;     // Max concurrent positions
  minLiquidity: number;         // Min market liquidity to trade
  cooldownAfterLoss: number;    // Minutes to wait after a loss
}

const LIMITS: RiskLimits = {
  maxPositionSize: 50,          // $50 max per trade
  maxDailyLoss: 100,            // Stop if down $100/day
  maxOpenPositions: 5,          // Max 5 open positions
  minLiquidity: 10000,          // Only trade markets with $10k+ liquidity
  cooldownAfterLoss: 30,        // 30 min cooldown after loss
};

async function checkRiskLimits(): Promise<boolean> {
  const portfolio = await getPortfolioStatus();
  
  // Check daily P&L
  if (portfolio.dailyPnL < -LIMITS.maxDailyLoss) {
    console.log('🛑 DAILY LOSS LIMIT HIT - Trading disabled');
    return false;
  }
  
  // Check position count
  if (portfolio.openPositions.length >= LIMITS.maxOpenPositions) {
    console.log('⚠️ Max positions reached');
    return false;
  }
  
  // Check cooldown
  const lastLoss = portfolio.lastLossTime;
  if (lastLoss && Date.now() - lastLoss < LIMITS.cooldownAfterLoss * 60000) {
    console.log('⏳ In cooldown period after loss');
    return false;
  }
  
  return true;
}

// Wrap all trades with risk check
async function safeTrade(params: TradeParams) {
  if (!await checkRiskLimits()) {
    console.log('Trade blocked by risk manager');
    return null;
  }
  
  if (params.amount > LIMITS.maxPositionSize) {
    params.amount = LIMITS.maxPositionSize;
    console.log(`Position sized down to $${LIMITS.maxPositionSize}`);
  }
  
  return executeTrade(params);
}

Essential safeguards:

  • Start with paper trading or tiny amounts ($1-5 per trade)
  • Implement kill switch via Telegram command
  • Log every trade to a database for post-analysis
  • Set up alerts for unusual activity
  • Never risk more than you can afford to lose

Controlling Your Bot via Telegram

OpenClaw lets you monitor and control your bot from Telegram:

# Check bot status
/status

# View portfolio
"What's my current Polymarket portfolio?"

# Manual trade
"Buy $20 of YES on the Bitcoin $100k market at max 40 cents"

# Pause trading
/cron disable ai-strategy

# Resume trading
/cron enable ai-strategy

# Check recent trades
"Show my trades from the last 24 hours"

# Emergency stop all
/cron disable-all

Advanced Strategy Ideas

News-Driven Trading

Use OpenClaw's web fetch to monitor news sources. When relevant news breaks, have Claude analyze the impact and execute trades before the market adjusts.

Social Sentiment

Monitor Twitter/X and prediction market forums for sentiment shifts. Combine with price data for contrarian signals.

Multi-Market Arbitrage

Compare prices across Polymarket, Kalshi, and betting exchanges. Trade when prices diverge beyond transaction costs.

Event Clustering

Identify correlated events and trade the relationship. E.g., if Fed rate decision affects multiple markets, trade them together.

⚠️ Important Disclaimer

Automated trading involves significant risk. You can lose money—especially with untested strategies. This guide is for educational purposes only. Always start with paper trading, use small amounts, and never trade more than you can afford to lose. Prediction markets may have legal restrictions in your jurisdiction.

Related Guides

Explore More