How to Build a Polymarket Trading Bot in Python

Build a Polymarket trading bot in Python. Stream every trade, skip markets that are resolving through UMA, and place orders with Polymarket's official SDK.

A Polymarket trading bot has three parts: data in, a rule, and orders out. Most guides spend their time on the orders. This one builds a small, complete bot around two live streams: every trade on Polymarket, and every UMA resolution event. It uses one simple rule that you can read in a minute.

This is an educational example. It is not financial advice, and the strategy is not a claim of profit. Run it in dry-run mode first.


Architecture of the example Polymarket trading bot. Two Bravado streams, Live Trades at /stream/polymarket/partner/trades and UMA at /uma/ws, feed the bot's state (seen_fills, resolving, orders_per_market) and its rule: follow large buys, skip markets that are resolving. Orders go through Polymarket's polymarket-client SDK (place_limit_order, cancel_market_orders, cancel_all) to the Polymarket CLOB. A disputed frame on a market with open orders triggers cancel_market_orders.

What you will learn

  • What a Polymarket bot needs, part by part

  • How to stream every Polymarket fill over one WebSocket

  • How to watch UMA proposals and disputes in real time

  • How to place and cancel orders with Polymarket's current Python SDK

  • How to put it together in one script, with dry run on by default

What you will need

  • Python 3.10 or newer

  • pip install websockets polymarket-client

  • A Bravado account on a paid plan with WebSocket access, and an API key with the stream.read scope. The UMA stream also needs a paid plan.

  • BRAVADO_API_KEY and BRAVADO_API_SECRET set in your server environment

  • For live trading only: a funded Polymarket wallet, with POLYMARKET_PRIVATE_KEY and POLYMARKET_WALLET_ADDRESS set. Check Polymarket's geographic restrictions first.

What does a Polymarket trading bot actually need?

Every bot, simple or complex, has the same four parts.

1. Market data in

The bot needs to see what is happening now. Here that means two streams: live trades and UMA resolution events.

2. A rule

A rule turns data into a decision. Ours has a signal (when to act) and a guard (when not to).

3. Order placement

The bot signs and sends orders to Polymarket's order book (the CLOB). We use Polymarket's official SDK for this.

4. Safety

Dry run, size caps and a way to stop. These matter more than the signal.

Part

What it does

Source in this guide

Trade data

Every fill on Polymarket

Bravado Live Trades WebSocket

Resolution data

Proposals, disputes, settlements

Bravado UMA WebSocket

Orders

Place and cancel

polymarket-client (AsyncSecureClient)

Safety

Dry run, caps, logs

Your code

What strategy will we build?

We will build a resolution-aware large-trade follower. It has one signal and one guard.

1. The signal: follow large buys

When someone buys a large amount of one outcome, the bot places a small limit order on the same outcome. "Large" is a threshold you choose.

2. The guard: skip markets that are resolving

If a market has a UMA proposal or dispute in flight, the bot does not enter it. If a dispute arrives on a market where the bot has orders, it cancels them.

3. Why the guard matters

A Polymarket market does not settle when the event ends. Someone proposes an answer to UMA's Optimistic Oracle. Anyone can dispute it during a challenge window. Only then does the market settle. A large buy late in this process may be a bet on how the resolution goes, not on the event. A follower bot should not blindly copy that.

For how disputes work and what they look like in live data, see our guide How to Track Polymarket UMA Disputes in Real Time with WebSockets.


Table of the seven checks each trade frame passes before an order: not a duplicate by transactionHash, assetId and side; side is BUY; amount at least MIN_AMOUNT; price between 0.10 and 0.90; conditionId present and the trade at most 5 seconds old; the market not in the resolving set; and under one order per market. Any failure is a logged skip. In dry run, the default, the bot only logs the order.

These are the knobs. The defaults are examples, not recommendations.

Parameter

Default

Meaning

MIN_AMOUNT

5000

Minimum trade notional (amount, in USD) to count as large

PRICE_MIN, PRICE_MAX

0.10, 0.90

Skip outcomes priced near 0 or 1

ORDER_SIZE

5

Shares per order

MAX_ORDERS_PER_MARKET

1

One order per market per run

ORDER_LIFETIME_S

600

Order lifetime (GTD) in seconds

DRY_RUN

True

Log orders instead of sending them

How do you stream every Polymarket trade?

Bravado's Live Trades WebSocket sends every fill across all Polymarket markets on one connection. There is no subscribe message. The volume is on the order of tens of trades per second (Bravado's docs measured 20–50 per second), so filter on your side.

1. Connect and sign

Sign the upgrade with HMAC. The payload is the timestamp, the method, the path and the SHA-256 of an empty body, joined by newlines. Sign again on every reconnect.

import hashlib, hmac, os, time

