DEV Community

Benjamin-Cup
Benjamin-Cup

Posted on

🤖 Building Risk Management into a Polymarket Crypto Up/Down TWAP Trading Bot

polymarket #trading #bot #python #cryptocurrency

Polymarket's 5-minute Crypto Up/Down markets look simple:

BTC goes up → UP

BTC goes down → DOWN

But building a bot that can trade these markets continuously is much more complicated than predicting the next BTC move.

The bot needs to consider:

  • Chainlink TWAP
  • External crypto spot prices
  • Strike price
  • Time remaining
  • Polymarket token prices
  • Order-book liquidity
  • Execution speed
  • Position size
  • Market volatility
  • Data freshness

After working on automated strategies for these markets, one lesson stands out:

The trading signal is only one part of the system. Risk management determines how the system behaves when the signal is wrong.


1. Don't Treat Spot Price as the Settlement Price

A common mistake is to build a strategy around the current BTC price alone.

For short-duration Polymarket crypto markets, the settlement mechanism uses a Chainlink-based TWAP.

That creates an important relationship between:

Exchange Spot Price
        ↓
Chainlink / TWAP
        ↓
Polymarket Market Price
Enter fullscreen mode Exit fullscreen mode

These values don't necessarily move at exactly the same speed.

For example, BTC can suddenly move higher on an exchange:

BTC Spot
   │
   ├── +0.20%
   ├── +0.35%
   └── +0.50%
          ↓
     TWAP catches up
          ↓
   Polymarket reprices
Enter fullscreen mode Exit fullscreen mode

This difference can provide useful information for a trading strategy.

But it also creates risk.

A sudden spot move does not automatically mean the final TWAP outcome will move in the same direction.


2. Position Sizing Is the First Risk Control

A good signal with an oversized position can still destroy an account.

Instead of asking:

"How much can I make on this trade?"

the risk engine should first ask:

"How much can I afford to lose?"

For example, a bot might start with a maximum risk budget of around 0.5–1% of bankroll per trade.

For a $10,000 account:

0.5% = $50
1.0% = $100
Enter fullscreen mode Exit fullscreen mode

The exact value depends on the strategy and risk tolerance, but the important idea is to keep individual trades from dominating the account.

Position size can also be dynamic:

Position Size =
Base Size
× Signal Strength
× Liquidity Factor
× Volatility Factor
× Risk Factor
Enter fullscreen mode Exit fullscreen mode

The bot doesn't need to use the same position size in every market.


3. TWAP vs. Spot Divergence

One of the most useful things to monitor is the relationship between spot price and TWAP.

Conceptually:

TWAP deviation = Spot Price - TWAP
Enter fullscreen mode Exit fullscreen mode

Imagine:

Normal:

Spot  ──────────
TWAP  ──────────
Enter fullscreen mode Exit fullscreen mode

Then BTC suddenly moves:

Spot  ─────────────────────

TWAP  ──────────
Enter fullscreen mode Exit fullscreen mode

Now the system knows the market is experiencing a significant short-term move.

That could represent:

  • Strong momentum
  • Temporary dislocation
  • A delayed TWAP response
  • A potential reversal
  • Increased uncertainty

Instead of automatically increasing exposure, the risk engine can become more conservative.

For example:

Large TWAP deviation
        ↓
Reduce position size
        ↓
Require stronger confirmation
        ↓
Or skip the trade
Enter fullscreen mode Exit fullscreen mode

4. Time Remaining Changes Everything

A 5-minute market shouldn't be treated identically at every point in its lifecycle.

At the beginning:

5:00 remaining
Enter fullscreen mode Exit fullscreen mode

there is significant uncertainty.

Near the end:

0:30 remaining
Enter fullscreen mode Exit fullscreen mode

the relationship between:

  • Strike
  • TWAP
  • Spot
  • UP/DOWN price
  • Remaining time

becomes much more important.

A useful signal engine can therefore include time as an input:

Signal =
Momentum
+ TWAP relationship
+ Strike distance
+ Time remaining
+ Market price
Enter fullscreen mode Exit fullscreen mode

This is much more useful than simply checking:

BTC > previous BTC price
Enter fullscreen mode Exit fullscreen mode

5. Don't Chase Sudden Moves

Another common failure mode is buying immediately after a large crypto move.

Example:

BTC +0.10%
      ↓
