DEV Community

Benjamin-Cup
Benjamin-Cup

Posted on

Building a Polymarket TWAP Trading Bot: Using Coinbase for Real-Time Risk Management

Building a Polymarket TWAP Trading Bot: Using Coinbase for Real-Time Risk Management

How an external Coinbase price feed can help a Polymarket trading bot detect rapid market changes and manage open positions

Automated trading is not only about finding a good entry.

In short-duration crypto markets, the market can change significantly only a few seconds after a position is opened.

Building Polymarket Trading Bot

That creates a second problem:

What should the bot do when the conditions behind the original trade start changing?

This is the problem I have been working on with a Polymarket TWAP trading bot.

The system combines Polymarket market data with Coinbase real-time price movement to create an additional risk-management layer.

The goal is not to use Coinbase to predict the final Polymarket outcome.

Instead, Coinbase acts as an external market-movement signal that can help the bot recognize potentially dangerous conditions faster.


1. The Problem With Entry-Only Strategies

A simple trading bot might look like this:

Market Data
    ↓
Signal
    ↓
BUY
    ↓
Wait for Resolution
Enter fullscreen mode Exit fullscreen mode

This is easy to understand, but it ignores what happens after the position is opened.

A more complete system looks like:

Market Data
    ↓
Signal
    ↓
BUY
    ↓
Monitor Position
    ↓
Risk Detection
    ↓
HOLD / REDUCE / EXIT
Enter fullscreen mode Exit fullscreen mode

This difference becomes especially important in short-duration markets.

A trade that looked attractive five seconds ago may have a completely different risk profile now.


2. Understanding the Role of TWAP

Polymarket crypto markets can use defined resolution rules and specific resolution sources. The market metadata exposes fields such as resolutionSource, so a trading system should treat the resolution mechanism as part of its market state rather than assuming that any external spot price is the settlement value.

This creates an important distinction:

External Exchange Price
        ↓
Market Information

Polymarket Market
        ↓
Trading Price

Resolution Mechanism
        ↓
Final Outcome
Enter fullscreen mode Exit fullscreen mode

These are related, but they are not necessarily identical.

Therefore, I don't use Coinbase as a replacement for the actual resolution source.

I use it as another data stream.


3. Why Coinbase?

Coinbase can provide a fast view of movement in the underlying crypto market.

For example, the bot can monitor:

BTC Price
Price Change
Short-Term Momentum
Volatility
Direction
Enter fullscreen mode Exit fullscreen mode

Imagine the bot has already purchased an UP token.

Then Coinbase suddenly shows a significant downward movement.

The bot can detect:

Coinbase
BTC starts moving down
        ↓
Risk Signal
        ↓
Check Polymarket Position
        ↓
Evaluate Liquidity
        ↓
HOLD / REDUCE / EXIT
Enter fullscreen mode Exit fullscreen mode

The important point is that Coinbase is not making the trading decision by itself.

It is one input into the risk engine.


4. External Data vs. Polymarket Data

I think about the system as two separate views of the market.

Polymarket

The bot monitors:

  • UP/DOWN token prices
  • Order book
  • Bid/ask
  • Liquidity
  • Market status
  • Time remaining
  • Current position

Polymarket's CLOB APIs provide market price information and historical price data that can be incorporated into this state.

Coinbase

The bot monitors:

  • BTC price
  • Short-term price changes
  • Momentum
  • Volatility
  • Rapid movements

The two feeds answer different questions.

Polymarket
"What is happening inside the prediction market?"

Coinbase
"What is happening in the underlying crypto market?"
Enter fullscreen mode Exit fullscreen mode

Combining those views can give the risk engine more information.


5. Detecting a Risk Event

A basic implementation can calculate short-term price movement.

For example:

price_change = current_price - previous_price

price_change_pct = (
    price_change / previous_price
) * 100
Enter fullscreen mode Exit fullscreen mode

But one price update isn't necessarily useful.

Instead, the bot can monitor multiple windows:

1 second
3 seconds
5 seconds
10 seconds
30 seconds
Enter fullscreen mode Exit fullscreen mode

For example:

BTC

1s   → -0.03%
3s   → -0.08%
5s   → -0.17%
10s  → -0.21%
Enter fullscreen mode Exit fullscreen mode

The risk engine can interpret persistent movement differently from random noise.


6. Risk Score

Instead of creating one simple rule like:

if btc_change < -0.20:
    sell()
Enter fullscreen mode Exit fullscreen mode

I prefer thinking in terms of a risk score.

For example:

Coinbase movement
        +
Polymarket movement
        +
Order-book condition
        +
Position size
        +
Volatility
        +
Time remaining
        ↓
    Risk Score
Enter fullscreen mode Exit fullscreen mode

Then:

Low Risk
   ↓
HOLD

Medium Risk
   ↓
REDUCE