BRAVADO_KEY = os.environ["BRAVADO_API_KEY"]
BRAVADO_SECRET = os.environ["BRAVADO_API_SECRET"]
HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(BRAVADO_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": BRAVADO_KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}
import hashlib, hmac, os, time

BRAVADO_KEY = os.environ["BRAVADO_API_KEY"]
BRAVADO_SECRET = os.environ["BRAVADO_API_SECRET"]
HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(BRAVADO_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": BRAVADO_KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}
import hashlib, hmac, os, time

BRAVADO_KEY = os.environ["BRAVADO_API_KEY"]
BRAVADO_SECRET = os.environ["BRAVADO_API_SECRET"]
HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(BRAVADO_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": BRAVADO_KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}
import hashlib, hmac, os, time

BRAVADO_KEY = os.environ["BRAVADO_API_KEY"]
BRAVADO_SECRET = os.environ["BRAVADO_API_SECRET"]
HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(BRAVADO_SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": BRAVADO_KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}

2. Read the frames

The first frame is a snapshot with the last 200 trades, newest first. After that, each new fill arrives as a trade frame.

{
  "type": "trade",
  "trade": {
    "outcome": "Spirit",
    "side": "SELL",
    "price": 0.999,
    "size": 5.37,
    "amount": 5.36463,
    "timestamp": 1788624830000,
    "assetId": "61368774849738226433217302604163725833749767729515136801666479828182608187817",
    "conditionId": "0xf86b33b82a0e0b44d2c30c3264e2ed9f95ebfc4d98275d124f69c77d3fa68bb7",
    "trader": "0xd93461E85B794F0a2fA3a1E9390681db1dF8ab75",
    "transactionHash": "0xdfdd21ca739637b2135de5914e72ee93e9b5ef2b2f443e978b96df75839f0ea2"
  }
}
{
  "type": "trade",
  "trade": {
    "outcome": "Spirit",
    "side": "SELL",
    "price": 0.999,
    "size": 5.37,
    "amount": 5.36463,
    "timestamp": 1788624830000,
    "assetId": "61368774849738226433217302604163725833749767729515136801666479828182608187817",
    "conditionId": "0xf86b33b82a0e0b44d2c30c3264e2ed9f95ebfc4d98275d124f69c77d3fa68bb7",
    "trader": "0xd93461E85B794F0a2fA3a1E9390681db1dF8ab75",
    "transactionHash": "0xdfdd21ca739637b2135de5914e72ee93e9b5ef2b2f443e978b96df75839f0ea2"
  }
}
{
  "type": "trade",
  "trade": {
    "outcome": "Spirit",
    "side": "SELL",
    "price": 0.999,
    "size": 5.37,
    "amount": 5.36463,
    "timestamp": 1788624830000,
    "assetId": "61368774849738226433217302604163725833749767729515136801666479828182608187817",
    "conditionId": "0xf86b33b82a0e0b44d2c30c3264e2ed9f95ebfc4d98275d124f69c77d3fa68bb7",
    "trader": "0xd93461E85B794F0a2fA3a1E9390681db1dF8ab75",
    "transactionHash": "0xdfdd21ca739637b2135de5914e72ee93e9b5ef2b2f443e978b96df75839f0ea2"
  }
}
{
  "type": "trade",
  "trade": {
    "outcome": "Spirit",
    "side": "SELL",
    "price": 0.999,
    "size": 5.37,
    "amount": 5.36463,
    "timestamp": 1788624830000,
    "assetId": "61368774849738226433217302604163725833749767729515136801666479828182608187817",
    "conditionId": "0xf86b33b82a0e0b44d2c30c3264e2ed9f95ebfc4d98275d124f69c77d3fa68bb7",
    "trader": "0xd93461E85B794F0a2fA3a1E9390681db1dF8ab75",
    "transactionHash": "0xdfdd21ca739637b2135de5914e72ee93e9b5ef2b2f443e978b96df75839f0ea2"
  }
}

(Trimmed. The full frame also has id, eventTitle, marketQuestion, priceCents, eventSlug, eventImage, traderName and traderImage.)

These are the fields the bot uses:

Field

Type

Used for

side

"BUY" / "SELL"

Only follow buys

price

number, 0–1

Price band filter and order price

amount

number

Notional (price × size), the "large" test

assetId

string

The outcome token to trade

conditionId

string

Join to UMA state. May be empty, so skip those

timestamp

number, Unix ms

Ignore stale trades

transactionHash

string

Part of the dedupe key

3. Dedupe and filter

Dedupe on the tuple (transactionHash, assetId, side). Do not dedupe on id; it is not stable across restarts or server instances. Do not use the hash alone: one transaction can carry several fills.

Use the snapshot only to fill the dedupe set. Those trades are already a few seconds old, so the bot should not act on them.

seen_fills: set[tuple] = set()

def fill_key(t: dict) -> tuple:
    return (t.get("transactionHash"), t["assetId"], t["side"])
seen_fills: set[tuple] = set()

def fill_key(t: dict) -> tuple:
    return (t.get("transactionHash"), t["assetId"], t["side"])
seen_fills: set[tuple] = set()

def fill_key(t: dict) -> tuple:
    return (t.get("transactionHash"), t["assetId"], t["side"])
seen_fills: set[tuple] = set()

def fill_key(t: dict) -> tuple:
    return (t.get("transactionHash"), t["assetId"], t["side"])

4. Reconnect and gaps

If the socket drops, reconnect with a fresh signature. You get a new snapshot. The trade socket does not backfill trades you missed while you were away. Bravado has REST endpoints you can call to fill gaps yourself, but they work per wallet or per token, not market-wide:

Need

Endpoint

A wallet's trades

GET /trader-analytics/traders/{address}/trades

One token's volume

GET /clob-proxy/volume-history?market={tokenId}

One token's price history

GET /clob-proxy/prices-history?market={tokenId}&startTs={unixSeconds}&fidelity={minutes}

For this bot a small gap is acceptable. It only acts on fresh trades, so a missed trade is a missed signal, not a wrong position.

How do you watch UMA resolution in real time?

The UMA stream at wss://partner-api.bravadotrade.com/uma/ws pushes every Polymarket proposal, dispute and settlement as a uma frame. There is no subscribe message. The signing is the same, with path /uma/ws.


Table of the UMA frames the bot sees: a pending proposal with seen_pending true and block 0, where the guard starts; the confirmed proposal; a pending dispute, which cancels orders on that market; the confirmed dispute, the source of truth; and settled, with payout. Tiles show 103 of 151 disputes seen pending first in our sample, a median pending lead of about 1.2 seconds, and that a pending transaction can lose a mempool race.

1. Read the frame

{
  "type": "uma",
  "seq": 11254,
  "stage": "proposed",
  "answer": "no",
  "question_id": "0xf559249060ef8c94b8e38fc9c341758a12095ad26c5f9f0f7f7b03fc24a906dd",
  "condition_id": "0xf837021913e1a86f9dc9d2ab1f29b90df89b0ad942fb24284a0b402b667e5952",
  "title": "Set 1 Winner: ...",
  "block": 0,
  "seen_pending": true
}
{
  "type": "uma",
  "seq": 11254,
  "stage": "proposed",
  "answer": "no",
  "question_id": "0xf559249060ef8c94b8e38fc9c341758a12095ad26c5f9f0f7f7b03fc24a906dd",
  "condition_id": "0xf837021913e1a86f9dc9d2ab1f29b90df89b0ad942fb24284a0b402b667e5952",
  "title": "Set 1 Winner: ...",
  "block": 0,
  "seen_pending": true
}
{
  "type": "uma",
  "seq": 11254,
  "stage": "proposed",
  "answer": "no",
  "question_id": "0xf559249060ef8c94b8e38fc9c341758a12095ad26c5f9f0f7f7b03fc24a906dd",
  "condition_id": "0xf837021913e1a86f9dc9d2ab1f29b90df89b0ad942fb24284a0b402b667e5952",
  "title": "Set 1 Winner: ...",
  "block": 0,
  "seen_pending": true
}
{
  "type": "uma",
  "seq": 11254,
  "stage": "proposed",
  "answer": "no",
  "question_id": "0xf559249060ef8c94b8e38fc9c341758a12095ad26c5f9f0f7f7b03fc24a906dd",
  "condition_id": "0xf837021913e1a86f9dc9d2ab1f29b90df89b0ad942fb24284a0b402b667e5952",
  "title": "Set 1 Winner: ...",
  "block": 0,
  "seen_pending": true
}

(Trimmed for space. Frames also carry proposer, disputer, price_raw, payout, request_ts, tx and log_index where relevant.)

Field

Meaning

stage

proposed, disputed or settled

answer

yes, no, 50-50, too-early or other

condition_id

The market. Same id as conditionId on the trade feed

seen_pending

true while seen only in the mempool (block is 0)

block, tx

Set once the transaction is mined

seq

Message sequence number. A jump means you missed frames

2. Track state per market

The bot keeps one set: resolving, the condition ids with any UMA activity seen this session. A proposal or dispute adds the market. A settled market stays in the set too, because it is finished. The guard is simple: never enter a market in resolving.

3. Handle the pending and mined pair

A proposal or dispute decoded from the mempool arrives first with seen_pending: true and block: 0. The same question_id arrives again once it is mined. For a guard, act on the first one. Adding a market to a set twice is harmless. Settlements are mined-only.

The head start is small but real: in our sample, 103 of 151 disputes showed up as pending a median of about 1.2 seconds before on-chain confirmation. Occasionally two dispute transactions race in the mempool and only one is mined, so a pending alert may never get a matching confirmation. Treat the confirmed frame as the source of truth. For a guard that only blocks new orders, acting early is the safe direction.

4. Watch seq

The UMA stream has no replay. If seq jumps, you missed frames, and a market you care about may have changed stage. Before the next order on any market, check it with GET /uma/market?condition_id=<0x conditionId> (1 credit per response, signed with HMAC including sorted query parameters; see Authentication). GET /uma/recent?stage=disputed&limit=100 is useful after a long disconnect.

How do you place the order?

Polymarket's legacy py-clob-client is archived and no longer works. Use the official SDK, polymarket-client.

1. Authenticate

import os
from polymarket import AsyncSecureClient

client = await AsyncSecureClient.create(
    private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
    wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
)
import os
from polymarket import AsyncSecureClient

client = await AsyncSecureClient.create(
    private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
    wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
)
import os
from polymarket import AsyncSecureClient

client = await AsyncSecureClient.create(
    private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
    wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
)
import os
from polymarket import AsyncSecureClient

client = await AsyncSecureClient.create(
    private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
    wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
)

2. Place a limit order

We use a Good-Till-Date (GTD) limit order so a stale order expires on its own. Polymarket expires GTD orders one minute early, and the expiration must be at least three minutes ahead. So for an effective lifetime of N seconds, use now + 60 + N.

import time

expiration = int(time.time()) + 60 + 600  # about 10 minutes
response = await client.place_limit_order(
    asset_id=asset_id,
    side="BUY",
    price="0.52",
    size="5",
    expiration=expiration,
)
if response.ok:
    print(response.order_id, response.status)  # live, matched or delayed
else:
    print(response.code, response.message)
import time

expiration = int(time.time()) + 60 + 600  # about 10 minutes
response = await client.place_limit_order(
    asset_id=asset_id,
    side="BUY",
    price="0.52",
    size="5",
    expiration=expiration,
)
if response.ok:
    print(response.order_id, response.status)  # live, matched or delayed
else:
    print(response.code, response.message)
import time

expiration = int(time.time()) + 60 + 600  # about 10 minutes
response = await client.place_limit_order(
    asset_id=asset_id,
    side="BUY",
    price="0.52",
    size="5",
    expiration=expiration,
)
if response.ok:
    print(response.order_id, response.status)  # live, matched or delayed
else:
    print(response.code, response.message)
import time

expiration = int(time.time()) + 60 + 600  # about 10 minutes
response = await client.place_limit_order(
    asset_id=asset_id,
    side="BUY",
    price="0.52",
    size="5",
    expiration=expiration,
)
if response.ok:
    print(response.order_id, response.status)  # live, matched or delayed
else:
    print(response.code, response.message)

The price must follow the market's tick size and the size must meet its minimum order size. The SDK calls an outcome's trading id asset_id: a token id for CTF markets, a position id for Polymarket Protocol V2 markets. The trade feed's assetId is the outcome token id. If the market is V2, fetch it with the SDK first and use the id it gives you.

3. Cancel on a dispute

When a dispute arrives on a market where the bot has orders, cancel every open order for that market by condition id:

await client.cancel_market_orders(market=condition_id)
await client.cancel_market_orders(market=condition_id)
await client.cancel_market_orders(market=condition_id)
await client.cancel_market_orders(market=condition_id)

The SDK also has cancel_order(order_id=...) for one order and cancel_all() for everything. Use cancel_all() as your kill switch.

How do you put it all together?

1. One loop, two sockets, shared state

Both streams run as tasks in one asyncio loop. They share resolving and the order count per market.

2. Dry run first

DRY_RUN = True by default. In dry run, the bot never creates a trading client. It only logs what it would do.

3. The full script

# pip install websockets polymarket-client
# Educational example. Not financial advice. DRY_RUN is on by default.
import asyncio, hashlib, hmac, json, logging, os, time
import websockets

DRY_RUN = True
MIN_AMOUNT = 5000          # USD notional of the trade we follow
PRICE_MIN, PRICE_MAX = 0.10, 0.90
ORDER_SIZE = "5"           # shares
MAX_ORDERS_PER_MARKET = 1
ORDER_LIFETIME_S = 600
MAX_TRADE_AGE_MS = 5000

HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"
KEY = os.environ["BRAVADO_API_KEY"]
SECRET = os.environ["BRAVADO_API_SECRET"]

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("bot")

resolving: set[str] = set()          # condition ids with UMA activity
orders_per_market: dict[str, int] = {}
seen_fills: set[tuple] = set()
last_seq: int | None = None
client = None                        # AsyncSecureClient when live

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}

async def stream(path: str, handler, silence_s: float | None = None) -> None:
    backoff = 1
    while True:
        try:
            async with websockets.connect(HOST + path, additional_headers=sign_headers(path),
                                          ping_interval=20, ping_timeout=30) as ws:
                backoff = 1
                while True:
                    # A socket can stay open and go quiet. Treat silence as a drop.
                    raw = await asyncio.wait_for(ws.recv(), timeout=silence_s)
                    await handler(json.loads(raw))
        except asyncio.TimeoutError:
            log.warning("%s silent for %ss: reconnecting", path, silence_s)
        except websockets.ConnectionClosed as e:
            code, reason = (e.rcvd.code, e.rcvd.reason) if e.rcvd else (None, "")
            log.warning("%s closed: %s %s", path, code, reason)
            if "CREDIT_LIMIT" in reason:
                log.error("out of credits: stopping %s", path)
                return                   # fix the refusal before retrying
        except Exception as e:
            log.warning("%s error: %s", path, e)
            backoff = min(backoff * 2, 30)
        await asyncio.sleep(backoff)     # fresh signature on every reconnect

# ---- UMA guard ----
async def on_uma(f: dict) -> None:
    global last_seq
    if f.get("type") != "uma":
        if f.get("type") == "error":
            log.error("uma error: %s", f)
        return
    seq = f.get("seq")
    if seq is not None and last_seq is not None and seq > last_seq + 1:
        log.warning("uma seq gap %s -> %s: re-check markets before trading", last_seq, seq)
    if seq is not None:
        last_seq = seq
    cid = f.get("condition_id")
    if not cid:
        return
    resolving.add(cid)
    if f.get("stage") == "disputed" and orders_per_market.get(cid):
        log.info("DISPUTE on %s (%s): cancelling orders", cid, f.get("title"))
        if not DRY_RUN:
            await client.cancel_market_orders(market=cid)

# ---- trade signal ----
async def on_trade_frame(f: dict) -> None:
    if f.get("type") == "snapshot":
        for t in f.get("trades", []):
            seen_fills.add((t.get("transactionHash"), t["assetId"], t["side"]))
        return
    if f.get("type") != "trade":
        return
    t = f["trade"]
    key = (t.get("transactionHash"), t["assetId"], t["side"])
    if key in seen_fills:
        return
    seen_fills.add(key)

    cid = t.get("conditionId")
    if (t["side"] != "BUY" or t["amount"] < MIN_AMOUNT
            or not (PRICE_MIN <= t["price"] <= PRICE_MAX) or not cid):
        return
    if time.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:
        return
    if cid in resolving:
        log.info("skip %s: UMA activity on this market", t.get("marketQuestion"))
        return
    if orders_per_market.get(cid, 0) >= MAX_ORDERS_PER_MARKET:
        return
    await place(t, cid)

async def place(t: dict, cid: str) -> None:
    price = f"{t['price']:.2f}"          # check the market's tick size
    orders_per_market[cid] = orders_per_market.get(cid, 0) + 1
    log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",
             t.get("marketQuestion"), t["outcome"], price, t["amount"], t["trader"])
    if DRY_RUN:
        return
    expiration = int(time.time()) + 60 + ORDER_LIFETIME_S
    r = await client.place_limit_order(asset_id=t["assetId"], side="BUY",
                                       price=price, size=ORDER_SIZE, expiration=expiration)
    log.info("order ok=%s %s", r.ok, r.order_id if r.ok else r.message)

async def main() -> None:
    global client
    if not DRY_RUN:
        from polymarket import AsyncSecureClient
        client = await AsyncSecureClient.create(
            private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
            wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
        )
    try:
        await asyncio.gather(stream(UMA_PATH, on_uma),
                             stream(TRADES_PATH, on_trade_frame, silence_s=30))
    finally:
        if client is not None:
            await client.cancel_all()     # kill switch on exit

asyncio.run(main())
# pip install websockets polymarket-client
# Educational example. Not financial advice. DRY_RUN is on by default.
import asyncio, hashlib, hmac, json, logging, os, time
import websockets

DRY_RUN = True
MIN_AMOUNT = 5000          # USD notional of the trade we follow
PRICE_MIN, PRICE_MAX = 0.10, 0.90
ORDER_SIZE = "5"           # shares
MAX_ORDERS_PER_MARKET = 1
ORDER_LIFETIME_S = 600
MAX_TRADE_AGE_MS = 5000

HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"
KEY = os.environ["BRAVADO_API_KEY"]
SECRET = os.environ["BRAVADO_API_SECRET"]

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("bot")

resolving: set[str] = set()          # condition ids with UMA activity
orders_per_market: dict[str, int] = {}
seen_fills: set[tuple] = set()
last_seq: int | None = None
client = None                        # AsyncSecureClient when live

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}

async def stream(path: str, handler, silence_s: float | None = None) -> None:
    backoff = 1
    while True:
        try:
            async with websockets.connect(HOST + path, additional_headers=sign_headers(path),
                                          ping_interval=20, ping_timeout=30) as ws:
                backoff = 1
                while True:
                    # A socket can stay open and go quiet. Treat silence as a drop.
                    raw = await asyncio.wait_for(ws.recv(), timeout=silence_s)
                    await handler(json.loads(raw))
        except asyncio.TimeoutError:
            log.warning("%s silent for %ss: reconnecting", path, silence_s)
        except websockets.ConnectionClosed as e:
            code, reason = (e.rcvd.code, e.rcvd.reason) if e.rcvd else (None, "")
            log.warning("%s closed: %s %s", path, code, reason)
            if "CREDIT_LIMIT" in reason:
                log.error("out of credits: stopping %s", path)
                return                   # fix the refusal before retrying
        except Exception as e:
            log.warning("%s error: %s", path, e)
            backoff = min(backoff * 2, 30)
        await asyncio.sleep(backoff)     # fresh signature on every reconnect

# ---- UMA guard ----
async def on_uma(f: dict) -> None:
    global last_seq
    if f.get("type") != "uma":
        if f.get("type") == "error":
            log.error("uma error: %s", f)
        return
    seq = f.get("seq")
    if seq is not None and last_seq is not None and seq > last_seq + 1:
        log.warning("uma seq gap %s -> %s: re-check markets before trading", last_seq, seq)
    if seq is not None:
        last_seq = seq
    cid = f.get("condition_id")
    if not cid:
        return
    resolving.add(cid)
    if f.get("stage") == "disputed" and orders_per_market.get(cid):
        log.info("DISPUTE on %s (%s): cancelling orders", cid, f.get("title"))
        if not DRY_RUN:
            await client.cancel_market_orders(market=cid)

# ---- trade signal ----
async def on_trade_frame(f: dict) -> None:
    if f.get("type") == "snapshot":
        for t in f.get("trades", []):
            seen_fills.add((t.get("transactionHash"), t["assetId"], t["side"]))
        return
    if f.get("type") != "trade":
        return
    t = f["trade"]
    key = (t.get("transactionHash"), t["assetId"], t["side"])
    if key in seen_fills:
        return
    seen_fills.add(key)

    cid = t.get("conditionId")
    if (t["side"] != "BUY" or t["amount"] < MIN_AMOUNT
            or not (PRICE_MIN <= t["price"] <= PRICE_MAX) or not cid):
        return
    if time.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:
        return
    if cid in resolving:
        log.info("skip %s: UMA activity on this market", t.get("marketQuestion"))
        return
    if orders_per_market.get(cid, 0) >= MAX_ORDERS_PER_MARKET:
        return
    await place(t, cid)

async def place(t: dict, cid: str) -> None:
    price = f"{t['price']:.2f}"          # check the market's tick size
    orders_per_market[cid] = orders_per_market.get(cid, 0) + 1
    log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",
             t.get("marketQuestion"), t["outcome"], price, t["amount"], t["trader"])
    if DRY_RUN:
        return
    expiration = int(time.time()) + 60 + ORDER_LIFETIME_S
    r = await client.place_limit_order(asset_id=t["assetId"], side="BUY",
                                       price=price, size=ORDER_SIZE, expiration=expiration)
    log.info("order ok=%s %s", r.ok, r.order_id if r.ok else r.message)

