DEV Community

Benjamin-Cup
Benjamin-Cup

Posted on

Building a TWAP-Based Mean Reversion Polymarket Trading bot

Short-duration crypto markets can move faster than the underlying settlement reference. That can create temporary differences between the Polymarket price and the probability implied by the 60-second TWAP.

In this tutorial, we'll build a simple Polymarket Trading bot signal using twap_60s.

This is an educational example. The thresholds and model below are illustrative and should be backtested before live trading.

Polymarket Twap trading bot

Strategy Overview

The idea is simple:

BTC Price
   ↓
twap_60s
   ↓
Probability Model
   ↓
Compare with Polymarket Price
   ↓
Calculate Edge
   ↓
Trade / No Trade
Enter fullscreen mode Exit fullscreen mode

For example:

UP market price:    $0.64
Model probability:  55%

Difference:         -9%
Enter fullscreen mode Exit fullscreen mode

If the model estimates UP at only 55%, the bot can evaluate whether the DOWN side offers sufficient edge.


1. Get the 60-Second TWAP

Polymarket provides Chainlink-computed TWAP data through its real-time infrastructure. For this strategy, we use only the 60-second TWAP.

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=60,
                symbols=["btc/usd"],
            )
        ) as stream:

            async for event in stream:
                print(
                    "TWAP:",
                    event.payload.value
                )


asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

The important parameter is:

window_seconds=60
Enter fullscreen mode Exit fullscreen mode

See the official Polymarket TWAP documentation for the current API.


2. Calculate BTC/TWAP Distance

A useful feature is the distance between the current BTC price and twap_60s.

def twap_distance(btc_price, twap_60s):

    return (
        btc_price - twap_60s
    ) / twap_60s
Enter fullscreen mode Exit fullscreen mode

Example:

btc_price = 101000
twap_60s = 100500

distance = twap_distance(
    btc_price,
    twap_60s
)

print(f"{distance:.2%}")
Enter fullscreen mode Exit fullscreen mode

Output:

0.50%
Enter fullscreen mode Exit fullscreen mode

BTC is 0.50% above the 60-second TWAP.

This is a feature, not automatically a trading signal.


3. Estimate the Probability

Now create a simple probability model.

import math


def sigmoid(x):
    return 1 / (1 + math.exp(-x))


def estimate_probability(
    price_distance,
    twap_distance
):

    score = (
        5 * price_distance
        + 8 * twap_distance
    )

    return sigmoid(score)
Enter fullscreen mode Exit fullscreen mode

For example:

probability = estimate_probability(
    price_distance=0.008,
    twap_distance=0.005
)

print(f"UP probability: {probability:.2%}")
Enter fullscreen mode Exit fullscreen mode

In a real system, these coefficients should be trained using historical data.


4. Compare With the Polymarket Price

Suppose:

Model P(UP) = 55%
UP Ask      = $0.64
Enter fullscreen mode Exit fullscreen mode

Calculate the edge:

def calculate_edge(
    probability,
    execution_price,
    costs=0.0
):

    return (
        probability
        - execution_price
        - costs
    )
Enter fullscreen mode Exit fullscreen mode

For UP:

up_edge = calculate_edge(
    probability=0.55,
    execution_price=0.64,
    costs=0.01
)

print(f"UP edge: {up_edge:.2%}")
Enter fullscreen mode Exit fullscreen mode

Result:

UP edge: -10%
Enter fullscreen mode Exit fullscreen mode

The model does not support buying UP.


5. Check the Opposite Side

If:

P(UP) = 55%
Enter fullscreen mode Exit fullscreen mode

then:

P(DOWN) = 45%
Enter fullscreen mode Exit fullscreen mode

Suppose DOWN is available at $0.38.

down_probability = 1 - 0.55

down_edge = calculate_edge(
    probability=down_probability,
    execution_price=0.38,
    costs=0.01
)

print(f"DOWN edge: {down_edge:.2%}")
Enter fullscreen mode Exit fullscreen mode

Result:

DOWN edge: 6%
Enter fullscreen mode Exit fullscreen mode

Now we have a potential signal:

Model DOWN probability: 45%
DOWN price:              38%
Estimated net edge:       6%
Enter fullscreen mode Exit fullscreen mode

6. Add a Trading Filter

Don't trade every small difference.

MIN_EDGE = 0.03


def generate_signal(
    up_probability,
    up_ask,
    down_ask
):

    down_probability = 1 - up_probability

    up_edge = (
        up_probability
        - up_ask
    )

    down_edge = (
        down_probability
        - down_ask
    )

    if up_edge >= MIN_EDGE:
        return "BUY_UP", up_edge

    if down_edge >= MIN_EDGE:
        return "BUY_DOWN", down_edge

    return "NO_TRADE", 0
Enter fullscreen mode Exit fullscreen mode

Example:

