Merlin is a fully autonomous, institutional-grade quantitative event-driven trading bot designed to operate on Polymarket's Central Limit Order Book (CLOB) via the Polygon network.
The bot implements Positive Expected Value (+EV) and Late-Stage Probability Capture strategies, executing trades autonomously in prediction markets without human intervention. The entire trading lifecycle—from identifying market inefficiencies to claiming settlements—is 100% automated and asynchronous.
Note
Support the project by signing up on Polymarket through the Referral Link.
The codebase is organized in a modular structure with decoupled components, each having a single responsibility:
- config.ts: Environment variable validator and configuration provider (e.g., contract addresses for
USDC,CTF). - trades.ts: Disk storage manager. Handles real and simulated (dry-run) trades in isolated directories with auto-migration and trade settlement routines.
- telegram.ts: Telemetry module providing remote control commands and real-time alerts via Telegram (
/status,/pnl,/trades,/analyze,/help). - ai.ts: Advanced AI filters using Claude (
claude-haiku-4-5) to skip ambiguous markets (haikuFilter), validate news via Google News RSS (newsCheck), and run post-mortem analyses (aiPostMortem). - exchange.ts: Web3 network clients (Polygon provider), Polymarket CLOB client, Gnosis Safe transaction relayer, order book health analysis, and stale order cancellation.
- bot.ts: Core orchestrator that schedules and coordinates the periodic trading loop (runs every 30 seconds).
- summary.ts: Independent script to compile and display formatted statistics for ROI, Win Rate, and Net P&L.
-
Dry Run Simulator: Allows full bot testing without risking real capital (
DRY_RUN=true). It fetches real order books in real-time and simulates execution virtualizing P&L tracking undertrades/dry_trades.json. - Late-Stage +EV Capture: Scans Polymarket for markets near their resolution time, comparing the implied market probability (represented by price) against remaining time to secure mathematically favorable expected value (+EV).
-
Liquidity Recycling (Early Take Profit): Liquidates positions early in the order book once they reach a high price (e.g.,
$\ge 98.5¢$ ) to immediately free up trading capital, rather than waiting for blockchain oracle resolution. - Guillotine Stop-Loss: Triggers automatic market-sell orders if a position suffers a severe decline from the entry price (e.g., a 40% drop).
- Stale Order Pruning: An automated safety routine that cancels any open buy/sell order that has been unfilled in the exchange for more than 5 minutes to avoid adverse selection risks.
- Anti-Volatility News Check: Queries Google News RSS for the target market. If Claude determines the event has already concluded or if Google News triggers a rate limit (HTTP 429), the bot skips the market as a precaution.
The following flowchart describes the execution loop managed by bot.ts every 30 seconds:
graph TD
A([Start Cycle]) --> B[Fetch Pending Positions & Redeem Closed Ones]
B --> C[Manage Active Positions: Check Stop-Loss / Take-Profit]
C --> D[Fetch Inminent Polymarket Markets]
D --> E[Filter Markets by Volume, Time & Keyword Exclusions]
E --> F[Apply AI Haiku Filter: Skip Ambiguous Questions]
F --> G{For Each Candidate}
G --> H[Run Google News RSS & Claude Check]
H -- Unsafe/Decided --> I[Skip Market]
H -- Safe --> J[Retrieve Order Book & Analyze Liquidity]
J --> K{Valid Price, Spread & Profit Margin?}
K -- No --> I
K -- Yes --> L[Place Limit Order: Real or Dry Run]
L --> M[Record Trade in Local History]
M --> N([End Cycle])
I --> G
The bot's runtime behavior is fully configured via environment variables. Create your .env file by duplicating the template:
cp .env.example .env| Variable | Default Value | Description |
|---|---|---|
DRY_RUN |
true |
Enables virtual simulation mode (no real funds or signatures required). |
BET_PCT |
0.10 |
Dynamic percentage of current USDC balance to allocate per trade (e.g., 0.10 = 10%). |
BET_AMOUNT_USDC |
5.0 |
Fallback minimum USDC amount allocated per trade. |
MAX_CONCURRENT_BETS |
2 |
Maximum number of simultaneous active trades allowed. |
MIN_PRICE |
0.60 |
Minimum token entry price (YES/NO) to control risk. |
MAX_PRICE |
0.75 |
Maximum token entry price allowed (prevents buying overpriced favorites). |
TAKE_PROFIT_PRICE |
0.985 |
Target price to trigger early take-profit position liquidation. |
STOP_LOSS_PCT |
0.40 |
Maximum loss percentage tolerated before triggering emergency liquidation. |
TIME_WINDOW_MINUTES |
120 |
Lookahead window: scan only markets resolving within this timeframe. |
MIN_MINUTES_LEFT |
2 |
Minimum time remaining before market closure to avoid liquidity traps. |
MIN_VOLUME |
5000 |
Minimum volume in USDC required to trade a market. |
MAX_SPREAD |
0.04 |
Maximum bid-ask spread allowed (in USDC). |
BLOCK_OU_MARKETS |
true |
Prevents entering Over/Under markets subject to decaying odds. |
BLOCK_LIVESPORTS |
true |
Prevents placing bids on real-time live sports markets. |
EXCLUDE_CRYPTO_KEYWORDS |
(Configured) | Comma-separated keywords to filter out highly volatile crypto assets. |
Install typescript dependencies, cryptographic tools, and the structured logging library (winston):
npm installIf you configure DRY_RUN=false, you will need to register and approve L2 API credentials for Polymarket. Run the authentication setup helper:
npm run setup-authStart in Development Mode (Direct TS Execution):
npm run devBuild for Production (Compiles TS to JS):
npm run buildStart in Production Mode:
npm startStart as a Persistent Daemon (PM2):
npx pm2 start ecosystem.config.cjsPrint Local Performance Summary:
npm run summaryWhen configured, the bot updates a designated Telegram channel. You can interact with the bot using the following commands:
/status: Returns current USDC balance, number of active slots occupied, and execution cycle stats./trades: Returns the details of the last 10 operations (active and settled)./pnl: Computes gross profits, losses, net P&L, and overall ROI./analyze: Triggers an AI Post-Mortem analyzing the last 50 trades to identify winning and losing patterns./help: Displays the available command list.
⚠️ Disclaimer: Merlin is experimental software built for quantitative trading on DeFi Web3 protocols. Market anomalies, oracle failures, illiquidity, and unexpected blockchain network disruptions can result in a partial or total loss of capital. Use at your own risk.