Pakistan Ka Pehla Professional Trading Bot CourseModule 1

1.1Prediction Markets Ka Khel — Yeh Gambling Nahi Hai

25 min 5 code blocks Practice Lab Homework Quiz (4Q)

The CLOB API Architecture: Prediction Market Execution

In high-frequency prediction market trading, we don't use simple swaps. We interface directly with the Central Limit Order Book (CLOB) API. This lesson teaches the technical architecture of the Polymarket CLOB and how to manage order-book depth for high-fidelity execution.

🏗️ The CLOB Stack

  1. The API Client: py-clob-client (Python).
  2. The Wallet: EOA (Externally Owned Account) on the Polygon network.
  3. The Order Types: Limit Orders (for specific price entry) vs. Market Orders (for immediate liquidity capture).
Technical Snippet

Technical Snippet: Initializing the CLOB Client

python
from clob_client.client import ClobClient

def initialize_oracle_client(private_key):
    client = ClobClient(
        host="https://clob.polymarket.com",
        key=private_key,
        chain_id=137 # Polygon
    )
    # Create an API Key for automated signing
    api_creds = client.create_api_key()
    return client, api_creds
Key Insight

Nuance: Gasless Trading

Polymarket's CLOB uses an Off-chain Matching / On-chain Settlement model. Your bot signs the order hash locally (free) and only pays for the execution if the trade is matched. This allows for high-volume order canceling without burning MATIC.

📊 CLOB vs AMM — Which Is Better for Bots?

FeatureCLOB (Polymarket)AMM (Uniswap-style)
Price controlExact limit priceMarket price only
SlippageMinimal on deep marketsDepends on pool depth
SpeedNear-instant matchingRequires block confirmation
Gas costOff-chain signing = freeEvery swap pays gas
Bot-friendlyYes — REST + WebSocketRequires on-chain calls
Best forHigh-frequency, preciseDeFi token swaps

For a prediction market bot, CLOB wins on every dimension that matters.

🔑 Order Types Explained

code
ORDER TYPE COMPARISON
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

LIMIT ORDER (Preferred for bots)
┌──────────────────────────────────────┐
│ Bot says: "Buy 100 YES shares        │
│            at exactly $0.72 or less" │
│                                      │
│ Result: Waits in order book until    │
│         a seller matches the price   │
│         (or order expires)           │
└──────────────────────────────────────┘

MARKET ORDER (Use with caution)
┌──────────────────────────────────────┐
│ Bot says: "Buy 100 YES shares        │
│            at whatever price exists" │
│                                      │
│ Result: Fills immediately at best    │
│         available ask — risk of      │
│         high slippage on thin books  │
└──────────────────────────────────────┘
Practice Lab

Practice Lab: Order Book Discovery

  1. Setup: Install py-clob-client.
  2. Fetch: Use the get_orderbook(market_id) method to retrieve the active Bids and Asks for a high-volume market.
  3. Analyze: Identify the "Spread" (the difference between the highest bid and lowest ask). Calculate the potential slippage for a $1,000 order.

📺 Recommended Videos & Resources

  • py-clob-client Official Documentation — Complete library reference and examples
    • Type: GitHub Documentation
    • Link description: Search GitHub for "polymarket py-clob-client" for the latest API documentation
  • Polygon Network Setup Guide — Polygon (MATIC) blockchain fundamentals
    • Type: Official Documentation
    • Link description: Learn about Polygon network, EOA accounts, and transaction signing
  • Web3.py Cryptography & Signing — Python library for blockchain interaction and order signing
    • Type: Documentation
    • Link description: Search "Web3.py documentation cryptography" for transaction signing tutorials
  • Cryptographic Hashing in Python — hashlib library for generating order hashes
    • Type: Python Official Docs
    • Link description: Reference for hash generation using SHA-256 and similar algorithms
  • Polymarket CLOB API Endpoint Reference — Real endpoint structure and response formats
    • Type: API Documentation
    • Link description: Bookmark this for understanding the actual CLOB endpoints and parameters

🎯 Mini-Challenge

5-Minute Practical Task: Set up a local Polygon testnet environment using MetaMask or Hardhat. Create a test EOA (Externally Owned Account), fund it with testnet MATIC from a faucet, and verify you can call the py-clob-client library to fetch your account balance. Screenshot the successful output and note your account address.

🖼️ Visual Reference

code
📊 CLOB Order Flow Architecture
┌──────────────────────────────────────────────┐
│  Python Bot (Your Code)                      │
│  - Creates Order Object                      │
│  - Signs Hash Locally (Free)                 │
└──────────────┬───────────────────────────────┘
               │
               ▼
┌──────────────────────────────────────────────┐
│  CLOB API (Polymarket Servers)               │
│  - Off-chain Matching Engine                 │
│  - Validates Order Signature                 │
└──────────────┬───────────────────────────────┘
               │
               ▼
┌──────────────────────────────────────────────┐
│  Polygon Blockchain Settlement               │
│  - On-chain Only if Trade Matched            │
│  - Zero Gas if Not Filled (Gasless!)         │
└──────────────────────────────────────────────┘

