8.3 — Email Alerts — Trade Notifications Setup Karo
Email Alerts — Trade Notifications Setup Karo
Of course! Here is the full lesson content, written in the requested tone and format.
MODULE 8: Database & Monitoring — Trade Logging Aur Performance Tracking
LESSON 8.3: Email Alerts — Trade Notifications Setup Karo
Assalam-o-Alaikum, future trading wizards! Umeed hai sab khairiyat se honge.
Pichle lessons mein humne database setup karna seekha. Aapka bot ab trades ko log kar raha hai, which is great. Lekin agar bot chal raha hai aur aap so rahe ho, aur us ne koi bara panga kar diya ya koi zabardast profit miss kar diya, to aapko kaise pata chalega? Apka bot andha nahi hona chahiye, aur na hi aap. Aaj hum apne bot ko "aankhein" aur "awaaz" denge using email alerts.
Chalo scene on karte hain.
Kyun Zaroori Hai? Why This Matters
Simple si baat hai: Your bot is your digital employee working 24/7. Agar aapka employee koi ajeeb-o-ghareeb harkat kare, ya koi bohat acha kaam kare, you need to know instantly. Email alerts aapka "digital chowkidar" hain. Yeh aapko batata hai ke:
- Trade execute hui hai.
- Bot mein koi error aa gaya hai.
- Bot zinda bhi hai ya crash ho kar baitha hua hai.
Without alerts, you're flying blind. Aur trading mein andha hona matlab paisa gawana.
Step 1: Gmail ko Tyaar Karna — The App Password Scene
Sab se pehle, hum Gmail use karenge alerts bhejne ke liye. It's free, reliable, aur sab ka account hota hai. Lekin yahan ek bohat important cheez hai. Aap apna regular Gmail password code mein nahi daal sakte. Google itna bewaqoof nahi hai. Security reasons ki wajah se, especially agar aapke account pe 2-Factor Authentication (2FA) on hai (aur honi chahiye!), aapko ek App Password generate karna hoga.
App Password Kaise Banayein:
- Apne Google Account pe jao: myaccount.google.com
- Left side pe Security pe click karo.
- Scroll down to "How you sign in to Google" aur wahan 2-Step Verification pe click karo. Agar yeh off hai, to pehle isko on karna parega. No excuses.
- 2-Step Verification page pe bilkul neeche jao, wahan aapko App passwords ka option milega.
- Is pe click karo, apna password dobara enter karo.
- "Select app" mein "Mail" chuno, aur "Select device" mein "Other (Custom name)" chuno.
- Naam de do, for example, "Polymarket Oracle Bot".
- Generate pe click karo.
Google aapko ek 16-character ka password dega. Yeh password copy kar ke kahin safe jagah save kar lo. Yeh dobara nazar nahi aye ga. Yahi password hum apne code mein use karenge.
Ab, is password ko code mein direct likhna aqlmandi nahi hai. Hum isko environment variables mein rakhenge. Apne project ke root folder mein ek file banao .env aur us mein yeh daalo:
# .env file
ORACLE_SMTP_USER="your.email@gmail.com"
ORACLE_SMTP_PASS="your_16_character_app_password_here"
ORACLE_EMAIL_TO="email_to_receive_alerts@domain.com"
Yaad se .gitignore file mein .env ko add kar dena taake yeh ghalti se bhi GitHub pe na chala jaye.
Step 2: The Core Code — Chalo Email Bhejte Hain
Ab aate hain asal code pe. Python mein email bhejna bachon ka khel hai, thanks to the built-in smtplib and email libraries. smtplib aapka postman hai jo email server se baat karta hai, aur email library email ko format karne mein madad karti hai (like subject, body, etc.).
Humara poora alert system is ek function ke gird ghumay ga. Isko aaram se samjho.
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from dotenv import load_dotenv
# Make sure to load environment variables at the start of your script
load_dotenv()
def send_alert(subject, body_html, to_email=None):
"""Gmail se HTML email bhejo."""
# Step 1: Credentials load karo .env file se
smtp_user = os.environ.get('ORACLE_SMTP_USER', '')
smtp_pass = os.environ.get('ORACLE_SMTP_PASS', '')
# Agar 'to_email' nahi dia, to apne aap ko hi bhej do
to = to_email or os.environ.get('ORACLE_EMAIL_TO', smtp_user)
# Step 2: Safety Check - Agar config nahi hai to function se nikal jao
if not smtp_user or not smtp_pass:
print(f'[ALERT] Email not configured — printing instead:')
print(f' Subject: {subject}')
# print(f' Body: {body_html}') # Optional: to avoid clutter
return False
# Step 3: Email message tayyar karo
msg = MIMEMultipart('alternative')
msg['Subject'] = f'[Oracle] {subject}'
msg['From'] = smtp_user
msg['To'] = to
# Hum HTML format use kar rahe hain taake email achi dikhe
msg.attach(MIMEText(body_html, 'html'))
# Step 4: Gmail ke server se connect karke email bhejo
try:
# 'smtp.gmail.com' is Gmail's server, 587 is the port for TLS
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls() # Encrypts the connection
server.login(smtp_user, smtp_pass) # Login with App Password
server.sendmail(smtp_user, to, msg.as_string()) # Bhej do!
print(f'[ALERT] Email sent: {subject}')
return True
except Exception as e:
print(f'[ALERT] Email failed: {e}')
return False
Code Breakdown (Samajhna Zaroori Hai):
os.environ.get(...): Yeh.envfile se credentials uthata hai. Humnedotenvlibrary use ki hai iske liye.if not smtp_user...: Yeh ek guard clause hai. Agar ghalti se.envfile configure nahi hui, to bot crash nahi hoga. Sirf console pe print kar dega. Professional code hamesha aise fail-safes use karta hai.MIMEMultipart('alternative'): Yeh object email ka structure banata hai. 'alternative' ka matlab hai ke aap is mein plain text aur HTML dono versions daal sakte ho, aur email client user ki preference ke hisab se dikhaye ga. Hum simple rakhte hue sirf HTML daal rahe hain.msg.attach(MIMEText(body_html, 'html')): Yahan hum apni HTML content ko email body mein attach kar rahe hain.with smtplib.SMTP(...) as server:: Yeh context manager use karna best practice hai. Connection khud-ba-khud close ho jata hai, chahe error aaye ya na aaye.server.starttls(): Bohat important! Yeh aapke login credentials aur email content ko encrypt karta hai. Iske baghair plain text mein sab kuch jayega, which is a huge security risk.server.login(smtp_user, smtp_pass): Yahan App Password use ho raha hai. Agar regular password dala to "Authentication error" aayega.
Step 3: Alert Types — Sirf Trade Alerts Kaafi Nahi Hain
Ab jab humara email bhejne ka function tayyar hai, chalo isko use karke mukhtalif qisam ke alerts banate hain.
1. Trade Executed Alert
Yeh sab se common aur zaroori alert hai. Jab bhi execution.py mein koi trade successful ho, hum yeh alert bhejeinge.
def alert_trade(action, question, side, price, amount, strategy):
"""Email alerts ensure you're never unaware of critical trading events even when offline.
Real-time notifications are essential for 24/7 operations without constant monitoring.
---
## 📺 Recommended Videos & Resources
- **[SMTP & Email Sending in Python](https://docs.python.org/3/library/smtplib.html)** — Email protocol
- Type: Python Official Docs
- Link description: Learn smtplib for sending emails
- **[Gmail SMTP Configuration](https://www.youtube.com/results?search_query=gmail+smtp+python+app+password)** — Gmail setup
- Type: YouTube
- Link description: Search "Gmail SMTP Python app password 2024"
- **[Discord/Slack Webhooks](https://discord.com/developers/docs/intro)** — Alternative notifications
- Type: Official Documentation
- Link description: Learn Discord webhooks for real-time alerts
- **[HTML Email Templates](https://www.youtube.com/results?search_query=html+email+templates+python)** — Professional formatting
- Type: YouTube
- Link description: Search "HTML email templates Python"
- **[Email Delivery Reliability](https://en.wikipedia.org/wiki/Email_deliverability)** — Ensuring emails arrive
- Type: Wikipedia
- Link description: Learn about SPF, DKIM, DMARC for deliverability
---
## 🎯 Mini-Challenge
**5-Minute Practical Task:** Write an alert function that: (1) Takes event type (ENTRY/EXIT/ALERT), (2) Formats an HTML email with trade details, (3) Sends via Gmail SMTP, (4) Handles failures gracefully. Test with a sample trade event.
---
## 🖼️ Visual Reference
📊 Alert System Architecture ┌──────────────────────────┐ │ Trading Event │ │ (ENTRY/EXIT/ERROR) │ └───────────┬──────────────┘ │ ▼ ┌──────────────────────────┐ │ Check Alert Rules │ │ - Critical = Always │ │ - Normal = Every trade │ │ - Optional = Summaries │ └───────────┬──────────────┘ ┌──┴──┐ │ │ ┌─NO─┘ │ ▼ │ [SKIP] │ ┌─YES─┘ ▼ ┌──────────────────────────┐ │ Format Alert │ │ (Subject + HTML body) │ └───────────┬──────────────┘ │ ▼ ┌──────────────────────────┐ │ Send via SMTP │ │ (Gmail / SendGrid) │ └───────────┬──────────────┘ ┌──┴──┐ │ │ ┌─OK─┘ │ ▼ │ [SENT] ┌─ERR┘ ▼ [LOG ERROR] [RETRY if critical]
---
Lesson Summary
Quiz: [Module 8 Lesson 8.3]
4 questions to test your understanding. Score 60% or higher to pass.