一键导入
polymarket-openclaw-trading-bot
Build and operate AI-powered trading bots for Polymarket prediction markets with CLOB arbitrage on BTC 5m/15m windows
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Build and operate AI-powered trading bots for Polymarket prediction markets with CLOB arbitrage on BTC 5m/15m windows
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | polymarket-openclaw-trading-bot |
| description | Build and operate AI-powered trading bots for Polymarket prediction markets with CLOB arbitrage on BTC 5m/15m windows |
| triggers | ["how do I set up a Polymarket trading bot","create a bot to trade BTC 5 minute markets on Polymarket","configure OpenClaw AI decision engine for Polymarket","implement Polymarket CLOB arbitrage strategy","debug Polymarket trading bot order execution","set up wallet authentication for Polymarket bot","run a TypeScript prediction market trading bot","configure trade strategies for Polymarket short-duration markets"] |
Skill by ara.so — Hermes Skills collection.
A TypeScript/Node.js trading bot for Polymarket prediction markets using the CLOB (Central Limit Order Book) API. Specializes in short-duration BTC markets (5m/15m windows) with rule-based strategies, optional OpenClaw AI decision layer, strict risk management, and real-time market polling.
trade_1 or trade_2 strategies with entry/exit rulesgit clone https://github.com/Predictly-MCP-Labs/polymarket-openclaw-ai-btc-arbitrage-trading-bot.git
cd polymarket-openclaw-ai-btc-arbitrage-trading-bot
npm install
Prerequisites:
Create .env file (never commit this):
# Required wallet credentials
POLYMARKET_PRIVATE_KEY=0x... # Your wallet private key
POLYMARKET_FUNDER_ADDRESS=0x... # Funder/deposit proxy address
# Optional signature type (defaults to proxy-friendly)
POLYMARKET_SIGNATURE_TYPE=POLY_PROXY # EOA | POLY_PROXY | POLY_GNOSIS_SAFE | POLY_1271
Environment Variable Reference:
POLYMARKET_PRIVATE_KEY: Wallet private key for signing CLOB operations (required)POLYMARKET_FUNDER_ADDRESS: Address holding trading collateral (required)PROXY_WALLET_ADDRESS: Alternate alias for funder addressPOLYMARKET_SIGNATURE_TYPE: Signature method for your account typeThe bot uses TOML for strategy configuration:
# Core strategy settings
strategy = "trade_1" # or "trade_2"
trade_usd = 10.0 # Notional per buy in USD
max_retries = 3 # Retries for transient errors
entry_buy_cooldown_sec = 30 # Pause after failed entry
# Market selection
[market]
market_coin = "btc" # btc | eth | sol | xrp
market_period = "5" # 5 | 15 | 60 | 240 | 1440 (minutes)
# trade_1 strategy: time/price exits
[trade_1]
buy_range_start_pct = 40 # Enter when price is 40-60%
buy_range_end_pct = 60
exit_time_pct = 80 # Exit at 80% of window elapsed
exit_price_min_pct = 55 # Only exit if price >= 55%
emergency_swap_enabled = false
# trade_2 strategy: ratio-based
[trade_2]
entry_ratio_min = 1.05
entry_ratio_max = 1.25
exit_ratio_threshold = 0.95
exit_time_emergency_pct = 90
emergency_swap_enabled = true
# Optional OpenClaw AI decision layer
[openclaw]
enabled = false # Set true to activate
mode = "deterministic" # deterministic | http
min_edge_bps = 50 # Minimum edge in basis points
max_spread_bps = 200 # Maximum allowed spread
lookback_points = 12 # Price history window
# Optional HTTP/LLM integration
# [openclaw.http]
# url = "https://your-openclaw-service.example.com/decide"
# bearer_token = "optional_token"
# timeout_ms = 2500
# Development mode with hot reload
npm run dev
# Production build and run
npm run build
npm start
import { ClobClient } from "@polymarket/clob-client";
import { Wallet } from "ethers";
// Create wallet from private key
const wallet = new Wallet(process.env.POLYMARKET_PRIVATE_KEY!);
// Initialize CLOB client
const clobClient = new ClobClient(
"https://clob.polymarket.com", // host
137, // Polygon chain ID
wallet,
{
funderAddress: process.env.POLYMARKET_FUNDER_ADDRESS,
signatureType: parseInt(process.env.POLYMARKET_SIGNATURE_TYPE || "1")
}
);
// Derive or create API credentials
const apiCreds = await clobClient.deriveApiKey();
console.log("API Key:", apiCreds.apiKey);
import { getMarket } from "./services/gamma";
// Build market slug from config
const coin = config.market.market_coin; // "btc"
const period = config.market.market_period; // "5"
const slug = `will-btc-close-higher-in-${period}-minutes`;
// Fetch market metadata
const market = await getMarket(slug);
console.log("Market ID:", market.id);
console.log("Condition ID:", market.condition_id);
console.log("Tokens:", market.tokens); // [UP token, DOWN token]
import { Trade } from "./trade/trade";
// Create trade instance
const trade = new Trade(
clobClient,
config.trade_usd,
config.max_retries,
config.entry_buy_cooldown_sec
);
// Update prices (fetches from CLOB)
await trade.updatePrices(
market.tokens[0].token_id, // UP token
market.tokens[1].token_id // DOWN token
);
// Make trading decision based on strategy
import { make_trading_decision } from "./trade/decision";
const decision = await make_trading_decision(
trade,
config.strategy,
config.trade_1,
config.trade_2,
market.end_date_iso
);
console.log("Decision:", decision);
// Buy UP token
const buyResult = await trade.buy(
market.tokens[0].token_id, // UP token ID
"UP"
);
if (buyResult.success) {
console.log("Buy successful:", buyResult.orderId);
} else {
console.error("Buy failed:", buyResult.error);
}
// Sell position
const sellResult = await trade.sell("UP");
if (sellResult.success) {
console.log("Sell successful:", sellResult.orderId);
}
import { TradeAction } from "./trade/decision";
function evaluateTrade1Strategy(
trade: Trade,
config: Trade1Config,
endTimeIso: string
): TradeAction {
const now = Date.now();
const endTime = new Date(endTimeIso).getTime();
const timeElapsedPct = ((now - (endTime - 5 * 60 * 1000)) / (5 * 60 * 1000)) * 100;
const upPrice = trade.upPrice;
const downPrice = trade.downPrice;
// Entry logic: price in range, not already holding
if (!trade.hasBought) {
const priceInRange =
upPrice >= config.buy_range_start_pct &&
upPrice <= config.buy_range_end_pct;
if (priceInRange) {
return { action: "BUY_UP", reason: "Price in entry range" };
}
return { action: "HOLD", reason: "Waiting for entry conditions" };
}
// Exit logic: time threshold or price target
const shouldExitTime = timeElapsedPct >= config.exit_time_pct;
const shouldExitPrice = upPrice >= config.exit_price_min_pct;
if (shouldExitTime && shouldExitPrice) {
return { action: "CLOSE_POSITION", reason: "Time and price exit met" };
}
return { action: "HOLD", reason: "Holding position" };
}
import { getOpenClawDecision } from "./trade/openclaw";
if (config.openclaw.enabled) {
const openclawDecision = await getOpenClawDecision(
trade,
{
upPrice: trade.upPrice,
downPrice: trade.downPrice,
timeToExpiry: (new Date(market.end_date_iso).getTime() - Date.now()) / 1000,
hasBought: trade.hasBought,
positionSide: trade.positionSide
},
config.openclaw
);
console.log("OpenClaw signal:", openclawDecision.action);
console.log("Reason:", openclawDecision.reason);
}
import { retryOnTransient } from "./utils/retry";
async function placeOrderWithRetry(
clobClient: ClobClient,
tokenId: string,
side: "BUY" | "SELL",
size: number,
maxRetries: number
) {
return retryOnTransient(
async () => {
const order = await clobClient.createMarketOrder({
tokenID: tokenId,
side,
amount: size.toString()
});
const result = await clobClient.postOrder(order);
return result;
},
maxRetries,
(error) => {
// Check if error is transient (network, 5xx, 429)
const isTransient =
error.message.includes("ECONNRESET") ||
error.message.includes("429") ||
error.message.includes("5xx");
return isTransient;
}
);
}
.env with wallet credentialstrade.toml:
[market]
market_coin = "btc"
market_period = "5"
strategy = "trade_1"
trade_usd = 5.0
npm run devChange only the period in trade.toml:
[market]
market_period = "15"
[openclaw]
enabled = true
mode = "deterministic"
min_edge_bps = 50
max_spread_bps = 200
lookback_points = 12
Run separate processes with different configs:
# Terminal 1: 5-minute BTC
cp trade.toml trade-5m.toml
# Edit trade-5m.toml: market_period = "5"
CONFIG_PATH=trade-5m.toml npm run dev
# Terminal 2: 15-minute BTC
cp trade.toml trade-15m.toml
# Edit trade-15m.toml: market_period = "15"
CONFIG_PATH=trade-15m.toml npm run dev
| Module | Path | Purpose |
|---|---|---|
| Entry point | src/index.ts | Bootstrap, auth, market loop |
| CLOB service | src/services/clob.ts | Wallet, signer, client setup |
| Gamma API | src/services/gamma.ts | Market metadata by slug |
| Config | src/config/toml.ts | TOML parsing and validation |
| Env validation | src/config/validateEnv.ts | Zod schema for env vars |
| Slug builder | src/config/slug.ts | Coin + period → market slug |
| Decision engine | src/trade/decision.ts | Strategy routing (trade_1/trade_2) |
| Price polling | src/trade/prices.ts | Quote fetching and display |
| Trade execution | src/trade/trade.ts | Buy/sell, cooldowns, balances |
| OpenClaw | src/trade/openclaw.ts | AI decision layer |
| Retry logic | src/utils/retry.ts | Transient error handling |
| Error messages | src/utils/tradingErrorMessage.ts | Human-friendly errors |
Cause: Malformed POLYMARKET_PRIVATE_KEY
Fix: Ensure private key starts with 0x and is 64 hex characters:
POLYMARKET_PRIVATE_KEY=0xabcdef1234567890...
Possible causes:
max_spread_bps exceeded)Debug:
const balance = await clobClient.getBalance();
console.log("USDC balance:", balance.usdc);
console.log("Current spread:", Math.abs(trade.upPrice - trade.downPrice));
Expected behavior: After a failed buy, bot waits entry_buy_cooldown_sec before retrying
Adjust: Lower cooldown in trade.toml:
entry_buy_cooldown_sec = 10 # Instead of 30
Check:
[openclaw].enabled = true in trade.toml"deterministic" or "http" with valid endpointDebug:
console.log("OpenClaw config:", config.openclaw);
console.log("Edge BPS:", calculatedEdge);
Symptoms: "401 Unauthorized" or "Invalid signature"
Fix:
POLYMARKET_SIGNATURE_TYPE matches your account:
EOA for standard walletsPOLY_PROXY for Polymarket proxy accountsconst newCreds = await clobClient.createApiKey();
Error: Market slug not found
Cause: Coin/period combination doesn't match active Polymarket markets
Fix: Verify active markets at polymarket.com and adjust:
[market]
market_coin = "btc" # Check available coins
market_period = "5" # Check available periods
Extend decision engine with custom strategy:
// src/trade/customStrategy.ts
export function customDecision(
trade: Trade,
customConfig: any
): TradeAction {
// Your custom logic
const momentum = calculateMomentum(trade.priceHistory);
if (momentum > customConfig.momentum_threshold) {
return { action: "BUY_UP", reason: "Strong upward momentum" };
}
return { action: "HOLD", reason: "Waiting for momentum" };
}
// Register in decision.ts
import { customDecision } from "./customStrategy";
if (config.strategy === "custom") {
return customDecision(trade, config.custom);
}
const markets = [
{ coin: "btc", period: "5" },
{ coin: "eth", period: "5" },
{ coin: "btc", period: "15" }
];
for (const market of markets) {
const slug = buildSlug(market.coin, market.period);
const marketData = await getMarket(slug);
// Run parallel trading loops
runMarketLoop(marketData, config);
}
import { Trade } from "./trade/trade";
async function backtestStrategy(
historicalData: PricePoint[],
config: TomlConfig
) {
const results = [];
for (const dataPoint of historicalData) {
const trade = new Trade(mockClient, config.trade_usd, 1, 0);
trade.upPrice = dataPoint.upPrice;
trade.downPrice = dataPoint.downPrice;
const decision = await make_trading_decision(
trade,
config.strategy,
config.trade_1,
config.trade_2,
dataPoint.endTime
);
results.push({ time: dataPoint.time, decision });
}
return results;
}
trade_usd values initiallymax_retries and cooldownsPolymarket trading bot, Polymarket CLOB API, Polymarket arbitrage bot, BTC 5 minute Polymarket, BTC 15 minute Polymarket, TypeScript prediction market bot, Polymarket API credentials, OpenClaw AI trading, Polymarket wallet setup, CLOB order execution
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