{"slug": "i-built-a-live-trading-bot-in-python-here-s-what-actually-works-polymarket-twap", "title": "I Built a Live Trading Bot in Python. Here's What Actually Works (Polymarket TWAP Edition).", "summary": "A developer writing as Almach built a roughly 4,000-line Python trading bot for Polymarket that generates signals from the platform's public RTDS Chainlink TWAP feeds (30-second and 60-second windows) and executes orders through Polymarket's CLOB API. The system is organized into five modules — signal generation, position execution, exit management, state persistence, and health monitoring — with Claude Code generating about 95% of the code, including the asyncio event loop, database layer, and deployment scripts. The developer reports that six weeks of paper trading across at least 30 signals caught two strategy failures, a liquidity trap near TWAP settlement windows and a signal-timing issue in low-liquidity hours, and that state recovery after process restarts proved harder than the trading logic itself.", "body_md": "Build a Python trading bot with Claude AI, Polymarket CLOB integration, and live Polymarket TWAP (Chainlink) signals. Paper trading to production in one guide.\n\n**TL;DR** \n\nI built a production algorithmic trading system using Python, Claude Code for development, Polymarket’s CLOB API for execution, and Polymarket’s Real-Time Data Streaming (RTDS) Chainlink TWAP feeds for signals. This guide covers the full architecture: signal generation from 30s/60s TWAP updates, position management, exit strategies, and the paper-to-live progression that prevented costly mistakes.\n\n**By Almach**\n\nPolymarket trading bots • Quantitative trading • Rust • Web3 infrastructure\n\nTelegram: [https://t.me/almachquant](https://t.me/almachquant)\n\nYouTube: [https://www.youtube.com/@almachquant](https://www.youtube.com/@almachquant)\n\nPolymarket: [https://polymarket.com/@almach](https://polymarket.com/@almach)\n\n**Key takeaways**\n\n01 A production trading bot needs five core modules: signal generation, position execution, exit management, state persistence, and health monitoring\n\n02 Claude Code wrote 95% of the 4,000-line codebase autonomously, including the asyncio event loop, database layer, and deployment scripts\n\n03 Paper trading with at least 30 signals before going live prevented two strategy failures that would have cost real money\n\n04 The biggest technical challenge was not the trading logic but state recovery after process restarts\n\n05 Polymarket’s CLOB API requires careful order book analysis because liquidity varies dramatically between markets — and TWAP-resolved markets demand even tighter depth checks around resolution windows\n\nI built a production algorithmic trading system using Python, Claude Code for development, Polymarket’s CLOB API for execution, and Polymarket’s public RTDS WebSocket for live Chainlink TWAP price updates (30-second and 60-second windows). This guide covers the full architecture: signal generation from TWAP streams, position management, exit strategies, and the paper-to-live progression that prevented costly mistakes.\n\nA production Python trading bot needs five core modules to run continuously without losing state: signal generation, position management, exit strategies, state persistence, and health monitoring. I built this system using Python and Claude Code across a 4,000-line codebase, with Polymarket RTDS Chainlink TWAP feeds for signals and the CLOB for execution. Paper trading at least 30 signals over 6 weeks before going live prevented two strategy failures — a liquidity trap near TWAP settlement windows and a signal-timing issue during low-liquidity hours — that would have cost real money.\n\nWhen I started building a trading bot, I expected the hard part to be the trading logic. It wasn’t. The hard part was building a system that could run continuously for weeks without losing state, crashing silently, or entering impossible positions — especially once Polymarket switched crypto up/down markets to TWAP-based resolution (5-minute markets on 30s TWAP, 15-minute and 4-hour markets on 60s TWAP).\n\nA production trading bot needs five core modules that work together:\n\nEach module can fail independently, so the system needs to handle partial failures gracefully. A TWAP signal can fail without crashing position management. An API call can timeout without losing the position state. The monitoring system watches everything and alerts when something goes wrong.\n\nThe entire codebase is about 4,000 lines of Python. Claude Code wrote 95% of it, including the most complex parts: the asyncio event loop, the database schema and queries, and the deployment scripts.\n\nNote: The repo is private for now, but I'm planning to open source the core trading logic once it's hardened further.\n\nSignals are the input to the entire system. My signals come from Polymarket’s RTDS Chainlink TWAP feeds (no Chainlink credentials required).\n\nPolymarket RTDS delivers real-time 30-second and 60-second Chainlink TWAP updates over a public WebSocket. I subscribe to topics such as `crypto_prices_twap_thirty` and `crypto_prices_twap_sixty` for pairs like `btc/usd`, `eth/usd`, etc. I watch consecutive TWAP prints and detect momentum breakouts when the latest TWAP moves more than 2-sigma relative to the recent window of TWAP values. When a TWAP breakout occurs, I look for corresponding Polymarket up/down prediction markets that are still underpriced relative to the new TWAP trajectory.\n\nThe key insight is that prediction-market prices still lag the official TWAP updates by 15–60 seconds in many cases, creating a small window to position ahead of the eventual resolution source.\n\nHere’s how the signal generation actually works in code (using the official `polymarket-client`):\n\n``` python\nfrom polymarket import AsyncPublicClient\nfrom polymarket.streams import CryptoPricesChainlinkTwapSpec\nimport asyncio\nfrom collections import deque\n\nasync def detect_twap_breakout(twap_history: deque, current_twap: float) -> float | None:\n    \"\"\"\n    Watch recent Chainlink TWAP values (30s or 60s window) and detect 2-sigma breakouts.\n    Returns signal strength (0-1) if breakout detected.\n    \"\"\"\n    if len(twap_history) < 20:\n        return None\n\n    values = list(twap_history)\n    mean = sum(values) / len(values)\n    variance = sum((x - mean) ** 2 for x in values) / len(values)\n    std_dev = variance ** 0.5\n\n    if std_dev == 0:\n        return None\n\n    z_score = (current_twap - mean) / std_dev\n\n    if z_score > 2.0:  # Upside breakout on TWAP\n        return min(1.0, z_score / 3.0)  # Cap at 3-sigma\n    return None\n\n# Example subscription loop\nasync def stream_twap_signals():\n    history = deque(maxlen=20)\n    async with AsyncPublicClient() as client:\n        async with await client.subscribe(\n            CryptoPricesChainlinkTwapSpec(window_seconds=30, symbols=[\"btc/usd\"])\n        ) as stream:\n            async for event in stream:\n                twap = float(event.payload.value)\n                history.append(twap)\n                strength = await detect_twap_breakout(history, twap)\n                if strength:\n                    # Emit signal to position manager queue\n                    await signal_queue.put({\n                        \"symbol\": event.payload.symbol,\n                        \"twap\": twap,\n                        \"window_s\": event.payload.window_seconds,\n                        \"strength\": strength,\n                        \"ts\": event.payload.timestamp\n                    })\n```\n\nWhen a signal fires, the system calculates how many standard deviations the latest TWAP has moved above the recent mean of TWAP prints. A 2-sigma TWAP move is rare; when it lines up with an underpriced Polymarket market that resolves on the same TWAP feed, the edge becomes real.\n\nThe efficiency gap exists because:\n\nThis isn’t an edge that lasts forever. As more bots subscribe to the same public RTDS feed, the 15–60 second window compresses. But for now, it’s consistent enough to trade.\n\nSignals feed into a queue. The position manager processes signals one at a time, ensuring we never accidentally open two positions on the same market.\n\nOnce a TWAP signal arrives, the position manager decides: do we take this trade, or skip it?\n\nThe decision logic checks:\n\nIf all checks pass, the position manager places a limit order on the Polymarket CLOB. The CLOB is Polymarket’s central limit order book. It’s lower latency than the REST API but requires understanding the order book structure — especially critical now that resolution is driven by the same TWAP feeds we are monitoring.\n\nThe position manager tracks every open position in SQLite. Each position stores:\n\nThis database survives process restarts. On startup, the position manager reads the database and reconstructs the exact state it was in before the crash.\n\nThe hardest part of algorithmic trading is exits. Most retail traders focus on entries but skip profitable or know when to close positions. It’s the difference between “cool idea” and “actual profit.”\n\nI use three exit types:\n\nThe exit manager runs every minute, checks all open positions against the latest RTDS TWAP and market mid, and executes exits that meet criteria. It places exit orders as limit orders too, so we get the best available prices.\n\nHere’s why the split profit target works. Say I enter a position at $0.45 on a binary market with $100 per trade:\n\n*Winning trades (55% of the time):*\n\n*Losing trades (45% of the time):*\n\nExpected value calculation:\n\n```\nEV = (0.55 × $3.15) + (0.45 × -$3.00)\nEV = $1.73 + (-$1.35)\nEV = +$0.38 per $100 bet\n```\n\nThat’s positive EV at a 55% win rate. Drop to 54% and the math flips negative. This is why signal quality (TWAP z-score strength) matters more than quantity. A 60% win rate turns $0.38 per $100 into $0.60 per $100. Signal strength compounds.\n\nThe split exit structure protects against reversal. If the market hits 2% and I’ve already cashed out half, the second half can either hit 5% or get stopped out. Either way, I’ve locked 50% of the winning outcome. That’s risk management.\n\nThe asymmetry is deliberate. I lose 3% on losers but capture 2-5% on winners because prices on TWAP-resolved markets still bounce. A tight 1% stop gets triggered by noise. A 3% stop lets the position breathe.\n\nThe position database tracks exit status for each open position:\n\n```\nCREATE TABLE positions (\n    id INTEGER PRIMARY KEY,\n    market_id TEXT,\n    entry_price REAL,\n    entry_qty INTEGER,\n    entry_time TEXT,\n    stop_loss_price REAL,      -- 0.4365 for 0.45 entry\n    target_one_price REAL,     -- 0.459 (2% profit)\n    target_two_price REAL,     -- 0.4725 (5% profit)\n    exit_status TEXT,          -- 'open', 'half_closed', 'closing', 'closed'\n    target_one_filled_at TEXT,\n    target_two_filled_at TEXT,\n    twap_window INTEGER,       -- 30 or 60\n    linked_symbol TEXT         -- e.g. 'btc/usd'\n);\n```\n\nOn every minute, the exit manager reads the latest RTDS TWAP and current market price and compares against these thresholds. When target one hits, it updates exit_status to ‘half_closed’ and records the fill time. This prevents double-exits and ensures the second half of the position doesn’t exit prematurely.\n\nLimit orders are crucial here. Market orders on Polymarket can slip 0.5-1% depending on order book depth. A limit order at target_one_price of $0.459 sits on the book until filled. If the market only reaches $0.458, the order stays open. If it bounces to $0.461, it fills at $0.459 (better than market order at $0.461). Over 100 trades, limit order precision saves 0.3-0.5% in aggregate slippage.\n\nThe real lesson: don’t set stop losses too tight on TWAP-resolved prediction markets. Binary outcomes mean prices bounce around more than equity markets. A 1% stop gets triggered by noise. 3% gives the position room to breathe while still protecting against real reversals.\n\nThe trickiest exit is time decay near the TWAP window. As the market approaches resolution, prices converge hard to the TWAP path. If I’m long and the market isn’t moving with the TWAP, the time decay works against me. Exiting stale positions frees capital for new TWAP signals.\n\nOne thing that surprised me: the time-decay / TWAP-proximity exit generated more total profit than the pure profit-target exit. Not because individual exits were bigger, but because freeing stale capital meant the bot could take 2-3 more trades per day. Capital velocity matters more than any single trade’s P&L.\n\nI paper-traded for 6 weeks before going live. Paper trading means simulating trades without real money, just tracking P&L against live RTDS TWAP feeds and CLOB order books.\n\nPaper trading revealed two strategy failures:\n\nThe fix was a simple gate before position entry:\n\n``` python\nasync def check_market_liquidity_and_twap_window(market_id: str, twap_window: int) -> bool:\n    \"\"\"\n    Only enter if order book has sufficient depth AND we are not too close to the TWAP resolution window.\n    Skip if spread > 1% of mid-price or total depth < threshold.\n    \"\"\"\n    order_book = await polymarket.get_order_book(market_id)\n    best_bid = order_book['bids'][0]['price']\n    best_ask = order_book['asks'][0]['price']\n    mid = (best_bid + best_ask) / 2\n    spread_pct = ((best_ask - best_bid) / mid) * 100\n\n    total_depth = sum(qty for _, qty in order_book['bids'][:5]) + \\\n                  sum(qty for _, qty in order_book['asks'][:5])\n\n    if spread_pct > 1.0:  # Spread too wide\n        return False\n    if total_depth < 500:  # Not enough size to exit\n        return False\n    # Extra guard: skip if market closes within 2× the TWAP window\n    if seconds_to_resolution(market_id) < (twap_window * 2):\n        return False\n    return True\n```\n\nThis single filter would have prevented 7 bad trades and saved ~$2,000 in real losses.\n\nThe time-of-day filter was even simpler:\n\n``` php\nasync def is_peak_trading_hour() -> bool:\n    \"\"\"\n    Only process TWAP signals during peak US trading hours.\n    12pm-11pm UTC captures most US market activity.\n    \"\"\"\n    now_utc = datetime.datetime.utcnow()\n    current_hour = now_utc.hour\n\n    # Peak hours: 12pm-11pm UTC (7am-6pm EST)\n    if 12 <= current_hour < 23:\n        return True\n    return False\n\nasync def should_process_signal(signal: dict) -> bool:\n    if not await is_peak_trading_hour():\n        return False  # Skip this TWAP signal\n    return True\n```\n\nThat’s it. One hour check prevented $1,500 in unnecessary slippage by avoiding markets where the book moves like molasses around live TWAP updates.\n\nBoth failures would have cost real money live. The 6-week cost in time was worth it.\n\nI ran at least 30 paper trades before going live. That’s the minimum to see the major failure modes once you’re trading against the official Chainlink TWAP feeds. Anything less and you’re just guessing.", "url": "https://wpnews.pro/news/i-built-a-live-trading-bot-in-python-here-s-what-actually-works-polymarket-twap", "canonical_source": "https://dev.to/almachquant/i-built-a-live-trading-bot-in-python-heres-what-actually-works-polymarket-twap-edition-1amd", "published_at": "2026-12-02 16:09:17+00:00", "updated_at": "2026-12-02 16:16:20.703570+00:00", "lang": "en", "topics": ["ai-tools", "ai-agents", "developer-tools"], "entities": ["Polymarket", "Claude Code", "Chainlink", "Almach", "Python"], "also_reported_by": [], "takeaway": "Paper trade at least 30 signals over six weeks before going live, and treat state persistence and recovery after process restarts as the core engineering problem rather than the trading logic itself.", "recommendation": {"advice": "Run paper trading for at least 30 signals before deploying real capital, and build explicit state persistence and restart recovery into the system from the start.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/i-built-a-live-trading-bot-in-python-here-s-what-actually-works-polymarket-twap", "markdown": "https://wpnews.pro/news/i-built-a-live-trading-bot-in-python-here-s-what-actually-works-polymarket-twap.md", "text": "https://wpnews.pro/news/i-built-a-live-trading-bot-in-python-here-s-what-actually-works-polymarket-twap.txt", "jsonld": "https://wpnews.pro/news/i-built-a-live-trading-bot-in-python-here-s-what-actually-works-polymarket-twap.jsonld"}}