High Risk
   ↓
EXIT
Enter fullscreen mode Exit fullscreen mode

This creates a much more flexible risk-management architecture.


7. Example: Position Management

Suppose the bot owns:

100 UP tokens
Enter fullscreen mode Exit fullscreen mode

Then the external market suddenly moves against the position.

The risk engine could respond in stages.

Low risk

Risk Score = 20

Action:
HOLD
Enter fullscreen mode Exit fullscreen mode

The bot continues monitoring.

Medium risk

Risk Score = 65

Action:
REDUCE

Sell 30 tokens
Enter fullscreen mode Exit fullscreen mode

The bot reduces exposure without completely abandoning the position.

High risk

Risk Score = 90

Action:
EXIT

Close remaining position
Enter fullscreen mode Exit fullscreen mode

The exact thresholds should be determined through testing rather than assuming that a particular number is universally effective.


8. Why Not Just Use a Stop Loss?

A traditional stop loss is useful, but it only looks at the position's price.

A risk engine can consider more information.

For example:

Stop Loss

Token price
     ↓
Exit
Enter fullscreen mode Exit fullscreen mode

versus:

Risk Engine

Coinbase movement
       +
Polymarket price
       +
Order book
       +
Liquidity
       +
Position exposure
       +
Time remaining
       ↓
Decision
Enter fullscreen mode Exit fullscreen mode

This allows the system to react to changes in market conditions before relying exclusively on the token price.

However, this also introduces additional model complexity and the possibility of false signals.


9. Avoiding Market Noise

This is one of the hardest parts.

Crypto markets move constantly.

If the bot reacts to every small movement, it may start over-trading.

For example:

BTC

+0.04%
-0.05%
+0.03%
-0.06%
+0.02%
Enter fullscreen mode Exit fullscreen mode

A naive risk engine could continuously generate:

RISK
SAFE
RISK
SAFE
RISK
Enter fullscreen mode Exit fullscreen mode

That is not useful.

The system needs filtering.

Possible techniques include:

Thresholds

Ignore very small movements.

Time windows

Measure movement over several seconds rather than individual ticks.

Confirmation

Require multiple signals before changing the position.

Position-aware risk

Use different sensitivity depending on the size of the position.

Time-to-expiration

Change risk sensitivity as the market approaches its end.


10. Position Size Changes the Risk

The same price movement can have very different consequences depending on position size.

Consider:

Account: $5,000

Position A: $25
Position B: $1,000
Enter fullscreen mode Exit fullscreen mode

A small market movement is much more important when the position represents a large percentage of the account.

Therefore, the risk engine can consider:

exposure_ratio = position_value / account_value
Enter fullscreen mode Exit fullscreen mode

Then the system can become more defensive when exposure increases.

Conceptually:

Higher Exposure
      ↓
Higher Risk Sensitivity
Enter fullscreen mode Exit fullscreen mode

11. The Architecture

The architecture I am experimenting with looks approximately like this:

                  ┌─────────────────┐
                  │    Coinbase     │
                  │   Price Feed    │
                  └────────┬────────┘
                           │
                           ▼
                  ┌─────────────────┐
                  │  Risk Signal    │
                  │     Engine      │
                  └────────┬────────┘
                           │
                           ▼
┌─────────────────┐ ┌─────────────────┐
│   Polymarket    │→│ Position Manager│
│ Market Data     │ └────────┬────────┘
└─────────────────┘          │
                             ▼
                     ┌───────────────┐
                     │   Decision    │
                     └───────┬───────┘
                             │
                    ┌────────┼────────┐
                    ▼        ▼        ▼
                   HOLD    REDUCE    EXIT
Enter fullscreen mode Exit fullscreen mode

The important design principle is separation.

The strategy does not need to manage every risk decision.


12. Strategy vs. Risk Management

This distinction is important.

Strategy

The strategy asks:

"Is there an opportunity?"

For example:

Order book
Momentum
TWAP state
Probability
Liquidity
       ↓
BUY
Enter fullscreen mode Exit fullscreen mode

Risk Engine

The risk engine asks:

"Should we continue holding this position?"

For example:

Coinbase movement
Polymarket movement
Volatility
Liquidity
Exposure
Time remaining
       ↓
HOLD / REDUCE / EXIT
Enter fullscreen mode Exit fullscreen mode

This separation makes the system easier to test.


13. A Simplified Risk Loop

The implementation can be structured around a continuous loop:

while position_is_open:

    coinbase_data = get_coinbase_state()

    polymarket_data = get_polymarket_state()

    exposure = get_position_exposure()

    volatility = calculate_volatility()

    risk_score = calculate_risk(
        coinbase_data,
        polymarket_data,
        exposure,
        volatility
    )

    if risk_score >= EMERGENCY_LEVEL:
        emergency_exit()

    elif risk_score >= REDUCE_LEVEL:
        reduce_position()

    else:
        continue_holding()
