DEV Community

Benjamin-Cup
Benjamin-Cup

Posted on

Building a TWAP Trading Bot with External BTC/ETH Price Feeds

Short-duration prediction markets can be difficult to trade if you only look at the current Polymarket price.

A more interesting approach is to ask:

Is the Polymarket probability correctly pricing the underlying asset?

For crypto markets such as BTC Up/Down or ETH Up/Down, your bot can combine Polymarket's order book with external BTC/ETH market data to estimate a fair probability.

If Polymarket says:

UP = $0.56
Enter fullscreen mode Exit fullscreen mode

but your model estimates:

Probability of UP = 0.64
Enter fullscreen mode Exit fullscreen mode

there may be an 8 percentage-point edge.

Instead of entering the entire position immediately, the bot can use TWAP (Time-Weighted Average Price) to execute gradually.

polymarket trading bot


1. The Basic Principle

The strategy has three components:

External BTC/ETH Market Data
             │
             ▼
      Probability Model
             │
             ▼
   Fair Probability Estimate
             │
             ▼
Compare with Polymarket
             │
             ▼
          Edge
             │
             ▼
        TWAP Execution
Enter fullscreen mode Exit fullscreen mode

The important idea is that Polymarket price becomes an input, not the only source of information.

For example:

Polymarket UP:       0.56
Model probability:   0.64

Edge = 0.64 - 0.56
     = 0.08
Enter fullscreen mode Exit fullscreen mode

The model believes UP is worth approximately $0.64, while the market is offering it at $0.56.

That creates a theoretical edge of $0.08 per share before fees, slippage, and model error.


2. Why External Price Data Matters

A prediction market's price tells you what traders are currently willing to pay.

But the underlying BTC or ETH market contains additional information.

For example, your bot can monitor:

  • BTC/USDT price
  • ETH/USDT price
  • short-term momentum
  • realized volatility
  • volume
  • order-book imbalance
  • distance from the market strike
  • time remaining
  • recent price acceleration

Suppose a BTC Up/Down market has:

Strike:        $100,000
Current BTC:   $100,250
Time remaining: 3 minutes

Polymarket UP:  $0.55
Enter fullscreen mode Exit fullscreen mode

If BTC is rapidly moving upward and your model estimates a 63% probability of finishing above the strike, buying at $0.55 may be attractive.

The important distinction is:

Market price ≠ true probability
Enter fullscreen mode Exit fullscreen mode

Your goal is to estimate whether the difference is large enough to trade.


3. Building a Simple Probability Model

You don't need a sophisticated machine-learning model to build the first version.

A simple model can combine several signals:

P(UP) =
    momentum
  + volatility
  + order-book imbalance
  + distance from strike
  + time remaining
Enter fullscreen mode Exit fullscreen mode

In practice, you should normalize each feature and assign weights.

For example:

def estimate_probability(
    momentum,
    volatility,
    imbalance,
    distance,
    time_remaining
):
    score = (
        0.30 * momentum +
        0.15 * volatility +
        0.20 * imbalance +
        0.25 * distance +
        0.10 * time_remaining
    )

    probability = 0.50 + score

    return max(0.01, min(0.99, probability))
Enter fullscreen mode Exit fullscreen mode

This is only an educational example.

A production model should be calibrated using historical data rather than choosing weights manually.


4. Measuring Distance From the Strike

For Up/Down markets, the relationship between the current underlying price and the strike can be extremely important.

For example:

distance = (btc_price - strike) / strike
Enter fullscreen mode Exit fullscreen mode

If:

BTC = 100,250
Strike = 100,000
Enter fullscreen mode Exit fullscreen mode

then:

distance = 0.0025
Enter fullscreen mode Exit fullscreen mode

The same distance means something very different when there are 10 seconds remaining versus 10 minutes remaining.

Therefore, a better model uses both:

distance from strike
+
time remaining
+
volatility
Enter fullscreen mode Exit fullscreen mode

For example:

import math

def normalized_distance(price, strike, volatility, seconds_left):
    if volatility <= 0 or seconds_left <= 0:
        return 0.0

    return (
        (price - strike) / strike
    ) / (
        volatility * math.sqrt(seconds_left)
    )
Enter fullscreen mode Exit fullscreen mode

This gives the model a way to understand how significant the current price difference is relative to expected movement.


