5.3 — Capstone: Launch Your Polymarket Trading Bot
Capstone: Launch Your Polymarket Trading Bot
Bhai, ye raha final lesson — ab sab kuch combine karo aur apna Polymarket trading bot launch karo. Data pipeline, AI signal engine, trading strategies, risk management, monitoring — sab ek production system mein. This bot will analyze markets, generate signals, execute trades, and report results 24/7 while you sleep.
Complete Bot Architecture
┌───────────────────────────────────────────────────────────┐
│ POLYMARKET ORACLE │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 1. DATA │ │ 2. NEWS │ │ 3. SIGNAL │ │
│ │ COLLECTOR │ │ SCANNER │ │ ENGINE │ │
│ │ │ │ │ │ │ │
│ │ Every │ │ Every │ │ Every │ │
│ │ 15 min │ │ 30 min │ │ hour │ │
│ │ │ │ │ │ │ │
│ │ Polymarket│ │ Reuters │ │ Stage 1: │ │
│ │ API → │ │ Dawn │ │ Gemini │ │
│ │ SQLite │ │ Twitter │ │ Flash │ │
│ │ │ │ → SQLite │ │ │ │
│ │ Markets, │ │ │ │ Stage 2: │ │
│ │ prices, │ │ Headlines,│ │ Claude │ │
│ │ volumes │ │ sentiment │ │ Haiku │ │
│ │ │ │ │ │ │ │
│ └─────┬─────┘ └─────┬─────┘ │ Stage 3: │ │
│ │ │ │ Claude │ │
│ └────────────────┴──────────┤ Sonnet │ │
│ └─────┬─────┘ │
│ │ │
│ ┌──────────┐ ┌──────────┐ ┌──────┴─────┐ │
│ │ 6. MONITOR│ │ 5. EXEC │ │ 4. STRATEGY│ │
│ │ │ │ │ │ ROUTER │ │
│ │ P&L track │ │ Polymarket│ │ │ │
│ │ Telegram │ │ CLOB API │ │ Theta │ │
│ │ alerts │ │ Limit │ │ Sniper │ │
│ │ Daily │ │ orders │ │ OR │ │
│ │ summary │ │ │ │ Geo Scout │ │
│ │ │ │ │ │ │ │
│ └──────────┘ └──────────┘ └────────────┘ │
│ │
└───────────────────────────────────────────────────────────┘
Component Integration
The Main Entry Point
# main.py — Bot orchestrator
import asyncio
import schedule
import signal
import sys
from datetime import datetime
from components.data_collector import DataCollector
from components.news_scanner import NewsScanner
from components.signal_engine import SignalEngine
from components.strategy_router import StrategyRouter
from components.executor import Executor
from components.monitor import Monitor
from config import Config
class PolymarketOracle:
def __init__(self):
self.config = Config.load("config.yaml")
self.collector = DataCollector(self.config)
self.scanner = NewsScanner(self.config)
self.engine = SignalEngine(self.config)
self.router = StrategyRouter(self.config)
self.executor = Executor(self.config)
self.monitor = Monitor(self.config)
self.running = True
async def run_pipeline(self):
"""Full pipeline: collect → scan → signal → route → execute → monitor."""
try:
# Step 1: Fetch latest market data
markets = await self.collector.fetch_active_markets()
print(f"[{datetime.now()}] Tracking {len(markets)} markets")
# Step 2: Scan news for relevant headlines
articles = await self.scanner.fetch_and_filter()
print(f"[SCAN] {len(articles)} relevant articles found")
# Step 3: Generate trading signals
signals = await self.engine.generate_signals(markets, articles)
print(f"[SIGNAL] {len(signals)} actionable signals")
# Step 4: Route signals to strategies
for signal in signals:
strategy = self.router.select_strategy(signal)
trade = strategy.evaluate(signal)
if trade and trade["action"] != "SKIP":
# Step 5: Execute trade
if self.config.mode == "live":
result = await self.executor.place_order(trade)
else:
result = self.executor.paper_trade(trade)
# Step 6: Log and alert
self.monitor.log_trade(trade, result)
if trade["action"] == "BUY":
await self.monitor.send_alert(
f"🟢 BUY {trade['market_id']}\n"
f"Price: ${trade['price']}\n"
f"Size: ${trade['size']}\n"
f"Strategy: {trade['strategy']}\n"
f"Confidence: {trade['confidence']:.0%}"
)
except Exception as e:
await self.monitor.send_alert(f"🔴 PIPELINE ERROR: {str(e)}")
print(f"[ERROR] Pipeline failed: {e}")
async def run_daily_report(self):
"""Generate and send daily P&L report."""
report = self.monitor.generate_daily_report()
await self.monitor.send_alert(report)
def start(self):
"""Start the bot with scheduled tasks."""
print("=" * 50)
print(" POLYMARKET ORACLE — Starting...")
print(f" Mode: {self.config.mode}")
print(f" Max position: ${self.config.max_position}")
print(f" Daily loss limit: ${self.config.max_daily_loss}")
print("=" * 50)
# Schedule tasks
schedule.every(15).minutes.do(
lambda: asyncio.run(self.run_pipeline())
)
schedule.every().day.at("23:00").do(
lambda: asyncio.run(self.run_daily_report())
)
# Graceful shutdown
signal.signal(signal.SIGINT, lambda s, f: self._shutdown())
signal.signal(signal.SIGTERM, lambda s, f: self._shutdown())
while self.running:
schedule.run_pending()
asyncio.get_event_loop().run_until_complete(asyncio.sleep(30))
def _shutdown(self):
print("\n[SHUTDOWN] Graceful shutdown initiated...")
self.running = False
self.monitor.generate_daily_report()
sys.exit(0)
if __name__ == "__main__":
oracle = PolymarketOracle()
oracle.start()
Configuration File
# config.yaml
mode: paper # "paper" or "live"
# Risk management
max_position: 50 # Max $ per trade
max_daily_loss: 25 # Stop trading if daily loss exceeds
max_portfolio: 200 # Max total exposure across all positions
max_trades_per_day: 20 # Circuit breaker
# Market selection
min_volume: 50000 # Only trade markets with $50K+ volume
min_edge: 0.10 # Minimum probability edge (10%)
min_confidence: 0.65 # Minimum AI confidence score
price_range: [0.15, 0.85] # Avoid extreme prices
# AI configuration
gemini_key: ${GEMINI_API_KEY}
claude_key: ${ANTHROPIC_API_KEY}
signal_model: "claude-sonnet-4-6"
filter_model: "gemini-2.5-flash"
# News sources
news_sources:
- name: reuters
url: "https://feeds.reuters.com/reuters/worldNews"
- name: dawn
url: "https://www.dawn.com/feeds/home"
- name: business_recorder
url: "https://www.brecorder.com/feeds"
# Notifications
telegram_bot_token: ${TELEGRAM_BOT_TOKEN}
telegram_chat_id: ${TELEGRAM_CHAT_ID}
# Database
db_path: "oracle.db"
Launch Checklist
Before going live, verify all 10 items:
| # | Check | How to Verify | Status |
|---|---|---|---|
| 1 | Polymarket API keys | Place $1 test trade, verify it appears | ☐ |
| 2 | Database initialized | Run python -c "from db import init; init()" | ☐ |
| 3 | AI API keys working | Run signal engine on 3 test markets | ☐ |
| 4 | Signal accuracy | Backtest on 10 historical markets → >60% | ☐ |
| 5 | Risk limits configured | Verify config.yaml limits match your bankroll | ☐ |
| 6 | Telegram alerts | Send test alert, confirm delivery | ☐ |
| 7 | VPS provisioned | SSH in, Python 3.11+ installed | ☐ |
| 8 | PM2 configured | pm2 start main.py --name oracle, verify restart | ☐ |
| 9 | Database backup cron | crontab -e: daily backup to Google Drive | ☐ |
| 10 | 2-week paper trading | Positive returns in simulation | ☐ |
Going Live: The First Week Protocol
DAY 1: LAUNCH
├── Deploy to VPS with PM2 (auto-restart on crash)
├── Start with Theta Sniper ONLY (safest strategy)
├── Max position: $10 per trade (minimum viable bet)
├── Monitor EVERY trade via Telegram — don't trust blindly
├── Check: Are signals firing? Are orders executing? Is P&L tracking?
└── End of day: Review all trades. Any errors? Any missed signals?
DAY 2-3: VALIDATE
├── If Theta Sniper win rate > 55%: Continue
├── If win rate < 50%: Check signal calibration
│ ├── Are you entering too early? (Increase min_confidence to 0.75)
│ ├── Are you entering too late? (Decrease pipeline interval to 10 min)
│ └── Is the AI miscalibrated? (Review reasoning in signal logs)
├── Compare paper trading results vs. live results
└── Any slippage? Check limit order pricing strategy
DAY 4-5: ADD STRATEGY
├── Enable Geo Scout alongside Theta Sniper
├── Still at $10 max per trade
├── Two strategies diversify across different market types
├── Check: Do the strategies ever conflict? (Both say buy on same market)
└── If conflict: Theta Sniper takes priority (more conservative)
DAY 6-7: WEEKLY REVIEW
├── Total trades executed
├── Win rate per strategy
├── Average profit per winning trade
├── Average loss per losing trade
├── Max drawdown (largest peak-to-trough decline)
├── Total P&L for the week
│
├── IF POSITIVE: Continue to Week 2 (scale phase)
└── IF NEGATIVE: Go back to paper trading, debug signal engine
Scaling Protocol
WEEK 1: $10/trade (validation)
WEEK 2: $10/trade (confirmation)
WEEK 3: $25/trade (first scale)
WEEK 4: $25/trade (confirmation)
MONTH 2: $50/trade (if consistently profitable)
MONTH 3: $100/trade (if 60%+ win rate sustained)
NEVER:
├── Risk more than 5% of bankroll on single trade
├── Scale up after a losing week (scale ONLY after winning weeks)
├── Increase both position size AND number of trades simultaneously
└── Go from $10 to $100 in one jump (gradual scaling catches errors)
BANKROLL MANAGEMENT:
Starting bankroll: $200 (PKR 56,000)
├── Week 1-2: $10 max × 20 trades = $200 max exposure (100%)
├── If profitable: Add $200 more (bankroll = $400 + profits)
├── Month 2: $50 max × 10 positions = $500 max exposure
└── Month 3+: Scale based on Sharpe ratio, not feelings
Common Failure Modes & Fixes
| Failure Mode | Symptom | Fix |
|---|---|---|
| Overconfidence | AI says 85% but market says 70% | Trust market more initially. Only override when your edge source is clear |
| API rate limits | 429 errors from Polymarket | Add exponential backoff: wait 2^n seconds between retries |
| Stale data | Signal based on 3-hour-old news | Add freshness check: reject signals from data > 2 hours old |
| Slippage | Model says buy at $0.65, executed at $0.68 | Use limit orders always. Set max slippage tolerance (3 cents) |
| Weekend gaps | Markets move on weekends, bot is slow | Add weekend monitoring schedule (check every 2 hours) |
| Correlation risk | 3 positions all on Pakistan events | Max 2 positions on correlated markets. Diversify themes |
| AI hallucination | Signal engine invents facts | Always verify reasoning against actual headlines in log |
| Database corruption | SQLite locked during concurrent writes | Use WAL mode: PRAGMA journal_mode=WAL |
Cost Analysis (Pakistani Trader)
MONTHLY OPERATING COSTS:
VPS (DigitalOcean $5 or Contabo): PKR 1,400
Gemini API (Flash filter): Free tier
Claude API (Haiku + Sonnet): PKR 2,800 (~$10)
Telegram Bot: Free
Domain (optional): PKR 200
────────────────────────────────────────────────────
TOTAL INFRASTRUCTURE: PKR 4,400/month
TRADING CAPITAL:
Starting bankroll: PKR 56,000 ($200)
Monthly top-up (if scaling): PKR 28,000 ($100)
FUNDING PATH:
PKR → Binance P2P → USDC → Polygon → Polymarket
Fee: ~1-2% total (P2P spread + network fee)
BREAK-EVEN ANALYSIS:
Monthly cost: PKR 4,400
At $10/trade, need ~3 profitable trades/month to cover costs
At 60% win rate, 20 trades/month → 12 wins
Average win: $3-5 per trade → $36-60/month profit
After costs: $26-50/month = PKR 7,300-14,000
Month 3+ at $50/trade:
Average win: $15-25 → $180-300/month
After costs: $164-284/month = PKR 46,000-80,000/month
Your Capstone Deliverables
| # | Deliverable | Verification |
|---|---|---|
| 1 | Working bot deployed on VPS | All 6 components start and run without errors |
| 2 | 2 weeks paper trading | Positive returns, >55% win rate documented |
| 3 | Risk management dashboard | Live P&L, drawdown, exposure tracking in SQLite |
| 4 | Telegram integration | Trade alerts + daily P&L summary received |
| 5 | Documentation | README: architecture, setup, strategy params, troubleshooting |
| 6 | Signal accuracy report | Backtest on 20 historical markets with results table |
Practice Lab
Task 1: Full Deployment Deploy your bot to a VPS (DigitalOcean $5/month or Contabo). Verify all 6 components start correctly with PM2. Trigger a manual pipeline run and confirm: data collection, news scanning, signal generation, and Telegram alert all work.
Task 2: 48-Hour Paper Trading Run paper trading for 48 hours. Analyze: how many signals fired? How many trades would have been executed? What's the paper P&L? Are there any signals that look wrong (AI confidence high but trade would have lost)?
Task 3: Telegram Dashboard Set up your Telegram alerts. Configure: trade alerts (every trade), daily summary (11 PM), and error alerts (any pipeline failure). Run for 24 hours and verify all 3 alert types are received.
Pakistan Case Study
Meet Owais — software engineer at a Karachi fintech, built his Polymarket bot as a side project.
Month 0 (Setup):
- Completed this course over 3 weekends
- Hardware: Contabo VPS (PKR 1,500/month)
- Starting bankroll: $200 (PKR 56,000 via Binance P2P)
- Focus: SBP monetary policy + Pakistan political markets
Month 1 (Paper Trading):
- 2 weeks paper trading: 58% win rate on Theta Sniper
- Identified edge: Dawn breaks SBP news 3-4 hours before Reuters
- Paper P&L: +$32 on $200 bankroll (16% monthly return)
- Bugs found: timezone mismatch in news timestamps, fixed in Day 3
Month 2 (Live — $10 trades):
- Went live on Day 1 of Month 2
- 47 trades, 28 wins (59.6% win rate)
- Big win: SBP rate decision market — bought YES at $0.38, sold at $0.72 ($3.40 profit per share, 100 shares = $34)
- Big loss: Cricket World Cup market — emotional override of bot signal ($-18)
- Monthly P&L: +$48 (24% return)
- Lesson learned: NEVER override the bot's decision with gut feeling
Month 3 (Scaled — $25 trades):
- Increased to $25/trade after 2 consecutive profitable weeks
- Added Geo Scout strategy alongside Theta Sniper
- 52 trades, 33 wins (63.5%)
- Monthly P&L: +$142 (35% return on growing bankroll)
- Total bankroll: $200 + $48 + $142 + $100 top-up = $490
Month 6 (Current):
- Trading at $50-75/trade
- Bankroll: $1,340
- Monthly P&L: $280-380 (PKR 78,000-106,000)
- Monthly costs: PKR 4,400
- Net monthly income: PKR 74,000-102,000
- Still working full-time job — bot runs autonomously
- Total time spent per week: 2-3 hours (reviewing trades + weekly calibration)
His key insight: "Sabse important cheez patience thi. Pehle 2 hafte paper trading kiye — boring tha, but usne mujhe dikhaya ki mera system actually kaam karta hai. Phir $10 se shuru kiya — slow tha, but main ne har bug pakda. Ab $50-75 pe trade karta hoon aur monthly PKR 80K+ aata hai while I sleep. The bot's edge is real: Pakistani news sources + AI speed + systematic execution. Gut feeling gamblers can't compete with that."
Key Takeaways
- Launch with MINIMUM risk ($10/trade) and scale only after PROVEN profitability
- Paper trade for 2 weeks — this is non-negotiable. It catches bugs and validates your edge
- Fund via Binance P2P → USDC → Polygon — the Pakistani path works, ~1-2% total fees
- The 6 components (collector, scanner, signal engine, strategy router, executor, monitor) must all work independently and together
- Never risk more than 5% of bankroll on a single trade — position sizing is more important than signal accuracy
- Scale gradually: $10 → $25 → $50 → $100, only after winning weeks, never after losing weeks
- Monitor daily — even automated systems need human oversight. Review Telegram alerts every morning
- Monthly cost: PKR 4,400 — achievable for any Pakistani developer/student
- Pakistani news advantage is real: Dawn/BR break South Asian news hours before Western wire services
- The compounding effect: $200 starting → $1,000+ in 6 months is achievable at 20-30% monthly returns
Congratulations! You've completed the Polymarket Oracle course. You now have a complete trading bot — from data pipeline to AI signals to execution to monitoring. Deploy it, validate it, scale it. The edge is yours.
Lesson Summary
Launch Your Trading Bot Capstone Quiz
4 questions to test your understanding. Score 60% or higher to pass.