This guide connects two pieces of infrastructure that launched within two weeks of each other: Coinbase’s Agentic Wallets (your agent’s money) and Polymarket’s CLI (your agent’s trading terminal). By the end, you’ll have an agent that can query prediction markets, analyze odds, and place trades autonomously — with spending guardrails that keep risk bounded.
Not sure if Coinbase Agentic Wallets are the right choice for your agent? See the Agent Wallet Comparison for all options.
We’ll build this in five steps, starting with read-only operations (zero risk) and progressively adding capabilities.
Prerequisites
Before you start, make sure you have the following installed and available.
For the wallet (Coinbase Agentic Wallets):
- Node.js 18+ (for the
npx awalCLI) - A Coinbase Developer Platform account (developer.coinbase.com)
- Some USDC to fund the agent (start with $20 for testing)
For trading (Polymarket CLI):
- Rust toolchain (for building from source) OR Homebrew (macOS/Linux)
- No wallet needed for read-only operations — you can browse markets immediately
Optional but recommended:
- A Moltbook identity (see our Layer 1 guide)
jqinstalled for parsing JSON output
Step 1: Browse Markets (Read-Only, No Wallet)
Start here. The Polymarket CLI lets you explore markets, read prices, and check order books without any wallet or authentication. This is your zero-risk sandbox for understanding the data your agent will work with.
Install the CLI
# Option A: Homebrew (recommended)
brew tap Polymarket/polymarket-cli \
https://github.com/Polymarket/polymarket-cli
brew install polymarket
# Option B: Build from source
git clone https://github.com/Polymarket/polymarket-cli
cd polymarket-cli
cargo install --path .
# Option C: Install script
curl -sSL https://raw.githubusercontent.com/Polymarket/polymarket-cli/main/install.sh | sh
Verify the installation
polymarket --version
polymarket status # Check API health
Explore markets
# List active markets
polymarket markets list --limit 10
# Search for specific topics
polymarket markets search "bitcoin"
polymarket markets search "fed rate"
# Browse by category
polymarket events list --tag politics
polymarket events list --tag crypto
# Get details on a specific market
polymarket markets get will-bitcoin-hit-100k
Read order books and prices
# Check the order book for a specific token
polymarket clob book TOKEN_ID
# Get the current midpoint price
polymarket clob midpoint TOKEN_ID
# View price history
polymarket clob price-history TOKEN_ID --interval 1d
JSON output for scripting
Every command supports JSON output — this is what your agent will actually consume:
# Pipe market data through jq
polymarket -o json markets list --limit 100 | jq '.[].question'
# Get midpoint programmatically
polymarket -o json clob midpoint TOKEN_ID | jq '.mid'
# Full market details as structured data
polymarket -o json markets get market-slug | jq '{
question: .question,
yes_price: .tokens[0].price,
volume: .volume
}'
Spend some time here. Run searches, read order books, and get comfortable with the data format. Your intelligence layer (Layer 4) will consume this JSON, so understanding the schema now saves debugging later.
Interactive shell mode
For exploration, the CLI has a REPL mode:
polymarket shell
# polymarket> markets search "bitcoin" --limit 3
# polymarket> clob book TOKEN_ID
# polymarket> exit
Step 2: Set Up Your Agent Wallet
Now let’s give your agent money. Coinbase Agentic Wallets are purpose-built for this: the private key stays locked in Coinbase’s trusted execution environment, the agent never sees it, and you can set spending limits that are enforced at the infrastructure level.
Create the wallet
# The awal CLI handles everything
npx awal
# Follow the guided setup:
# 1. Authenticate with your Coinbase Developer Platform account
# 2. A new wallet is created in Coinbase's secure enclave
# 3. You receive a wallet address and session credentials
Check status and fund
# See your agent's wallet status
npx awal status
# Fund the wallet with USDC (from your Coinbase account)
npx awal fund 20
# Verify the balance
npx awal balance
Start with a small amount. $20 of USDC is more than enough for testing. You can always add more later.
Configure spending limits
This is the critical safety feature. Set limits before your agent ever places a trade:
# Set a session spending cap (total per operating session)
# Example: agent can spend max $10 per session
npx awal config set session-cap 10
# Set per-transaction limit
# Example: no single trade can exceed $2
npx awal config set tx-limit 2
These limits are enforced by Coinbase’s infrastructure, not by your agent’s code. Even if your agent’s decision-making is compromised by a prompt injection attack or a bug, it physically cannot exceed these limits. Adjust them upward only as you build confidence in your agent’s performance.
Test with a simple transfer
# Send a small amount to verify everything works
npx awal send 0.10 YOUR_OWN_ADDRESS
# Trade tokens (gasless on Base)
npx awal trade 1 usdc eth
Step 3: Connect Wallet to Polymarket
Now we bridge Layer 2 and Layer 3. Polymarket operates on the Polygon network and uses proxy wallets (modified Gnosis Safes). You’ll need to get your agent’s key configured for Polymarket’s system.
Import your wallet into the Polymarket CLI
# Option A: Import via private key
# (If your Agentic Wallet provides an exportable key)
polymarket wallet import 0xYOUR_PRIVATE_KEY
# Option B: Create a new Polymarket wallet and fund from Agentic Wallet
polymarket wallet create
polymarket wallet show # Get the address
# Then fund this wallet from your Agentic Wallet
npx awal send 10 POLYMARKET_WALLET_ADDRESS
Approve USDC for trading
# Set up the approval for Polymarket's trading contracts
polymarket approve set # Requires MATIC for gas on Polygon
# Verify your collateral balance
polymarket clob balance --asset-type collateral
Note on bridging: Coinbase Agentic Wallets operate on Base by default, while Polymarket runs on Polygon. You’ll need USDC on Polygon to trade. If your USDC is on Base, bridge it using a cross-chain bridge or send USDC directly to your Polygon address from an exchange. This friction is likely to decrease as cross-chain infrastructure matures.
Verify the connection
# Check your Polymarket orders (should be empty)
polymarket clob orders
# Check your trade history
polymarket clob trades
# Check your positions
polymarket data positions YOUR_ADDRESS
If all three commands return without errors, your wallet is connected and ready to trade.
Step 4: Place Your First Trade
Time to put it all together. We’ll walk through a complete trade lifecycle: find a market, analyze it, place a bet, and monitor the position.
Find a market
# Search for a market you want to trade
polymarket -o json markets search "bitcoin" --limit 5
# Pick one and get the full details
polymarket -o json markets get bitcoin-above-100k
Look at the response for the tokens array. Each market has two tokens: one for “Yes” and one for “No.” You’ll need the token_id of whichever side you want to bet on.
Analyze the opportunity
# Check the order book depth
polymarket clob book TOKEN_ID
# Check recent price movement
polymarket clob price-history TOKEN_ID --interval 1h
For your first trade, pick a market where you have a strong view and the odds are liquid (high volume). Don’t try to be clever with an algorithm — just make a manual decision to verify the mechanics work.
Place a market order
# Buy $2 worth of "Yes" shares
polymarket clob market-order \
--token TOKEN_ID \
--side buy \
--amount 2
# Or place a limit order at a specific price
polymarket clob create-order \
--token TOKEN_ID \
--side buy \
--price 0.45 \
--size 5
Monitor your position
# Check your positions and their current value
polymarket data positions YOUR_ADDRESS
polymarket data value YOUR_ADDRESS
# View your active orders
polymarket clob orders
# Cancel an order if needed
polymarket clob cancel ORDER_ID
# Cancel all open orders
polymarket clob cancel-all
Congratulations — you’ve completed a full loop through Layers 2 and 3. Your agent can now hold money and trade with it on a prediction market.
Step 5: Automate with Scripts
Now let’s turn this from a manual process into something your agent can do autonomously. Here’s a basic Python wrapper that ties the wallet and trading layers together:
Simple market scanner
#!/usr/bin/env python3
"""
agent_scanner.py — Scan Polymarket for opportunities
Uses Layer 3 (Polymarket CLI) in read-only mode.
No wallet needed for this script.
"""
import json
import subprocess
import sys
def run_poly(args):
"""Run a Polymarket CLI command and return parsed JSON."""
result = subprocess.run(
["polymarket", "-o", "json"] + args,
capture_output=True, text=True
)
if result.returncode != 0:
print(f"Error: {result.stderr}", file=sys.stderr)
return None
return json.loads(result.stdout)
def scan_markets(query, limit=20):
"""Scan markets matching a query."""
markets = run_poly(["markets", "search", query, "--limit", str(limit)])
if not markets:
return []
opportunities = []
for market in markets:
yes_price = market.get("tokens", [{}])[0].get("price", 0)
volume = market.get("volume", 0)
# Simple filter: look for markets with meaningful volume
# and prices between 0.20-0.80 (most room for movement)
if volume > 10000 and 0.20 <= yes_price <= 0.80:
opportunities.append({
"question": market["question"],
"yes_price": yes_price,
"implied_prob": f"{yes_price * 100:.1f}%",
"volume": volume,
"slug": market.get("slug", "")
})
return sorted(opportunities, key=lambda x: x["volume"], reverse=True)
if __name__ == "__main__":
query = sys.argv[1] if len(sys.argv) > 1 else "crypto"
print(f"Scanning markets for: {query}\n")
opps = scan_markets(query)
for opp in opps[:10]:
print(f" {opp['question']}")
print(f" Yes: {opp['implied_prob']} | Volume: ${opp['volume']:,.0f}")
print()
Autonomous trader (with safety checks)
#!/usr/bin/env python3
"""
agent_trader.py — Simple autonomous trading loop
Connects Layer 2 (wallet), Layer 3 (trading), and basic Layer 4 (logic).
WARNING: This trades real money. Start with tiny amounts.
"""
import json
import subprocess
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
log = logging.getLogger()
# Safety configuration
MAX_BET_SIZE = 2.0 # Maximum bet in USDC
MAX_DAILY_SPEND = 10.0 # Maximum daily total spend
SCAN_INTERVAL = 300 # Seconds between scans (5 minutes)
MIN_EDGE = 0.10 # Minimum edge (10%) before betting
daily_spent = 0.0
def run_poly(args):
result = subprocess.run(
["polymarket", "-o", "json"] + args,
capture_output=True, text=True
)
if result.returncode != 0:
return None
return json.loads(result.stdout)
def check_balance():
"""Check available collateral balance."""
result = run_poly(["clob", "balance", "--asset-type", "collateral"])
return float(result.get("balance", 0)) if result else 0
def evaluate_market(market):
"""
Simple evaluation function. Replace this with your
Layer 4 intelligence (LLM calls, sentiment analysis, etc.)
Returns: (should_bet, side, confidence)
"""
# PLACEHOLDER: This is where your LLM/analysis goes
# For now, return no action
return False, None, 0.0
def place_bet(token_id, side, amount):
"""Place a market order with safety checks."""
global daily_spent
# Safety check: daily limit
if daily_spent + amount > MAX_DAILY_SPEND:
log.warning(f"Daily limit reached (${daily_spent:.2f}/{MAX_DAILY_SPEND})")
return False
# Safety check: per-bet limit
if amount > MAX_BET_SIZE:
log.warning(f"Bet size ${amount} exceeds max ${MAX_BET_SIZE}")
return False
# Safety check: verify balance
balance = check_balance()
if balance < amount:
log.warning(f"Insufficient balance: ${balance:.2f}")
return False
log.info(f"Placing {side} order: ${amount} on {token_id}")
result = run_poly([
"clob", "market-order",
"--token", token_id,
"--side", side,
"--amount", str(amount)
])
if result:
daily_spent += amount
log.info(f"Order placed. Daily total: ${daily_spent:.2f}")
return True
log.error("Order failed")
return False
def main():
log.info("Agent starting. Max bet: $%.2f, Daily limit: $%.2f",
MAX_BET_SIZE, MAX_DAILY_SPEND)
while True:
try:
# Scan markets
markets = run_poly(["markets", "list", "--limit", "50"])
if not markets:
log.warning("Failed to fetch markets")
time.sleep(SCAN_INTERVAL)
continue
for market in markets:
should_bet, side, confidence = evaluate_market(market)
if should_bet and confidence > MIN_EDGE:
tokens = market.get("tokens", [])
token_id = tokens[0]["token_id"] if side == "buy" else tokens[1]["token_id"]
bet_size = min(confidence * MAX_BET_SIZE, MAX_BET_SIZE)
place_bet(token_id, side, bet_size)
log.info("Scan complete. Sleeping %d seconds.", SCAN_INTERVAL)
time.sleep(SCAN_INTERVAL)
except KeyboardInterrupt:
log.info("Agent stopped by operator.")
break
except Exception as e:
log.error("Error: %s", e)
time.sleep(SCAN_INTERVAL)
if __name__ == "__main__":
main()
The evaluate_market function is deliberately left as a placeholder. This is where your Layer 4 intelligence goes — LLM calls, sentiment analysis, cross-market correlation, whatever your strategy is. The scaffolding around it handles all the wallet and trading mechanics.
Troubleshooting
“Command not found: polymarket”
If you installed via Homebrew, try brew link polymarket. If you built from source, make sure ~/.cargo/bin is in your PATH.
“Insufficient balance” on Polymarket
Your USDC needs to be on the Polygon network. If you funded from a Coinbase Agentic Wallet (which defaults to Base), you’ll need to bridge the funds. Check your wallet address on polygonscan.com to verify your Polygon USDC balance.
“Approval required”
Run polymarket approve set before trading. This authorizes Polymarket’s contracts to interact with your USDC. You’ll need a small amount of MATIC for gas on this one-time transaction.
JSON parsing errors in scripts
Make sure you’re using the -o json flag. Without it, the CLI outputs human-readable tables that won’t parse as JSON.
Wallet won’t connect
Verify your private key format — the Polymarket CLI expects a hex string starting with 0x. Run polymarket wallet show to confirm the wallet address matches what you expect.
What’s Next
You now have a working Layer 2 + Layer 3 setup. Your agent can hold money and trade on prediction markets. The next steps are:
- Add intelligence: Replace the
evaluate_marketplaceholder with real analysis. Start with simple heuristics, then add LLM-powered evaluation. See The Agent Betting Stack for strategy ideas. - Add identity: Register on Moltbook to access premium data providers and build reputation. See Moltbook Identity for Prediction Market Agents.
- Lock down security: Before running your agent in production, read Security Best Practices for Agent Betting.
- Scale carefully: Increase spending limits gradually as you build confidence. Double your limits only after the agent has been profitable at the current limits for at least a week.
- Explore wallet options: See Agent Wallet Comparison for every wallet option compared side by side.
- Learn the APIs: See The Complete Prediction Market API Reference for every endpoint across all platforms.
- Look up terms: See Agent Betting Glossary for definitions of every term in this tutorial.