Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk9 min

Building a Polymarket TWAP Divergence Bot: Data Feed, Signal, Execution and Limits

A practical engineering guide to a Polymarket TWAP divergence bot: what the API documents, how to define the signal, how to execute slices, and why profitability still has to be proven.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Polymarket TWAP divergence bot has four parts. It keeps a local order book from the WebSocket market feed. It compares the live price with a time-weighted average that you define. It sends orders only when the gap passes a threshold and every safety gate is open. It records every order and fill so you can reconcile them. Polymarket documents the feed, the order types and the rate limits. It does not document the signal, and nothing in the API documentation shows that a TWAP rule makes money.

This guide keeps those three layers apart: what Polymarket documents, what you must decide yourself, and what nobody has established. The platform details come from Polymarket’s real-time data docs, its place-orders docs and its rate-limits page. One finding on trade direction comes from a 2026 microstructure working paper. Interface details and limits change, so recheck them against the current documentation before you deploy.

As an Amazon Associate I earn from qualifying purchases.

Two things people mean by “TWAP bot”

The phrase covers two different designs, and mixing them up leads to muddled code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • TWAP as a signal. You compute a time-weighted average of some reference series. You trade when the current price diverges from it. This is the subject of this article.
  • TWAP as an execution schedule. You split a large order into equal slices over a time window. This changes how you trade, not whether you trade.

The two combine well. A divergence signal can decide direction and size, and a sliced schedule can work that size into the book. Polymarket’s order documentation describes order primitives only: creating and signing an order, submitting it, and the order types. It does not describe a built-in TWAP order, so any scheduling logic lives in your bot.

#1 Best Overall
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
  • Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
  • Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
  • CanaKit Turbine Black Case for the Raspberry Pi 5
  • CanaKit Low Noise Bearing System Fan
  • Mega Heat Sink - Black Anodized

What is documented, what you decide, what is unproven

Layer Status Where it comes from
Market data subscription by token ID, book snapshots, incremental price changes, tick-size change events Documented Polymarket real-time data documentation
Local order creation and signing, separate submission, FAK and FOK behavior Documented Polymarket place-orders documentation
IP-based sliding-window limits and separate per-signer limits for order and cancel calls Documented, subject to change Polymarket rate-limits page, as read in 2026
Reference series, TWAP window, sampling interval, threshold, sizing Your design decisions Not settled by any platform page
Profitability after spread, fees, slippage and latency Not established Must be measured on your own data

Step 1: Define the signal before writing any code

Most failed bots in this category are underspecified, not broken. A TWAP comparison is meaningless until you pin down five things.

Choose the reference series

Decide what the TWAP is an average of. The candidates are different and lead to different strategies:

  • Polymarket’s own token price. The signal is then short-term mean reversion against its own recent history.
  • An external underlying market price, for markets that track one. The signal is then a lag or mismatch between that market and the prediction market.
  • An oracle series.
  • Another benchmark you can name and reproduce.

Compare candidate reference data on instrument match, timestamp quality, update cadence, missing-data behavior and licensing or access terms. The sources reviewed here do not identify a best provider. They also do not confirm that any particular commercial data stream, Chainlink Data Streams included, is a directly usable reference for Polymarket markets. Check that against the specific market’s own resolution source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose how the TWAP is built

A TWAP can be computed from prices sampled at fixed intervals, or reconstructed from trades. Fixed-interval sampling from your local book (midpoint or best bid and ask) is simpler and entirely under your control. Trade-based reconstruction needs reliable trade data, and the direction caveat below applies to it. Whichever you pick, specify:

Rank #2
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
  • Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM)
  • Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
  • CanaKit Premium High-Gloss Raspberry Pi 4 Case with Integrated Fan Mount, CanaKit Low Noise Bearing System Fan
  • CanaKit 3.5A USB-C Raspberry Pi 4 Power Supply (US Plug) with Noise Filter, Set of Heat Sinks, Display Cable - 6 foot (Supports up to 4K60p)
  • CanaKit USB-C PiSwitch (On/Off Power Switch for Raspberry Pi 4)
  • the sampling interval;
  • the horizon (how many samples or how many minutes);
  • what happens when an observation is missing: carry forward the last value, skip, or invalidate the whole window.

