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.
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.
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.
(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.
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.
(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.
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.
importtimeexpiration = int(time.time()) + 60 + 600 # about 10minutesresponse = awaitclient.place_limit_order(asset_id=asset_id,side="BUY",price="0.52",size="5",expiration=expiration,)ifresponse.ok:print(response.order_id,response.status) # live,matched or delayedelse:print(response.code,response.message)
importtimeexpiration = int(time.time()) + 60 + 600 # about 10minutesresponse = awaitclient.place_limit_order(asset_id=asset_id,side="BUY",price="0.52",size="5",expiration=expiration,)ifresponse.ok:print(response.order_id,response.status) # live,matched or delayedelse:print(response.code,response.message)
importtimeexpiration = int(time.time()) + 60 + 600 # about 10minutesresponse = awaitclient.place_limit_order(asset_id=asset_id,side="BUY",price="0.52",size="5",expiration=expiration,)ifresponse.ok:print(response.order_id,response.status) # live,matched or delayedelse:print(response.code,response.message)
importtimeexpiration = int(time.time()) + 60 + 600 # about 10minutesresponse = awaitclient.place_limit_order(asset_id=asset_id,side="BUY",price="0.52",size="5",expiration=expiration,)ifresponse.ok:print(response.order_id,response.status) # live,matched or delayedelse: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:
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. Notfinancial advice. DRY_RUNis on by default.
importasyncio,hashlib,hmac,json,logging,os,timeimportwebsocketsDRY_RUN = TrueMIN_AMOUNT = 5000 # USD notional of the trade we followPRICE_MIN,PRICE_MAX = 0.10,0.90ORDER_SIZE = "5" # sharesMAX_ORDERS_PER_MARKET = 1ORDER_LIFETIME_S = 600MAX_TRADE_AGE_MS = 5000HOST = "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 withUMA activity
orders_per_market:dict[str,int] = {}
seen_fills:set[tuple] = set()
last_seq:int | None = Noneclient = None #AsyncSecureClient when livedef 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}asyncdef stream(path: str,handler,silence_s: float | None = None) -> None:backoff = 1while True:try:asyncwithwebsockets.connect(HOST + path,additional_headers=sign_headers(path),ping_interval=20,ping_timeout=30)as ws:backoff = 1while True:
# A socket can stay open and go quiet. Treatsilenceas a drop.
raw = awaitasyncio.wait_for(ws.recv(),timeout=silence_s)awaithandler(json.loads(raw))except asyncio.TimeoutError:log.warning("%s silent for %ss: reconnecting",path,silence_s)except websockets.ConnectionClosedas e:code,reason = (e.rcvd.code,e.rcvd.reason)ife.rcvdelse(None,"")log.warning("%s closed: %s %s",path,code,reason)if"CREDIT_LIMIT"inreason:log.error("out of credits: stopping %s",path)return # fix the refusal before retryingexcept Exceptionas e:log.warning("%s error: %s",path,e)backoff = min(backoff * 2,30)awaitasyncio.sleep(backoff) # fresh signature on every reconnect
# ---- UMA guard ----
asyncdef on_uma(f: dict) -> None:global last_seqiff.get("type") != "uma":iff.get("type") == "error":log.error("uma error: %s",f)returnseq = f.get("seq")ifseq 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)ifseq is not None:last_seq = seqcid = f.get("condition_id")ifnot cid:returnresolving.add(cid)iff.get("stage") == "disputed"and orders_per_market.get(cid):log.info("DISPUTE on %s (%s): cancelling orders",cid,f.get("title"))ifnot DRY_RUN:awaitclient.cancel_market_orders(market=cid)
# ---- trade signal ----
asyncdef on_trade_frame(f: dict) -> None:iff.get("type") == "snapshot":fortinf.get("trades",[]):seen_fills.add((t.get("transactionHash"),t["assetId"],t["side"]))returniff.get("type") != "trade":returnt = f["trade"]key = (t.get("transactionHash"),t["assetId"],t["side"])ifkeyinseen_fills:returnseen_fills.add(key)cid = t.get("conditionId")if(t["side"] != "BUY"or t["amount"] < MIN_AMOUNTor not(PRICE_MIN <= t["price"] <= PRICE_MAX)or not cid):returniftime.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:returnifcidinresolving:log.info("skip %s: UMA activity on this market",t.get("marketQuestion"))returniforders_per_market.get(cid,0) >= MAX_ORDERS_PER_MARKET:returnawaitplace(t,cid)asyncdef 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) + 1log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",t.get("marketQuestion"),t["outcome"],price,t["amount"],t["trader"])if DRY_RUN:returnexpiration = int(time.time()) + 60 + ORDER_LIFETIME_Sr = awaitclient.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_idifr.okelser.message)asyncdefmain() -> None:global clientifnot DRY_RUN:from polymarket importAsyncSecureClientclient = awaitAsyncSecureClient.create(private_key=os.environ["POLYMARKET_PRIVATE_KEY"],wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],)try:awaitasyncio.gather(stream(UMA_PATH,on_uma),stream(TRADES_PATH,on_trade_frame,silence_s=30))finally:ifclient is not None:awaitclient.cancel_all() # kill switchon exitasyncio.run(main())
# pip install websockets polymarket-client
# Educational example. Notfinancial advice. DRY_RUNis on by default.
importasyncio,hashlib,hmac,json,logging,os,timeimportwebsocketsDRY_RUN = TrueMIN_AMOUNT = 5000 # USD notional of the trade we followPRICE_MIN,PRICE_MAX = 0.10,0.90ORDER_SIZE = "5" # sharesMAX_ORDERS_PER_MARKET = 1ORDER_LIFETIME_S = 600MAX_TRADE_AGE_MS = 5000HOST = "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 withUMA activity
orders_per_market:dict[str,int] = {}
seen_fills:set[tuple] = set()
last_seq:int | None = Noneclient = None #AsyncSecureClient when livedef 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}asyncdef stream(path: str,handler,silence_s: float | None = None) -> None:backoff = 1while True:try:asyncwithwebsockets.connect(HOST + path,additional_headers=sign_headers(path),ping_interval=20,ping_timeout=30)as ws:backoff = 1while True:
# A socket can stay open and go quiet. Treatsilenceas a drop.
raw = awaitasyncio.wait_for(ws.recv(),timeout=silence_s)awaithandler(json.loads(raw))except asyncio.TimeoutError:log.warning("%s silent for %ss: reconnecting",path,silence_s)except websockets.ConnectionClosedas e:code,reason = (e.rcvd.code,e.rcvd.reason)ife.rcvdelse(None,"")log.warning("%s closed: %s %s",path,code,reason)if"CREDIT_LIMIT"inreason:log.error("out of credits: stopping %s",path)return # fix the refusal before retryingexcept Exceptionas e:log.warning("%s error: %s",path,e)backoff = min(backoff * 2,30)awaitasyncio.sleep(backoff) # fresh signature on every reconnect
# ---- UMA guard ----
asyncdef on_uma(f: dict) -> None:global last_seqiff.get("type") != "uma":iff.get("type") == "error":log.error("uma error: %s",f)returnseq = f.get("seq")ifseq 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)ifseq is not None:last_seq = seqcid = f.get("condition_id")ifnot cid:returnresolving.add(cid)iff.get("stage") == "disputed"and orders_per_market.get(cid):log.info("DISPUTE on %s (%s): cancelling orders",cid,f.get("title"))ifnot DRY_RUN:awaitclient.cancel_market_orders(market=cid)
# ---- trade signal ----
asyncdef on_trade_frame(f: dict) -> None:iff.get("type") == "snapshot":fortinf.get("trades",[]):seen_fills.add((t.get("transactionHash"),t["assetId"],t["side"]))returniff.get("type") != "trade":returnt = f["trade"]key = (t.get("transactionHash"),t["assetId"],t["side"])ifkeyinseen_fills:returnseen_fills.add(key)cid = t.get("conditionId")if(t["side"] != "BUY"or t["amount"] < MIN_AMOUNTor not(PRICE_MIN <= t["price"] <= PRICE_MAX)or not cid):returniftime.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:returnifcidinresolving:log.info("skip %s: UMA activity on this market",t.get("marketQuestion"))returniforders_per_market.get(cid,0) >= MAX_ORDERS_PER_MARKET:returnawaitplace(t,cid)asyncdef 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) + 1log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",t.get("marketQuestion"),t["outcome"],price,t["amount"],t["trader"])if DRY_RUN:returnexpiration = int(time.time()) + 60 + ORDER_LIFETIME_Sr = awaitclient.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_idifr.okelser.message)asyncdefmain() -> None:global clientifnot DRY_RUN:from polymarket importAsyncSecureClientclient = awaitAsyncSecureClient.create(private_key=os.environ["POLYMARKET_PRIVATE_KEY"],wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],)try:awaitasyncio.gather(stream(UMA_PATH,on_uma),stream(TRADES_PATH,on_trade_frame,silence_s=30))finally:ifclient is not None:awaitclient.cancel_all() # kill switchon exitasyncio.run(main())
# pip install websockets polymarket-client
# Educational example. Notfinancial advice. DRY_RUNis on by default.
importasyncio,hashlib,hmac,json,logging,os,timeimportwebsocketsDRY_RUN = TrueMIN_AMOUNT = 5000 # USD notional of the trade we followPRICE_MIN,PRICE_MAX = 0.10,0.90ORDER_SIZE = "5" # sharesMAX_ORDERS_PER_MARKET = 1ORDER_LIFETIME_S = 600MAX_TRADE_AGE_MS = 5000HOST = "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 withUMA activity
orders_per_market:dict[str,int] = {}
seen_fills:set[tuple] = set()
last_seq:int | None = Noneclient = None #AsyncSecureClient when livedef 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}asyncdef stream(path: str,handler,silence_s: float | None = None) -> None:backoff = 1while True:try:asyncwithwebsockets.connect(HOST + path,additional_headers=sign_headers(path),ping_interval=20,ping_timeout=30)as ws:backoff = 1while True:
# A socket can stay open and go quiet. Treatsilenceas a drop.
raw = awaitasyncio.wait_for(ws.recv(),timeout=silence_s)awaithandler(json.loads(raw))except asyncio.TimeoutError:log.warning("%s silent for %ss: reconnecting",path,silence_s)except websockets.ConnectionClosedas e:code,reason = (e.rcvd.code,e.rcvd.reason)ife.rcvdelse(None,"")log.warning("%s closed: %s %s",path,code,reason)if"CREDIT_LIMIT"inreason:log.error("out of credits: stopping %s",path)return # fix the refusal before retryingexcept Exceptionas e:log.warning("%s error: %s",path,e)backoff = min(backoff * 2,30)awaitasyncio.sleep(backoff) # fresh signature on every reconnect
# ---- UMA guard ----
asyncdef on_uma(f: dict) -> None:global last_seqiff.get("type") != "uma":iff.get("type") == "error":log.error("uma error: %s",f)returnseq = f.get("seq")ifseq 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)ifseq is not None:last_seq = seqcid = f.get("condition_id")ifnot cid:returnresolving.add(cid)iff.get("stage") == "disputed"and orders_per_market.get(cid):log.info("DISPUTE on %s (%s): cancelling orders",cid,f.get("title"))ifnot DRY_RUN:awaitclient.cancel_market_orders(market=cid)
# ---- trade signal ----
asyncdef on_trade_frame(f: dict) -> None:iff.get("type") == "snapshot":fortinf.get("trades",[]):seen_fills.add((t.get("transactionHash"),t["assetId"],t["side"]))returniff.get("type") != "trade":returnt = f["trade"]key = (t.get("transactionHash"),t["assetId"],t["side"])ifkeyinseen_fills:returnseen_fills.add(key)cid = t.get("conditionId")if(t["side"] != "BUY"or t["amount"] < MIN_AMOUNTor not(PRICE_MIN <= t["price"] <= PRICE_MAX)or not cid):returniftime.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:returnifcidinresolving:log.info("skip %s: UMA activity on this market",t.get("marketQuestion"))returniforders_per_market.get(cid,0) >= MAX_ORDERS_PER_MARKET:returnawaitplace(t,cid)asyncdef 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) + 1log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",t.get("marketQuestion"),t["outcome"],price,t["amount"],t["trader"])if DRY_RUN:returnexpiration = int(time.time()) + 60 + ORDER_LIFETIME_Sr = awaitclient.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_idifr.okelser.message)asyncdefmain() -> None:global clientifnot DRY_RUN:from polymarket importAsyncSecureClientclient = awaitAsyncSecureClient.create(private_key=os.environ["POLYMARKET_PRIVATE_KEY"],wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],)try:awaitasyncio.gather(stream(UMA_PATH,on_uma),stream(TRADES_PATH,on_trade_frame,silence_s=30))finally:ifclient is not None:awaitclient.cancel_all() # kill switchon exitasyncio.run(main())
# pip install websockets polymarket-client
# Educational example. Notfinancial advice. DRY_RUNis on by default.
importasyncio,hashlib,hmac,json,logging,os,timeimportwebsocketsDRY_RUN = TrueMIN_AMOUNT = 5000 # USD notional of the trade we followPRICE_MIN,PRICE_MAX = 0.10,0.90ORDER_SIZE = "5" # sharesMAX_ORDERS_PER_MARKET = 1ORDER_LIFETIME_S = 600MAX_TRADE_AGE_MS = 5000HOST = "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 withUMA activity
orders_per_market:dict[str,int] = {}
seen_fills:set[tuple] = set()
last_seq:int | None = Noneclient = None #AsyncSecureClient when livedef 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}asyncdef stream(path: str,handler,silence_s: float | None = None) -> None:backoff = 1while True:try:asyncwithwebsockets.connect(HOST + path,additional_headers=sign_headers(path),ping_interval=20,ping_timeout=30)as ws:backoff = 1while True:
# A socket can stay open and go quiet. Treatsilenceas a drop.
raw = awaitasyncio.wait_for(ws.recv(),timeout=silence_s)awaithandler(json.loads(raw))except asyncio.TimeoutError:log.warning("%s silent for %ss: reconnecting",path,silence_s)except websockets.ConnectionClosedas e:code,reason = (e.rcvd.code,e.rcvd.reason)ife.rcvdelse(None,"")log.warning("%s closed: %s %s",path,code,reason)if"CREDIT_LIMIT"inreason:log.error("out of credits: stopping %s",path)return # fix the refusal before retryingexcept Exceptionas e:log.warning("%s error: %s",path,e)backoff = min(backoff * 2,30)awaitasyncio.sleep(backoff) # fresh signature on every reconnect
# ---- UMA guard ----
asyncdef on_uma(f: dict) -> None:global last_seqiff.get("type") != "uma":iff.get("type") == "error":log.error("uma error: %s",f)returnseq = f.get("seq")ifseq 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)ifseq is not None:last_seq = seqcid = f.get("condition_id")ifnot cid:returnresolving.add(cid)iff.get("stage") == "disputed"and orders_per_market.get(cid):log.info("DISPUTE on %s (%s): cancelling orders",cid,f.get("title"))ifnot DRY_RUN:awaitclient.cancel_market_orders(market=cid)
# ---- trade signal ----
asyncdef on_trade_frame(f: dict) -> None:iff.get("type") == "snapshot":fortinf.get("trades",[]):seen_fills.add((t.get("transactionHash"),t["assetId"],t["side"]))returniff.get("type") != "trade":returnt = f["trade"]key = (t.get("transactionHash"),t["assetId"],t["side"])ifkeyinseen_fills:returnseen_fills.add(key)cid = t.get("conditionId")if(t["side"] != "BUY"or t["amount"] < MIN_AMOUNTor not(PRICE_MIN <= t["price"] <= PRICE_MAX)or not cid):returniftime.time() * 1000 - t["timestamp"] > MAX_TRADE_AGE_MS:returnifcidinresolving:log.info("skip %s: UMA activity on this market",t.get("marketQuestion"))returniforders_per_market.get(cid,0) >= MAX_ORDERS_PER_MARKET:returnawaitplace(t,cid)asyncdef 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) + 1log.info("FOLLOW %s | %s @ %s | trigger $%.0f by %s",t.get("marketQuestion"),t["outcome"],price,t["amount"],t["trader"])if DRY_RUN:returnexpiration = int(time.time()) + 60 + ORDER_LIFETIME_Sr = awaitclient.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_idifr.okelser.message)asyncdefmain() -> None:global clientifnot DRY_RUN:from polymarket importAsyncSecureClientclient = awaitAsyncSecureClient.create(private_key=os.environ["POLYMARKET_PRIVATE_KEY"],wallet=os.environ["POLYMARKET_WALLET_ADDRESS"],)try:awaitasyncio.gather(stream(UMA_PATH,on_uma),stream(TRADES_PATH,on_trade_frame,silence_s=30))finally:ifclient is not None:awaitclient.cancel_all() # kill switchon exitasyncio.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.
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.
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:
Run in dry run for at least a few days and read the logs.
Log every skipped trade with its reason.
Keep orders small and capped per market.
Alert on seq gaps and on silent sockets. The script reconnects on silence; add an alert too.
Check a market with GET /uma/market before the first order.
Read each market's resolution rules. A large buy is not information you can verify.
Keep cancel_all() one command away.
This guide is educational. It is not financial advice, and nothing here suggests the strategy is profitable.