Pakistan Ka Pehla Professional Trading Bot CourseModule 9

9.2Cost Optimization — AI Spend Minimize Karo

25 min 3 code blocks Quiz (4Q)

Cost Optimization — AI Spend Minimize Karo

Chalo bhaiyon, welcome back.

COURSE: Pakistan Ka Pehla Professional Trading Bot Course

MODULE 9: Going Live — Bot Deploy Karna Aur Optimize Karna

LESSON 9.2: Cost Optimization — AI Spend Minimize Karo

Assalam-o-Alaikum, bot masters. Pichle lessons mein humne bot banaya, strategy likhi, aur usko test kiya. Ab waqt hai asal game ka — bot ko live market mein utaarna. Lekin live jaane se pehle ek bohot zaroori, seedhi baat. Agar aapka trading account $30 ka hai aur aapka bot AI pe roz $15 phoonk raha hai, tou bhai 2 din mein account bhi khatam aur trading ka shauq bhi.

Ye lesson paise banaanay se zyaada paise bachaanay ke baaray mein hai. Because in the world of algo trading, a dollar saved is a dollar you can lose on a bad trade instead of on API calls. Simple. Chalo, scene on karte hain.

The Big Picture: Kharcha $15/day se $1/day Pe Kaisay Laana Hai

Pehle, let's look at the summary of what we're going to achieve. Ye koi fancy marketing nahi, this is the exact logic running in our Polymarket Oracle bot. Is code ko dekho, ye poori lesson ka roadmap hai.

python
# filename: utils/cost_summary.py

def optimize_ai_costs():
    """AI cost optimization strategies ka summary."""
    
    tips = {
        '1_gemini_first': {
            'saving': '90% of Haiku calls',
            'how': 'Gemini (free) filters 200 markets to 15 candidates. Only 15 go to Haiku.'
        },
        '2_cache_analysis': {
            'saving': '80% of repeat calls', 
            'how': 'Skip markets analyzed <4h ago with <2% price change.'
        },
        '3_skip_cache': {
            'saving': '50% of Sonnet calls',
            'how': 'If Sonnet SKIPped a market, dont re-analyze for 6+ hours.'
        },
        '4_batch_analysis': {
            'saving': '60% token cost',
            'how': 'Send 5 candidates in one Haiku call instead of 5 separate calls.'
        },
        '5_no_opus': {
            'saving': '$3/day',
            'how': 'Use Sonnet for everything except sports exits. Opus is 5x more expensive.'
        }
    }
    
    total_daily_without = 15.0  # $15/day agar sab kuch full power pe chalao
    total_daily_with = 1.0     # $1/day hamari optimization ke saath
    
    print(f'Without optimization: ${total_daily_without}/day = ~PKR {total_daily_without*280}/day')
    print(f'With optimization: ${total_daily_with}/day = ~PKR {total_daily_with*280}/day')
    print(f'Monthly Savings: ~PKR {((total_daily_without-total_daily_with)*30)*280:,}')
    print("-" * 20)
    
    for name, tip in tips.items():
        print(f'Strategy -> {name}: saves {tip["saving"]} — {tip["how"]}')

# Run karke dekho
optimize_ai_costs()

Output:

code
Without optimization: $15.0/day = ~PKR 4200.0/day
With optimization: $1.0/day = ~PKR 280.0/day
Monthly Savings: ~PKR 117,600.0
--------------------
Strategy -> 1_gemini_first: saves 90% of Haiku calls — Gemini (free) filters 200 markets to 15 candidates. Only 15 go to Haiku.
Strategy -> 2_cache_analysis: saves 80% of repeat calls — Skip markets analyzed <4h ago with <2% price change.
Strategy -> 3_skip_cache: saves 50% of Sonnet calls — If Sonnet SKIPped a market, dont re-analyze for 6+ hours.
Strategy -> 4_batch_analysis: saves 60% token cost — Send 5 candidates in one Haiku call instead of 5 separate calls.
Strategy -> 5_no_opus: saves $3/day — Use Sonnet for everything except sports exits. Opus is 5x more expensive.

