Pakistan Ka Pehla Professional Trading Bot CourseModule 2

2.3Config-Driven Architecture — YAML Se Sab Control Karo

25 min 4 code blocks Quiz (4Q)

Config-Driven Architecture — YAML Se Sab Control Karo

Bismillah. Chalo bhai, shuru karte hain.

COURSE: Pakistan Ka Pehla Professional Trading Bot Course

MODULE: Python Bot Architecture — Ek Professional Bot Ka Skeleton (Module 2)

LESSON: Config-Driven Architecture — YAML Se Sab Control Karo (Lesson 2.3)

Assalam-o-Alaikum, future bot masters! Last lesson mein humne project structure dekha. Aaj ek aisi cheez pe baat karenge jo ek bachay ke code aur ek professional-grade bot ke beech ka farq hai. Scene yeh hai ke jab tumhara bot live chal raha ho, tum har choti cheez ke liye code band karke, edit karke, phir se deploy nahi karna chahte. That's a recipe for disaster.

Isi liye, hum seekhenge Config-Driven Architecture. Matlab, bot ka dimaagh code mein hardcode nahi hoga, balke ek alag file se control hoga jisko hum config.yaml kehte hain. Let's get into it.

1

Hardcoding Ka Masla Kya Hai? (The Problem with Hardcoding)

Socho tumne ek bot banaya jo Polymarket pe "Pakistan to win the next T20 match" pe bet karta hai. Tumne code mein likh diya:

python
# execution_hardcoded.py

def place_bet_on_pakistan_win():
    bet_amount_pkr = 5000  # Hardcoded value
    market_odds = 1.85     # Hardcoded value
    
    if market_odds > 1.5:
        print(f"Placing bet of {bet_amount_pkr} PKR on Pakistan to win.")
        # ... actual bet placing logic ...
    else:
        print("Odds too low, not betting.")

place_bet_on_pakistan_win()

Ab kal ko tumne bet amount 5000 se 7000 PKR karna hai. Ya odds ki condition 1.5 se 1.6 karni hai. Tumhe kya karna paray ga?

  1. execution_hardcoded.py file kholo.
  2. Value change karo.
  3. Code ko save karo.
  4. Agar bot server pe chal raha hai, tou usko stop karo.
  5. Naya code deploy karo.
  6. Bot ko restart karo.

Bhai, yeh bohat lamba aur risky kaam hai. Production mein aisi harkatain nahi chalti. What if you make a typo while editing? Poora bot crash ho sakta hai.

The solution? Saari settings ko code se bahar nikaal do.

2

Enter YAML: The Control Panel for Your Bot

