Pakistan Ka Pehla Professional Trading Bot CourseModule 1

1.4Hands-On Lab: Market Dashboard Banao

30 min 3 code blocks Quiz (4Q)

Hands-On Lab: Market Dashboard Banao

Assalam-o-Alaikum, traders! Umeed hai sab khairiyat se honge. Pichle lessons mein humne theory aur chotay chotay code snippets dekhe. Ab waqt hai asli kaam ka — in sab pieces ko jor kar apna pehla proper trading tool banane ka.

Yeh woh script hai jo aap roz subah chai ke saath run karenge to get a full market overview. No more manual browsing, no more guesswork. Sirf data, sirf logic.

Chalo, scene on kartay hain.

COURSE: Pakistan Ka Pehla Professional Trading Bot Course

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

LESSON 1.4: Hands-On Lab: Market Dashboard Banao

Maqsad Kya Hai? (What's the Goal?)

Ab tak humne alag alag functions banaye:

  1. fetch_active_markets() - Polymarket se data uthanay ke liye.
  2. filter_markets() - Kaam ki markets nikalne ke liye.
  3. score_market() - Har market ko ek potential score denay ke liye.

Yeh sab tukron mein tha. Aaj hum in sab ko ek single, powerful script mein combine karenge. Yeh script saari active markets fetch karegi, unko hamari strategy ke hisaab se score karegi, aur top opportunities ko ek saaf suthri CSV file mein save kar degi.

Basically, apna pehla trading tool ban gaya! Yeh aapka daily driver hoga. Isko run kiya, CSV kholi, aur 5 minute mein pata chal gaya ke aaj kahan paisa lag sakta hai.

The Code: Chalo Isko Samjhein

Pehle poora code dekho, phir iska post-mortem karte hain, line by line. Yeh wohi code hai jo hamare project ka dil banega.

python
# Required libraries - yeh Python mein built-in aati hain
import csv
import random
from datetime import datetime, timedelta

# ==============================================================================
# NOTE: Yeh neeche walay functions humne pichle lessons (1.1, 1.2, 1.3) mein
#       banaye thay. Yahan hum inko sirf mock kar rahe hain taake yeh script
#       standalone chal sakay. Asal bot mein yeh real API calls hongi.
# ==============================================================================

def fetch_active_markets(limit=100):
    """
    MOCK FUNCTION: Simulates fetching active markets from Polymarket.
    Asal mein, yeh Polymarket API ko call karega.
    """
    print(f"Fetching {limit} markets from Polymarket (simulation)...")
    # Kuch sample markets banatay hain, bilkul real data jaisi
    sample_markets = [
        {'id': '0x001', 'question': 'Will Pakistan win the next T20 match against India?', 'volume24hr': 25000, 'creation_date': datetime.now() - timedelta(days=2)},
        {'id': '0x002', 'question': 'Will the KSE-100 index close above 75,000 points by the end of the week?', 'volume24hr': 150000, 'creation_date': datetime.now() - timedelta(days=1)},
        {'id': '0x003', 'question': 'Will the price of Bitcoin be over $70,000 on July 30, 2024?', 'volume24hr': 500000, 'creation_date': datetime.now() - timedelta(days=10)},
        {'id': '0x004', 'question': 'Will the next government complete its 5-year term?', 'volume24hr': 5000, 'creation_date': datetime.now() - timedelta(days=30)},
        {'id': '0x005', 'question': 'Will Babar Azam score a 50 in the next PSL match?', 'volume24hr': 8000, 'creation_date': datetime.now() - timedelta(hours=12)},
        {'id': '0x006', 'question': 'A market with very low liquidity and almost no chance', 'volume24hr': 10, 'creation_date': datetime.now() - timedelta(days=5)},
    ]
    # Thori randomness daal detay hain
    return random.sample(sample_markets, len(sample_markets))

def score_market(market):
    """
    MOCK FUNCTION: Simulates scoring a market based on our strategy.
    Asal bot mein, yahan AI models (Gemini/Haiku) aur custom logic chalegi.
    """
    score = 0
    reasons = []
    tradeable = True

    # Rule 1: Volume check - Kam se kam $1000 volume ho
    if market.get('volume24hr', 0) < 1000:
        tradeable = False
        reasons.append("Low Volume")
    else:
        score += 30  # Acha volume hai, score barhao
        reasons.append("Good Volume")

    # Rule 2: Market age - Bohat purani market na ho
    if market['creation_date'] < datetime.now() - timedelta(days=15):
        score -= 20 # Purani market, less interesting
        reasons.append("Old Market")
    else:
        score += 20 # Fresh market hai
    
    # Rule 3: Keyword check (simple example)
    keywords = ['Pakistan', 'KSE-100', 'Bitcoin', 'PSL']
    if any(keyword.lower() in market['question'].lower() for keyword in keywords):
        score += 40
        reasons.append("Relevant Keywords")

    # Final random adjustment to simulate complex scoring
    score += random.randint(-10, 10)
    
    return {
        'score': max(0, min(100, score)), # Score ko 0-100 ke beech rakho
        'reasons': reasons,
        'tradeable': tradeable
    }

# ==============================================================================
# AAJ KA ASLI CODE - The Dashboard Builder
# ==============================================================================

def build_dashboard():
    """
    Yeh function saaray tukron ko jorta hai: Fetch -> Score -> Sort -> Save
    """
    print("Dashboard generation started...")
    # Step 1: Data fetch karo
    markets = fetch_active_markets(100)
    
    # Step 2: Har market ko score karo aur ek nayi list mein daalo
    scored = []
    for m in markets:
        result = score_market(m)
        # Sirf "tradeable" markets ko consider karo
        if result['tradeable']:
            scored.append({
                'question': m['question'][:80], # Question ko thora chota karlo
                'score': result['score'],
                'volume': m.get('volume24hr', 0),
                'reasons': ' | '.join(result['reasons']) # Reasons ko ek string banalo
            })
    
    # Step 3: Score ke hisaab se sort karo, sabse upar sabse high score
    scored.sort(key=lambda x: x['score'], reverse=True)
    
    # Step 4: Top 20 results ko CSV file mein save kardo
    filename = f"market_dashboard_{datetime.now().strftime('%Y-%m-%d')}.csv"
    with open(filename, 'w', newline='', encoding='utf-8') as f:
        # Fieldnames define kartay hain CSV ke columns
        fieldnames = ['score', 'question', 'volume', 'reasons']
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        
        writer.writeheader() # Column headings likho
        writer.writerows(scored[:20]) # Top 20 rows likh do
    
    print(f"Dashboard ready! {len(scored)} tradeable markets found. Results saved to {filename}")
    return scored

# Script ko run karne ke liye
if __name__ == "__main__":
    top_markets = build_dashboard()
    print("\n--- Top 5 Opportunities Today ---")
    for i, market in enumerate(top_markets[:5]):
        print(f"{i+1}. Score: {market['score']} | Vol: ${market['volume']} | {market['question']}")

📺 Recommended Videos & Resources

  • Building a Stock Market Dashboard in Python — Real-time data visualization
    • Type: YouTube
    • Link description: Search "building market dashboard Python" for step-by-step tutorials
  • CSV File Handling in Python — Complete csv module documentation
    • Type: Python Official Docs
    • Link description: Reference for reading/writing CSV files with DictWriter
  • Pandas for Data Analysis — Advanced data manipulation and analysis
    • Type: Official Documentation
    • Link description: Learn Pandas for more complex market analysis
  • Real-Time Market Data APIs — Connecting to live data feeds
    • Type: YouTube
    • Link description: Search for "real-time market data Python APIs"
  • Dashboard Design Best Practices — Understanding information architecture
    • Type: Wikipedia
    • Link description: Learn dashboard design principles for trader tools

🎯 Mini-Challenge

5-Minute Practical Task: Run the Market Dashboard script from this lesson. Modify it to: (1) Filter for only markets with volume > 50,000, (2) Add a new column called "risk_level" (High/Medium/Low based on volume), and (3) Save results to a CSV file. Verify the CSV is created and open it to confirm data looks correct.

🖼️ Visual Reference

code
📊 Market Dashboard Pipeline
┌────────────────────────────────┐
│ Step 1: Fetch Markets           │
│ (100 from Polymarket)           │
└────────────┬───────────────────┘
             │
             ▼
┌────────────────────────────────┐
│ Step 2: Score Each Market       │
│ (Volume, Age, Keywords)         │
└────────────┬───────────────────┘
             │
             ▼
┌────────────────────────────────┐
│ Step 3: Filter Tradeable        │
│ (Only score >= threshold)       │
└────────────┬───────────────────┘
             │
             ▼
┌────────────────────────────────┐
│ Step 4: Sort by Score           │
│ (Highest score first)           │
└────────────┬───────────────────┘
             │
             ▼
┌────────────────────────────────┐
│ Step 5: Save to CSV             │
│ (market_dashboard_YYYY-MM-DD)   │
└────────────────────────────────┘

Code Ka Post-Mortem

Chalo ab is code ki cheer-phaar karte hain.

Step 1: Data Fetch Karna (fetch_active_markets)

python
markets = fetch_active_markets(100)

Simple si baat hai. Hum apne helper function ko bula rahe hain ke bhai, jao aur Polymarket se 100 taza markets utha ke lao.

Real Bot Connection: Hamare production-grade bot mein, yeh kaam scanner.py karta hai. Woh sirf data fetch nahi karta, balke continuously new markets ke liye listen karta rehta hai via websockets. Lekin abhi ke liye, yeh simple fetch kaafi hai.

Lesson Summary

3 runnable code examples4-question knowledge check below

Quiz: Hands-On Lab: Market Dashboard Banao

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