5. Add Order-Book Imbalance

External exchange order books can provide another short-term signal.

For example:

BTC Bid Volume:  850 BTC
BTC Ask Volume:  500 BTC
Enter fullscreen mode Exit fullscreen mode

A simple imbalance calculation is:

def order_book_imbalance(bid_volume, ask_volume):
    total = bid_volume + ask_volume

    if total == 0:
        return 0.0

    return (bid_volume - ask_volume) / total
Enter fullscreen mode Exit fullscreen mode

The result is between approximately:

-1 → strong selling pressure
 0 → balanced
+1 → strong buying pressure
Enter fullscreen mode Exit fullscreen mode

You can then incorporate this into your probability model.

However, don't assume that order-book imbalance automatically predicts the market direction. Short-term order books can contain noise, cancellations, spoofing, and rapidly changing liquidity.


6. Calculate the Trading Edge

Once the model produces a probability, compare it with the Polymarket price.

For an UP position:

def calculate_edge(model_probability, market_price):
    return model_probability - market_price
Enter fullscreen mode Exit fullscreen mode

Example:

model_probability = 0.64
market_price = 0.56

edge = calculate_edge(
    model_probability,
    market_price
)

print(edge)
Enter fullscreen mode Exit fullscreen mode

Result:

0.08
Enter fullscreen mode Exit fullscreen mode

That means the model sees an 8 percentage-point difference.

But don't automatically trade every positive edge.

A better rule might be:

if edge > minimum_edge:
    consider trade
Enter fullscreen mode Exit fullscreen mode

For example:

MIN_EDGE = 0.05

if edge > MIN_EDGE:
    print("Potential UP opportunity")
Enter fullscreen mode Exit fullscreen mode

The threshold should account for fees, slippage, execution risk, and model uncertainty.


7. Why Use TWAP?

Suppose your model detects:

UP probability = 0.65
Polymarket UP = 0.55
Edge = 0.10
Enter fullscreen mode Exit fullscreen mode

You want to buy $1,000 worth of UP shares.

Buying everything immediately can create problems:

Large market order
       ↓
Consumes liquidity
       ↓
Average entry price increases
       ↓
Expected edge decreases
Enter fullscreen mode Exit fullscreen mode

Instead, TWAP divides the order into smaller pieces.

For example:

Total position: $1,000
Duration:       120 seconds
Slices:         12

Each slice:     ~$83
Enter fullscreen mode Exit fullscreen mode

The execution might look like:

00s   → $83
10s   → $83
20s   → $83
30s   → $83
40s   → $83
...
110s  → $83
Enter fullscreen mode Exit fullscreen mode

This reduces the risk of entering the entire position at an unfavorable price.


8. Make TWAP Adaptive

A fixed TWAP schedule is useful, but an adaptive TWAP can be more interesting.

Instead of:

Buy exactly $83 every 10 seconds
Enter fullscreen mode Exit fullscreen mode

your bot can adjust order size according to the current edge.

For example:

Edge       Order Size
---------------------
0.03       $30
0.05       $60
0.08       $100
0.12       $150
Enter fullscreen mode Exit fullscreen mode

Example:

def calculate_order_size(edge, base_size):
    if edge < 0.03:
        return 0

    multiplier = min(edge / 0.05, 2.0)

    return base_size * multiplier
Enter fullscreen mode Exit fullscreen mode

This means stronger model conviction can lead to faster execution.

But position sizing should also have hard limits.


9. Add a Stop Condition

The model can change while the TWAP is running.

Imagine:

Initial model probability = 0.64
Initial market price      = 0.56
Edge                      = 0.08
Enter fullscreen mode Exit fullscreen mode

Thirty seconds later:

Model probability = 0.57
Market price      = 0.56
Edge              = 0.01
Enter fullscreen mode Exit fullscreen mode

The original thesis has disappeared.

Your bot should not blindly continue buying.

if edge < MIN_EDGE:
    cancel_remaining_orders()
    stop_twap()
Enter fullscreen mode Exit fullscreen mode

This is one of the biggest advantages of combining TWAP + probability modeling.

TWAP controls execution.

The probability model controls whether the trade should continue.


10. Complete Strategy Flow

