USDT shed $16 billion in market cap during Terra's collapse. USDC dropped $12 billion when Silicon Valley Bank failed. Your portfolio management system probably missed both events until it was too late.
This 45-minute Python tutorial builds an automated monitoring system that emails you when stablecoin market caps move beyond 5% thresholds. No more discovering depegging events from Twitter.
What You Will Build
- Real-time monitoring system tracking $180+ billion in combined USDT and USDC market cap
- Automated email alerts triggered by market cap changes exceeding 5% within 60-minute intervals
- Python script using CoinGecko's free API tier — 10,000 monthly calls included
Prerequisites and Setup Requirements
Python 3.8+ (download from python.org) | CoinGecko API key (free tier sufficient) | Gmail with 2FA enabled | Basic command line knowledge
Time commitment: 45 minutes active setup, then fully automated
The free CoinGecko tier provides 10,000 API calls monthly with a 30-second rate limit between requests. Perfect for hourly monitoring — you'll use roughly 1,440 calls per month running checks every hour.
Core Implementation Steps
CoinGecko API Authentication
Navigate to coingecko.com/en/api and create your free account. Copy your API key from the dashboard immediately after email verification. Store this securely.
The authenticated API provides higher rate limits than anonymous calls and guarantees access during high-traffic periods. During major market events, anonymous endpoints often get throttled while authenticated requests continue processing.
Python Environment Setup
Install required libraries: pip install requests schedule
Create stablecoin_monitor.py with this foundation:
import requests
import json
import smtplib
from email.mime.text import MIMEText
from datetime import datetime
import schedule
import time
API_KEY = "your_coingecko_api_key_here"
BASE_URL = "https://api.coingecko.com/api/v3"
def get_stablecoin_data():
headers = {"x-cg-demo-api-key": API_KEY}
endpoint = f"{BASE_URL}/coins/markets"
params = {
"vs_currency": "usd",
"ids": "tether,usd-coin",
"order": "market_cap_desc"
}
response = requests.get(endpoint, headers=headers, params=params)
return response.json() if response.status_code == 200 else None
This targets $USDT and $USDC specifically using their CoinGecko IDs: "tether" and "usd-coin". The endpoint returns real-time market cap data in USD.
Market Cap Change Detection Algorithm
previous_caps = {}
def check_market_cap_changes(current_data, threshold=5.0):
alerts = []
for coin in current_data:
coin_id = coin['id']
current_cap = coin['market_cap']
coin_name = coin['name']
if coin_id in previous_caps:
previous_cap = previous_caps[coin_id]
change_percent = ((current_cap - previous_cap) / previous_cap) * 100
if abs(change_percent) >= threshold:
alerts.append({
'name': coin_name,
'change': change_percent,
'current_cap': current_cap,
'previous_cap': previous_cap
})
previous_caps[coin_id] = current_cap
return alerts
The 5% threshold isn't arbitrary. During May 2022's Terra collapse, USDT dropped 12% in 48 hours while USDC fell 8% during March 2023's banking crisis. Normal trading rarely moves stablecoin market caps beyond 2-3%.
Gmail SMTP Integration
def send_alert_email(alerts, recipient_email, gmail_password):
sender_email = "your_gmail@gmail.com"
subject = f"STABLECOIN ALERT: {len(alerts)} Significant Changes Detected"
body = "STABLECOIN MARKET CAP ALERTS\n"
body += f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
for alert in alerts:
direction = "INCREASED" if alert['change'] > 0 else "DECREASED"
body += f"{alert['name']} market cap {direction} by {alert['change']:.2f}%\n"
body += f"Previous: ${alert['previous_cap']:,.0f}\n"
body += f"Current: ${alert['current_cap']:,.0f}\n\n"
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = recipient_email
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login(sender_email, gmail_password)
server.send_message(msg)
Critical security note: use Gmail App Passwords, not your regular password. Enable 2FA in Gmail settings, then generate a unique App Password for this script. Never hardcode credentials — use environment variables in production.
Complete Monitoring System
def monitor_stablecoins():
try:
print(f"Checking stablecoin market caps at {datetime.now()}")
data = get_stablecoin_data()
if not data:
print("Failed to fetch data from CoinGecko API")
return
alerts = check_market_cap_changes(data, threshold=5.0)
if alerts:
print(f"ALERT: {len(alerts)} significant changes detected")
send_alert_email(alerts, "your_email@gmail.com", "your_app_password")
else:
print("No significant market cap changes detected")
except Exception as e:
print(f"Error during monitoring: {str(e)}")
if __name__ == "__main__":
monitor_stablecoins() # Run immediately
schedule.every(1).hours.do(monitor_stablecoins)
print("Stablecoin monitoring started. Press Ctrl+C to stop.")
while True:
schedule.run_pending()
time.sleep(60)
The script runs continuously with error handling that prevents crashes during API downtime. Failed requests are logged but don't break the monitoring schedule.
Testing and Production Deployment
Before going live with the 5% threshold, test with 1% for 2-3 hours to verify email delivery. Change this line temporarily:
alerts = check_market_cap_changes(data, threshold=1.0)
You should receive test emails during normal market fluctuations. This validates your SMTP configuration and helps you understand baseline volatility patterns.
What most tutorials skip: stablecoin market caps move differently than prices. While USDT might trade at $0.998 (a 0.2% price deviation), its market cap could simultaneously drop 8% due to redemptions. Your system catches the redemption pressure — the real systemic risk signal.
Traditional portfolio monitors track prices. Smart money tracks market cap velocity. When $2 billion exits USDT in 6 hours, that's not normal trading — that's institutional flight. Your system will catch it before the headlines hit Bloomberg.