Pakistan Ka Pehla Professional Trading Bot CourseModule 2

2.4Smart Scheduler — APScheduler Se Bot Ko Automate Karo

30 min 6 code blocks Quiz (4Q)

Smart Scheduler — APScheduler Se Bot Ko Automate Karo

Of course. Here is the full lesson content, written in the requested tone and format.

Pakistan Ka Pehla Professional Trading Bot Course

MODULE 2: Python Bot Architecture — Ek Professional Bot Ka Skeleton

LESSON 2.4: Smart Scheduler — APScheduler Se Bot Ko Automate Karo

Assalam-o-Alaikum, developers. Pichle lessons mein humne bot ke alag alag parts pe baat ki. Lekin woh sab parts mil kar kaam kaise karenge? Unko time pe trigger kon karega? Tum har waqt bot ke saamne to nahi beth sakte, aakhir sona bhi hota hai.

Toh scene yeh hai ke ek professional bot ko ek dimaagh (brain) chahiye jo usko bataye ke kab, kya karna hai. Yeh lesson usi dimaagh ke baare mein hai. Hum seekhenge ke apne bot ko 24/7 autopilot pe kaise daalna hai, taake tum so rahe ho, aur bot tumhare liye market mein kaam kar raha ho. Yeh hai asli passive income ki taraf pehla qadam.

Simple Loops Ka Masla — Why while True is a Bad Idea

Sab se pehle, ek naya developer sochega, "Yaar, simple hai. Ek while True loop lagata hoon aur usmein time.sleep() daal deta hoon."

python
import time

def run_strategy():
    print("Strategy chal rahi hai...")
    # API calls, calculations, etc.

while True:
    run_strategy()
    time.sleep(60) # Har 60 seconds baad chalao

Dekhne mein theek lagta hai, lekin yeh approach professional nahi hai. Iske do bare masle hain:

  1. Rigid Hai: Agar tumhein ek strategy har 5 minute mein chalani hai aur doosri har 2 ghante mein? Is simple loop se yeh manage karna bohat mushkil aur messy ho jayega.
  2. Blocking Hai: Agar run_strategy() ko chalne mein 2 minute lag gaye, to sleep(60) uske baad shuru hoga. Tumhari timing poori out ho jayegi.

Humein is se behtar, ek "smart" tareeka chahiye.

The Smart Polling Loop — Ek Behtar Shuruaat

Chalo, pehle ek custom solution dekhte hain jo while True se lakh darje behtar hai. Isko hum "Smart Polling Loop" kehte hain. Yeh wahi logic hai jo humare Polymarket Oracle bot ke initial versions mein use hua tha.

Yeh raha code, isko ghaur se dekho. Hum isko line-by-line torenge.

python
import time
import signal
import sys
from datetime import datetime, timezone

# Strategy registry with intervals
MODULES = {
    'theta_sniper': {'interval_min': 120, 'last_run': 0},
    'geo_scout':    {'interval_min': 480, 'last_run': 0},
    'position_mgr': {'interval_min': 30,  'last_run': 0},
}

running = True

def signal_handler(sig, frame):
    global running
    print('\n[SYSTEM] Shutting down gracefully... Intezar karein.')
    running = False

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

def main_loop():
    print('[BOT] Starting smart scheduler...')
    while running:
        now = time.time() # Current time ka timestamp le lo
        for name, mod in MODULES.items():
            # Check karo ke pichli run se ab tak kitna time guzar gaya
            elapsed = (now - mod['last_run']) / 60
            
            # Agar time interval poora ho gaya hai, to strategy chalao
            if elapsed >= mod['interval_min']:
                print(f'[{name.upper()}] Running... ({datetime.now(timezone.utc).strftime("%H:%M UTC")})')
                
                # Asal bot mein yahan strategy ka function call hoga
                # For example: strategies.theta_sniper.run()
                
                # Update karo ke strategy abhi chali hai
                mod['last_run'] = now
                
        # Thori der ruko, taake CPU pe 100% load na aaye
        time.sleep(10)

if __name__ == '__main__':
    main_loop()

Code Breakdown:

  1. MODULES Dictionary: Yeh humare bot ka control panel hai. Har key ek strategy ka naam hai (jaise theta_sniper jo humare strategies/theta_sniper.py se aayega). Value mein do cheezein hain:

    • interval_min: Yeh strategy kitni der baad chalni chahiye (minutes mein).
    • last_run: Humne isko aakhri baar kab chalaya tha. Shuru mein yeh 0 hai taake bot foran pehli dafa sab strategies chala de.
  2. signal_handler & signal.signal: Yeh bohat, bohat important hai. Isko kehte hain "Graceful Shutdown". Jab tum server pe Ctrl+C dabate ho (ya VPS provider usko band karne ka signal bhejta hai), to yeh function call hota hai. Yeh running variable ko False kar deta hai. Is se humara while loop aaram se apni current iteration poori karke band ho jata hai. Iske baghair, bot adhoore kaam (jaise open trade) chhor kar band ho sakta hai, jo ke ek financial disaster hai.

  3. main_loop():

    • while running:: Jab tak running variable True hai, yeh loop chalta rahega.
    • now = time.time(): Hum har loop ke start mein current time note kar lete hain.
    • for name, mod in MODULES.items():: Hum ek-ek karke apni saari strategies check karte hain.
    • elapsed = (now - mod['last_run']) / 60: Yeh simple calculation batati hai ke is strategy ko chale hue kitne minute ho gaye hain.
    • if elapsed >= mod['interval_min']:: Core logic. Agar strategy ka time aa gaya hai, to usko chalao.
    • mod['last_run'] = now: Bohat zaroori step. Jaise hi strategy chalti hai, hum uska last_run time update kar dete hain taake woh agle interval tak dobara na chale.
    • time.sleep(10): Loop har 10 second baad check karta hai. Isko 300 (5 minutes) bhi kar sakte hain, lekin 10-30 seconds aam taur pe theek rehta hai. Is se CPU free rehta hai.