Carrying values forward through a feed outage quietly produces a flat, confident-looking TWAP. For a bot that trades on divergence, invalidating the window is usually safer.

State the divergence in units

Write the formula down in one place. Two common forms:

  • Absolute: d = Pnow − TWAP, measured in price points. Prediction-market tokens trade between 0 and 1, so this reads directly as probability points.
  • Relative: d = (Pnow − TWAP) / TWAP. This becomes unstable when the price is near 0, where a one-tick move is a very large percentage.

Because of that instability at the extremes, an absolute measure, or a version scaled by recent volatility, is often easier to reason about. Also decide whether the entry threshold has a dead band (enter at one level, exit at a smaller one) so the bot does not flip around the threshold. These are design examples, not a documented or validated rule.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decide the direction of the bet

Divergence can be read two ways: price will revert toward the TWAP, or the move will continue. The API gives you no reason to prefer one. Your validation data has to answer that, per market type.

Rank #3
ELECROW CrowPi Case Kit for Raspberry Pi 5, 9-Inch Display
  • Not including the Raspberry Pi 5 (8GB), the Crowpi advanced version comes with the Raspberry Pi 5
  • ELECROW Black Case for the Raspberry Pi 5, CrowPi is equipped with a 9-inch HD touchscreen along with a camera; All the regular components used in DIY electronics are packed into the CrowPi development board, such as LCD, LED matrix, buzzer, light sensor, PIR sensor, ultrasonic sensor, IR sensor, etc
  • Raspberry Pi Sensors: The Crowpi raspberry pi 5 programming kit is jam-packed with lots of buttons such as 19 different sensors in a tidy easy to use package; You don't have to wait and wire things
  • Build Quality: Solid ABS shell and well made components in one place make it strong and convenient to travel
  • Programming Lessons: This raspberry pi 5 learning kit ships with step by step instructions and provides 21 lessons to take you through identifying components reading code and running it in the terminal

Step 2: Build a local order book from the stream

Polymarket’s real-time documentation describes subscriptions by token ID. The event model includes full book snapshots with bid and ask levels, and price-change updates carrying price, size, side, best bid and ask, and timestamps. Tick-size change events are also part of the documented stream. Treat all of this as a stateful feed. A price-change message only makes sense relative to the book it modifies.

  1. Subscribe to the token IDs of the markets you trade. A binary market has a token for each outcome, so subscribe to the one you actually trade and be explicit about which outcome your TWAP refers to.
  2. On the first snapshot, build the book: bid levels and ask levels with sizes.
  3. Apply each price-change update to the local book and record the event timestamp and your own receipt time.
  4. Track the time of the last event per token. If no event arrives within a threshold you set, mark the book stale.
  5. If an update cannot be reconciled with your local state, or you reconnect, discard the book and wait for a fresh snapshot rather than patching.
  6. Apply tick-size change events to your price rounding, since an order at an invalid tick will not be accepted.

The documentation page shows language-specific encodings of the messages. Verify field names against the client library and version you actually use instead of copying them from an example in another language.

Step 3: Gate every order

The signal says “trade”. The gates decide whether the bot may. Check all of these immediately before each order:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The book is fresh: the last event is within your staleness limit, and the TWAP window is fully populated.
  • The market is open and tradable.
  • The order meets the minimum size and sits on a valid tick.
  • The available balance covers the order.
  • Position and exposure caps, per market and in total, are not exceeded.
  • The kill switch is off. Define it up front: for example a loss limit, repeated order rejections, repeated feed gaps, or throttling errors.

Do not infer who the aggressor was from a price-change side