async def main() -> None:
    global client
    if not DRY_RUN:
        from polymarket import AsyncSecureClient
        client = await AsyncSecureClient.create(
            private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
            wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
        )
    try:
        await asyncio.gather(stream(UMA_PATH, on_uma),
                             stream(TRADES_PATH, on_trade_frame, silence_s=30))
    finally:
        if client is not None:
            await client.cancel_all()     # kill switch on exit

asyncio.run(main())
# pip install websockets polymarket-client
# Educational example. Not financial advice. DRY_RUN is on by default.
import asyncio, hashlib, hmac, json, logging, os, time
import websockets

DRY_RUN = True
MIN_AMOUNT = 5000          # USD notional of the trade we follow
PRICE_MIN, PRICE_MAX = 0.10, 0.90
ORDER_SIZE = "5"           # shares
MAX_ORDERS_PER_MARKET = 1
ORDER_LIFETIME_S = 600
MAX_TRADE_AGE_MS = 5000

HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"
KEY = os.environ["BRAVADO_API_KEY"]
SECRET = os.environ["BRAVADO_API_SECRET"]

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("bot")

resolving: set[str] = set()          # condition ids with UMA activity
orders_per_market: dict[str, int] = {}
seen_fills: set[tuple] = set()
last_seq: int | None = None
client = None                        # AsyncSecureClient when live

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}