Yeh approach choti applications ke liye aala hai. Lekin jab bot complex hota hai, to humein ek dedicated library ki zaroorat parti hai.

The Professional's Choice: APScheduler

Advanced Python Scheduler (APScheduler) ek library hai jo scheduling ke saare masle hal kar deti hai. Yeh powerful, flexible, aur production-ready hai. Isko install karna simple hai:

bash
pip install apscheduler

APScheduler ke 3 main components hain:

  1. Scheduler: The main guy. Yeh jobs ko manage karta hai. (BlockingScheduler, BackgroundScheduler)
  2. Trigger: Yeh batata hai ke job kab chalani hai. (interval, cron, date)
  3. Job Store: Yeh batata hai ke jobs ko kahan save karna hai (memory, database, etc.).

Chalo iske triggers ko code examples ke saath dekhte hain.

Trigger Type 1: interval

Yeh sab se common hai. "Har 5 minute baad yeh function chalao."

python
import time
from apscheduler.schedulers.blocking import BlockingScheduler

def check_kse_100():
    # Imagine karo yahan PSX se KSE-100 index ka data fetch ho raha hai
    print("Fetching KSE-100 Index... Abhi rate hai 55,000 PKR.")

# Scheduler ko initialize karo
scheduler = BlockingScheduler(timezone="Asia/Karachi")

# Job add karo: 'check_kse_100' function ko har 10 seconds baad chalao
scheduler.add_job(check_kse_100, 'interval', seconds=10)

print("Scheduler start ho gaya hai. Press Ctrl+C to exit.")

try:
    scheduler.start()
except (KeyboardInterrupt, SystemExit):
    pass

Is code mein, BlockingScheduler use hua hai. Iska matlab hai ke jab tak scheduler chal raha hai, tumhara program aur koi kaam nahi karega. Yeh simple scripts ke liye theek hai. Lekin humare bot mein aur bhi kaam ho sakte hain, isliye hum BackgroundScheduler use karenge.

Trigger Type 2: cron

Yeh bohat powerful hai. Is se tum bilkul a specific time pe job chala sakte ho, jaise cricket match shuru hone se pehle. "Har subah 9:15 AM, Monday to Friday, market open hone se pehle data download karo."

python
import time
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler

def pre_market_data_download():
    # Pre-market data refresh ensures the bot has fresh data before trading begins
    # This scheduling pattern is used in production trading systems worldwide

Scheduling is critical for trading bots that need to refresh data, reset states, and prepare for market activity at specific times.

---

## 📺 Recommended Videos & Resources
- **[APScheduler Documentation](https://apscheduler.readthedocs.io/)** — Python scheduling library
  - Type: Official Documentation
  - Link description: Learn scheduling patterns with BackgroundScheduler
- **[Cron Job Syntax Explained](https://en.wikipedia.org/wiki/Cron)** — Understanding cron expressions
  - Type: Wikipedia
  - Link description: Learn cron syntax for scheduling tasks
- **[Background Tasks in Python](https://www.youtube.com/results?search_query=python+background+tasks+scheduling)** — Running tasks asynchronously
  - Type: YouTube
  - Link description: Search "Python background tasks and scheduling"
- **[Trading Hours by Market](https://en.wikipedia.org/wiki/Trading_hours)** — Market opening/closing times
  - Type: Wikipedia
  - Link description: Understand trading hours for PSX, crypto, and prediction markets
- **[Time Zones in Python](https://docs.python.org/3/library/datetime.html#timezone-objects)** — Managing time across regions
  - Type: Python Official Docs
  - Link description: Learn datetime and timezone handling for global trading

---

## 🎯 Mini-Challenge
**5-Minute Practical Task:** Write a Python script using APScheduler to: (1) Print "Market scan starting..." every 5 minutes, (2) Print "Daily reset at 8 AM" once per day, (3) Print the current time when each task runs. Test the script for 30 seconds to verify both tasks trigger correctly.

---

## 🖼️ Visual Reference

📊 Bot Scheduling Timeline (Trading Day) ┌─────────────────────────────────────────┐ │ 08:00 AM │ Pre-market Scan │ │ (Trigger) │ Refresh data, warm up APIs │ └─────────────┼─────────────────────────────┘ │ ┌─────────────▼──────────────────────────┐ │ 09:00 AM │ Market Opens │ │ (Continuous)│ Scan every 5 mins │ │ │ Check conditions, trade │ └─────────────┬──────────────────────────┘ │ ┌─────────────▼──────────────────────────┐ │ 04:00 PM │ Market Closes │ │ (Trigger) │ End-of-day analysis │ │ │ Log results to database │ └─────────────┬──────────────────────────┘ │ ┌─────────────▼──────────────────────────┐ │ 05:00 PM │ Daily Reset │ │ (Trigger) │ Clear state, prepare for │ │ │ next day │ └─────────────────────────────────────────┘

code

---

Lesson Summary

6 runnable code examples4-question knowledge check below

Quiz: Smart Scheduler — APScheduler Se Bot Ko Automate Karo

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