How to Build a Polymarket Trading Bot After TWAP Implemented
DEV Community

How to Build a Polymarket Trading Bot After TWAP Implemented

Polymarket switched its short-duration crypto up/down markets (BTC, ETH, SOL, XRP, and others) to Time-Weighted Average Price (TWAP) resolution on August 7, 2026, at 00:00 UTC. This replaced single-price snapshot settlement with Chainlink-powered averages, sharply reducing last-second manipulation. For bot builders, the change is material. Strategies that relied on predicting or reacting to a single expiry-tick price no longer work the same way. Bots must now incorporate continuous TWAP feeds, model averages over the lookback window, and adapt signals and risk rules accordingly. This article covers the full process of building a production-oriented trading bot in the post-TWAP environment. What Changed with TWAP - 5-minute markets**: Resolve against a 30-second Chainlink TWAP. - 15-minute and 4-hour markets**: Resolve against a 60-second Chainlink TWAP. Both the opening price (the “price to beat”) and the final settlement price come from the applicable TWAP feed. The averaging window is a trailing lookback immediately before market close. Sustaining a manipulated price across the full window is far more expensive than a single-tick push, which is the core integrity improvement. Liquidity rewards of $1 million were also rolled out across affected markets through August 2026 to support depth during the transition. Prerequisites - Python 3.11+ (recommended for most bots) or Node.js 24+ - Funded Polygon wallet holding pUSD (or USDC.e that can be wrapped/bridged via Polymarket flows) plus a small amount of POL/MATIC for any residual gas - Private key for an EOA or appropriate proxy/Safe setup - Basic familiarity with async programming, WebSockets, and order-book concepts - VPS or always-on host with low-latency connectivity to Polymarket endpoints (US East often works well) Install the current official SDKs: # Python (unified client recommended) pip install polymarket-client # TypeScript npm install @polymarket/client Older py-clob-client / @polymarket/clob-client packages are deprecated; migrate to the unified or v2 clients. Accessing Real-Time TWAP Data Polymarket exposes Chainlink-computed 30 s and 60 s TWAPs via two paths. The recommended production route is Polymarket’s public Real-Time Data Streaming (RTDS) WebSocket-no Chainlink credentials required. TypeScript (SDK) import { createPublicClient } from "@polymarket/client"; const client = createPublicClient(); const stream = await client.subscribe([ { topic: "prices.crypto.chainlink.twap", windowSeconds: 30, // or 60 symbols: ["btc/usd"], // omit for all }, ]); for await (const event of stream) { console.log({ symbol: event.payload.symbol, value: event.payload.value, // keep as string/decimal windowSeconds: event.payload.windowSeconds, observedAt: new Date(event.payload.timestamp).toISOString(), }); } Python (async) import asyncio from polymarket import AsyncPublicClient from polymarket.streams import CryptoPricesChainlinkTwapSpec async def main(): async with AsyncPublicClient() as client: async with await client.subscribe( CryptoPricesChainlinkTwapSpec( window_seconds=30, symbols=["btc/usd"], ) ) as stream: async for event in stream: print( event.payload.symbol, event.payload.value, event.payload.window_seconds, event.payload.timestamp, ) asyncio.run(main()) Low-level RTDS endpoint: wss://ws-live-data.polymarket.com. Send PING every 5 seconds and subscribe with topics crypto_prices_twap_thirty or crypto_prices_twap_sixty. Direct Chainlink Data Streams access is available if you already hold credentials and need the raw signed reports. Always treat the TWAP value as a high-precision decimal/string; do not coerce to floating-point early. Core Bot Architecture A robust post-TWAP bot separates concerns: - Data Layer - RTDS TWAP stream + CLOB WebSocket (order books, trades, market lifecycle) + Gamma/Data API for discovery and positions. - Signal / Strategy Engine - Compares current TWAP trajectory, predicted average at expiry, external spot prices, and Polymarket odds. - Risk Engine - Position limits, daily loss caps, max notional per market, inventory skew, kill switches. - Execution Layer - Order construction, signing (EIP-712), submission via CLOB, cancellation, and fill confirmation. - Monitoring & Logging - Persistent logs, PnL tracking, alerts (Telegram/Discord), and health checks. Strategy Considerations After TWAP Legacy “last-second sniping” or pure expiry-tick prediction loses effectiveness. Useful post-TWAP approaches include: - Modeling the running TWAP and projecting the final average given recent volatility. - Mean-reversion or momentum signals that incorporate the full window rather than a single print. - Market-making that earns spread + liquidity rewards while managing inventory against the expected TWAP path. - Cross-venue arbitrage that accounts for the averaging window instead of instantaneous price. - Probability models that output fair value for the Up/Down token and trade when the order book diverges meaningfully after costs and fees. Because both open and close reference TWAP, directional bias must be calculated relative to the opening TWAP, not a single tick. Placing and Managing Orders Use the secure/authenticated client. Example high-level flow with the unified Python SDK (similar patterns exist in TypeScript): - Create AsyncSecureClient with private key and wallet address. - Discover markets via slug, event, or token ID (Gamma API or SDK helpers). - Retrieve order book, midpoint, and tick size. - Construct limit or market orders (GTC, GTD, FOK, FAK). - Submit, monitor via user WebSocket channel, and cancel as needed. Always respect tick size, negative-risk flags (if applicable), and current fees. Batch orders when quoting multiple levels. Prefer WebSocket order-book updates over REST polling for latency-sensitive strategies. Risk Management Essentials - Hard per-market and portfolio notional limits. - Daily / weekly loss circuit breakers that pause or flatten. - Maximum open orders and position concentration rules. - Inventory-aware quoting (skew quotes when long/short). - Kill switch triggered by connectivity loss, large drawdowns, or anomalous TWAP updates. - Paper-trading / simulation mode before any real capital. - Separate trading wallet with only the capital you are willing to lose. Deployment and Operations - Run on a VPS with process supervision (systemd, Docker + restart policies, or PM2). - Use multiple RPC providers for redundancy. - Implement exponential backoff and automatic reconnection for both RTDS and CLOB WebSockets. - Persist state (positions, open orders, PnL) to SQLite or Postgres. - Alert on fills, errors, and risk breaches. - Continuously monitor Polymarket docs and the @PolymarketDevs account for feed or rule changes. Sample High-Level Skeleton (Python) Pseudocode outline - expand with full error handling, risk checks, and logging async def bot_loop(): public = AsyncPublicClient() secure = await AsyncSecureClient.create(private_key=..., wallet=...) Subscribe to TWAP + relevant market books Maintain running state of current TWAPs and order books while True: Evaluate strategy signals using latest TWAP + book signal = generate_signal(current_twap, order_book, time_to_expiry) if signal and risk_engine.allows(signal): await secure.place_limit_order(...) # or market order Log and track await asyncio.sleep(0.05) # or event-driven *Best Practices and Common Pitfalls * - Keep TWAP values as exact decimals. - Account for the trailing nature of the window and any latency between Chainlink observation and your receipt. - Test extensively in paper mode across different market durations. - Never hard-code credentials; use environment variables or a secrets manager. - Monitor for changes in feed IDs, window definitions, or resolution rules. - Start with small size and strict risk limits. - Understand that prediction markets remain high-risk; even robust bots can lose money. Conclusion The August 2026 TWAP upgrade improves market integrity and forces trading bots to become more sophisticated. By combining Polymarket’s free RTDS TWAP stream with the CLOB API, a clean modular architecture, and disciplined risk controls, developers can build bots that operate effectively in the new regime. Focus first on reliable data ingestion and risk management; edge comes later through refined signals that properly model the averaging window. Always consult the official documentation at docs.polymarket.com (especially the Chainlink TWAP and trading quickstart pages) for the latest SDK examples, feed details, and API changes before deploying capital. Trading involves substantial risk of loss. Top comments (0)

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.