2.1 — Project Structure — Folders Aur Files Ka Blueprint
Project Structure — Folders Aur Files Ka Blueprint
Assalam-o-Alaikum, bot masters! Taqi bhai here. Welcome to Module 2 of Pakistan's first professional trading bot course.
Pichle module mein humne environment set kiya tha. Ab asli kaam shuru ho raha hai — bot ka skeleton, uska dhancha banana.
COURSE: Pakistan Ka Pehla Professional Trading Bot Course
MODULE: Python Bot Architecture — Ek Professional Bot Ka Skeleton (Module 2)
LESSON: Project Structure — Folders Aur Files Ka Blueprint (Lesson 2.1)
DURATION: 25 minutes
Kyun Zaroori Hai Yeh Sab? (The Hook)
Yaar dekho, ek cheez seedhi samajh lo. Ek "chalta hai" wala bot aur ek professional, production-grade bot mein zameen aasman ka farak hota hai. Farak unki soch mein hota hai, unke structure mein hota hai. Agar tumhara code ek kachre ka dher hai jisme sab kuch main.py mein ghusa hua hai, toh jab market mein aag lagegi, tumhara bot sabse pehle jalega. Trust me, I've seen it happen.
Aaj jo structure hum banayenge, yeh koi aam structure nahi hai. Yeh bilkul wohi blueprint hai jo mere Polymarket Oracle bot mein production mein chal raha hai, a bot that has handled millions of dollars in volume. Toh ghor se suno, kyunki yeh lesson tumhare 100 ghante ka debugging time bachayega.
The Blueprint: Hamare Bot Ka Naqsha
Pehle, ek nazar daalo ke hum bana kya rahe hain. Yeh hai hamare project ka final structure:
polymarket-bot/
├── main.py # Bot ka dimagh, sab ko yehi control karega
├── config.yaml # API keys ke ilawa saari settings yahan
├── .env # Secret stuff: API keys, passwords
├── scanner.py # Market ki ankhain, data yahan se ayega
├── execution.py # Bot ke haath, trade yehi file karegi
├── db.py # Bot ki yaadasht, har cheez yahan record hogi
├── alerts.py # Notifier, trade ho ya error, yeh batayega
├── ai/
│ ├── __init__.py
│ ├── gemini.py # Tier 1 AI: Sasta, fast, for basic analysis
│ ├── haiku.py # Tier 2 AI: Thora behtar, for deeper analysis
│ └── sonnet.py # Tier 3 AI: Sabse powerful, final decision maker
└── strategies/
├── __init__.py
├── theta_sniper.py # Strategy 1: Options selling ke liye
└── geo_scout.py # Strategy 2: Geopolitical events ke liye
Dekh ke pareshan nahi hona. Har file ka ek maqsad hai, aur hum ek ek ko samjhenge.
Chalo, Dhancha Banate Hain (Let's Build the Skeleton)
Yeh saare folders aur files haath se banane ki zaroorat nahi. Hum developers hain, hum automate karte hain. Apne project folder mein ek file banao create_skeleton.py aur usmein yeh code daalo:
# create_skeleton.py
import os
# Project structure jo hum banayenge:
project_name = 'polymarket-bot'
if not os.path.exists(project_name):
os.makedirs(project_name)
os.chdir(project_name) # Move into the project directory
# Define directories and files
dirs = ['ai', 'strategies']
files = [
'main.py',
'scanner.py',
'execution.py',
'db.py',
'alerts.py',
'config.yaml',
'.env',
'ai/__init__.py',
'ai/gemini.py',
'ai/haiku.py',
'ai/sonnet.py',
'strategies/__init__.py',
'strategies/theta_sniper.py',
'strategies/geo_scout.py'
]
print(f"Creating skeleton for '{project_name}'...")
# Create directories
for d in dirs:
os.makedirs(d, exist_ok=True)
print(f" Created directory: {d}/")
# Create files
for f in files:
# Handle files inside directories
if '/' in f:
dir_path = os.path.dirname(f)
os.makedirs(dir_path, exist_ok=True)
with open(f, 'a') as fp:
pass # Just create the file, 'a' mode creates if not exists
print(f" Created file: {f}")
print('\nBot skeleton ready! Ab ismein jaan daalne ka time hai.')
Terminal mein python create_skeleton.py chalao aur jaadu dekho. Saare folders aur files ban jayenge.
os.makedirs(d, exist_ok=True): Yeh command directory banata hai.exist_ok=Trueka matlab hai ke agar directory pehle se bani hui hai toh error mat do, chup chaap aage barho.open(f, 'a').close(): Yeh file banane ka ek simple tareeka hai.'a'(append mode) file ko create kar deta hai agar woh exist nahi karti.
Ab jab hamara blueprint tayyar hai, chalo har kamre mein jaa kar dekhte hain ke wahan kya hoga.
Har File Ka Ek Kaam (Separation of Concerns)
Yeh software engineering ka sabse ahem usool hai. Har module, har file ka sirf ek kaam hona chahiye. Is se code saaf rehta hai, debug karna asaan hota hai, aur features add karna halwa ho jata hai.
1. main.py - The Conductor
Yeh tumhare bot ka orchestra conductor ya team ka captain hai. Iska kaam khud kaam karna nahi, balkay doosron se kaam karwana hai. Yeh scanner se data mangwayega, strategy se signal lega, aur execution ko trade ka order dega.
main.py ka sample code:
# main.py
import time
import scanner
import execution
import db
from strategies import theta_sniper
from ai import haiku
def main_loop():
print("Bot starting... Market ko scan kar raha hoon.")
while True:
# Step 1: Market Scan Karo
market_data = scanner.find_hot_markets()
if not market_data:
print("Koi khaas opportunity nahi mili. Waiting for 5 mins.")
time.sleep(300) # 5 minute ruko
continue
for market in market_data:
print(f"\nAnalyzing market: {market['name']}")
# Step 2: Strategy se pucho kya karna hai
strategy_decision = theta_sniper.analyze(market)
# Step 3: AI se second opinion lo
ai_opinion = haiku.get_analysis(market['details'])
print(f" AI Opinion: {ai_opinion['sentiment']}")
# Step 4: Final Decision and Execution
if strategy_decision['action'] == 'BUY' and ai_opinion['confidence'] > 0.8:
print(f" DECISION: Buying {strategy_decision['shares']} shares.")
trade_result = execution.place_buy_order(market['id'], strategy_decision['shares'])
# Step 5: Database mein record karo
db.log_trade(trade_result)
else:
print(" DECISION: Hold. Conditions met nahi huin.")
time.sleep(300) # Har loop ke baad 5 min ka break
if __name__ == "__main__":
db.setup_database() # Bot start hone se pehle DB ready karo
main_loop()
Samjhe? main.py ne khud kuch nahi kiya. Usne sirf scanner, theta_sniper, haiku, execution, aur db ko unke kaam bataye. This is clean. This is professional.
2. scanner.py - The Scout
Yeh tumhari ankhain hain market mein. Iska sirf ek kaam hai: data laana. Chahe woh Binance API se ho, KSE (PSX) ki website se ho, ya Polymarket ke GraphQL endpoint se.
This is the foundation of Module 2. Each component has a single responsibility, making the bot easy to maintain and debug.
📺 Recommended Videos & Resources
- Python Project Structure & Modular Design — Best practices for Python projects
- Type: Official Guide
- Link description: Learn about package structure, init.py, and module organization
- Design Patterns — Separation of Concerns — Software architecture principles
- Type: Design Patterns Reference
- Link description: Understand modular design for scalable bots
- Python Package Management with pip — Creating and importing Python modules
- Type: Python Official Docs
- Link description: Learn how to organize code into modules and packages
- YAML Configuration Files — Configuration management for bots
- Type: YAML Specification
- Link description: Learn how to use config.yaml for bot settings
- Environment Variables in Python — Managing secrets and API keys
- Type: Python Official Docs
- Link description: Learn os.environ and .env file handling
🎯 Mini-Challenge
5-Minute Practical Task: Create the basic folder structure for a trading bot project locally. Create: (1) main.py, (2) config.yaml, (3) .env (with dummy API keys), (4) folders for ai/ and strategies/. Initialize empty init.py files in each subdirectory. Verify the structure with a file tree command and confirm all files are created.
🖼️ Visual Reference
📊 Bot Architecture — Separation of Concerns
┌──────────────────────────────────┐
│ main.py │
│ (Bot Conductor/Orchestrator) │
└────────────┬─────────────────────┘
│
┌────────┼────────┬────────┐
▼ ▼ ▼ ▼
┌───────┐┌────────┐┌──────┐┌──────┐
│scanner│execution│db.py │alerts │
│ .py │ .py │ │ .py │
└───────┘└────────┘└──────┘└──────┘
│ │ │ │
│ │ │ │
└────────┴────────┴────────┘
│
▼
Strategies & AI Modules
(ai/gemini.py, etc.)
Lesson Summary
Quiz: Project Structure — Folders Aur Files Ka Blueprint
4 questions to test your understanding. Score 60% or higher to pass.