Of course. Here is the full lesson content, written in the requested tone and format.
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.
while True is a Bad IdeaSab se pehle, ek naya developer sochega, "Yaar, simple hai. Ek while True loop lagata hoon aur usmein time.sleep() daal deta hoon."
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:
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.
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.
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()
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.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.
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.
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:
pip install apscheduler
APScheduler ke 3 main components hain:
BlockingScheduler, BackgroundScheduler)interval, cron, date)Chalo iske triggers ko code examples ke saath dekhte hain.
intervalYeh sab se common hai. "Har 5 minute baad yeh function chalao."
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.
cronYeh 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."
import time
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
def pre_market_data_download():
# Yahan pe hum scanner.py se data fetch kar