Pakistan Ka Pehla Professional Trading Bot CourseModule 1

1.2Polymarket API Se Pehla Data Fetch — Gamma API Explorer

30 min 6 code blocks Practice Lab Quiz (4Q)

Polymarket API Se Pehla Data Fetch — Gamma API Explorer

Assalam-o-Alaikum, bot masters! Umeed hai sab khairiyat se honge.

Chalo bhai, اصل کام shuru karte hain. Theory bohat ho gayi, ab haath gande karne ka time hai. Agar trading bot banana hai, toh sabse pehli cheez hai data. Data nahi, toh bot andha hai. Aur hum yahan andhon ki fauj nahi bana rahe.

COURSE: Pakistan Ka Pehla Professional Trading Bot Course

MODULE 1: Prediction Markets 101 — Polymarket Pe Paise Kaise Bante Hain

LESSON 1.2: Polymarket API Se Pehla Data Fetch — Gamma API Explorer

Hook: Data Hi Paisa Hai

Suno. Stock market ho, crypto ho, ya Polymarket — jis ke paas data pehle aur saaf suthra aata hai, wohi jeet'ta hai. Yeh lesson aapka pehla qadam hai us jeet ki taraf. Hum Polymarket ka live data, direct unke server se, apne computer pe laana seekhenge. Bina kisi permission ke, bina ek روپیہ kharch kiye.

Gamma API - Aapka Free Data Source

Polymarket ka ek public API hai, jiska naam hai Gamma API. Iski sabse achi baat? Yeh bilkul FREE hai aur iske liye koi API key ya authentication nahi chahiye. Matlab, Pakistan mein baithke, aap seedha real-time data access kar sakte hain. Koi credit card, koi sign-up ka jhanjhat nahi.

Yeh API "read-only" hai, yaani aap is se sirf data dekh sakte hain, trade nahi laga sakte. Trade lagane ke liye alag APIs hain, jo hum aage modules mein cover karenge. Abhi ke liye, hamara maqsad market ko samjhna hai, aur uske liye data nikalna zaroori hai.

Setup: Sirf Ek Library Chahiye

Hum Python use kar rahe hain. Agar aapke paas Python 3.11+ installed hai, toh bas ek library install karni hai. Apna terminal ya command prompt kholo aur likho:

bash
pip install requests

Bas. Hogaya setup. requests library humein internet se data fetch karne mein help karti hai. Bohat simple aur powerful hai.

Pehla Data Fetch: Top Markets by Volume

Chalo, ab code likhte hain. Hamara goal hai Polymarket ke top 20 active markets ko fetch karna, unko 24-ghante ke volume ke hisaab se sort karke. Volume ka matlab hai ke kitna paisa us market mein lag raha hai. Jahan zyada volume, wahan zyada action.

Yeh raha poora code. Isko copy karke ek file fetch_markets.py mein save karo aur run karo. Phir hum iska post-mortem karte hain.

python
import requests
import json
from datetime import datetime, timezone

# Gamma API ka base URL. Isko capital mein likhna ek convention hai for constants.
GAMMA_BASE = "https://gamma-api.polymarket.com"

def fetch_active_markets(limit=20):
    """
    Polymarket se active markets fetch karo — FREE, no auth.
    Volume ke hisaab se sorted.
    """
    print("Fetching active markets from Polymarket Gamma API...")

    # API endpoint aur parameters
    params = {
        "active": "true",       # Sirf active markets
        "closed": "false",      # Jo markets band na hui hon
        "limit": limit,         # Kitne results chahiye
        "order": "volume24hr",  # Volume ke hisaab se sort karo
        "ascending": "false"    # Ziada volume walay pehle
    }

    try:
        # Asal API call yahan ho rahi hai
        r = requests.get(f"{GAMMA_BASE}/markets", params=params, timeout=15)
        r.raise_for_status()  # Agar koi error aaye (like 404, 500), toh exception raise karo

        print("Data received successfully!")
        return r.json()

    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return []

# Chalo, function ko call karte hain
markets = fetch_active_markets()

# Pehle 5 markets ka data print karte hain
print("\n--- Top 5 Active Markets by 24hr Volume ---")
for m in markets[:5]:
    # 'outcomePrices' kabhi string hota hai, kabhi list. Data cleaning zaroori hai.
    prices_str = m.get('outcomePrices', '[0, 0]')
    try:
        prices = json.loads(prices_str)
    except (json.JSONDecodeError, TypeError):
        prices = [0, 0] # Default value agar parsing fail ho

    # Probability nikalte hain
    yes_price = float(prices[0]) * 100
    no_price = float(prices[1]) * 100

    # Volume aur end date ko format karte hain
    volume = m.get('volume24hr', 0)
    end_date_str = m.get('endDate')

    # Question ko thora chota karlete hain display ke liye
    question = m.get('question', 'N/A')

    print(f"\nQ: {question[:70]}...")
    print(f"  YES: {yes_price:.1f}% | NO: {no_price:.1f}%")
    print(f"  24hr Volume: ${volume:,.0f}")
    if end_date_str:
        end_date = datetime.fromisoformat(end_date_str.replace('Z', '+00:00'))
        print(f"  Expires: {end_date.strftime('%d-%b-%Y %H:%M')} UTC")