It is tempting to read the side of a price-change event as buy or sell pressure and feed that into the signal. A 2026 working paper by Philipp D. Dubach, “The Anatomy of a Decentralized Prediction Market: Microstructure Evidence from the Polymarket Order Book”, tested this. In its data, direction inferred from the book feed agreed with on-chain trade direction only about 59% of the time. The paper reports a volume-weighted agreement of 0.592 in one comparison and a panel mean of 0.615, with a stated confidence interval. The “about 59%” figure is a rounded description of that study’s sample and method. It is not a platform-wide statistic. The paper recommends using on-chain OrderFilled events for any direction-dependent analysis. If your signal does not need trade direction, as a price-versus-TWAP signal does not, you avoid the problem entirely.

Rank #4
CanaKit Raspberry Pi 5 Desktop PC with SSD (Fully Assembled) (256 GB SSD)
  • Fully assembled for plug-and-play operation
  • Includes Raspberry Pi 5 with 8GB RAM
  • 256 GB PCIe Pi NVMe SSD (Pre-loaded with Pi 64-Bit OS)
  • M.2 HAT+
  • CanaKit Turbine Black Case for the Pi 5

Step 4: Execute and reconcile

Polymarket’s place-orders documentation describes creating and signing an order locally, then submitting it in a separate request. Treat these as two steps that can each fail. A signed order that was never accepted is not a position.

Pick the order behavior for each slice

Approach Behavior (per Polymarket’s order docs) Main benefit Main risk
FAK Fills whatever is immediately available and cancels the remainder Tolerates thin books; the schedule keeps moving Partial fills leave a residual; the schedule drifts from plan
FOK Fills the full amount immediately or does not fill at all Clean outcomes: a slice is either done or not Missed slices in thin books, and no price improvement from waiting
Resting limit order Sits in the book at your price Price control; avoids crossing the spread Non-fill risk; an open order can go stale as the signal moves

Compare them on partial-fill tolerance, schedule drift, price impact, and whether the strategy is willing to hold a residual position.

Handle unfilled size explicitly

Because FAK and FOK differ on partial fills, the slice policy has to say what happens to the part that did not execute. Pick one rule and code it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • carry the shortfall into the next slice;
  • drop it and accept a smaller position;
  • stop the schedule when cumulative shortfall passes a limit.

Keep an order and fill ledger. Reconcile it against the exchange’s open orders on a timer and after every reconnect, so a lost acknowledgement cannot leave you with an untracked order or an unknown position. A divergence signal can also disappear while a slice is pending. Decide whether a resting slice is cancelled when the divergence falls back inside the dead band.

Best Value
RasTech Raspberry Pi 5 8GB Kit with Active Cooler and Pi5 Case
  • 【What you Get】You will get 1*Pi 5 8GB Single Board,1*RasTech Case,1*Active Cooler,1*Screwdriver,1*Installation instructions,12-month free warranty, lifetime service, 24-hour prompt and friendly response.
  • 【More Connectors】There are two USB 3.0 ports(5Gbps simultaneously) and two USB 2.0 ports, which triple total bandwidth ,support any combination of up to two cameras or displays. Peak SD card performance is doubled through support for the SDR104 high-speed mode. It provides a smooth desktop experience for you. Offer Gigabit Ethernet and a PCIe interface, along with dual-band Wi-Fi and Bluetooth 5.0/BLE wireless capability. The RasTech Pi 5 Kit use the new 27W 5.1V 5A USB-C power connector.
  • 【 Support Dual 4Kp60 Display 】Each of the two microHDMI sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs (requires separate M.2 HAT).
  • 【 Excellent Chips And Applications】Pi 5 is a full-size Pi computer using silicon built in-house at Pi. The RP1 “southbridge” provides the bulk of the I/O capabilities for Pi 5. Pi 5 is more friendly and convenient in the development of Internet of Things, Web development, machine identification, automatic control and other electronic equipment applications and network.
  • 【 Faster CPU, Better GPU 】 Pi 5 features a Broadcom BCM2712 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz, it delivers a 2–3× increase in CPU performance relative to RaspberryPi 4. The 800MHz VideoCore VII GPU is compatible to OpenGL ES 3.1 and Vulkan 1.2, substantial uplift in graphics performance. Pi 5 Offers lightning-fast CPU speed, a PCI Express interface, a Real Time Clock (RTC) and a power button and runs significantly cooler than Pi 4.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Step 5: Respect the rate limits