🇵🇰 Pakistan Case Study: Trading During Pakistani Night

The Timezone Advantage: Pakistan Standard Time (PKT = UTC+5) creates a natural edge. When it is 11pm in Karachi, it is:

  • 6pm in London (UK market close)
  • 1pm in New York (US afternoon session)
  • 7am in Tokyo (Asian market open)

News breaks at US market close that Western traders initially misprice because their analysts have gone home. A Pakistani developer running a CLOB bot between 10pm–3am PKT catches this window.

PKR Math on a Small Account:

code
Starting capital: $100 (≈ PKR 28,000)
CLOB limit order: Buy 50 YES shares at $0.74
If market resolves YES:
  Payout: 50 × $1.00 = $50
  Cost:   50 × $0.74 = $37
  Profit: $13 (≈ PKR 3,640) in one trade

Monthly target (4 similar trades):
  Gross profit: $52 (≈ PKR 14,560)
  MATIC gas (negligible on Polygon): ~$0.50
  Net: ≈ PKR 14,420/month on PKR 28,000 = 51% ROI

Local Payment Note: To fund a Polygon wallet from Pakistan, use Binance P2P with JazzCash or EasyPaisa to buy USDC, then bridge to Polygon. This is the most reliable fiat-to-CLOB pipeline for Pakistani traders as of 2026.

Homework

Homework: The Order Signer

Write a Python function that takes a market_id, side (BUY/SELL), and price. The function must generate a signed order hash ready for the CLOB API.

Key Takeaways

  • The CLOB is an off-chain matching engine that settles on-chain — your bot signs for free and only pays gas when a trade actually fills
  • Limit orders are the professional choice for bots: they guarantee price entry and avoid slippage on thin order books
  • CLOB is strictly superior to AMM for prediction market bots because it offers precise price control, minimal spread cost, and WebSocket-based real-time data
  • Pakistani traders operating in the 10pm–3am PKT window have a measurable information arbitrage advantage against Western traders who are asleep
  • To fund your bot from Pakistan: Binance P2P (JazzCash/EasyPaisa) → USDC → Polygon bridge is the cleanest fiat-to-CLOB pipeline

Order Book Depth Analysis

Understanding the order book is the difference between executing at your intended price and losing 5-10% to slippage on a thin book.

python
def analyze_order_book_depth(client, market_id: str, trade_size_usd: float) -> dict:
    """
    Analyze if a market has sufficient liquidity for your trade size.
    Returns slippage estimate and recommended order type.
    """
    book = client.get_order_book(market_id)

    # Sum available liquidity on the ask side (for buying YES)
    asks = sorted(book['asks'], key=lambda x: float(x['price']))

    cumulative_liquidity = 0
    weighted_avg_price = 0

    for ask in asks:
        price = float(ask['price'])
        size = float(ask['size'])
        value = price * size

        if cumulative_liquidity + value >= trade_size_usd:
            # How much do we fill at this price level?
            remaining = trade_size_usd - cumulative_liquidity
            weighted_avg_price += (remaining / trade_size_usd) * price
            cumulative_liquidity = trade_size_usd
            break
        else:
            weighted_avg_price += (value / trade_size_usd) * price
            cumulative_liquidity += value

    best_ask = float(asks[0]['price']) if asks else None
    slippage_pct = ((weighted_avg_price - best_ask) / best_ask * 100) if best_ask else None

    return {
        "best_ask": best_ask,
        "weighted_avg_for_trade": round(weighted_avg_price, 4),
        "estimated_slippage_pct": round(slippage_pct, 2) if slippage_pct else None,
        "recommendation": "USE_LIMIT" if slippage_pct and slippage_pct > 1.0 else "MARKET_OK",
        "sufficient_liquidity": cumulative_liquidity >= trade_size_usd
    }

# Usage:
# result = analyze_order_book_depth(client, "market-123", 100.0)
# Output: {"best_ask": 0.72, "weighted_avg_for_trade": 0.741,
#          "estimated_slippage_pct": 2.92, "recommendation": "USE_LIMIT"}

The Pakistani Trader's Starting Capital Guide

Starting capital determines which markets you can trade and what position sizing is practical:

Starting CapitalPKR EquivalentPractical Position SizeMarkets Per MonthMonthly Target
$100PKR 28,000$5–$10 per trade8–12$12–$20
$250PKR 70,000$12–$25 per trade8–12$30–$50
$500PKR 140,000$25–$50 per trade10–15$60–$100
$1,000PKR 280,000$50–$100 per trade12–20$120–$200

Starting recommendation for Pakistani traders: $200–$500 (PKR 56,000–140,000). Below $100, transaction overhead erodes returns. Above $1,000 in the first 3 months, you're risking more than you've learned to protect.

The goal in months 1-3 is not profit — it's calibration. Learn the system, test your signal accuracy, understand how your bot behaves in real markets. Scale capital only after you've proven a positive expected value across 30+ trades.

Lesson Summary

Includes hands-on practice labHomework assignment included5 runnable code examples4-question knowledge check below

Quiz: The CLOB API Architecture: Prediction Market Execution

4 questions to test your understanding. Score 60% or higher to pass.