YAML (YAML Ain't Markup Language) ek simple, insaan ko samajh aanay wali data format hai. Yeh key-value pairs pe chalti hai, bilkul Python dictionaries ki tarah. Hum apne bot ki saari important settings — capital, bet size, risk management rules, strategy parameters — ek config.yaml file mein rakhenge.

Iska fayda? Settings change karni hain? Sirf text file edit karo, bot ko restart karo, and you're done. No code change needed.

Chalo, hamare Polymarket Oracle bot ki config file dekhte hain. Yeh woh file hai jo hamare scanner.py, execution.py, aur saari strategies istemal karengi.

File: config.yaml

yaml
# Global settings for the entire bot
total_eur: 30
max_per_trade_eur: 5
take_profit_pct: 94
stop_loss_move_pct: 12
alert_move_pct: 4
theta_stall_hours: 12
max_positions_per_theme: 2

# Strategy-specific settings
strategies:
  theta_sniper:
    enabled: true
    interval_min: 120
    max_allocation_pct: 25
    bet_size: 5
  geo_scout:
    enabled: true
    interval_min: 480
    max_allocation_pct: 20
    bet_size: 4

# Alerting and notification settings
alerts:
  triggers:
    trade_executed: true
    position_alert: true
    daily_summary: true
    heartbeat: true

Chalo isko section by section torte hain:

  • Global Settings: Yeh pooray bot pe apply hoti hain.
    • total_eur: Tumhara total capital kitna hai.
    • max_per_trade_eur: Ek trade mein maximum kitna paisa lagana hai. Risk management ka pehla rule.
    • take_profit_pct: Agar market price 94 cents (ya 94%) tak pohanch jaye, position close kardo aur profit lelo.
    • stop_loss_move_pct: Agar market price tumhare khilaf 12% move kar jaye, foran nikal jao. Loss ko control karna sab se zaroori hai.
  • Strategies: Yahan hum bot ke alag alag "dimaagh" define karte hain. Hamare case mein, theta_sniper aur geo_scout do alag strategies hain.
    • enabled: Kya yeh strategy chalani hai ya nahi? false kar do, bot isko ignore kar dega.
    • interval_min: Yeh strategy kitni der baad market scan karegi? theta_sniper har 120 minutes (2 ghantay) mein.
    • max_allocation_pct: Total capital ka kitna percent is strategy ko assign karna hai? theta_sniper ko 25% milega.
    • bet_size: Jab yeh strategy trade karegi, tou kitne EUR ka bet lagayegi.
  • Alerts: Bot tumse kaise baat karega. Telegram ya Discord pe messages.
    • trade_executed: Jab bhi trade ho, alert bhejo.
    • daily_summary: Roz raat ko summary report bhejo.

Dekha? Kitna clean aur organized hai.

3

Python Mein YAML Load Karna

Ab is file ko Python mein kaise use karna hai? Iske liye humein ek library chahiye: PyYAML.

Pehle isko install karo: pip install PyYAML

Ab woh code dekho jo maine tumhein pehle dikhaya tha. Yeh hamare bot ki main.py ya __init__.py mein sab se pehle run hoga.

python
import yaml
import os

# For demonstration, we'll create the config file if it doesn't exist.
# In a real project, this file will be there already.
CONFIG_TEMPLATE = """
total_eur: 30
max_per_trade_eur: 5
take_profit_pct: 94
stop_loss_move_pct: 12
alert_move_pct: 4
theta_stall_hours: 12
max_positions_per_theme: 2

strategies:
  theta_sniper:
    enabled: true
    interval_min: 120
    max_allocation_pct: 25
    bet_size: 5
  geo_scout:
    enabled: true
    interval_min: 480
    max_allocation_pct: 20
    bet_size: 4

alerts:
  triggers:
    trade_executed: true
    position_alert: true
    daily_summary: true
    heartbeat: true
"""

# Create the config.yaml file
if not os.path.exists('config.yaml'):
    with open('config.yaml', 'w') as f:
        f.write(CONFIG_TEMPLATE)

# --- The Core Logic Starts Here ---

def load_config(path='config.yaml'):
    """Loads the configuration from a YAML file."""
    print(f"Loading configuration from: {path}")
    try:
        with open(path, 'r') as f:
            # Always use safe_load to prevent arbitrary code execution from a malicious YAML file.
            config_data = yaml.safe_load(f)
        print("Configuration loaded successfully.")
        return config_data
    except FileNotFoundError:
        print(f"ERROR: Configuration file not found at {path}. Exiting.")
        exit(1) # Exit the script if config is missing
    except yaml configuration-related errors are properly handled to prevent runtime failures. Configuration-driven architectures allow bots to be deployed to different environments without code changes.

---

## 📺 Recommended Videos & Resources
- **[YAML Configuration Syntax](https://yaml.org/spec/1.2/spec.html)** — Complete YAML specification
  - Type: Official YAML Specification
  - Link description: Learn YAML syntax for configuration files
- **[PyYAML Documentation](https://pyyaml.org/)** — Python YAML parser and emitter
  - Type: Official Documentation
  - Link description: Reference for loading and parsing YAML files in Python
- **[Configuration Management Best Practices](https://www.youtube.com/results?search_query=configuration+management+python+best+practices)** — Professional config patterns
  - Type: YouTube
  - Link description: Search "configuration management Python" for best practices
- **[Environment-Specific Configurations](https://12factor.net/)** — Twelve-Factor App methodology
  - Type: Official Guide
  - Link description: Learn about configuration for development/production environments
- **[Error Handling in Python](https://docs.python.org/3/tutorial/errors.html)** — Exception handling and try-except blocks
  - Type: Python Official Docs
  - Link description: Learn robust error handling patterns

---

## 🎯 Mini-Challenge
**5-Minute Practical Task:** Create a config.yaml file with 3 sections: (1) API settings (timeout, max_retries), (2) Trading settings (min_volume, max_position_size), (3) Logging settings (log_level, log_file). Write a Python function using PyYAML to load this file and print a formatted report showing all settings. Test it with sample values.

---

## 🖼️ Visual Reference

📊 Configuration-Driven Bot Architecture ┌──────────────────────────┐ │ config.yaml │ │ ├─ api_settings │ │ ├─ trading_params │ │ └─ logging_config │ └────────────┬─────────────┘ │ │ load_config() ▼ ┌──────────────────────────┐ │ main.py │ │ (No hardcoded values!) │ │ Uses config dict for │ │ all settings │ └────────────┬─────────────┘ │ ┌────────┴────────┐ ▼ ▼ ┌─────────────┐ ┌──────────────┐ │ Development │ │ Production │ │ config.yaml │ │ config.yaml │ │ (test keys) │ │ (live keys) │ └─────────────┘ └──────────────┘

code

---

Lesson Summary

4 runnable code examples4-question knowledge check below

Quiz: Config-Driven Architecture — YAML Se Sab Control Karo

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