6.1 — CLOB API 101 — Polymarket Ka Trading Interface
CLOB API 101 — Polymarket Ka Trading Interface
Assalam-o-Alaikum, developers!
Welcome to Module 6 of Pakistan's first professional trading bot course. Pichle modules mein humne strategy banayi, signals generate kiye, aur market ko samjha. Lekin strategy aur signal sab bekaar hain agar aap uss information pe act na kar sako. Yeh module asli game hai — jahan rubber meets the road, aur hamara bot paisa banata ya gavata hai.
COURSE: Pakistan Ka Pehla Professional Trading Bot Course
MODULE 6: Execution Engine — Automatically Orders Place Karna
LESSON 6.1: CLOB API 101 — Polymarket Ka Trading Interface
Ab tak sab theory thi, ab practical shuru. Agar aapka bot market mein order place nahi kar sakta, tou woh sirf ek fancy calculator hai. Aaj hum seekhenge ke Polymarket ke trading engine, yaani CLOB, se direct baat kaise karte hain.
CLOB Kya Cheez Hai? Scene Samjho
CLOB ka matlab hai Central Limit Order Book.
Yeh naam sun ke pareshan nahi hona. Agar aapne kabhi Pakistan Stock Exchange (KSE) pe trading ki hai ya dekhi hai, tou aapko CLOB ka concept already pata hai. Yeh bilkul waisa hi system hai.
- Order Book: Ek list hoti hai jisme saare 'buy' (bids) aur 'sell' (asks) orders jama hote hain.
- Limit: Aap order place karte waqt ek specific price batate ho. "Main 'YES' token 0.60 pe khareedna chahta hoon, uss se mehnga nahi." Yeh ek limit order hai.
- Central: Saare orders ek central jagah pe match hote hain. Jab ek buyer ki price ek seller ki price se match karti hai, trade ho jaati hai.
Yeh system AMM (Automated Market Maker) jaise protocols se bohot fast aur efficient hota hai, isliye high-frequency trading ke liye perfect hai.
Sab se important baat: Polymarket ka CLOB Polygon blockchain pe chalta hai. Iska matlab har trade on-chain, transparent, aur immutable hai. Aapki har trade ko aap PolygonScan pe dekh sakte ho. Yeh Web3 ka asli power hai, aur aap Pakistani developers isko practically use karna seekh rahe ho.
The Tools of the Trade: py_clob_client
Khushkhabri yeh hai ke humein blockchain se direct, low-level pe baat nahi karni. Polymarket ne hamare liye ek zabardast Python library banayi hai: py_clob_client.
Pehle isko install karein. Apna terminal kholo aur likho:
pip install py_clob_client
Yeh library hamare liye saari heavy lifting karegi — authentication, order signing, aur CLOB API se communication. Hum bas isko commands denge.
Step 1: Wallet Setup - Apni Tijori Tayyar Karo
Blockchain pe kuch bhi karne ke liye, aapko ek wallet chahiye. Hamare bot ke liye, do cheezein critical hain:
- Private Key: Yeh aapke wallet ka master password hai. Isko KABHI BHI public code, jaise GitHub, pe share nahi karna. Yeh aapke bank account ka PIN, password, ATM card, sab kuch hai. Hum isko environment variable mein save karenge.
- Proxy Address: Polymarket CLOB direct aapke main wallet se interact nahi karta. Woh ek special smart contract wallet use karta hai jisko "Proxy" kehte hain. Yeh security ke liye acha hai. Aapka main wallet is proxy ko control karta hai. Agar aapke paas proxy nahi, tou client library aapke liye khud deploy kar degi.
Chalo, client setup karte hain. Ek file banao trader.py aur yeh code likho:
import os
from dotenv import load_dotenv
from py_clob_client.client import ClobClient
from py_clob_client.clob_types import ApiCreds
# .env file se environment variables load karo
load_dotenv()
# --- Wallet Configuration ---
# WARNING: Apni private key ko kabhi bhi direct code mein mat likhna.
# .env file mein aise save karo: PRIVATE_KEY="0x..."
private_key = os.getenv("PRIVATE_KEY")
if not private_key:
raise ValueError("PRIVATE_KEY environment variable set nahi hai!")
# Polymarket CLOB Polygon mainnet pe hai
chain_id = 137
# API credentials (optional, lekin rate limits se bachne ke liye zaroori)
api_creds = ApiCreds(
key=os.getenv("POLY_API_KEY"),
secret=os.getenv("POLY_API_SECRET"),
passphrase=os.getenv("POLY_API_PASSPHRASE"),
)
# --- Client Initialization ---
client = ClobClient(
chain_id=chain_id,
private_key=private_key,
api_creds=api_creds,
verbose=True
)
# Client ko start karo
client.init()
print(f"Bot is ready! Wallet address: {client.get_address()}")
print(f"Proxy address for trading: {client.get_proxy_address()}")
Yeh code chalane se pehle, ek .env file banao aur usmein apni details daalo:
PRIVATE_KEY="0xyour_private_key_here"
POLY_API_KEY="your_polymarket_api_key"
POLY_API_SECRET="your_polymarket_api_secret"
POLY_API_PASSPHRASE="your_polymarket_api_passphrase"
Pro Tip: Burner Wallet Jab bhi bot development ya testing kar rahe ho, hamesha ek naya, "burner" wallet istemal karo. Uss mein sirf utne hi funds (MATIC aur USDC) rakho jitne zaroori hain. Kabhi bhi apna main personal wallet, jisme aapke long-term assets hain, bot ke liye use mat karna.
Step 2: Token IDs — Market Ki Zuban
Har Polymarket market ke do possible outcomes hote hain: YES ya NO.
Example: PSL ka match hai, Lahore Qalandars vs. Karachi Kings. Market hai: "Will Lahore Qalandars win?"
- YES Token: Iski price represent karti hai ke Lahore ke jeetne ka kitna chance hai. Agar price 0.65 hai, iska matlab market 65% chance de rahi hai.
- NO Token: Iski price represent karti hai ke Lahore nahi jeetega. Iski price
1 - YES_pricehogi, yaani 0.35.
import requests
CLOB_BASE = 'https://clob.polymarket.com'
GAMMA_BASE = 'https://gamma-api.polymarket.com'
def get_token_id(market_id: str, side: str = 'YES') -> str:
"""Market ID aur side (YES/NO) ke basis pe correct token ID nikalta hai."""
url = f"{GAMMA_BASE}/markets/{market_id}"
response = requests.get(url, timeout=10)
response.raise_for_status()
market_data = response.json()
tokens = market_data.get('tokens', [])
for token in tokens:
if token.get('outcome', '').upper() == side.upper():
return token['token_id']
raise ValueError(f"Token ID not found for side: {side}")
# Usage example
# token_id = get_token_id("lahore-qalandars-psl-win", "YES")
Step 3: Querying the Order Book
Order book dekhna zaroori hai — isse aapko pata chalta hai ke market mein liquidity kaisi hai aur aapka order kahan fill hoga.
def get_order_book(token_id: str) -> dict:
"""Current order book fetch karo."""
url = f"{CLOB_BASE}/book"
params = {"token_id": token_id}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
return response.json()
def calculate_spread(order_book: dict) -> float:
"""Bid-ask spread calculate karo."""
bids = order_book.get("bids", [])
asks = order_book.get("asks", [])
if not bids or not asks:
return float('inf')
best_bid = float(bids[0]["price"])
best_ask = float(asks[0]["price"])
return round(best_ask - best_bid, 4)
CLOB Architecture Visualization
CLOB ORDER BOOK STRUCTURE
┌──────────────────────────────┐
│ Bids (buyers) │ Asks (sellers) │
│ Price | Size │ Price | Size │
├─────────────────────────────┤
│ 75.00 | 500 │ │
│ 74.95 | 1000 │ │
│ 74.90 | 2000 │ │
│ │ SPREAD: │
│ │ 75.05-75.00 │
│ │ = 0.05 (tight)│
│ │ 75.05 | 800 │
│ │ 75.10 | 400 │
│ │ 75.15 | 1200│
└──────────────────────────────┘
Your bot strategy:
- Tight spread (< 3c) = GOOD liquidity → trade
- Wide spread (> 8c) = POOR liquidity → skip
- For PKR 28,000 ($100) trade:
Tight spread cost: ~PKR 840 (3%)
Wide spread cost: ~PKR 2,240 (8%)
Pakistan Case Study: Adeel's Security Lesson
Background: Adeel from Islamabad built his first trading bot and made a common mistake — he pushed his code to a public GitHub repository with his private key accidentally included in the code (not in a .env file).
What happened: Within 6 hours, an automated bot scanned GitHub, found the key, and drained his Polygon wallet. Loss: $45 (PKR 12,600) in USDC and MATIC.
How to prevent this (Security Checklist):
| Step | Action | Status |
|---|---|---|
| 1 | Create .env file for all secrets | Mandatory |
| 2 | Add .env to .gitignore BEFORE first commit | Mandatory |
| 3 | Use python-dotenv to load in code | Mandatory |
| 4 | Use burner wallet with limited funds | Strongly recommended |
| 5 | Never paste private key in any chat/message | Non-negotiable |
Adeel's lesson: "I lost PKR 12,600 to a 5-second mistake. Now I run git status before every push and my .gitignore has .env as the first line. Cost of learning: expensive. Worth knowing early."
Practice Lab
Exercise 1: Install py_clob_client in a virtual environment. Create a .env file with placeholder values. Write code that loads the environment variables and prints them (masked) to confirm the loading works. This baseline test confirms your environment is set up correctly before adding real credentials.
Exercise 2: Using the get_order_book() function, query a real Polymarket market's order book (use https://clob.polymarket.com with any active market's token_id). Calculate the bid-ask spread. Is it below 3 cents (tradeable) or above 8 cents (skip)?
Exercise 3: Build a liquidity_check() function that takes a market's order book and returns: {"tradeable": bool, "spread": float, "best_bid": float, "best_ask": float, "total_bid_volume": float}. Test it with 3 different markets and compare their liquidity profiles.
Key Takeaways
- CLOB (Central Limit Order Book) is the same system as KSE — limit orders from buyers and sellers matched at a central venue. Polygon blockchain makes every trade transparent and auditable.
py_clob_clientabstracts all blockchain complexity — you give it commands, it handles signing, broadcasting, and confirmation- Private key security is non-negotiable:
.envfile +.gitignore+ burner wallet = three layers of protection. One mistake can drain your account in minutes. - The bid-ask spread is your true trading cost. A 5-cent spread on an 80-cent market is a 6.25% round-trip cost — always calculate this before deciding if a trade is worth it.
- Token IDs are market-specific and change — always fetch them dynamically via the Gamma API, never hardcode them.
Lesson Summary
Quiz: CLOB API 101 — Polymarket Ka Trading Interface
4 questions to test your understanding. Score 60% or higher to pass.