Enter fullscreen mode Exit fullscreen mode

This is only a simplified example.

A real system also needs to handle:

  • stale data
  • WebSocket disconnects
  • reconnects
  • duplicate events
  • partial fills
  • rejected orders
  • insufficient liquidity
  • API failures
  • timing differences
  • incorrect market state

14. Latency Is Part of the System

A risk signal is only useful if the bot can process it and react appropriately.

The desired pipeline is:

Coinbase WebSocket
        ↓
Price Update
        ↓
Risk Calculation
        ↓
Position Check
        ↓
Decision
        ↓
Order Submission
Enter fullscreen mode Exit fullscreen mode

The fewer unnecessary steps between the observation and decision, the easier it is to build a responsive system.

But speed alone isn't enough.

A faster system using stale or incorrect data is still making bad decisions faster.

Therefore:

Low latency and data quality have to be designed together.


15. Testing the Risk Engine

Before using a risk-management system with real capital, I would test the risk layer independently.

Historical replay

Feed historical market data into the risk engine.

Historical Data
      ↓
Risk Engine
      ↓
Simulated Decisions
Enter fullscreen mode Exit fullscreen mode

Paper trading

Run the complete system without sending real orders.

Stress testing

Simulate sudden movements:

-0.10%
-0.30%
-0.50%
-1.00%
Enter fullscreen mode Exit fullscreen mode

and measure how the risk engine responds.

Liquidity testing

Simulate a position that needs to be closed while the order book becomes thin.

Connection testing

Disconnect the Coinbase or Polymarket WebSocket and verify that the bot enters a safe state.

A production-oriented trading system should never assume that missing data means "nothing changed."


16. Coinbase Is Not a Prediction Oracle

This is the most important point of this approach.

I am not using Coinbase like this:

Coinbase goes down
       ↓
DOWN must win
       ↓
SELL everything
Enter fullscreen mode Exit fullscreen mode

That would be an oversimplification.

Instead:

Coinbase moves rapidly
       ↓
Market conditions changed
       ↓
Re-evaluate current position
       ↓
Risk engine decides
       ↓
HOLD / REDUCE / EXIT
Enter fullscreen mode Exit fullscreen mode

Coinbase becomes a risk-management input, not a prediction oracle.


17. The Bigger Engineering Idea

The interesting part of automated trading isn't only finding an entry.

A complete trading system needs to continuously answer:

What is happening?

What changed?

Does my original signal still make sense?

How much exposure do I have?

Is the market still liquid?

Should I continue holding?

Should I reduce?

Should I exit?
Enter fullscreen mode Exit fullscreen mode

This changes the architecture from:

Signal → Trade
Enter fullscreen mode Exit fullscreen mode

to:

Observe
   ↓
Analyze
   ↓
Enter
   ↓
Monitor
   ↓
Detect Risk
   ↓
Manage Position
   ↓
Exit
Enter fullscreen mode Exit fullscreen mode

That is the architecture I am interested in building.


Open-Source Project

I am continuing to experiment with Polymarket trading infrastructure and automated trading strategies.

The project is available on GitHub:

GitHub:

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

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 twap bot polymarket arbitrage 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

This repository is primarily intended for educational and research purposes. It includes strategy concepts, implementation approaches, and selected performance screenshots to help developers understand how different automated trading strategies can be designed and tested.

The repository does not provide a complete production-ready trading bot source code. Instead, it provides strategy descriptions and research materials that you can use as a foundation for developing your own system.

If you are interested in building a Polymarket Trading Bot, you can follow my tutorials and use the concepts in this repository to develop your own implementation.

For users who prefer a ready-to-deploy solution or require custom strategy development, commercial…




The repository is intended for research, experimentation, and educational purposes.

If you're interested in Polymarket bots, automated trading systems, Web3 development, or trading infrastructure, feel free to connect.

Telegram: @BenjaminCup

https://t.me/BenjaminCup


Final Thoughts

The biggest lesson from building automated trading systems is that the entry signal is only one part of the problem.

A bot can identify an opportunity correctly and still encounter a rapidly changing market immediately afterward.

Using an external market feed such as Coinbase gives the risk engine another real-time view of market conditions.

The architecture becomes:

Polymarket Data
       +
Coinbase Data
       ↓
Risk Engine
       ↓
Position Management
       ↓
HOLD / REDUCE / EXIT
Enter fullscreen mode Exit fullscreen mode

The objective isn't to predict every market movement.

It is to build a system that can observe changing conditions, reassess existing positions, and respond according to predefined risk rules.

That is where I believe a lot of the interesting engineering work in automated Polymarket trading exists.


polymarket #tradingbot #twap #crypto #web3 #python #algorithmictrading #riskmanagement #coinbase #automation

Top comments (0)