BTC +0.25%
      ↓
BTC +0.50%
      ↓
BUY UP
Enter fullscreen mode Exit fullscreen mode

The problem is that the move may already be partially priced into the Polymarket token.

The bot can instead require confirmation such as:

  • Momentum remains consistent.
  • TWAP is moving in the same direction.
  • Market price confirms the move.
  • Liquidity is sufficient.
  • Spread is acceptable.
  • The move isn't an isolated spike.

This doesn't guarantee a profitable trade.

It simply prevents the system from treating every price spike as a valid entry.


6. Liquidity Is Part of the Strategy

A trading signal can be correct and still result in a bad trade.

Suppose the bot calculates:

Expected entry = 0.70
Enter fullscreen mode Exit fullscreen mode

But the order book is thin:

0.70 → 10 shares
0.73 → 20 shares
0.76 → 30 shares
0.80 → 50 shares
Enter fullscreen mode Exit fullscreen mode

If the bot wants a large position, the average execution price could be much worse than 0.70.

That's why the execution engine should monitor:

Best Bid
Best Ask
Spread
Depth
Available Size
Expected Slippage
Recent Fills
Enter fullscreen mode Exit fullscreen mode

The signal engine answers:

Should I trade?

The execution engine answers:

How should I trade?

Those are different problems.


7. Use Circuit Breakers

Automated trading systems need a way to stop themselves.

For example:

Daily loss > threshold
        ↓
STOP NEW TRADES
Enter fullscreen mode Exit fullscreen mode

Other possible triggers include:

3–4 consecutive losses
        ↓
Pause

Abnormal volatility
        ↓
Pause

Thin liquidity
        ↓
Pause

Execution latency increases
        ↓
Pause

Market data becomes stale
        ↓
Pause
Enter fullscreen mode Exit fullscreen mode

The exact thresholds should be configurable rather than hard-coded.

For example:

MAX_DAILY_LOSS = 0.05
MAX_CONSECUTIVE_LOSSES = 4
MAX_DATA_AGE_MS = 1000
Enter fullscreen mode Exit fullscreen mode

The important principle is:

The bot needs permission to do nothing.


8. Data Freshness Is Risk Management

For a TWAP trading bot, stale data can be extremely dangerous.

Imagine:

Exchange feed      → LIVE
Polymarket feed    → LIVE
TWAP data          → STALE
Enter fullscreen mode Exit fullscreen mode

If the strategy continues trading, it may be making decisions using an outdated reference.

The system should track things like:

last_update_timestamp
feed_age
WebSocket status
reconnect state
duplicate messages
message sequence
clock drift
Enter fullscreen mode Exit fullscreen mode

A basic safety flow:

Data becomes stale
        ↓
Reject new orders
        ↓
Reconnect / recover
        ↓
Validate fresh data
        ↓
Resume trading
Enter fullscreen mode Exit fullscreen mode

This is not just infrastructure.

It is trading risk management.


9. Position Monitoring After Entry

Risk management shouldn't stop when an order fills.

After entering a position, the bot can continuously monitor:

Entry Price
Current Price
TWAP
Spot
Strike
Time Remaining
Position Size
Unrealized P&L
Enter fullscreen mode Exit fullscreen mode

For example:

BUY UP
   ↓
Monitor position
   ↓
TWAP relationship changes
   ↓
Spot momentum reverses
   ↓
Risk threshold reached
   ↓
Reduce / exit / hedge
Enter fullscreen mode Exit fullscreen mode

The exact exit logic depends on the strategy.

The important point is that entry and position management should be separate components.


10. Opposite-Side Hedging

Some strategies can also use the opposite token as a partial hedge.

For example:

BUY UP
  ↓
Market conditions deteriorate
  ↓
BUY smaller amount of DOWN
Enter fullscreen mode Exit fullscreen mode

The idea is to reduce directional exposure.

However, hedging has a cost.

You may pay:

  • Spread
  • Trading fees
  • Additional execution costs
  • Capital utilization

So a hedge should not automatically be considered "extra profit."

It is primarily a risk-management tool.

A bot could potentially activate a hedge when:

Volatility increases
OR
TWAP deviation becomes extreme
OR
Position exposure becomes too large
OR
Momentum reverses
Enter fullscreen mode Exit fullscreen mode

11. Don't Optimize Only for Win Rate