async def stream(path: str, handler, silence_s: float | None = None) -> None:
    backoff = 1
    while True:
        try:
            async with websockets.connect(HOST + path, additional_headers=sign_headers(path),
                                          ping_interval=20, ping_timeout=30) as ws:
                backoff = 1
                while True:
                    # A socket can stay open and go quiet. Treat silence as a drop.
                    raw = await asyncio.wait_for(ws.recv(), timeout=silence_s)
                    await handler(json.loads(raw))
        except asyncio.TimeoutError:
            log.warning("%s silent for %ss: reconnecting", path, silence_s)
        except websockets.ConnectionClosed as e:
            code, reason = (e.rcvd.code, e.rcvd.reason) if e.rcvd else (None, "")
            log.warning("%s closed: %s %s", path, code, reason)
            if "CREDIT_LIMIT" in reason:
                log.error("out of credits: stopping %s", path)
                return                   # fix the refusal before retrying
        except Exception as e:
            log.warning("%s error: %s", path, e)
            backoff = min(backoff * 2, 30)
        await asyncio.sleep(backoff)     # fresh signature on every reconnect

# ---- UMA guard ----
async def on_uma(f: dict) -> None:
    global last_seq
    if f.get("type") != "uma":
        if f.get("type") == "error":
            log.error("uma error: %s", f)
        return
    seq = f.get("seq")
    if seq is not None and last_seq is not None and seq > last_seq + 1:
        log.warning("uma seq gap %s -> %s: re-check markets before trading", last_seq, seq)
    if seq is not None:
        last_seq = seq
    cid = f.get("condition_id")
    if not cid:
        return
    resolving.add(cid)
    if f.get("stage") == "disputed" and orders_per_market.get(cid):
        log.info("DISPUTE on %s (%s): cancelling orders", cid, f.get("title"))
        if not DRY_RUN:
            await client.cancel_market_orders(market=cid)

