"""Paper-trade one Polymarket outcome against the live order book. Reads public data only and never sends an order. Simulated buys fill at the real asks and sells at the real bids, level by level, and pay the market's own taker fee. Every decision is appended to paper_trades.csv. python3 paper_trade.py [market-slug] [outcome-index] """ import csv import json import sys import time import urllib.request from datetime import datetime, timezone CLOB = "https://clob.polymarket.com" GAMMA = "https://gamma-api.polymarket.com" SECONDS = 10 # how often to check the book ROUNDS = 6 # how many checks before stopping SIZE = 50 # shares per simulated order TAKE_PROFIT = 0.02 # sell when the bid is 2 cents above our average price STOP_LOSS = 0.03 # sell when the bid is 3 cents below it def get(url): request = urllib.request.Request(url, headers={"User-Agent": "my-polymarket-bot/0.1"}) with urllib.request.urlopen(request, timeout=20) as response: return json.load(response) def fill(levels, shares, fee_rate): """Walk the book. Returns (shares filled, average price, total fee).""" left, cost, fee = shares, 0.0, 0.0 for level in levels: price, size = float(level["price"]), float(level["size"]) take = min(left, size) cost += take * price fee += take * fee_rate * price * (1 - price) left -= take if left <= 0: break done = shares - left return done, (cost / done if done else None), round(fee, 5) slug = sys.argv[1] if len(sys.argv) > 1 else None outcome = int(sys.argv[2]) if len(sys.argv) > 2 else 0 if slug: market = get(GAMMA + "/markets?slug=" + slug)[0] else: market = get(GAMMA + "/markets?active=true&closed=false&limit=1" "&order=volume24hr&ascending=false")[0] token = json.loads(market["clobTokenIds"])[outcome] fee_rate = float((market.get("feeSchedule") or {}).get("rate", 0)) if market.get("feesEnabled") else 0.0 print("paper trading", market["slug"], "outcome", json.loads(market["outcomes"])[outcome], "| taker fee rate", fee_rate) shares, entry, cash, best_bid = 0.0, None, 0.0, None with open("paper_trades.csv", "a", newline="") as log: writer = csv.writer(log) for round_number in range(ROUNDS): book = get(CLOB + "/book?token_id=" + token) bids = sorted(book["bids"], key=lambda l: float(l["price"]), reverse=True) asks = sorted(book["asks"], key=lambda l: float(l["price"])) if not bids or not asks: print("empty book, skipping") else: best_bid, best_ask = float(bids[0]["price"]), float(asks[0]["price"]) action = "hold" # Your strategy goes here. This demo buys once, then exits on a # take-profit or stop-loss measured at the price it could sell at. if shares == 0 and entry is None: done, avg, fee = fill(asks, SIZE, fee_rate) shares, entry, cash = done, avg, cash - done * avg - fee action = "BUY %g @ %.4f fee %.5f" % (done, avg, fee) elif shares and (best_bid >= entry + TAKE_PROFIT or best_bid <= entry - STOP_LOSS): done, avg, fee = fill(bids, shares, fee_rate) cash += done * avg - fee action = "SELL %g @ %.4f fee %.5f" % (done, avg, fee) shares -= done now = datetime.now(timezone.utc).isoformat(timespec="seconds") writer.writerow([now, market["slug"], outcome, best_bid, best_ask, action]) print(now, "bid %.3f ask %.3f" % (best_bid, best_ask), action) if round_number < ROUNDS - 1: time.sleep(SECONDS) mark = shares * best_bid if shares and best_bid else 0.0 print("result: %g shares held, cash %+.2f, value at the bid %.2f, total %+.2f" % (shares, cash, mark, cash + mark))