Pakistan Ka Pehla Professional Trading Bot CourseModule 8

8.4Performance Dashboard — Strategy Analytics

25 min 1 code blocks Quiz (4Q)

Performance Dashboard — Strategy Analytics

Alright, let's get this done.

Pakistan Ka Pehla Professional Trading Bot Course

MODULE 8: Database & Monitoring — Trade Logging Aur Performance Tracking

LESSON 8.4: Performance Dashboard — Strategy Analytics

(Duration: 25 minutes)

Bismillah: Dashboard Kyun Zaroori Hai?

Assalam-o-Alaikum, future trading tycoons. Chalo, seedhi baat kartay hain. Code likhna, bot banana, strategies design karna... yeh sab aasan hissa hai. Asal game hai performance track karna. Warna aap andhere mein teer chala rahay ho, aur broker ko commission de de kar कंगाल ho jao ge.

This lesson is the most important part of this module. Yeh aapke bot ka "report card" hai. Yahan hum data ko numbers se insights mein badlein ge. Yahan aap seekho ge ke konsi strategy "Shaheen Afridi" hai aur konsi "tail-ender" jo har ball pe out ho rahi hai.

Let's build the dashboard that you will look at every single morning before you even have your chai.

The "Subah ki Pehli Cheez" — The Daily Report

Har subah, aapko ek high-level summary chahiye. Bot ne kal kya teer maara? Kitnay paisay banaye ya gawaye? AI pe kitna kharcha hua? Yeh sab ek nazar mein.

Humara Polymarket Oracle bot saari trades positions table mein aur AI calls ai_log table mein save karta hai. Yeh data humaray db.py module ke through SQLite database mein store ho raha hai. Ab hum us data ko pull kar ke ek report banayeinge.

Yeh raha woh function jo aap har roz subah run karein ge. Isko aaram se dekho, hum isko cheer-phaar kar ke samjhein ge.

python
# --- Setup: Yeh code aapke db.py mein hoga ---
import sqlite3

def get_conn():
    """Database connection create karta hai."""
    conn = sqlite3.connect('trading_bot.db')
    conn.row_factory = sqlite3.Row # Dictionary-style access ke liye
    return conn

# --- Dummy Data: Taake aap code chala kar dekh sakein ---
def setup_dummy_data():
    """Lesson ke liye temporary data banata hai."""
    conn = get_conn()
    c = conn.cursor()
    # Purana data saaf karo
    c.execute('DROP TABLE IF EXISTS positions')
    c.execute('DROP TABLE IF EXISTS ai_log')
    # Naye tables banao
    c.execute('''
        CREATE TABLE positions (
            id INTEGER PRIMARY KEY,
            market_slug TEXT,
            strategy_name TEXT,
            cost_eur REAL,
            pnl_eur REAL,
            status TEXT
        )
    ''')
    c.execute('''
        CREATE TABLE ai_log (
            id INTEGER PRIMARY KEY,
            model_name TEXT,
            cost_usd REAL
        )
    ''')
    # Dummy data daalo
    positions_data = [
        ('will-pakistan-win-t20', 'theta_sniper', 50.0, 25.50, 'closed'),
        ('kse-100-above-80k', 'macro_trend', 100.0, -100.0, 'closed'),
        ('psl-final-winner', 'theta_sniper', 30.0, 15.0, 'closed'),
        ('us-election-2024', 'macro_trend', 200.0, 0, 'open')
    ]
    ai_log_data = [
        ('claude-3-haiku', 0.01),
        ('claude-3-haiku', 0.01),
        ('gemini-1.5-pro', 0.15),
        ('claude-3-sonnet', 0.05)
    ]
    c.executemany('INSERT INTO positions (market_slug, strategy_name, cost_eur, pnl_eur, status) VALUES (?, ?, ?, ?, ?)', positions_data)
    c.executemany('INSERT INTO ai_log (model_name, cost_usd) VALUES (?, ?)', ai_log_data)
    conn.commit()
    conn.close()
    print("Dummy database setup complete.")

# Pehle dummy data setup run karlo
setup_dummy_data()
# --- End of Setup ---


# --- Asal Lesson ka Code ---
def generate_performance_report():
    """Complete performance report generate karo."""
    print("\nGenerating Daily Performance Report...")
    conn = get_conn()
    
    # Overall stats
    total = conn.execute('SELECT COUNT(*) as n FROM positions WHERE status="closed"').fetchone()['n']
    wins = conn.execute('SELECT COUNT(*) as n FROM positions WHERE status="closed" AND pnl_eur > 0').fetchone()['n']
    total_pnl = conn.execute('SELECT COALESCE(SUM(pnl_eur), 0) as s FROM positions WHERE status="closed"').fetchone()['s']
    
    # AI costs
    ai_cost = conn.execute('SELECT COALESCE(SUM(cost_usd), 0) as s FROM ai_log').fetchone()['s']
    
    # Open positions
    open_count = conn.execute('SELECT COUNT(*) as n FROM positions WHERE status="open"').fetchone()['n']
    deployed = conn.execute('SELECT COALESCE(SUM(cost_eur), 0) as s FROM positions WHERE status="open"').fetchone()['s']
    
    conn.close()
    
    # Agar total trades 0 hain to division error se bacho
    win_rate = (wins / total * 100) if total > 0 else 0
    
    report = f'''
=== POLYMARKET ORACLE — PERFORMANCE REPORT ===
Total Trades: {total} | Wins: {wins} | Win Rate: {win_rate:.1f}% 
Total P&L: €{total_pnl:+.2f}
AI Cost: ${ai_cost:.2f}
Net Profit (approx): €{total_pnl - (ai_cost * 0.93):+.2f}  (assuming EUR/USD ~0.93)
----------------------------------------------
Open Positions: {open_count} | Deployed Capital: €{deployed:.2f}
==============================================='''
    print(report)
    return report

# Chala ke dekho
generate_performance_report()

Code Breakdown:

  1. get_conn(): Yeh function humaray db.py se aata hai. Simple sa SQLite connection banata hai. conn.row_factory = sqlite3.Row bohat zaroori hai. Is se aap column ko naam se access kar saktay ho (row['pnl_eur']) na ke index se (row[4]), jo code ko readable banata hai.
  2. total & wins: Hum positions table se COUNT(*) kar rahay hain. Pehli query total closed trades batati hai. Doosri query sirf woh trades ginti hai jahan pnl_eur > 0 hai. Simple.
  3. total_pnl: Yahan SUM(pnl_eur) kar rahay hain saari closed trades ka. Yeh aapko batata hai ke aapne total kitna profit ya loss kiya.
  4. COALESCE(..., 0): Yeh SQL ka ek chota sa hero hai. COALESCE ka matlab hai, "pehli non-NULL value return karo". Agar aapka bot naya hai aur koi trade close nahi hui, to SUM(pnl_eur) NULL return karega. NULL se Python mein calculation karoge to error aayega. COALESCE(SUM(pnl_eur), 0) kehta hai ke agar sum NULL hai, to 0 use karo. Crashing se bach gaye!
  5. ai_cost: Same logic, lekin ai_log table se. Yeh table tab update hoti hai jab ai/gemini.py ya ai/haiku.py

Lesson Summary

1 runnable code examples4-question knowledge check below

Quiz: [Module 8 Lesson 8.4]

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