# ---- trade signal ----
async def on_trade_frame(f: dict) -> None:
    if f.get("type") == "snapshot":
        for t in f.get("trades", []):
            seen_fills.add((t.get("transactionHash"), t["assetId"], t["side"]))
        return
    if f.get("type") != "trade":
        return
    t = f["trade"]
    key = (t.get("transactionHash"), t["assetId"], t["side"])
    if key in seen_fills:
        return
    seen_fills.add(key)

    cid = t.get("conditionId")
    if (t["side"] != "BUY" or t["amount"] < MIN_AMOUNT
            or not (PRICE_MIN <= t["price"] <= PRICE_MAX) or not cid):
        return
    if time.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:
        return
    if cid in resolving:
        log.info("skip %s: UMA activity on this market", t.get("marketQuestion"))
        return
    if orders_per_market.get(cid, 0) >= MAX_ORDERS_PER_MARKET:
        return
    await place(t, cid)

async def place(t: dict, cid: str) -> None:
    price = f"{t['price']:.2f}"          # check the market's tick size
    orders_per_market[cid] = orders_per_market.get(cid, 0) + 1
    log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",
             t.get("marketQuestion"), t["outcome"], price, t["amount"], t["trader"])
    if DRY_RUN:
        return
    expiration = int(time.time()) + 60 + ORDER_LIFETIME_S
    r = await client.place_limit_order(asset_id=t["assetId"], side="BUY",
                                       price=price, size=ORDER_SIZE, expiration=expiration)
    log.info("order ok=%s %s", r.ok, r.order_id if r.ok else r.message)

