Spaces:
Configuration error
Configuration error
File size: 6,507 Bytes
83bcbe3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | # Multi-Asset Real-Time Price Alert Bot ππ
A production-ready Python bot that monitors **commodities**, **cryptocurrencies**, and **stocks** in real-time, and sends instant **Telegram alerts** when prices enter your defined ranges.
## β¨ Features
| Feature | Details |
|---|---|
| **Multi-asset tracking** | Gold, Silver, Crude Oil, BTC, ETH, XRP, SOL, NVIDIA, Tesla, Google, Amazon, Oracle, S&P 500 |
| **Real-time crypto** | Binance WebSocket streaming with REST fallback |
| **Smart polling** | yfinance batch polling every 15s for stocks/commodities |
| **Dedup alerts** | State-machine logic β alerts only on range entry, resets on exit |
| **Telegram commands** | `/add`, `/remove`, `/list`, `/status`, `/help` |
| **Dry-run mode** | Test without Telegram via `--dry-run` |
| **Error handling** | Exponential backoff, auto-reconnect, structured logging |
## π Project Structure
```
photonic-perigee/
βββ main.py # Entry point & orchestrator
βββ config.py # Configuration & environment
βββ alert_engine.py # State-machine alert logic
βββ telegram_bot.py # Telegram commands & notifications
βββ logger.py # Rotating log setup
βββ fetchers/
β βββ __init__.py
β βββ stock_fetcher.py # yfinance polling
β βββ crypto_fetcher.py # Binance WebSocket + REST
βββ tests/
β βββ test_alert_engine.py # Unit tests
βββ requirements.txt
βββ .env.example
βββ README.md
```
## π Quick Start
### 1. Prerequisites
- **Python 3.10+** installed
- A **Telegram account**
### 2. Create a Telegram Bot
1. Open Telegram and search for **@BotFather**
2. Send `/newbot` and follow the prompts
3. You'll receive a **Bot Token** like `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`
4. **Get your Chat ID:**
- Search for **@userinfobot** on Telegram
- Send `/start` β it will reply with your Chat ID
- Alternatively, send a message to your bot, then visit:
```
https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates
```
Look for `"chat":{"id": YOUR_CHAT_ID}`
### 3. Install & Configure
```bash
# Clone / navigate to the project
cd photonic-perigee
# Create a virtual environment (recommended)
python -m venv venv
venv\Scripts\activate # Windows
# source venv/bin/activate # macOS/Linux
# Install dependencies
pip install -r requirements.txt
# Configure environment
copy .env.example .env # Windows
# cp .env.example .env # macOS/Linux
# Edit .env with your Telegram credentials
notepad .env
```
Fill in your `.env`:
```env
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
TELEGRAM_CHAT_ID=987654321
```
### 4. Run the Bot
```bash
# Live mode (sends Telegram alerts)
python main.py
# Dry-run mode (console alerts only, no Telegram needed)
python main.py --dry-run
```
### 5. Run Tests
```bash
python -m pytest tests/ -v
```
## π¬ Telegram Commands
| Command | Description | Example |
|---|---|---|
| `/add <ASSET> <MIN> <MAX>` | Start tracking an asset | `/add BTC 60000 62000` |
| `/remove <ASSET>` | Stop tracking an asset | `/remove BTC` |
| `/list` | Show all tracked assets | `/list` |
| `/status` | Bot health check & uptime | `/status` |
| `/help` | Show all commands | `/help` |
### Supported Asset Names
| Category | Assets |
|---|---|
| Commodities | `GOLD`, `SILVER`, `CRUDE_OIL` |
| Crypto | `BTC`, `ETH`, `XRP`, `SOL` |
| Stocks | `NVIDIA`, `TESLA`, `GOOGLE`, `AMAZON`, `ORACLE` |
| Indices | `SP500` |
## π How Alerts Work
The bot uses a **state machine** to avoid duplicate alerts:
```
Price OUTSIDE range β enters range β π ALERT sent
Price INSIDE range β stays inside β no alert (dedup)
Price INSIDE range β exits range β state resets
Price OUTSIDE range β re-enters β π ALERT sent again
```
### Sample Alert Message
```
π Price Alert β BTC
βββββββββββββββββββββββ
π° Current Price: $61,234.5600
π Target Range: $60,000.0000 β $62,000.0000
π Time (UTC): 2026-03-22 06:15:30
βββββββββββββββββββββββ
Price has entered your defined range!
```
## βοΈ Configuration
Edit `config.py` to customise:
| Setting | Default | Description |
|---|---|---|
| `STOCK_POLL_INTERVAL` | `15` | Seconds between yfinance polls |
| `CRYPTO_WS_RECONNECT_DELAY` | `5` | Seconds before WebSocket reconnect |
| `DEFAULT_RANGES` | See file | Pre-loaded price ranges |
## βοΈ Deployment
### Option A: Run on a VPS (e.g., DigitalOcean, AWS EC2)
```bash
# SSH into your server
ssh user@your-server
# Clone the project, install dependencies
git clone <your-repo-url>
cd photonic-perigee
python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt
# Configure .env
nano .env
# Run with nohup (persists after disconnecting)
nohup python main.py > output.log 2>&1 &
# Or use systemd for auto-restart (create /etc/systemd/system/pricealert.service):
```
**systemd service file** (`/etc/systemd/system/pricealert.service`):
```ini
[Unit]
Description=Price Alert Bot
After=network.target
[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/photonic-perigee
ExecStart=/home/ubuntu/photonic-perigee/venv/bin/python main.py
Restart=always
RestartSec=10
EnvironmentFile=/home/ubuntu/photonic-perigee/.env
[Install]
WantedBy=multi-user.target
```
```bash
sudo systemctl enable pricealert
sudo systemctl start pricealert
sudo systemctl status pricealert
```
### Option B: Run on Replit
1. Create a new **Python** Repl
2. Upload all project files
3. Add `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` in Replit's **Secrets** tab
4. Set the run command to `python main.py`
5. Click **Run** β the bot will stay alive as long as the Repl is active
6. Use Replit's **Always On** feature (paid) for 24/7 uptime
## π Logging
- **Console**: INFO level and above
- **File** (`bot.log`): DEBUG level, rotating at 5MB with 3 backups
- Log format: `2026-03-22 06:15:30 | INFO | main | Bot started`
## π‘οΈ Error Handling
| Scenario | Behaviour |
|---|---|
| yfinance API failure | Exponential backoff (max 120s) |
| Binance WebSocket disconnect | Auto-reconnect with backoff (5 attempts) |
| WebSocket fails repeatedly | Falls back to REST API polling |
| Telegram send failure | Logged, retried on next alert |
| Invalid command input | User-friendly error message |
## License
MIT
|