Scan prediction markets, filter profitable opportunities, and execute trades automatically with Python.
Prediction markets have become one of the most interesting applications of blockchain technology. Platforms like Polymarket allow traders to speculate on everything from cryptocurrency prices to politics, sports, and world events.
The challenge isn't placing trades—it's finding opportunities quickly enough.
When hundreds of markets are active simultaneously, manually checking prices, liquidity, and spreads becomes tedious. That's exactly why I built an automated trading bot in Python.
The bot continuously scans Polymarket, evaluates markets based on configurable rules, checks liquidity, and executes trades automatically.
The entire project is open source.
GitHub Repository
👉 https://github.com/mateosoul/Polymarket-Trading-Bot-Python
What We'll Build
By the end of this tutorial you'll understand how to build a bot that can:
- Connect to Polymarket
- Scan active prediction markets
- Filter markets using custom rules
- Check wallet balance
- Evaluate bid/ask spreads
- Execute market orders
- Avoid duplicate positions
- Manage trading risk automatically
The architecture is intentionally simple so you can customize it for your own strategies.
Installing Dependencies
Create a virtual environment and install the required packages.
pip install py-clob-client-v2 requests python-dotenv
We'll use:
- py-clob-client-v2 for authenticated trading
- requests for the public APIs
- python-dotenv for securely loading credentials
Configure Your Wallet
Create a .env file.
POLYMARKET_PRIVATE_KEY=YOUR_PRIVATE_KEY
POLYMARKET_FUNDER_ADDRESS=YOUR_WALLET_ADDRESS
Never commit this file to GitHub.
Connecting to Polymarket
The first step is creating an authenticated client.
import os
from dotenv import load_dotenv
from py_clob_client_v2 import ClobClient
load_dotenv()
client = ClobClient(
"https://clob.polymarket.com",
key=os.getenv("POLYMARKET_PRIVATE_KEY"),
chain_id=137,
signature_type=1,
funder=os.getenv("POLYMARKET_FUNDER_ADDRESS"),
)
client.set_api_creds(client.derive_api_key())
Once authenticated, the client can read balances, inspect order books, and submit trades.
Getting Active Markets
Polymarket exposes market information through the Gamma API.
We can retrieve active markets with only a few lines of code.
import requests
GAMMA_API = "https://gamma-api.polymarket.com"
def get_markets():
response = requests.get(
f"{GAMMA_API}/markets",
params={
"active": True,
"closed": False,
"limit": 100,
},
)
return response.json()
The response contains information such as:
- Market title
- Volume
- Prices
- Outcome tokens
- Liquidity
Building a Strategy
A trading bot is only as good as its strategy.
For this example we'll search for crypto markets where:
- YES price is between 15% and 40%
- Daily volume exceeds $10,000
- Liquidity is sufficient
import json
def find_markets():
candidates = []
for market in get_markets():
prices = json.loads(market["outcomePrices"])
volume = float(market["volume24hr"])
if (
len(prices) >= 2
and 0.15 <= float(prices[0]) <= 0.40
and volume >= 10000
):
candidates.append(market)
return candidates
Because the strategy is isolated from the trading engine, you can replace these filters with anything you like.
Examples include:
- Politics
- Sports
- AI markets
- Macroeconomics
- Custom watchlists
Reading Live Prices
Snapshot prices are useful, but trades should always use live order book data.
def get_price(token_id):
return {
"ask": float(client.get_price(token_id, side="BUY")["price"]),
"bid": float(client.get_price(token_id, side="SELL")["price"]),
"spread": float(client.get_spread(token_id)["spread"]),
}
The spread is particularly important.
Wide spreads usually indicate poor liquidity, making trades more expensive than expected.
Risk Management
Even simple bots should have safeguards.
A spread filter is easy to implement.
def should_trade(price):
return price["spread"] < 0.05
You can also add limits such as:
- Maximum number of open positions
- Maximum trade size
- Daily trading limit
- Stop-loss rules
- Profit targets
Risk management matters just as much as the strategy itself.
Executing Orders
Submitting a market order only requires a few lines.
from py_clob_client_v2 import (
MarketOrderArgs,
OrderType,
Side,
)
def buy(token_id, amount):
order = MarketOrderArgs(
token_id=token_id,
amount=amount,
side=Side.BUY,
order_type=OrderType.FOK,
)
signed = client.create_market_order(order)
return client.post_order(signed, OrderType.FOK)
The SDK handles order signing and authentication behind the scenes.
The Main Trading Loop
Now we can combine everything.
def main():
markets = find_markets()
for market in markets:
token_id = json.loads(
market["clobTokenIds"]
)[0]
price = get_price(token_id)
if should_trade(price):
buy(token_id, amount=10)
if __name__ == "__main__":
main()
The workflow is straightforward:
- Scan markets.
- Filter candidates.
- Refresh live prices.
- Check risk rules.
- Execute the trade.
Improving the Bot
The current implementation is intentionally lightweight, but there are plenty of ways to extend it.
Ideas include:
- Telegram notifications
- Discord alerts
- SQLite trade history
- Performance analytics
- Automatic position closing
- Multiple trading strategies
- Backtesting
- Machine learning filters
- Portfolio statistics
- Docker deployment
Because the project is modular, adding new features is relatively easy.
Why Open Source?
I wanted this repository to serve two purposes.
First, it's a useful starting point for anyone interested in algorithmic trading on Polymarket.
Second, it demonstrates how to work with all three major Polymarket APIs in a clean and maintainable Python project.
Whether you're learning APIs, automation, or crypto trading, you can use this project as a foundation for your own ideas.
Complete Source Code
The full project—including configuration, API wrappers, strategy implementation, and execution logic—is available on GitHub.
Repository
https://github.com/mateosoul/Polymarket-Trading-Bot-Python
If you find it useful, feel free to fork it, open issues, or contribute improvements.
⭐ Stars are always appreciated!
Contact
If you have questions, ideas, or want to collaborate on Python automation, trading bots, or blockchain development, feel free to reach out.
Telegram
Thanks for reading, and happy coding!

Top comments (0)