async def main() -> None:
    global client
    if not DRY_RUN:
        from polymarket import AsyncSecureClient
        client = await AsyncSecureClient.create(
            private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
            wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
        )
    try:
        await asyncio.gather(stream(UMA_PATH, on_uma),
                             stream(TRADES_PATH, on_trade_frame, silence_s=30))
    finally:
        if client is not None:
            await client.cancel_all()     # kill switch on exit

asyncio.run(main())
# pip install websockets polymarket-client
# Educational example. Not financial advice. DRY_RUN is on by default.
import asyncio, hashlib, hmac, json, logging, os, time
import websockets

DRY_RUN = True
MIN_AMOUNT = 5000          # USD notional of the trade we follow
PRICE_MIN, PRICE_MAX = 0.10, 0.90
ORDER_SIZE = "5"           # shares
MAX_ORDERS_PER_MARKET = 1
ORDER_LIFETIME_S = 600
MAX_TRADE_AGE_MS = 5000

HOST = "wss://partner-api.bravadotrade.com"
TRADES_PATH = "/stream/polymarket/partner/trades"
UMA_PATH = "/uma/ws"
KEY = os.environ["BRAVADO_API_KEY"]
SECRET = os.environ["BRAVADO_API_SECRET"]

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("bot")

resolving: set[str] = set()          # condition ids with UMA activity
orders_per_market: dict[str, int] = {}
seen_fills: set[tuple] = set()
last_seq: int | None = None
client = None                        # AsyncSecureClient when live