signal, edge = generate_signal(
    up_probability=0.55,
    up_ask=0.64,
    down_ask=0.38
)

print(signal, edge)
Enter fullscreen mode Exit fullscreen mode

Possible result:

BUY_DOWN 0.07
Enter fullscreen mode Exit fullscreen mode

7. Add Basic Risk Controls

A production bot should also check:

def risk_check(
    volatility,
    time_remaining,
    twap_fresh
):

    if not twap_fresh:
        return False

    if volatility > 0.08:
        return False

    if time_remaining < 15:
        return False

    return True
Enter fullscreen mode Exit fullscreen mode

The bot should avoid trading when:

  • twap_60s is stale
  • volatility is extreme
  • liquidity is poor
  • the market is close to resolution
  • the position limit has been reached

Strategy Architecture

       BTC/USD
          │
          ▼
      twap_60s
          │
          ▼
  Probability Model
          │
          ▼
    P(UP) / P(DOWN)
          │
          ▼
 Polymarket Order Book
          │
          ▼
     Edge Calculation
          │
          ▼
    Risk Management
          │
          ▼
       Execute
Enter fullscreen mode Exit fullscreen mode

The important distinction is that this isn't simply:

BTC goes up → buy DOWN.

Instead:

BTC movement → 60s TWAP → probability estimate → compare with executable Polymarket price → trade only when the edge is large enough.


Backtesting

Before using real capital, collect:

BTC price
twap_60s
Polymarket bid/ask
Time remaining
Model probability
Final outcome
Enter fullscreen mode Exit fullscreen mode

Then measure:

  • Win rate
  • Average edge
  • PnL
  • Drawdown
  • Slippage
  • Probability calibration

Most importantly, test whether the edge remains after fees and execution costs.


Conclusion

A Polymarket Trading bot can use twap_60s as a reference for probability-driven mean reversion instead of simply chasing short-term BTC momentum.

The core strategy is:

twap_60s
   ↓
Probability
   ↓
Market Price
   ↓
Edge
   ↓
Risk Check
   ↓
Trade
Enter fullscreen mode Exit fullscreen mode

The key question isn't:

"Did BTC just move?"

It's:

"Does the current Polymarket price accurately reflect the probability implied by the 60-second TWAP?"

For implementation details, see the official Polymarket documentation, my Polymarket Trading bot Python V2 repository, and my previous Polymarket Trading System tutorial.

You can also read my 5-minute crypto Up/Down Polymarket Trading bot tutorial.

Educational purposes only. This is not financial advice.

🤝 Collaboration & Contact
If you’re interested in building trading bots, buy trading bots, collaborating, exploring strategy improvements, or discussing about this system, feel free to reach out.

I’m especially open to connecting with:

Quant traders
Engineers building trading infrastructure
Researchers in prediction markets
Investors interested in market inefficiencies

📌 GitHub Repository
This repo has some Polymarket several bots in this system.
You can explore the full implementation, strategy logic, and ongoing updates about 5 min crypto market here:

GitHub logo Benjam1nCup / Polymarket-trading-bot-python-V2

polymarket bot polymarket twap bot polymarket arbitrage bot polymarket trading bot polymarket bot polymarket twap bot polymarket arbitrage bot polymarket trading bot polymarket bot polymarket twap bot polymarket arbitrage bot polymarket trading bot polymarket bot polymarket twap bot polymarket arbitrage bot polymarket trading bot polymarket bot

Polymarket Trading Bot | Polymarket Arbitrage Bot | Polymarket TWAP Trading Bot

An open-source and Strong Strategy collection of Polymarket trading bot and Polymarket arbitrage bot and Polymarket TWAP trading bot in Python for high-performance automated trading on polymarket crypto 5min and 15min markets.

Polymarket-benjamincup-bot-dashboard

Features

  • Explosive growth of Polymarket with surging trading volume and new short-term markets

  • Increasing dominance of automated bots and AI in 5-minute and 15-minute crypto prediction markets

  • Higher profitability potential through advanced arbitrage and market-making strategies

  • Stronger edge for Python-based bots with real-time orderbook intelligence and low-latency execution

  • Continuous evolution of sniper, ladder, stair, momentum, and copy trading strategies

  • Scalable daily profits as prediction markets move toward hundreds of billions in annual volume

  • Full future-proof architecture for new features, contracts, and high-frequency trading environments

Included Trading Bots

Designed for arbitrage, directional strategies, and ultra-short-term markets (including 5-minute and 15-minute rounds), this bot framework provides a robust…




💬 Get in Touch

If you have ideas, questions, or would like to collaborate or want these trading bots, don’t hesitate to reach out directly.
Feedback on your repo (based on your description & strategy)

Contact Info
Telegram
https://t.me/BenjaminCup

tags: #polymarket,#trading,#bot,#architecture,#tutorial,#TWAP

Top comments (0)