Polymarket’s rate-limits page, as read in 2026, says limits are applied by Cloudflare per IP address using sliding windows. CLOB order and cancellation calls are also subject to separate per-signer limits, described as token buckets. The page showed a general limit of 15,000 requests per 10 seconds, a Gamma API general limit of 4,000 requests per 10 seconds, and further endpoint-specific caps for Gamma, the Data API and the CLOB. These values can change. Read the page again before each deployment and keep the numbers in configuration, not in code.

The practical design follows from this:

  • Use the WebSocket for continuous market changes. Do not poll the book over REST.
  • Reserve REST calls for initial snapshots, resynchronization and reconciliation.
  • Add exponential backoff when you are throttled, and log every throttling response.
  • Count throttling events toward the kill switch. A bot that is being throttled is probably acting on late data.

Step 6: Validate before real money

A working integration proves only that orders go in and data comes out. It does not show that the strategy has an edge. The plan below is a recommended method, and none of it has been run for this article.

  1. Fix the benchmark and TWAP definition, including window and sampling rules, before looking at results.
  2. Replay historical data with aligned timestamps. Misaligned clocks between your reference series and the Polymarket feed can create apparent divergence that was never tradable.
  3. Model spread, fees, slippage, partial fills and latency in the replay. A divergence smaller than the spread you would cross is not a signal.
  4. Split the data. Choose parameters on one period and evaluate on a later one.
  5. Paper trade against live data, and compare the bot’s decisions with a simple baseline such as holding, or trading at random times with the same size and frequency.
  6. Keep logs of feed gaps and order acknowledgements, so you can tell a strategy failure from an infrastructure failure.

Scope any historical result to the period it covers. The working paper’s own results come from its historical event archive and should not be read as guaranteed current behavior of the platform.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failure modes

Symptom Likely cause Fix
Bot trades constantly around the threshold No dead band Use a separate, smaller exit threshold
Huge divergence near price 0 or 1 Percentage formula on a bounded price Use absolute points or volatility scaling
Stable TWAP during an outage, then a sudden “signal” Carried-forward values through a feed gap Invalidate the window on missing data
Position differs from the schedule Unhandled partial fills from FAK Define a shortfall rule and reconcile against the ledger
Orders rejected Invalid tick, size below minimum, or a stale tick-size assumption Honor tick-size change events and minimum size
Rising errors and delayed reactions Throttling from REST polling Move to the WebSocket and add backoff
Direction-based signal looks noisy Book side used as aggressor direction Drop it, or use on-chain fill events

A sensible build order

  1. Stream and log one market’s feed. Rebuild the book and verify it against periodic REST snapshots.
  2. Compute your TWAP and divergence offline from the logged data. Look at how often the signal fires and how large it is relative to the spread.
  3. Add the replay model with fees and slippage. Stop here if there is no margin after costs.
  4. Add order submission with the gates and the kill switch, using minimum size.
  5. Add the ledger and reconciliation, then paper trade, then size up slowly under hard exposure caps.

Check also that automated trading is permitted for you where you live and under the platform’s terms. Nothing in the sources reviewed here establishes legality in any jurisdiction.

Quick Recap

Bestseller No. 1
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM); CanaKit Turbine Black Case for the Raspberry Pi 5
$259.95
Bestseller No. 2
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM); Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
$159.99
Bestseller No. 4
CanaKit Raspberry Pi 5 Desktop PC with SSD (Fully Assembled) (256 GB SSD)
CanaKit Raspberry Pi 5 Desktop PC with SSD (Fully Assembled) (256 GB SSD)
Fully assembled for plug-and-play operation; Includes Raspberry Pi 5 with 8GB RAM; 256 GB PCIe Pi NVMe SSD (Pre-loaded with Pi 64-Bit OS)
$339.97

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.