Of course! Here is the full lesson content, written in the requested tone and format.
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.
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:
Without alerts, you're flying blind. Aur trading mein andha hona matlab paisa gawana.
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:
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.
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 .env file se credentials uthata hai. Humne dotenv library use ki hai iske liye.if not smtp_user...: Yeh ek guard clause hai. Agar ghalti se .env file 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.Ab jab humara email bhejne ka function tayyar hai, chalo isko use karke mukhtalif qisam ke alerts banate hain.
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):
"""Jab