One of the biggest mistakes when evaluating a trading bot is looking only at win rate.

Consider:

90 winning trades
10 losing trades
Enter fullscreen mode Exit fullscreen mode

That sounds excellent.

But what if:

Average winner = +2%

Average loser = -30%
Enter fullscreen mode Exit fullscreen mode

The win rate alone doesn't tell us much.

A proper evaluation should include:

  • Win rate
  • Average win
  • Average loss
  • Profit factor
  • Maximum drawdown
  • Expected value
  • Slippage
  • Fees
  • Number of trades
  • Average exposure
  • Execution latency

For short-duration markets, execution costs can also significantly affect the result.


12. Risk Management Architecture

A simplified architecture for a TWAP trading bot can look like this:

┌──────────────────────┐
│     Market Data      │
│                      │
│ Spot / TWAP / CLOB   │
└──────────┬───────────┘
           │
           ▼
┌──────────────────────┐
│   Data Validation    │
│                      │
│ Freshness / Health   │
└──────────┬───────────┘
           │
           ▼
┌──────────────────────┐
│    Signal Engine     │
│                      │
│ Momentum / TWAP      │
│ Strike / Time        │
└──────────┬───────────┘
           │
           ▼
┌──────────────────────┐
│    Risk Manager      │
│                      │
│ Position Size        │
│ Exposure             │
│ Circuit Breakers     │
│ Daily Loss           │
└──────────┬───────────┘
           │
           ▼
┌──────────────────────┐
│   Execution Engine   │
│                      │
│ Orders / Slippage    │
└──────────┬───────────┘
           │
           ▼
┌──────────────────────┐
│ Position Monitor     │
└──────────────────────┘
Enter fullscreen mode Exit fullscreen mode

This separation is important.

The signal engine should not be able to bypass the risk manager simply because a signal looks strong.


13. A Practical Decision Flow

Putting the pieces together:

New 5-minute market
        ↓
Load strike + market data
        ↓
Validate data freshness
        ↓
Read spot + TWAP
        ↓
Calculate TWAP deviation
        ↓
Check momentum
        ↓
Check time remaining
        ↓
Check liquidity
        ↓
Check current exposure
        ↓
Risk Manager
        ↓
 ┌──────┴──────┐
 │             │
Reject        Approve
 │             │
STOP       Calculate Size
              ↓
         Execute Order
              ↓
        Monitor Position
              ↓
        Exit / Hedge
Enter fullscreen mode Exit fullscreen mode

This is much closer to how I think a production trading system should be structured.


14. What I Learned

The hardest part of building a Polymarket Crypto Up/Down bot isn't creating a BUY signal.

It's answering three questions correctly:

1. Should I trade?

2. How much should I trade?

3. When should I stop?

The signal might come from momentum, TWAP deviation, or another strategy.

But the risk layer determines whether that signal is actually allowed to become an order.

That's why I prefer thinking about the system as:

Data
  ↓
Signal
  ↓
Risk
  ↓
Execution
  ↓
Position Management
Enter fullscreen mode Exit fullscreen mode

rather than:

Price ↑
  ↓
BUY
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Polymarket's 5-minute Crypto Up/Down markets move quickly, and the relationship between spot price, TWAP, strike, and market price can change within seconds.

A trading bot therefore needs more than a directional prediction.

It needs:

  • TWAP monitoring
  • External crypto price feeds
  • Momentum analysis
  • Time-aware signals
  • Position sizing
  • Liquidity checks
  • Slippage control
  • Data validation
  • Circuit breakers
  • Position monitoring
  • Optional hedging

The goal isn't to make every trade profitable.

The goal is to build a system that can control its exposure when the market behaves differently from the strategy's expectations.

In short-duration markets, risk management isn't an extra feature. It's part of the trading strategy itself.


GitHub

I'm working on Polymarket trading-bot strategies and infrastructure here:

👉 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 educational and development purposes.

Trading involves substantial risk, and historical, simulated, or example results should not be interpreted as guarantees of future performance.


Contact

If you're interested in discussing Polymarket bots, automated trading, or collaboration:

👉 Telegram: https://telegram.me/BenjaminCup


Tags

polymarket #tradingbot #python #cryptocurrency #algorithmictrading #twap #trading #riskmanagement #web3 #predictionmarkets

Top comments (0)