Code Ka Post-Mortem

  1. GAMMA_BASE: Yeh API ka main address hai. Isko ek variable mein rakhne se code saaf rehta hai.

  2. fetch_active_markets(limit=20): Yeh hamara main function hai.

    • params dictionary: Yahan hum API ko batate hain ke humein kya data chahiye.
      • active: "true", closed: "false": Humein woh markets chahiye jo abhi trade ho rahi hain. Na woh jo abhi shuru nahi hui, na woh jo band ho chuki hain.
      • order: "volume24hr": Yeh sabse important hai. Hum KSE mein bhi toh volume dekhte hain na? Jahan volume, wahan liquidity. Jahan liquidity, wahan aasaani se trade enter aur exit kar sakte ho.
      • ascending: "false": Humein highest volume markets pehle chahiye.
    • requests.get(...): Yeh line asal jaadu karti hai. Yeh Polymarket ke server ko request bhejti hai. timeout=15 ka matlab hai ke agar 15 second mein jawab nahi aaya, toh give up kar do. Important hai, warna aapka bot phans sakta hai.
    • r.raise_for_status(): Agar internet nahi chal raha ya Polymarket ka server down hai, toh yeh line error de degi. Yeh good practice hai.
    • return r.json(): API se data JSON format mein aata hai. Yeh line usko Python dictionary/list mein convert kar deti hai.
  3. The for loop:

    • m.get('outcomePrices', '[0, 0]'): Yeh market ka dil hai. outcomePrices ek list hoti hai jismein [YES_PRICE, NO_PRICE] hota hai. Yeh price 0 se 1 ke darmiyan hota hai, jo basically probability hai. Hum .get() use kar rahe hain taake agar yeh field na bhi ho, toh hamara code crash na kare.
    • json.loads(prices_str): Yeh ek ajeeb cheez hai. Kabhi kabhi Gamma API outcomePrices ko as a string bhej deta hai. Yeh line us string ko wapis list mein convert karti hai. Real-world data hamesha thora ganda hota hai, saaf karna parhta hai.
    • yes_price = float(prices[0]) * 100: Hum price ko 100 se multiply karke percentage bana rahe hain. 0.67 price ka matlab hai 67% chance.
    • volume = m.get('volume24hr', 0): 24 ghante mein kitne dollars ki trading hui hai.
    • endDate: Market kab expire hogi. Yeh date ISO format mein hoti hai, hum usko aam format mein convert kar rahe hain.

Pro Tip: Liquidity is King Jahan volume zyada hota hai, wahan slippage kam hota hai. Slippage ka matlab hai tumhara expected price aur actual execution price mein farq. Zyada volume = kam slippage = zyada profit margin.

Gamma API Response — Key Fields at a Glance

code
📋 Market Dictionary Structure (from Gamma API)
{
  "id":            "unique-market-id",
  "question":      "Will X happen by date Y?",
  "outcomePrices": "[0.67, 0.33]",   ← YES / NO probability (0-1)
  "volume24hr":    125000,            ← USD traded in last 24 hours
  "volume":        890000,            ← Total USD traded all time
  "endDate":       "2026-06-15T...",  ← UTC expiry datetime
  "active":        true,
  "closed":        false,
  "liquidity":     45000              ← Current liquidity pool
}

Key derived metrics your bot will use:
  yes_pct  = float(outcomePrices[0]) * 100   → e.g., 67.0%
  no_pct   = float(outcomePrices[1]) * 100   → e.g., 33.0%
  spread   = from CLOB order book             → not in Gamma

📺 Recommended Videos & Resources

  • Requests Library — HTTP for Humans — Complete guide to the requests library
    • Type: Official Documentation
    • Link description: Bookmark this for API calls, timeouts, error handling, and best practices
  • Working with JSON in Python — json.loads(), json.dumps(), and data parsing
    • Type: Python Official Docs
    • Link description: Learn JSON parsing for API responses
  • Gamma API Official Reference — Real Polymarket API documentation
    • Type: API Documentation
    • Link description: Reference for all available endpoints and parameters
  • REST API Fundamentals for Beginners — Basic REST/HTTP concepts
    • Type: YouTube
    • Link description: Search YouTube for "REST API tutorial Python requests library"
  • PSX/KSE Pakistan Stock Market Comparisons — Understanding volume and liquidity concepts from local market
    • Type: Official Website
    • Link description: Visit KSE.com.pk to see how volume is reported in the Pakistan Stock Exchange