A simplified production architecture could look like this:

             BTC / ETH Exchange
                    │
                    ▼
             WebSocket Feed
                    │
        ┌───────────┴───────────┐
        ▼                       ▼
   Price Data              Order Book
        │                       │
        └───────────┬───────────┘
                    ▼
             Feature Engine
                    │
                    ▼
           Probability Model
                    │
                    ▼
             Fair Probability
                    │
                    ▼
          ┌──────────────────┐
          │ Polymarket CLOB  │
          └────────┬─────────┘
                   ▼
          Market Probability
                   │
                   ▼
             Edge Calculator
                   │
          ┌────────┴────────┐
          ▼                 ▼
      No Edge            Positive Edge
          │                 │
        Ignore          TWAP Engine
                            │
                            ▼
                      Risk Manager
                            │
                            ▼
                    Order Execution
Enter fullscreen mode Exit fullscreen mode

The important architectural separation is:

Data
 ↓
Model
 ↓
Signal
 ↓
Execution
 ↓
Risk
Enter fullscreen mode Exit fullscreen mode

Don't put everything into one trading loop.


11. Example Trading Scenario

Imagine a 5-minute BTC Up/Down market.

BTC Strike:          $100,000
Current BTC:         $100,180
Time remaining:      92 seconds

Polymarket UP:       $0.54

Model probability:   $0.63
Enter fullscreen mode Exit fullscreen mode

Therefore:

Edge = 0.63 - 0.54
     = 0.09
Enter fullscreen mode Exit fullscreen mode

Your bot decides that:

Minimum edge = 0.05
Enter fullscreen mode Exit fullscreen mode

so the trade qualifies.

The bot wants to invest:

$600
Enter fullscreen mode Exit fullscreen mode

over:

90 seconds
Enter fullscreen mode Exit fullscreen mode

Instead of immediately buying $600:

TWAP
───────────────
10s  $50
20s  $50
30s  $50
40s  $50
...
Enter fullscreen mode Exit fullscreen mode

After several executions, BTC moves closer to the strike.

The model updates:

Model probability: 0.58
Market price:      0.56

Edge = 0.02
Enter fullscreen mode Exit fullscreen mode

Now:

0.02 < 0.05
Enter fullscreen mode Exit fullscreen mode

The bot stops the remaining TWAP orders.

This is much better than blindly completing the original $600 order.


12. Important Risk Considerations

This strategy is not guaranteed to be profitable.

The biggest risk is that your probability model is wrong.

If your model consistently estimates:

True probability = 0.65
Enter fullscreen mode Exit fullscreen mode

when the actual probability is closer to:

0.55
Enter fullscreen mode Exit fullscreen mode

then an apparent edge is actually a systematic model error.

You should therefore backtest:

  • Probability calibration
  • Expected value
  • Maximum drawdown
  • Execution slippage
  • Fill rate
  • Time-to-fill
  • Model latency
  • Fees
  • Different volatility regimes
  • Different distances from strike

Most importantly, evaluate the model using out-of-sample data.


13. A Better Mental Model

Don't think of this as:

"BTC is going up, so buy UP."

Think of it as:

"Given the current BTC price, volatility, order flow, strike distance, and remaining time, what is the probability that the market resolves UP?"

Then compare:

Your estimated probability
             vs
Polymarket implied probability
Enter fullscreen mode Exit fullscreen mode

Only when the difference is sufficiently large should the execution engine consider entering.

That changes the architecture from a simple momentum bot into a probability-driven execution system.


Conclusion

A TWAP strategy becomes much more powerful when execution and prediction are separated.

The external BTC/ETH market provides information about the underlying asset.

A probability model converts that information into an estimated outcome probability.

Polymarket provides the current market price.

The edge calculation determines whether there may be an opportunity.

Finally, TWAP executes the position gradually while continuously checking whether the original edge still exists.

The core idea is simple:

External Market Data
        ↓
Probability Model
        ↓
Fair Value
        ↓
Polymarket Price
        ↓
      Edge
        ↓
    TWAP Entry
        ↓
Continuous Re-evaluation
Enter fullscreen mode Exit fullscreen mode

The interesting engineering challenge isn't simply building a TWAP algorithm. It's building a system that can estimate probability, detect mispricing, execute efficiently, and stop when the edge disappears.

For implementation details around Polymarket's APIs and CLOB infrastructure, see the official Polymarket documentation.

🤝 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)