def sign_headers(path: str) -> dict:
    ts = str(int(time.time() * 1000))
    payload = "\n".join([ts, "GET", path, hashlib.sha256(b"").hexdigest()])
    sig = hmac.new(SECRET.encode(), payload.encode(), hashlib.sha256).hexdigest()
    return {"X-BRAVADO-API-KEY": KEY, "X-BRAVADO-TIMESTAMP": ts, "X-BRAVADO-SIGNATURE": sig}

async def stream(path: str, handler, silence_s: float | None = None) -> None:
    backoff = 1
    while True:
        try:
            async with websockets.connect(HOST + path, additional_headers=sign_headers(path),
                                          ping_interval=20, ping_timeout=30) as ws:
                backoff = 1
                while True:
                    # A socket can stay open and go quiet. Treat silence as a drop.
                    raw = await asyncio.wait_for(ws.recv(), timeout=silence_s)
                    await handler(json.loads(raw))
        except asyncio.TimeoutError:
            log.warning("%s silent for %ss: reconnecting", path, silence_s)
        except websockets.ConnectionClosed as e:
            code, reason = (e.rcvd.code, e.rcvd.reason) if e.rcvd else (None, "")
            log.warning("%s closed: %s %s", path, code, reason)
            if "CREDIT_LIMIT" in reason:
                log.error("out of credits: stopping %s", path)
                return                   # fix the refusal before retrying
        except Exception as e:
            log.warning("%s error: %s", path, e)
            backoff = min(backoff * 2, 30)
        await asyncio.sleep(backoff)     # fresh signature on every reconnect

# ---- UMA guard ----
async def on_uma(f: dict) -> None:
    global last_seq
    if f.get("type") != "uma":
        if f.get("type") == "error":
            log.error("uma error: %s", f)
        return
    seq = f.get("seq")
    if seq is not None and last_seq is not None and seq > last_seq + 1:
        log.warning("uma seq gap %s -> %s: re-check markets before trading", last_seq, seq)
    if seq is not None:
        last_seq = seq
    cid = f.get("condition_id")
    if not cid:
        return
    resolving.add(cid)
    if f.get("stage") == "disputed" and orders_per_market.get(cid):
        log.info("DISPUTE on %s (%s): cancelling orders", cid, f.get("title"))
        if not DRY_RUN:
            await client.cancel_market_orders(market=cid)

# ---- trade signal ----
async def on_trade_frame(f: dict) -> None:
    if f.get("type") == "snapshot":
        for t in f.get("trades", []):
            seen_fills.add((t.get("transactionHash"), t["assetId"], t["side"]))
        return
    if f.get("type") != "trade":
        return
    t = f["trade"]
    key = (t.get("transactionHash"), t["assetId"], t["side"])
    if key in seen_fills:
        return
    seen_fills.add(key)

    cid = t.get("conditionId")
    if (t["side"] != "BUY" or t["amount"] < MIN_AMOUNT
            or not (PRICE_MIN <= t["price"] <= PRICE_MAX) or not cid):
        return
    if time.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:
        return
    if cid in resolving:
        log.info("skip %s: UMA activity on this market", t.get("marketQuestion"))
        return
    if orders_per_market.get(cid, 0) >= MAX_ORDERS_PER_MARKET:
        return
    await place(t, cid)