🎯 Mini-Challenge

5-Minute Practical Task: Run the fetch_markets.py script from this lesson. Capture the output showing the top 5 markets by volume. Then, modify the script to fetch the top 3 markets expiring in the next 7 days (hint: filter by endDate). Save the modified script as fetch_markets_filtered.py and verify it works.

🖼️ Visual Reference

code
📊 Gamma API Request Flow
┌─────────────────────────────────┐
│ Your Python Script              │
│ fetch_active_markets()          │
└────────────┬────────────────────┘
             │
             │ HTTP GET Request
             │ (with params: active, volume24hr, etc.)
             ▼
┌─────────────────────────────────┐
│ Polymarket Gamma API Server     │
│ https://gamma-api.polymarket... │
│                                 │
│ Searches database for markets   │
└────────────┬────────────────────┘
             │
             │ JSON Response
             │ [
             │   {
             │     question: "...",
             │     outcomePrices: [0.67, 0.33],
             │     volume24hr: 125000,
             │     endDate: "2024-05-15T...",
             │     ...
             │   },
             │   ...
             │ ]
             ▼
┌─────────────────────────────────┐
│ Your Script                     │
│ Parses JSON → Display Markets   │
│ (YES: 67% | NO: 33%)            │
└─────────────────────────────────┘

🇵🇰 Pakistan Case Study: Spotting a Cricket Market Opportunity

Scenario: ICC T20 World Cup, Pakistan vs India. Market on Polymarket: "Will Pakistan win the match on June 9th?"

python
# Real-world filter example for cricket market discovery
def find_pakistan_cricket_markets(markets):
    """Find Pakistan-related markets — cultural edge for Pakistani traders."""
    pk_keywords = ['pakistan', 'PSL', 'PCB', 'babar', 'shaheen']
    results = []
    for m in markets:
        question_lower = m.get('question', '').lower()
        if any(kw in question_lower for kw in pk_keywords):
            yes_price = float(m.get('yes_price', 0)) * 100
            volume = float(m.get('volume24hr', 0))
            results.append({
                'question': m['question'],
                'yes_pct': yes_price,
                'volume_usd': volume,
                # PKR conversion at approximate 2026 rate
                'volume_pkr': volume * 280
            })
    return results

# Sample output:
# Q: Will Pakistan beat India in T20 WC on June 9?
# YES: 42.0% | Volume: $89,000 (PKR ~2.49 crore)

If your analysis — based on Shaheen Afridi's recent form, Pakistan's record at that venue, and news from Dawn — gives Pakistan a 58% chance while the market says 42%, you have a 16-cent edge. That is exactly where Theta Sniper enters.

Practice Lab

Practice Lab: Extending the Fetcher

python
# Add this to fetch_markets.py to filter by days to expiry
from datetime import datetime, timezone, timedelta

def filter_by_days_to_expiry(markets, max_days=7):
    """Return only markets expiring within max_days."""
    now = datetime.now(timezone.utc)
    result = []
    for m in markets:
        end_str = m.get('endDate', '')
        if not end_str:
            continue
        try:
            end_dt = datetime.fromisoformat(end_str.replace('Z', '+00:00'))
            days_left = (end_dt - now).days
            if 0 < days_left <= max_days:
                m['_days_to_expiry'] = days_left
                result.append(m)
        except ValueError:
            continue
    return sorted(result, key=lambda x: x['_days_to_expiry'])

# Usage:
soon_expiring = filter_by_days_to_expiry(markets, max_days=7)
print(f"\n--- Markets Expiring in 7 Days: {len(soon_expiring)} ---")
for m in soon_expiring[:3]:
    print(f"  {m['question'][:60]} — {m['_days_to_expiry']} days left")

💡 Key Takeaways

  • The Gamma API is completely free and requires no authentication — the perfect starting point for Pakistani developers with zero upfront investment
  • Volume is the single most important filter: high volume = liquidity = low slippage = you can actually enter and exit positions profitably
  • outcomePrices from the API represents probability (0.0 to 1.0), not price in dollars — always multiply by 100 to get the percentage
  • Real-world API data is messy: outcomePrices can arrive as a string or a list — always handle both cases with try/except
  • Pakistani cricket knowledge is a genuine trading edge: you can often forecast PCB-related markets more accurately than the Western traders who dominate Polymarket volume

Lesson Summary

Includes hands-on practice lab6 runnable code examples4-question knowledge check below

Quiz: Polymarket API Se Pehla Data Fetch — Gamma API Explorer

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