1.2 — Polymarket API Se Pehla Data Fetch — Gamma API Explorer
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:
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.
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
-
GAMMA_BASE: Yeh API ka main address hai. Isko ek variable mein rakhne se code saaf rehta hai. -
fetch_active_markets(limit=20): Yeh hamara main function hai.paramsdictionary: 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=15ka 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.
-
The
forloop:m.get('outcomePrices', '[0, 0]'): Yeh market ka dil hai.outcomePricesek 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 APIoutcomePricesko 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.
📺 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
📊 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%) │
└─────────────────────────────────┘
Lesson Summary
Quiz: Polymarket API Se Pehla Data Fetch — Gamma API Explorer
4 questions to test your understanding. Score 60% or higher to pass.