async def place(t: dict, cid: str) -> None:
    price = f"{t['price']:.2f}"          # check the market's tick size
    orders_per_market[cid] = orders_per_market.get(cid, 0) + 1
    log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",
             t.get("marketQuestion"), t["outcome"], price, t["amount"], t["trader"])
    if DRY_RUN:
        return
    expiration = int(time.time()) + 60 + ORDER_LIFETIME_S
    r = await client.place_limit_order(asset_id=t["assetId"], side="BUY",
                                       price=price, size=ORDER_SIZE, expiration=expiration)
    log.info("order ok=%s %s", r.ok, r.order_id if r.ok else r.message)

async def main() -> None:
    global client
    if not DRY_RUN:
        from polymarket import AsyncSecureClient
        client = await AsyncSecureClient.create(
            private_key=os.environ["POLYMARKET_PRIVATE_KEY"],
            wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],
        )
    try:
        await asyncio.gather(stream(UMA_PATH, on_uma),
                             stream(TRADES_PATH, on_trade_frame, silence_s=30))
    finally:
        if client is not None:
            await client.cancel_all()     # kill switch on exit

asyncio.run(main())

A few notes on this script:

  • It starts with an empty resolving set. A market proposed before the bot started is not in it. For a real run, check each market with GET /uma/market before the first order, or warm up by listening for a while first.

  • seen_fills grows forever. Cap it, or clear old keys, in a long-running bot.

  • The trade stream treats 30 seconds of silence as a drop and reconnects. The UMA stream can be quiet for a while, so it relies on pings instead.

  • If a stream closes with CREDIT_LIMIT_REACHED, the bot stops that stream instead of retrying.

  • The seq gap only logs a warning. A stricter bot pauses new orders until it has re-checked.


Two annotated JSON frames side by side: a Bravado trade frame with assetId and conditionId highlighted, and a UMA frame with seq, condition_id and seen_pending highlighted. A table explains that conditionId and condition_id join the feeds, assetId is used for the order, seq jumps mean missed frames, and seen_pending marks a mempool frame with block 0.

4. Log every decision

Log trades you skipped and why, not just orders you placed. When the bot does something odd, the skip log tells you which filter caused it.

Why use Bravado for a Polymarket bot?

You can build all of this on raw venue feeds and your own chain indexer. Bravado removes two of the hardest parts.

Live trades without running the connection. The Live Trades WebSocket gives you every Polymarket fill on one authenticated socket, already enriched with trader, traderName, marketQuestion and conditionId. On our side it wraps one upstream Polymarket connection with a 30-second silence watchdog, reconnects, removes duplicate frames, and sends the last 200 trades when you connect.

Resolution state without an indexer. The UMA API and WebSocket turn UMA's oracle events into data: stage, a classified answer, and a condition_id that joins straight to the trade feed. Proposals and disputes are decoded from the mempool and flagged with seen_pending before they are mined. In our sample, 103 of 151 disputes showed up as pending a median of about 1.2 seconds before on-chain confirmation.

What it does not do. The trade socket does not backfill gaps, and the UMA stream has no replay. Use the REST endpoints above to fill gaps per wallet or per token, and GET /uma/market to re-check one market.

Costs. Usage is measured in API credits:

Product

Cost

Live Trades WebSocket

1 credit per 100,000 bytes (for organisations enrolled in WebSocket billing)

UMA WebSocket

0.75 credit per delivered data message

UMA REST

1 credit per successful response

Data API

1 credit per request

Heartbeats, errors and idle time are not charged. The Free plan includes 5,000 credits per month, but the UMA API needs a paid plan, and the trade WebSocket needs a paid plan with WebSocket access. See API Credits for details.


Table of Bravado API credit costs: Live Trades WebSocket 1 credit per 100,000 bytes, UMA stream 0.75 credit per delivered message, UMA queries 1 credit per successful response, Data API 1 credit per request. The Free plan includes 5,000 credits per month; the UMA API needs a paid plan and the trade WebSocket needs a paid plan with WebSocket access.

Conclusion

A trading bot is mostly plumbing. The rule here fits in ten lines. The rest is reading two streams correctly, joining them on the market id, and staying safe.

Before you turn off dry run:

  1. Run in dry run for at least a few days and read the logs.

  2. Log every skipped trade with its reason.

  3. Keep orders small and capped per market.

  4. Alert on seq gaps and on silent sockets. The script reconnects on silence; add an alert too.

  5. Check a market with GET /uma/market before the first order.

  6. Read each market's resolution rules. A large buy is not information you can verify.

  7. Keep cancel_all() one command away.

This guide is educational. It is not financial advice, and nothing here suggests the strategy is profitable.

To get started, create a Market Data key in the Bravado Console and read the Live Trades WebSocket and UMA API docs.

Read more blogs

Trading insights, market analysis, and strategies for Polymarket prediction markets.

© 2026 Bravado. All rights reserved.

Not financial advice. Trade responsibly.

© 2026 Bravado. All rights reserved.

Not financial advice. Trade responsibly.

© 2026 Bravado. All rights reserved.

Not financial advice. Trade responsibly.

© 2026 Bravado. All rights reserved.

Not financial advice. Trade responsibly.