원클릭으로
polymarket-openclaw-ai-arbitrage-bot
AI-enhanced Polymarket CLOB trading bot for BTC 5m/15m arbitrage with OpenClaw decision engine
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
AI-enhanced Polymarket CLOB trading bot for BTC 5m/15m arbitrage with OpenClaw decision engine
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
Browser-based interface for viewing and filtering OpenClaw session tool call history with zero dependencies for local network deployment.
AI-powered quantitative research and backtesting platform with end-to-end workflow from research to strategy publication
Give your AI assistant a phone — OpenClaw plugin for real phone calls via Twilio + OpenAI Realtime API with in-call tools, transcripts, and call screening
Run multi-model consensus panels (Lite or Heavy) with your own agent backends—no hosted middleware, your models, your rules.
Build a multi-role JARVIS-style voice assistant with local ASR/TTS, OpenClaw LLM gateway, voice wake words, HUD effects, and speaker verification
Use 37 battle-tested marketing skills covering CRO, copywriting, SEO, paid ads, email, growth, and strategy with real data connectors for Google Ads, Search Console, Meta Ads, and X/Twitter
| name | polymarket-openclaw-ai-arbitrage-bot |
| description | AI-enhanced Polymarket CLOB trading bot for BTC 5m/15m arbitrage with OpenClaw decision engine |
| triggers | ["set up polymarket trading bot","configure openclaw arbitrage strategy","trade on polymarket btc 5 minute markets","implement polymarket clob automation","debug polymarket api credentials","run polymarket ai trading bot","configure polymarket arbitrage bot","troubleshoot polymarket wallet signing"] |
Skill by ara.so — Hermes Skills collection.
This skill enables AI coding agents to work with the OpenClaw Polymarket AI Trading Bot, a TypeScript-based automated trading system for Polymarket CLOB markets focusing on BTC 5-minute and 15-minute Up/Down prediction markets.
The bot automates short-horizon prediction market trading on Polymarket using:
trade_1 or trade_2 rule-based strategiesArchitecture: L1 wallet signing → API credential derivation → L2 authenticated CLOB client → market polling → strategy decision → order execution.
# Clone the repository
git clone https://github.com/lorine93s/openclaw-polymarket-ai-arbitrage-trading-bot
cd openclaw-polymarket-ai-arbitrage-trading-bot
# Install dependencies
npm install
# Copy environment template
cp .env.example .env
Edit .env with your credentials:
# Required: Polygon wallet private key (never commit this)
POLYMARKET_PRIVATE_KEY=your_private_key_here
# Required: Funder/proxy address that holds trading collateral
POLYMARKET_FUNDER_ADDRESS=0xYourFunderAddress
# Alternative to POLYMARKET_FUNDER_ADDRESS
# PROXY_WALLET_ADDRESS=0xYourProxyAddress
# Optional: Signature type (defaults to proxy-friendly)
# Options: EOA | POLY_PROXY | POLY_GNOSIS_SAFE | POLY_1271
POLYMARKET_SIGNATURE_TYPE=POLY_PROXY
Validation: The bot validates all required environment variables on startup using Zod schemas. Missing or invalid keys will trigger clear error messages.
# Strategy selection
strategy = "trade_1" # or "trade_2"
# Trade size in USD
trade_usd = 10.0
# Error handling
max_retries = 3
entry_buy_cooldown_sec = 30
# Market configuration
[market]
market_coin = "btc" # btc | eth | sol | xrp
market_period = "5" # "5" (5min) | "15" (15min) | "60" | "240" | "1440"
[trade_1]
# Entry conditions
entry_range_min = 0.45
entry_range_max = 0.55
buy_up_ratio_threshold = 1.05
buy_down_ratio_threshold = 1.05
# Exit conditions
exit_after_secs = 120
exit_up_ratio_threshold = 0.95
exit_down_ratio_threshold = 0.95
# Emergency swap
emergency_swap_enabled = true
emergency_swap_ratio_threshold = 1.15
[trade_2]
# Entry
entry_range_min = 0.40
entry_range_max = 0.60
buy_up_ratio_threshold = 1.08
buy_down_ratio_threshold = 1.08
# Exit targets
exit_up_profit_target = 0.65
exit_down_profit_target = 0.35
# Emergency behavior
emergency_swap_enabled = false
[openclaw]
enabled = true
mode = "deterministic" # or "http" for external LLM service
# Signal thresholds
min_edge_bps = 50 # Minimum edge in basis points (0.5%)
max_spread_bps = 200 # Maximum spread tolerance (2%)
lookback_points = 12 # Historical price points to analyze
# Optional: HTTP/LLM integration
# [openclaw.http]
# url = "https://your-openclaw-service.example.com/decide"
# bearer_token = "${OPENCLAW_API_TOKEN}"
# timeout_ms = 2500
# Development mode (with hot reload)
npm run dev
# Production build
npm run build
npm start
# Type checking
npm run typecheck
# Linting
npm run lint
import { formatSlug } from './config/slug';
// Generate Polymarket market slug
const slug = formatSlug('btc', '5');
// Returns: "will-btc-close-higher-in-the-next-5-minutes"
const ethSlug = formatSlug('eth', '15');
// Returns: "will-eth-close-higher-in-the-next-15-minutes"
import { initClobClient } from './services/clob';
// Initialize L1 client (for API key derivation)
const clobClient = await initClobClient();
// Derive or create API credentials
await clobClient.createOrDeriveAPIKey();
// Initialize L2 authenticated client
const l2Client = await initClobClient({ signatureType: 'POLY_PROXY', feeRecipient: 'YOUR_ADDRESS' });
import { getMarketBySlug } from './services/gamma';
const marketData = await getMarketBySlug(slug);
if (!marketData) {
throw new Error(`Market not found: ${slug}`);
}
console.log('Market ID:', marketData.id);
console.log('End time:', marketData.end_date_iso);
console.log('Tokens:', marketData.tokens);
// tokens[0] = { token_id, outcome: "Up" | "Down", price }
import { updatePrices } from './trade/prices';
import { Trade } from './trade/trade';
const trade = new Trade(
l2Client,
config,
marketData.tokens[0].token_id, // upTokenId
marketData.tokens[1].token_id, // downTokenId
marketData.end_date_iso
);
// Poll prices and update trade state
await updatePrices(trade, clobClient);
// Access current prices
console.log('UP price:', trade.upPrice);
console.log('DOWN price:', trade.downPrice);
console.log('Spread:', trade.upPrice + trade.downPrice);
import { createAndPostMarketOrder } from './trade/trade';
// Buy UP token
await createAndPostMarketOrder(
trade,
'BUY',
trade.upTokenId,
trade.upPrice,
10.0 // USD amount
);
// Sell position
if (trade.hasBought) {
await createAndPostMarketOrder(
trade,
'SELL',
trade.boughtTokenId,
trade.boughtSide === 'Up' ? trade.upPrice : trade.downPrice,
trade.boughtTokens // Sell all tokens
);
}
import { make_trading_decision } from './trade/decision';
// Execute strategy decision
await make_trading_decision(trade);
// The function internally:
// 1. Checks if in position (hasBought)
// 2. Evaluates exit conditions (time/price based)
// 3. Checks entry conditions if no position
// 4. Optionally consults OpenClaw decision engine
// 5. Executes buy/sell orders with retry logic
import { openclawDecision } from './trade/openclaw';
const decision = await openclawDecision(trade, config);
console.log('Action:', decision.action); // BUY_UP | BUY_DOWN | CLOSE_POSITION | HOLD
console.log('Reason:', decision.reason);
console.log('Confidence:', decision.confidence);
// decision.action values:
// - 'BUY_UP': Signal to buy UP token
// - 'BUY_DOWN': Signal to buy DOWN token
// - 'CLOSE_POSITION': Signal to exit current position
// - 'HOLD': No action recommended
import { retryWithPolicy } from './utils/retry';
import { formatTradingError } from './utils/tradingErrorMessage';
try {
await retryWithPolicy(
async () => {
return await clobClient.createOrder(orderArgs);
},
3, // maxRetries
'createOrder'
);
} catch (err) {
const friendlyMessage = formatTradingError(err);
console.error('Order failed:', friendlyMessage);
// Cooldown before retry
if (shouldCooldown(err)) {
await new Promise(r => setTimeout(r, config.entry_buy_cooldown_sec * 1000));
}
}
To trade both 5-minute and 15-minute markets simultaneously, run two separate processes:
Terminal 1 - 5 minute config (trade-5m.toml):
[market]
market_coin = "btc"
market_period = "5"
npm run dev -- --config=trade-5m.toml
Terminal 2 - 15 minute config (trade-15m.toml):
[market]
market_coin = "btc"
market_period = "15"
npm run dev -- --config=trade-15m.toml
// Check USDC balance before trading
const balance = await l2Client.getBalance();
console.log('Available USDC:', balance);
if (balance < config.trade_usd) {
throw new Error(`Insufficient balance: ${balance} < ${config.trade_usd}`);
}
// Trade state tracking
class Trade {
hasBought: boolean = false;
boughtSide: 'Up' | 'Down' | null = null;
boughtPrice: number = 0;
boughtTokens: number = 0;
boughtTokenId: string = '';
boughtTime: number = 0;
resetPosition() {
this.hasBought = false;
this.boughtSide = null;
this.boughtPrice = 0;
this.boughtTokens = 0;
this.boughtTokenId = '';
this.boughtTime = 0;
}
}
// Graceful shutdown handler
process.on('SIGINT', async () => {
console.log('\n⚠️ Shutdown signal received');
if (trade.hasBought) {
console.log('🔒 Warning: Position still open!');
console.log(` Side: ${trade.boughtSide}`);
console.log(` Tokens: ${trade.boughtTokens}`);
console.log(' Consider manual exit before shutdown');
}
process.exit(0);
});
Cause: Invalid or missing POLYMARKET_PRIVATE_KEY in .env.
Solution:
# Ensure private key is 64 hex characters (no 0x prefix in .env)
POLYMARKET_PRIVATE_KEY=abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890
Symptom: 401/403 errors from CLOB API.
Solution:
// Re-derive API credentials
const clobClient = await initClobClient();
await clobClient.createOrDeriveAPIKey();
// Verify funder address matches
console.log('Funder:', process.env.POLYMARKET_FUNDER_ADDRESS);
Common causes:
Debug approach:
// Add detailed logging
console.log('Attempting order:', {
side: 'BUY',
tokenId: trade.upTokenId,
price: trade.upPrice,
amount: config.trade_usd,
balance: await l2Client.getBalance()
});
// Check market status
const market = await getMarketBySlug(slug);
console.log('Market active:', new Date(market.end_date_iso) > new Date());
Symptom: HOLD action when expecting trades.
Solution:
# Relax thresholds in trade.toml
[openclaw]
min_edge_bps = 25 # Lower from 50
max_spread_bps = 300 # Increase from 200
lookback_points = 6 # Reduce data requirements
Symptom: Bot stuck in cooldown after failed buys.
Solution:
# Reduce cooldown period for testing
entry_buy_cooldown_sec = 10 # Down from 30
# Or check for persistent errors
# - Wallet signing issues
# - Invalid funder address
# - Credential problems
Symptom: Market not found: will-btc-close-higher-in-the-next-5-minutes
Solution:
// Verify market exists on Polymarket
// Check if period is active (markets may not exist outside trading hours)
// Try alternative period:
[market]
market_period = "15" # Switch from "5" if 5m market unavailable
Symptom: Bot slows down over time.
Solution:
// Limit lookback buffer size
const MAX_LOOKBACK = 100;
if (priceHistory.length > MAX_LOOKBACK) {
priceHistory = priceHistory.slice(-MAX_LOOKBACK);
}
// Add polling delays
await new Promise(r => setTimeout(r, 2000)); // 2s between polls
| File | Purpose |
|---|---|
src/index.ts | Entry point, market loop, CLOB auth |
src/config/toml.ts | Config schema and validation |
src/config/env.ts | Environment variable loading |
src/config/slug.ts | Market slug generation |
src/services/clob.ts | CLOB client initialization |
src/services/gamma.ts | Gamma API market data |
src/trade/trade.ts | Trade class, order execution |
src/trade/decision.ts | Strategy decision logic |
src/trade/prices.ts | Price polling and updates |
src/trade/openclaw.ts | OpenClaw AI decision engine |
src/utils/retry.ts | Retry policy for transient errors |
src/utils/tradingErrorMessage.ts | Human-readable error formatting |
trade_usd (5-10 USD) for testing