Dekha? Ye sirf numbers nahi hain. Ye aapke account ki life hai. Ab in strategies ko ek ek karke code ke saath phorte hain.

1

The Funnel Strategy: Gemini ko Sasta Gatekeeper Banao

Socho Polymarket pe 200 active markets hain. Agar hum har market ko analysis ke liye seedha Anthropic ke Haiku model (jo paid hai) pe bhej dein, tou din ka kharcha araam se $5-$10 ho jayega. No way.

Hum istemaal karengay "funnel" approach. Sab se upar, hum Google ka Gemini Pro use karengay, jiska free tier itna generous hai ke hamara kaam aaram se ho jaata hai. Gemini ka kaam simple hai: 200 markets mein se wo 10-15 markets nikaal ke de jahan koi "edge" ho sakta hai.

Ye basically ek screening test hai. Jo market screening test pass karegi, sirf wohi aagay paid AI ke paas jayegi.

Code Example:

Ye logic hamare scanner.py mein rehta hai. Yahan main ek simplified version dikha raha hoon.

python
# filename: scanner.py (Simplified)
import time
from ai.gemini import is_market_a_potential_candidate # Assume this function exists

# Mock function to simulate fetching all markets from Polymarket
def fetch_all_markets():
    print("Fetching 200 markets from Polymarket...")
    # Example: PSL final, KSE index movement, new government policy etc.
    return [
        {'id': '1', 'question': 'Will Pakistan win the T20 World Cup 2024?'},
        {'id': '2', 'question': 'Will KSE-100 index cross 80,000 by end of June?'},
        {'id': '3', 'question': 'Who will win the toss in the PAK vs IND match?'},
        # ... and 197 other markets
    ]

# This is our mock Gemini filter. Asal mein ye API call hogi.
# Hum yahan simple keyword matching se simulate kar rahay hain.
def mock_gemini_filter(market):
    """Simulates Gemini's logic to find markets with an edge."""
    keywords = ['win', 'cross', 'exceed', 'pass']
    # Gemini ko hum prompt detay hain to find markets that are predictable
    # and not pure chance (like a toss).
    if any(keyword in market['question'] for keyword in keywords) and 'toss' not in market['question']:
        print(f"  [GEMINI] ✅ Found potential in: {market['question']}")
        return True
    print(f"  [GEMINI] ❌ Skipping random market: {market['question']}")
    return False


def run_scanner():
    print("--- Starting Market Scan ---")
    all_markets = fetch_all_markets()
    potential_candidates = []
    
    print("\n--- Phase 1: Gemini Free Screening ---")
    for market in all_markets:
        # Asal code mein yahan `is_market_a_potential_candidate(market)` call hoga
        if mock_gemini_filter(market):
            potential_candidates.append(market)
            
    print(f"\n--- Scan Complete ---")
    print(f"Gemini ne {len(all_markets)} markets ko filter karke {len(potential_candidates)} candidates nikalay.")
    print("Ab sirf in candidates ko paid AI (Haiku) pe bhejengay.")
    # Next step would be: analyze_with_haiku(potential_candidates)

# Chala ke dekho
run_scanner()

Result: Gemini ne 200 mein se sirf 2-3 markets select keen. Baaqi sab ko pehle hi step pe reject kar diya. Humne 197 Haiku API calls bacha leen. That's a 90%+ saving, right there. Ye logic scanner.py aur ai/gemini.py mein implement hota hai.

2

Smart Caching: Akalmand Bano, Bar Bar Same Kaam Mat Karo

Ab humne Gemini se candidates tou nikaal liye. Let's say 15 markets. Bot har 10 minute mein chalta hai. Kya hum har 10 minute mein un 15 markets ko dobara Haiku pe bhejengay? Bilkul nahi. That's just dumb.

Hum caching use karengay. Hum har market ka analysis result apni database mein save karengay. Agli baar jab bot us market ko dekhega, tou pehle DB mein check karega:

  1. Kya isko pehle analyze kiya hai?
  2. Agar

Lesson Summary

3 runnable code examples4-question knowledge check below

Quiz: [Module 9 Lesson 9.2]

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