somilsadana commited on
Commit
83bcbe3
·
0 Parent(s):

Initial commit of full-stack assets tracker bot

Browse files
.env.example ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Telegram Bot Configuration
2
+ # Get your bot token from @BotFather on Telegram
3
+ TELEGRAM_BOT_TOKEN=your_bot_token_here
4
+
5
+ # Your Telegram Chat ID (send /start to @userinfobot to get it)
6
+ TELEGRAM_CHAT_ID=your_chat_id_here
.gitignore ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.env
6
+ .env
7
+ .venv
8
+ env/
9
+ venv/
10
+ ENV/
11
+ env.bak/
12
+ venv.bak/
13
+
14
+ # Bot data
15
+ state.json
16
+ bot.log
17
+
18
+ # Node
19
+ node_modules/
20
+ npm-debug.log
21
+ yarn-error.log
22
+
23
+ # Next.js
24
+ .next/
25
+ out/
26
+ build/
27
+
28
+ # Expo / React Native
29
+ .expo/
30
+ dist/
31
+ npm-debug.*
32
+ yarn-debug.*
33
+ yarn-error.*
34
+ # macOS
35
+ .DS_Store
.vscode/settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "git.ignoreLimitWarning": true
3
+ }
FULLSTACK_README.md ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Price Alert Bot - Full Stack Application
2
+
3
+ Your Telegram bot has been extended into a full-stack application with web and mobile interfaces.
4
+
5
+ ## Project Structure
6
+
7
+ ```
8
+ signals bot/
9
+ ├── backend/ # FastAPI backend
10
+ │ ├── main.py # API server with WebSocket support
11
+ │ └── requirements.txt
12
+ ├── web-app/ # Next.js web application
13
+ │ ├── src/app/
14
+ │ │ ├── page.tsx # Dashboard
15
+ │ │ └── globals.css
16
+ │ ├── package.json
17
+ │ └── tsconfig.json
18
+ ├── mobile-app/ # React Native mobile app
19
+ │ ├── App.tsx
20
+ │ ├── screens/
21
+ │ │ ├── DashboardScreen.tsx
22
+ │ │ ├── AddAssetScreen.tsx
23
+ │ │ └── AlertsScreen.tsx
24
+ │ ├── package.json
25
+ │ └── app.json
26
+ └── (original bot files) # Your existing Telegram bot
27
+ ```
28
+
29
+ ## Running the Application
30
+
31
+ ### 1. Start the Backend
32
+
33
+ ```bash
34
+ cd backend
35
+ pip install -r requirements.txt
36
+ python main.py
37
+ ```
38
+
39
+ The API runs on `http://localhost:8000`
40
+
41
+ **API Endpoints:**
42
+ - `GET /assets` - List tracked assets
43
+ - `POST /assets` - Add an asset
44
+ - `DELETE /assets/{name}` - Remove an asset
45
+ - `GET /assets/available` - List available assets
46
+ - `WS /ws` - WebSocket for real-time updates
47
+
48
+ ### 2. Start the Web App
49
+
50
+ ```bash
51
+ cd web-app
52
+ npm install
53
+ npm run dev
54
+ ```
55
+
56
+ Open `http://localhost:3000`
57
+
58
+ ### 3. Start the Mobile App
59
+
60
+ ```bash
61
+ cd mobile-app
62
+ npm install
63
+ npx expo start
64
+ ```
65
+
66
+ Scan the QR code with Expo Go app.
67
+
68
+ ## Features
69
+
70
+ | Feature | Web | Mobile |
71
+ |---------|-----|--------|
72
+ | View tracked assets | ✅ | ✅ |
73
+ | Add/remove assets | ✅ | ✅ |
74
+ | Real-time prices | ✅ | ✅ |
75
+ | Alert history | ✅ | ✅ |
76
+ | Dark theme | ✅ | ✅ |
77
+ | Push notifications | - | (Configure FCM) |
78
+
79
+ ## Configuration
80
+
81
+ Update `YOUR_SERVER_IP:8000` in mobile-app/screens/ with your backend server address.
82
+
83
+ For production, use environment variables:
84
+ - `NEXT_PUBLIC_API_URL` for web app
85
+ - Store backend URL in mobile app config
README.md ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi-Asset Real-Time Price Alert Bot 📈🔔
2
+
3
+ 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.
4
+
5
+ ## ✨ Features
6
+
7
+ | Feature | Details |
8
+ |---|---|
9
+ | **Multi-asset tracking** | Gold, Silver, Crude Oil, BTC, ETH, XRP, SOL, NVIDIA, Tesla, Google, Amazon, Oracle, S&P 500 |
10
+ | **Real-time crypto** | Binance WebSocket streaming with REST fallback |
11
+ | **Smart polling** | yfinance batch polling every 15s for stocks/commodities |
12
+ | **Dedup alerts** | State-machine logic — alerts only on range entry, resets on exit |
13
+ | **Telegram commands** | `/add`, `/remove`, `/list`, `/status`, `/help` |
14
+ | **Dry-run mode** | Test without Telegram via `--dry-run` |
15
+ | **Error handling** | Exponential backoff, auto-reconnect, structured logging |
16
+
17
+ ## 📁 Project Structure
18
+
19
+ ```
20
+ photonic-perigee/
21
+ ├── main.py # Entry point & orchestrator
22
+ ├── config.py # Configuration & environment
23
+ ├── alert_engine.py # State-machine alert logic
24
+ ├── telegram_bot.py # Telegram commands & notifications
25
+ ├── logger.py # Rotating log setup
26
+ ├── fetchers/
27
+ │ ├── __init__.py
28
+ │ ├── stock_fetcher.py # yfinance polling
29
+ │ └── crypto_fetcher.py # Binance WebSocket + REST
30
+ ├── tests/
31
+ │ └── test_alert_engine.py # Unit tests
32
+ ├── requirements.txt
33
+ ├── .env.example
34
+ └── README.md
35
+ ```
36
+
37
+ ## 🚀 Quick Start
38
+
39
+ ### 1. Prerequisites
40
+
41
+ - **Python 3.10+** installed
42
+ - A **Telegram account**
43
+
44
+ ### 2. Create a Telegram Bot
45
+
46
+ 1. Open Telegram and search for **@BotFather**
47
+ 2. Send `/newbot` and follow the prompts
48
+ 3. You'll receive a **Bot Token** like `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`
49
+ 4. **Get your Chat ID:**
50
+ - Search for **@userinfobot** on Telegram
51
+ - Send `/start` — it will reply with your Chat ID
52
+ - Alternatively, send a message to your bot, then visit:
53
+ ```
54
+ https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates
55
+ ```
56
+ Look for `"chat":{"id": YOUR_CHAT_ID}`
57
+
58
+ ### 3. Install & Configure
59
+
60
+ ```bash
61
+ # Clone / navigate to the project
62
+ cd photonic-perigee
63
+
64
+ # Create a virtual environment (recommended)
65
+ python -m venv venv
66
+ venv\Scripts\activate # Windows
67
+ # source venv/bin/activate # macOS/Linux
68
+
69
+ # Install dependencies
70
+ pip install -r requirements.txt
71
+
72
+ # Configure environment
73
+ copy .env.example .env # Windows
74
+ # cp .env.example .env # macOS/Linux
75
+
76
+ # Edit .env with your Telegram credentials
77
+ notepad .env
78
+ ```
79
+
80
+ Fill in your `.env`:
81
+ ```env
82
+ TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
83
+ TELEGRAM_CHAT_ID=987654321
84
+ ```
85
+
86
+ ### 4. Run the Bot
87
+
88
+ ```bash
89
+ # Live mode (sends Telegram alerts)
90
+ python main.py
91
+
92
+ # Dry-run mode (console alerts only, no Telegram needed)
93
+ python main.py --dry-run
94
+ ```
95
+
96
+ ### 5. Run Tests
97
+
98
+ ```bash
99
+ python -m pytest tests/ -v
100
+ ```
101
+
102
+ ## 💬 Telegram Commands
103
+
104
+ | Command | Description | Example |
105
+ |---|---|---|
106
+ | `/add <ASSET> <MIN> <MAX>` | Start tracking an asset | `/add BTC 60000 62000` |
107
+ | `/remove <ASSET>` | Stop tracking an asset | `/remove BTC` |
108
+ | `/list` | Show all tracked assets | `/list` |
109
+ | `/status` | Bot health check & uptime | `/status` |
110
+ | `/help` | Show all commands | `/help` |
111
+
112
+ ### Supported Asset Names
113
+
114
+ | Category | Assets |
115
+ |---|---|
116
+ | Commodities | `GOLD`, `SILVER`, `CRUDE_OIL` |
117
+ | Crypto | `BTC`, `ETH`, `XRP`, `SOL` |
118
+ | Stocks | `NVIDIA`, `TESLA`, `GOOGLE`, `AMAZON`, `ORACLE` |
119
+ | Indices | `SP500` |
120
+
121
+ ## 🔔 How Alerts Work
122
+
123
+ The bot uses a **state machine** to avoid duplicate alerts:
124
+
125
+ ```
126
+ Price OUTSIDE range → enters range → 🔔 ALERT sent
127
+ Price INSIDE range → stays inside → no alert (dedup)
128
+ Price INSIDE range → exits range → state resets
129
+ Price OUTSIDE range → re-enters → 🔔 ALERT sent again
130
+ ```
131
+
132
+ ### Sample Alert Message
133
+
134
+ ```
135
+ 🔔 Price Alert — BTC
136
+ ━━━━━━━━━━━━━━━━━━━━━━━
137
+ 💰 Current Price: $61,234.5600
138
+ 📊 Target Range: $60,000.0000 – $62,000.0000
139
+ 🕐 Time (UTC): 2026-03-22 06:15:30
140
+ ━━━━━━━━━━━━━━━━━━━━━━━
141
+ Price has entered your defined range!
142
+ ```
143
+
144
+ ## ⚙️ Configuration
145
+
146
+ Edit `config.py` to customise:
147
+
148
+ | Setting | Default | Description |
149
+ |---|---|---|
150
+ | `STOCK_POLL_INTERVAL` | `15` | Seconds between yfinance polls |
151
+ | `CRYPTO_WS_RECONNECT_DELAY` | `5` | Seconds before WebSocket reconnect |
152
+ | `DEFAULT_RANGES` | See file | Pre-loaded price ranges |
153
+
154
+ ## ☁️ Deployment
155
+
156
+ ### Option A: Run on a VPS (e.g., DigitalOcean, AWS EC2)
157
+
158
+ ```bash
159
+ # SSH into your server
160
+ ssh user@your-server
161
+
162
+ # Clone the project, install dependencies
163
+ git clone <your-repo-url>
164
+ cd photonic-perigee
165
+ python3 -m venv venv && source venv/bin/activate
166
+ pip install -r requirements.txt
167
+
168
+ # Configure .env
169
+ nano .env
170
+
171
+ # Run with nohup (persists after disconnecting)
172
+ nohup python main.py > output.log 2>&1 &
173
+
174
+ # Or use systemd for auto-restart (create /etc/systemd/system/pricealert.service):
175
+ ```
176
+
177
+ **systemd service file** (`/etc/systemd/system/pricealert.service`):
178
+ ```ini
179
+ [Unit]
180
+ Description=Price Alert Bot
181
+ After=network.target
182
+
183
+ [Service]
184
+ Type=simple
185
+ User=ubuntu
186
+ WorkingDirectory=/home/ubuntu/photonic-perigee
187
+ ExecStart=/home/ubuntu/photonic-perigee/venv/bin/python main.py
188
+ Restart=always
189
+ RestartSec=10
190
+ EnvironmentFile=/home/ubuntu/photonic-perigee/.env
191
+
192
+ [Install]
193
+ WantedBy=multi-user.target
194
+ ```
195
+
196
+ ```bash
197
+ sudo systemctl enable pricealert
198
+ sudo systemctl start pricealert
199
+ sudo systemctl status pricealert
200
+ ```
201
+
202
+ ### Option B: Run on Replit
203
+
204
+ 1. Create a new **Python** Repl
205
+ 2. Upload all project files
206
+ 3. Add `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` in Replit's **Secrets** tab
207
+ 4. Set the run command to `python main.py`
208
+ 5. Click **Run** — the bot will stay alive as long as the Repl is active
209
+ 6. Use Replit's **Always On** feature (paid) for 24/7 uptime
210
+
211
+ ## 📝 Logging
212
+
213
+ - **Console**: INFO level and above
214
+ - **File** (`bot.log`): DEBUG level, rotating at 5MB with 3 backups
215
+ - Log format: `2026-03-22 06:15:30 | INFO | main | Bot started`
216
+
217
+ ## 🛡️ Error Handling
218
+
219
+ | Scenario | Behaviour |
220
+ |---|---|
221
+ | yfinance API failure | Exponential backoff (max 120s) |
222
+ | Binance WebSocket disconnect | Auto-reconnect with backoff (5 attempts) |
223
+ | WebSocket fails repeatedly | Falls back to REST API polling |
224
+ | Telegram send failure | Logged, retried on next alert |
225
+ | Invalid command input | User-friendly error message |
226
+
227
+ ## License
228
+
229
+ MIT
alert_engine.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ alert_engine.py — Core alert logic with state-machine deduplication,
3
+ alert cooldown, and in-memory alert history.
4
+
5
+ State machine per asset:
6
+ OUTSIDE — price is outside the user-defined range
7
+ INSIDE — price has entered the range (alert was already sent)
8
+
9
+ Transitions:
10
+ OUTSIDE → INSIDE → triggers an alert (subject to cooldown)
11
+ INSIDE → INSIDE → no-op (dedup)
12
+ INSIDE → OUTSIDE → resets state so next entry can trigger again
13
+ OUTSIDE → OUTSIDE → no-op
14
+
15
+ Cooldown:
16
+ After an alert fires for an asset, the same asset cannot fire again
17
+ for ALERT_COOLDOWN_SECONDS seconds, even if it leaves and re-enters
18
+ the range. This prevents spam when price oscillates at a boundary.
19
+ """
20
+
21
+ import threading
22
+ from collections import deque
23
+ from dataclasses import dataclass, field
24
+ from datetime import datetime, timezone
25
+ from enum import Enum, auto
26
+ from typing import Callable, Deque, Optional
27
+
28
+ import config
29
+ from logger import get_logger
30
+
31
+ log = get_logger("alert_engine")
32
+
33
+
34
+ class RangeState(Enum):
35
+ OUTSIDE = auto()
36
+ INSIDE = auto()
37
+
38
+
39
+ @dataclass
40
+ class AssetAlert:
41
+ """Tracked state for a single asset."""
42
+ name: str
43
+ min_price: float
44
+ max_price: float
45
+ state: RangeState = RangeState.OUTSIDE
46
+ last_price: Optional[float] = None
47
+ last_alert_time: Optional[datetime] = None
48
+ # Whether alerts for this asset are paused by the user
49
+ paused: bool = False
50
+
51
+
52
+ @dataclass
53
+ class AlertEvent:
54
+ """Data object passed to the alert callback and stored in history."""
55
+ asset_name: str
56
+ price: float
57
+ min_price: float
58
+ max_price: float
59
+ timestamp: datetime
60
+
61
+
62
+ class AlertEngine:
63
+ """
64
+ Thread-safe alert engine that evaluates price updates against
65
+ user-defined ranges and fires callbacks on state transitions.
66
+
67
+ Features:
68
+ - Deduplication via INSIDE/OUTSIDE state machine
69
+ - Per-asset alert cooldown (configurable via config.ALERT_COOLDOWN_SECONDS)
70
+ - In-memory alert history (capped at config.ALERT_HISTORY_MAX)
71
+ - Per-asset pause/resume
72
+ - save/load via persistence module
73
+ """
74
+
75
+ def __init__(self, on_alert: Callable[[AlertEvent], None]) -> None:
76
+ self._lock = threading.Lock()
77
+ self._assets: dict[str, AssetAlert] = {}
78
+ self._on_alert = on_alert
79
+ self._history: Deque[AlertEvent] = deque(maxlen=config.ALERT_HISTORY_MAX)
80
+ # Global pause flag — silences ALL alerts when True
81
+ self._globally_paused: bool = False
82
+
83
+ # ── Pause / Resume ───────────────────────────────────────────────────
84
+
85
+ def pause_all(self) -> None:
86
+ """Pause all alert notifications globally."""
87
+ with self._lock:
88
+ self._globally_paused = True
89
+ log.info("All alerts paused globally")
90
+
91
+ def resume_all(self) -> None:
92
+ """Resume all alert notifications globally."""
93
+ with self._lock:
94
+ self._globally_paused = False
95
+ log.info("All alerts resumed globally")
96
+
97
+ def is_paused(self) -> bool:
98
+ with self._lock:
99
+ return self._globally_paused
100
+
101
+ # ── Asset management ─────────────────────────────────────────────────
102
+
103
+ def add_asset(self, name: str, min_price: float, max_price: float) -> None:
104
+ """Add or update a tracked asset with a price range."""
105
+ name = name.upper()
106
+ with self._lock:
107
+ if name in self._assets:
108
+ existing = self._assets[name]
109
+ existing.min_price = min_price
110
+ existing.max_price = max_price
111
+ existing.state = RangeState.OUTSIDE # reset on range change
112
+ log.info("Updated range for %s: $%.4f – $%.4f", name, min_price, max_price)
113
+ else:
114
+ self._assets[name] = AssetAlert(
115
+ name=name, min_price=min_price, max_price=max_price
116
+ )
117
+ log.info("Added asset %s: $%.4f – $%.4f", name, min_price, max_price)
118
+
119
+ def remove_asset(self, name: str) -> bool:
120
+ """Remove a tracked asset. Returns True if it existed."""
121
+ name = name.upper()
122
+ with self._lock:
123
+ if name in self._assets:
124
+ del self._assets[name]
125
+ log.info("Removed asset %s", name)
126
+ return True
127
+ return False
128
+
129
+ def get_tracked_assets(self) -> dict[str, tuple[float, float]]:
130
+ """Return {name: (min, max)} for all tracked assets."""
131
+ with self._lock:
132
+ return {
133
+ name: (a.min_price, a.max_price)
134
+ for name, a in self._assets.items()
135
+ }
136
+
137
+ def get_asset_details(self) -> list[dict]:
138
+ """Return detailed info for all tracked assets (for /list command and persistence)."""
139
+ with self._lock:
140
+ result = []
141
+ for a in self._assets.values():
142
+ result.append({
143
+ "name": a.name,
144
+ "min": a.min_price,
145
+ "max": a.max_price,
146
+ "state": a.state.name,
147
+ "last_price": a.last_price,
148
+ "last_alert": a.last_alert_time.isoformat() if a.last_alert_time else None,
149
+ "paused": a.paused,
150
+ })
151
+ return result
152
+
153
+ def get_asset_price(self, name: str) -> Optional[float]:
154
+ """Return the latest known price for an asset, or None if unavailable."""
155
+ name = name.upper()
156
+ with self._lock:
157
+ asset = self._assets.get(name)
158
+ return asset.last_price if asset else None
159
+
160
+ # ── Alert History ────────────────────────────────────────────────────
161
+
162
+ def get_alert_history(self, limit: int = 10) -> list[AlertEvent]:
163
+ """Return up to `limit` most-recent alert events (newest first)."""
164
+ with self._lock:
165
+ events = list(self._history)
166
+ events.reverse()
167
+ return events[:limit]
168
+
169
+ # ── Price evaluation ─────────────────────────────────────────────────
170
+
171
+ def on_price_update(self, name: str, price: float) -> None:
172
+ """
173
+ Called by fetchers whenever a new price is received.
174
+ Evaluates the state machine and fires the alert callback if needed.
175
+ """
176
+ name = name.upper()
177
+ with self._lock:
178
+ asset = self._assets.get(name)
179
+ if asset is None:
180
+ return # not tracked
181
+
182
+ asset.last_price = price
183
+ in_range = asset.min_price <= price <= asset.max_price
184
+
185
+ if in_range and asset.state == RangeState.OUTSIDE:
186
+ # Check global pause
187
+ if self._globally_paused or asset.paused:
188
+ log.debug("%s would alert at $%.4f but is paused", name, price)
189
+ asset.state = RangeState.INSIDE # still update state
190
+ return
191
+
192
+ # Check cooldown
193
+ if asset.last_alert_time is not None:
194
+ now_utc = datetime.now(timezone.utc)
195
+ elapsed = (now_utc - asset.last_alert_time).total_seconds()
196
+ if elapsed < config.ALERT_COOLDOWN_SECONDS:
197
+ remaining = int(config.ALERT_COOLDOWN_SECONDS - elapsed)
198
+ log.debug(
199
+ "%s in range but cooldown active (%ds remaining)", name, remaining
200
+ )
201
+ asset.state = RangeState.INSIDE
202
+ return
203
+
204
+ # Price just entered the range → fire alert
205
+ asset.state = RangeState.INSIDE
206
+ now = datetime.now(timezone.utc)
207
+ asset.last_alert_time = now
208
+ event = AlertEvent(
209
+ asset_name=name,
210
+ price=price,
211
+ min_price=asset.min_price,
212
+ max_price=asset.max_price,
213
+ timestamp=now,
214
+ )
215
+ self._history.append(event)
216
+ log.info(
217
+ "🔔 ALERT: %s entered range [$%.4f – $%.4f] at $%.4f",
218
+ name, asset.min_price, asset.max_price, price,
219
+ )
220
+ # Release lock before callback to avoid deadlocks
221
+ self._lock.release()
222
+ try:
223
+ self._on_alert(event)
224
+ finally:
225
+ self._lock.acquire()
226
+
227
+ elif not in_range and asset.state == RangeState.INSIDE:
228
+ # Price exited the range → reset for re-alerting
229
+ asset.state = RangeState.OUTSIDE
230
+ log.debug(
231
+ "%s exited range at $%.4f — state reset to OUTSIDE", name, price
232
+ )
backend/main.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ backend/main.py — FastAPI server exposing the alert engine via REST & WebSocket.
3
+
4
+ Endpoints:
5
+ GET / — health check
6
+ GET /status — uptime, asset counts, alert stats
7
+ GET /assets/available — list all supported assets ← MUST be before /assets/{name}
8
+ GET /assets — list tracked assets
9
+ POST /assets — add / update a tracked asset
10
+ DELETE /assets/{name} — stop tracking an asset
11
+ GET /history — last 100 alert events
12
+ WS /ws — real-time price & alert stream
13
+ """
14
+
15
+ import asyncio
16
+ import json
17
+ import logging
18
+ import sys
19
+ import os
20
+ import threading
21
+ from collections import deque
22
+ from contextlib import asynccontextmanager
23
+ from datetime import datetime, timezone
24
+ from enum import Enum
25
+ from typing import Any, Deque
26
+
27
+ import aiohttp
28
+ import uvicorn
29
+ import websockets
30
+ import yfinance as yf
31
+ from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect
32
+ from fastapi.middleware.cors import CORSMiddleware
33
+ from pydantic import BaseModel
34
+
35
+ # ── Allow importing root-level config when run from backend/ ─────────────────
36
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
37
+ if ROOT_DIR not in sys.path:
38
+ sys.path.insert(0, ROOT_DIR)
39
+
40
+ import config as cfg # noqa: E402 (import after sys.path fix)
41
+
42
+ PORT = int(os.getenv("BACKEND_PORT", "8000"))
43
+
44
+ # ── Logging ───────────────────────────────────────────────────────────────────
45
+ logging.basicConfig(
46
+ level=logging.INFO,
47
+ format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
48
+ datefmt="%Y-%m-%d %H:%M:%S",
49
+ )
50
+ log = logging.getLogger("backend")
51
+
52
+ # ─── Pydantic Models ──────────────────────────────────────────────────────────
53
+
54
+
55
+ class RangeState(str, Enum):
56
+ OUTSIDE = "OUTSIDE"
57
+ INSIDE = "INSIDE"
58
+
59
+
60
+ class AssetAlert(BaseModel):
61
+ name: str
62
+ min_price: float
63
+ max_price: float
64
+ state: RangeState = RangeState.OUTSIDE
65
+ last_price: float | None = None
66
+ last_alert_time: str | None = None
67
+
68
+
69
+ class AddAssetRequest(BaseModel):
70
+ name: str
71
+ min_price: float
72
+ max_price: float
73
+
74
+
75
+ class AlertEvent(BaseModel):
76
+ asset_name: str
77
+ price: float
78
+ min_price: float
79
+ max_price: float
80
+ timestamp: str
81
+
82
+
83
+ # ─── Alert Engine ─────────────────────────────────────────────────────────────
84
+
85
+
86
+ class AlertEngine:
87
+ """Thread-safe alert engine with cooldown and in-memory history."""
88
+
89
+ def __init__(self) -> None:
90
+ self._lock = threading.Lock()
91
+ self._assets: dict[str, dict] = {}
92
+ self._callbacks: list = []
93
+ self._history: Deque[AlertEvent] = deque(maxlen=cfg.ALERT_HISTORY_MAX)
94
+ self._start_time = datetime.now(timezone.utc)
95
+
96
+ # ── Asset management ─────────────────────────────────────────────────
97
+
98
+ def add_asset(self, name: str, min_price: float, max_price: float) -> AssetAlert:
99
+ name = name.upper()
100
+ with self._lock:
101
+ if name in self._assets:
102
+ self._assets[name].update({
103
+ "min_price": min_price,
104
+ "max_price": max_price,
105
+ "state": RangeState.OUTSIDE,
106
+ })
107
+ log.info("Updated range for %s: $%.4f – $%.4f", name, min_price, max_price)
108
+ else:
109
+ self._assets[name] = {
110
+ "name": name,
111
+ "min_price": min_price,
112
+ "max_price": max_price,
113
+ "state": RangeState.OUTSIDE,
114
+ "last_price": None,
115
+ "last_alert_time": None,
116
+ }
117
+ log.info("Added asset %s: $%.4f – $%.4f", name, min_price, max_price)
118
+ return AssetAlert(**self._assets[name])
119
+
120
+ def remove_asset(self, name: str) -> bool:
121
+ name = name.upper()
122
+ with self._lock:
123
+ if name in self._assets:
124
+ del self._assets[name]
125
+ log.info("Removed asset %s", name)
126
+ return True
127
+ return False
128
+
129
+ def get_tracked_assets(self) -> list[AssetAlert]:
130
+ with self._lock:
131
+ return [AssetAlert(**a) for a in self._assets.values()]
132
+
133
+ def get_active_assets(self) -> dict[str, tuple[float, float]]:
134
+ with self._lock:
135
+ return {n: (a["min_price"], a["max_price"]) for n, a in self._assets.items()}
136
+
137
+ def get_history(self) -> list[dict]:
138
+ with self._lock:
139
+ return list(self._history)
140
+
141
+ # ── Price evaluation ─────────────────────────────────────────────────
142
+
143
+ def on_price_update(self, name: str, price: float) -> AlertEvent | None:
144
+ name = name.upper()
145
+ with self._lock:
146
+ asset = self._assets.get(name)
147
+ if not asset:
148
+ return None
149
+
150
+ asset["last_price"] = price
151
+ in_range = asset["min_price"] <= price <= asset["max_price"]
152
+
153
+ if in_range and asset["state"] == RangeState.OUTSIDE:
154
+ # Cooldown check
155
+ if asset["last_alert_time"] is not None:
156
+ last_t = datetime.fromisoformat(asset["last_alert_time"])
157
+ elapsed = (datetime.now(timezone.utc) - last_t).total_seconds()
158
+ if elapsed < cfg.ALERT_COOLDOWN_SECONDS:
159
+ asset["state"] = RangeState.INSIDE
160
+ return None
161
+
162
+ asset["state"] = RangeState.INSIDE
163
+ now = datetime.now(timezone.utc)
164
+ asset["last_alert_time"] = now.isoformat()
165
+ event = AlertEvent(
166
+ asset_name=name,
167
+ price=price,
168
+ min_price=asset["min_price"],
169
+ max_price=asset["max_price"],
170
+ timestamp=now.isoformat(),
171
+ )
172
+ self._history.append(event)
173
+ log.info(
174
+ "🔔 ALERT: %s entered range [$%.4f – $%.4f] at $%.4f",
175
+ name, asset["min_price"], asset["max_price"], price,
176
+ )
177
+ self._notify(event)
178
+ return event
179
+
180
+ elif not in_range and asset["state"] == RangeState.INSIDE:
181
+ asset["state"] = RangeState.OUTSIDE
182
+ log.debug("%s exited range at $%.4f — state reset", name, price)
183
+ return None
184
+
185
+ # ── Subscriptions ─────────────────────────────────────────────────────
186
+
187
+ def subscribe(self, callback) -> None:
188
+ self._callbacks.append(callback)
189
+
190
+ def _notify(self, event: AlertEvent) -> None:
191
+ for cb in self._callbacks:
192
+ try:
193
+ cb(event)
194
+ except Exception as exc:
195
+ log.warning("Alert callback error: %s", exc)
196
+
197
+ # ── Stats ─────────────────────────────────────────────────────────────
198
+
199
+ def uptime_seconds(self) -> float:
200
+ return (datetime.now(timezone.utc) - self._start_time).total_seconds()
201
+
202
+
203
+ engine = AlertEngine()
204
+
205
+ # Load defaults from shared config
206
+ for _name, (_min, _max) in cfg.DEFAULT_RANGES.items():
207
+ engine.add_asset(_name, _min, _max)
208
+
209
+ # ─── WebSocket Manager ────────────────────────────────────────────────────────
210
+
211
+
212
+ class ConnectionManager:
213
+ def __init__(self) -> None:
214
+ self._connections: list[WebSocket] = []
215
+ self._lock = asyncio.Lock()
216
+
217
+ async def connect(self, websocket: WebSocket) -> None:
218
+ await websocket.accept()
219
+ async with self._lock:
220
+ self._connections.append(websocket)
221
+ log.info("WS client connected (total: %d)", len(self._connections))
222
+
223
+ async def disconnect(self, websocket: WebSocket) -> None:
224
+ async with self._lock:
225
+ if websocket in self._connections:
226
+ self._connections.remove(websocket)
227
+ log.info("WS client disconnected (total: %d)", len(self._connections))
228
+
229
+ async def broadcast(self, message: dict) -> None:
230
+ """Broadcast to all connected WebSocket clients; remove dead ones."""
231
+ dead: list[WebSocket] = []
232
+ async with self._lock:
233
+ targets = list(self._connections)
234
+ for ws in targets:
235
+ try:
236
+ await ws.send_json(message)
237
+ except Exception:
238
+ dead.append(ws)
239
+ for ws in dead:
240
+ await self.disconnect(ws)
241
+
242
+
243
+ manager = ConnectionManager()
244
+
245
+ # ── Bridge: sync alert callback → async broadcast ────────────────────────────
246
+ # We schedule the coroutine on the running event loop from a sync context.
247
+ _loop: asyncio.AbstractEventLoop | None = None
248
+
249
+
250
+ def _on_alert(event: AlertEvent) -> None:
251
+ """Sync callback wired into the alert engine — schedules async broadcast."""
252
+ if _loop is not None and _loop.is_running():
253
+ asyncio.run_coroutine_threadsafe(
254
+ manager.broadcast({"type": "alert", "data": event.model_dump()}),
255
+ _loop,
256
+ )
257
+
258
+
259
+ def _on_price_update(name: str, price: float) -> None:
260
+ """Broadcast every price tick to WebSocket clients."""
261
+ if _loop is not None and _loop.is_running():
262
+ asyncio.run_coroutine_threadsafe(
263
+ manager.broadcast({
264
+ "type": "price_update",
265
+ "data": {
266
+ "name": name,
267
+ "price": price,
268
+ "timestamp": datetime.now(timezone.utc).isoformat(),
269
+ },
270
+ }),
271
+ _loop,
272
+ )
273
+
274
+
275
+ engine.subscribe(_on_alert)
276
+
277
+ # ─── FastAPI App ──────────────────────────────────────────────────────────────
278
+
279
+
280
+ @asynccontextmanager
281
+ async def lifespan(app: FastAPI):
282
+ global _loop
283
+ _loop = asyncio.get_running_loop()
284
+ log.info("Starting background price fetchers…")
285
+ t1 = asyncio.create_task(poll_stocks(), name="stock_poller")
286
+ t2 = asyncio.create_task(stream_crypto(), name="crypto_streamer")
287
+ yield
288
+ t1.cancel()
289
+ t2.cancel()
290
+ await asyncio.gather(t1, t2, return_exceptions=True)
291
+ log.info("Backend shut down cleanly.")
292
+
293
+
294
+ app = FastAPI(
295
+ title="Price Alert API",
296
+ version="2.0.0",
297
+ description="Real-time multi-asset price alert engine",
298
+ lifespan=lifespan,
299
+ )
300
+
301
+ app.add_middleware(
302
+ CORSMiddleware,
303
+ allow_origins=["*"],
304
+ allow_credentials=True,
305
+ allow_methods=["*"],
306
+ allow_headers=["*"],
307
+ )
308
+
309
+ # ─── REST Endpoints ───────────────────────────────────────────────────────────
310
+
311
+
312
+ @app.get("/")
313
+ async def root() -> dict:
314
+ return {"status": "running", "message": "Price Alert API v2", "docs": "/docs"}
315
+
316
+
317
+ @app.get("/status")
318
+ async def status() -> dict:
319
+ uptime = engine.uptime_seconds()
320
+ hours = int(uptime // 3600)
321
+ minutes = int((uptime % 3600) // 60)
322
+ seconds = int(uptime % 60)
323
+ tracked = engine.get_tracked_assets()
324
+ crypto = sum(1 for a in tracked if a.name in cfg.BINANCE_SYMBOLS)
325
+ history = engine.get_history()
326
+ return {
327
+ "uptime": f"{hours}h {minutes}m {seconds}s",
328
+ "tracked_assets": len(tracked),
329
+ "crypto_assets": crypto,
330
+ "stock_assets": len(tracked) - crypto,
331
+ "alerts_fired": len(history),
332
+ "cooldown_seconds": cfg.ALERT_COOLDOWN_SECONDS,
333
+ "ws_clients": len(manager._connections),
334
+ }
335
+
336
+
337
+ # ⚠️ /assets/available MUST be declared before /assets/{name} to avoid route shadowing
338
+ @app.get("/assets/available")
339
+ async def available_assets() -> dict:
340
+ commodities = [k for k in cfg.YFINANCE_TICKERS if k in ("GOLD", "SILVER", "CRUDE_OIL")]
341
+ stocks = [k for k in cfg.YFINANCE_TICKERS if k not in commodities]
342
+ return {
343
+ "commodities": sorted(commodities),
344
+ "stocks": sorted(stocks),
345
+ "crypto": sorted(cfg.BINANCE_SYMBOLS.keys()),
346
+ "all": sorted(cfg.ALL_ASSETS),
347
+ }
348
+
349
+
350
+ @app.get("/assets")
351
+ async def list_assets() -> list[AssetAlert]:
352
+ return engine.get_tracked_assets()
353
+
354
+
355
+ @app.post("/assets", status_code=201)
356
+ async def add_asset(req: AddAssetRequest) -> AssetAlert:
357
+ name = req.name.upper()
358
+ if name not in cfg.ALL_ASSETS:
359
+ raise HTTPException(400, f"Unknown asset '{name}'. See /assets/available.")
360
+ if req.min_price >= req.max_price:
361
+ raise HTTPException(400, "min_price must be strictly less than max_price.")
362
+ return engine.add_asset(name, req.min_price, req.max_price)
363
+
364
+
365
+ @app.delete("/assets/{name}")
366
+ async def remove_asset(name: str) -> dict:
367
+ if not engine.remove_asset(name.upper()):
368
+ raise HTTPException(404, f"Asset '{name.upper()}' is not being tracked.")
369
+ return {"message": f"Asset {name.upper()} removed successfully."}
370
+
371
+
372
+ @app.get("/history")
373
+ async def alert_history() -> list[dict]:
374
+ """Return up to the last 100 alert events (newest first)."""
375
+ events = engine.get_history()
376
+ events.reverse()
377
+ return [e.model_dump() if hasattr(e, "model_dump") else dict(e) for e in events]
378
+
379
+
380
+ # ─── WebSocket ────────────────────────────────────────────────────────────────
381
+
382
+
383
+ @app.websocket("/ws")
384
+ async def websocket_endpoint(websocket: WebSocket) -> None:
385
+ await manager.connect(websocket)
386
+ # Send a welcome snapshot so the client knows what's tracked
387
+ await websocket.send_json({
388
+ "type": "snapshot",
389
+ "data": [a.model_dump() for a in engine.get_tracked_assets()],
390
+ })
391
+ try:
392
+ while True:
393
+ raw = await websocket.receive_text()
394
+ try:
395
+ msg = json.loads(raw)
396
+ if msg.get("type") == "ping":
397
+ await websocket.send_json({"type": "pong"})
398
+ except json.JSONDecodeError:
399
+ pass
400
+ except WebSocketDisconnect:
401
+ await manager.disconnect(websocket)
402
+
403
+
404
+ # ─── Background Price Fetchers ────────────────────────────────────────────────
405
+
406
+
407
+ async def poll_stocks() -> None:
408
+ """Poll yfinance for stocks/commodities on a fixed interval."""
409
+ log.info("Stock poller started (interval=%ds)", cfg.STOCK_POLL_INTERVAL)
410
+ while True:
411
+ try:
412
+ active = engine.get_active_assets()
413
+ to_fetch = {n: cfg.YFINANCE_TICKERS[n] for n in cfg.YFINANCE_TICKERS if n in active}
414
+ if to_fetch:
415
+ data = await asyncio.to_thread(_fetch_stocks_sync, to_fetch)
416
+ for name, price in data.items():
417
+ if price:
418
+ engine.on_price_update(name, price)
419
+ _on_price_update(name, price)
420
+ except Exception as exc:
421
+ log.warning("Stock poller error: %s", exc)
422
+ await asyncio.sleep(cfg.STOCK_POLL_INTERVAL)
423
+
424
+
425
+ def _fetch_stocks_sync(to_fetch: dict[str, str]) -> dict[str, float | None]:
426
+ """Sync yfinance fetch helper (runs in thread pool)."""
427
+ results: dict[str, float | None] = {}
428
+ for name, ticker_str in to_fetch.items():
429
+ try:
430
+ fi = yf.Ticker(ticker_str).fast_info
431
+ price = None
432
+ try:
433
+ price = fi.last_price
434
+ except AttributeError:
435
+ pass
436
+ if not price:
437
+ try:
438
+ price = fi.lastPrice
439
+ except AttributeError:
440
+ pass
441
+ results[name] = float(price) if price and float(price) > 0 else None
442
+ except Exception as exc:
443
+ log.debug("yfinance error for %s: %s", ticker_str, exc)
444
+ results[name] = None
445
+ return results
446
+
447
+
448
+ async def stream_crypto() -> None:
449
+ """Stream crypto prices from Binance WebSocket with REST fallback."""
450
+ log.info("Crypto streamer started")
451
+ failures = 0
452
+ while True:
453
+ try:
454
+ active = engine.get_active_assets()
455
+ streams = [
456
+ f"{sym}@miniTicker"
457
+ for name, sym in cfg.BINANCE_SYMBOLS.items()
458
+ if name in active
459
+ ]
460
+ if not streams:
461
+ await asyncio.sleep(10)
462
+ continue
463
+
464
+ url = f"wss://stream.binance.com:9443/stream?streams={'/'.join(streams)}"
465
+ async with websockets.connect(url, ping_interval=20, ping_timeout=10) as ws:
466
+ log.info("Binance WebSocket connected ✓ (%d streams)", len(streams))
467
+ failures = 0
468
+ async for raw_msg in ws:
469
+ try:
470
+ msg = json.loads(raw_msg)
471
+ data = msg.get("data", {})
472
+ name = cfg.BINANCE_SYMBOL_TO_NAME.get(data.get("s", "").lower())
473
+ if name and "c" in data:
474
+ price = float(data["c"])
475
+ engine.on_price_update(name, price)
476
+ _on_price_update(name, price)
477
+ except (json.JSONDecodeError, ValueError, KeyError):
478
+ pass
479
+ except Exception as exc:
480
+ failures += 1
481
+ backoff = min(cfg.CRYPTO_WS_RECONNECT_DELAY * failures, 60)
482
+ log.warning("Crypto streamer error (attempt %d): %s — retry in %ds", failures, exc, backoff)
483
+ await asyncio.sleep(backoff)
484
+
485
+
486
+ # ─── Entry point ──────────────────────────────────────────────────────────────
487
+
488
+ if __name__ == "__main__":
489
+ uvicorn.run("main:app", host="0.0.0.0", port=PORT, reload=False)
backend/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi==0.109.0
2
+ uvicorn[standard]==0.27.0
3
+ websockets==12.0
4
+ python-dotenv==1.0.0
5
+ yfinance==0.2.36
6
+ aiohttp==3.9.3
7
+ pydantic==2.5.3
commodities-alerts.html ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Commodity Price Alerts</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #1a1a1a; color: #f8fafc; min-height: 100vh; padding: 1rem; }
10
+ .container { max-width: 800px; margin: 0 auto; }
11
+ header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #333; }
12
+ h1 { font-size: 1.5rem; background: linear-gradient(135deg, #f59e0b, #d97706); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
13
+ .debug { background: #111; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-family: monospace; font-size: 0.75rem; white-space: pre-wrap; max-height: 80px; overflow-y: auto; color: #94a3b8; }
14
+ .card { background: #222; border: 1px solid #333; border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; transition: all 0.3s; }
15
+ .card:hover { border-color: #f59e0b; }
16
+ .card.flash { animation: flash 0.5s ease 3; }
17
+ @keyframes flash { 0%,100% { border-color: #333; box-shadow: none; } 50% { border-color: #f59e0b; box-shadow: 0 0 30px #f59e0b50; } }
18
+ .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
19
+ .asset-name { font-size: 1.25rem; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
20
+ .asset-icon { font-size: 1.5rem; }
21
+ .price { font-size: 1.75rem; font-weight: 700; color: #f59e0b; margin-bottom: 0.5rem; }
22
+ .unit { font-size: 0.875rem; color: #94a3b8; margin-bottom: 0.5rem; }
23
+ .range { color: #94a3b8; font-size: 0.875rem; margin-bottom: 0.75rem; }
24
+ .state { padding: 0.4rem 0.8rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; display: inline-block; }
25
+ .state.inside { background: #22c55e20; color: #22c55e; }
26
+ .state.outside { background: #374151; color: #94a3b8; }
27
+ .btn { padding: 0.5rem 1rem; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.875rem; }
28
+ .btn-primary { background: #f59e0b; color: #1a1a1a; }
29
+ .btn-primary:hover { background: #fbbf24; }
30
+ .btn-danger { background: transparent; color: #ef4444; border: 1px solid #ef4444; }
31
+ .btn-danger:hover { background: #ef4444; color: white; }
32
+ .modal { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; align-items: center; justify-content: center; z-index: 100; }
33
+ .modal.active { display: flex; }
34
+ .modal-content { background: #222; border: 1px solid #333; border-radius: 16px; padding: 2rem; width: 90%; max-width: 400px; }
35
+ .modal h2 { margin-bottom: 1.5rem; }
36
+ .form-group { margin-bottom: 1rem; }
37
+ .form-group label { display: block; margin-bottom: 0.5rem; color: #94a3b8; font-size: 0.875rem; }
38
+ .form-group input, .form-group select { width: 100%; padding: 0.75rem; background: #1a1a1a; border: 1px solid #333; border-radius: 8px; color: #f8fafc; font-size: 1rem; }
39
+ .form-group input:focus, .form-group select:focus { outline: none; border-color: #f59e0b; }
40
+ .btn-block { width: 100%; padding: 1rem; margin-top: 0.5rem; }
41
+ .toast { position: fixed; top: 20px; right: 20px; background: #222; border: 2px solid #22c55e; border-radius: 12px; padding: 1rem 1.5rem; z-index: 1000; animation: slideIn 0.3s; }
42
+ @keyframes slideIn { from { opacity: 0; transform: translateX(120%); } to { opacity: 1; transform: translateX(0); } }
43
+ .toast-title { font-weight: 700; margin-bottom: 0.25rem; display: flex; align-items: center; gap: 0.5rem; }
44
+ .toast-msg { font-size: 0.875rem; color: #94a3b8; }
45
+ .empty { text-align: center; padding: 3rem; color: #94a3b8; }
46
+ .section-title { font-size: 1.1rem; margin: 1.5rem 0 1rem; color: #94a3b8; }
47
+ .alert-item { background: #222; border: 1px solid #333; border-radius: 8px; padding: 1rem; margin-bottom: 0.5rem; display: flex; gap: 1rem; align-items: center; }
48
+ .status { display: flex; gap: 1rem; margin-bottom: 1rem; font-size: 0.875rem; color: #94a3b8; }
49
+ .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #f59e0b; }
50
+ .note { background: #333; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.875rem; color: #94a3b8; }
51
+ </style>
52
+ </head>
53
+ <body>
54
+ <div id="toasts"></div>
55
+
56
+ <div class="container">
57
+ <header>
58
+ <h1>🥇 Commodity Alerts</h1>
59
+ <button class="btn btn-primary" onclick="showModal()">+ Add Alert</button>
60
+ </header>
61
+
62
+ <div class="note">Prices from Yahoo Finance (via proxy)</div>
63
+ <div class="status"><span class="status-dot"></span> Live commodity prices</div>
64
+ <div id="debug" class="debug">Initializing...</div>
65
+ <div id="alertsContainer"></div>
66
+
67
+ <div class="section-title">📋 Alert History</div>
68
+ <div id="historyContainer"></div>
69
+ </div>
70
+
71
+ <div id="modal" class="modal" onclick="if(event.target===this)hideModal()">
72
+ <div class="modal-content">
73
+ <h2>Add Commodity Alert</h2>
74
+ <div class="form-group">
75
+ <label>Commodity</label>
76
+ <select id="assetSelect">
77
+ <option value="">Select commodity...</option>
78
+ <option value="GC=F">Gold ($/oz)</option>
79
+ <option value="SI=F">Silver ($/oz)</option>
80
+ <option value="PL=F">Platinum ($/oz)</option>
81
+ <option value="PA=F">Palladium ($/oz)</option>
82
+ <option value="CL=F">Crude Oil ($/bbl)</option>
83
+ <option value="NG=F">Natural Gas ($/MMBtu)</option>
84
+ <option value="HG=F">Copper ($/lb)</option>
85
+ <option value="ZC=F">Corn ($/bu)</option>
86
+ <option value="ZS=F">Soybeans ($/bu)</option>
87
+ <option value="ZW=F">Wheat ($/bu)</option>
88
+ </select>
89
+ </div>
90
+ <div class="form-group">
91
+ <label>Min Price</label>
92
+ <input type="number" id="minPrice" step="any" placeholder="1900">
93
+ </div>
94
+ <div class="form-group">
95
+ <label>Max Price</label>
96
+ <input type="number" id="maxPrice" step="any" placeholder="2000">
97
+ </div>
98
+ <button class="btn btn-primary btn-block" onclick="addAlert()">Add Alert</button>
99
+ <button class="btn btn-danger btn-block" onclick="hideModal()">Cancel</button>
100
+ </div>
101
+ </div>
102
+
103
+ <script>
104
+ const COMMODITY_ICONS = {
105
+ 'GC=F': '🥇', 'SI=F': '🥈', 'PL=F': '🥉', 'PA=F': '⚪',
106
+ 'CL=F': '🛢️', 'NG=F': '🔥', 'HG=F': '🔶', 'ZC=F': '🌽',
107
+ 'ZS=F': '🟢', 'ZW=F': '🍞'
108
+ };
109
+
110
+ const COMMODITY_NAMES = {
111
+ 'GC=F': 'Gold', 'SI=F': 'Silver', 'PL=F': 'Platinum', 'PA=F': 'Palladium',
112
+ 'CL=F': 'Crude Oil', 'NG=F': 'Natural Gas', 'HG=F': 'Copper', 'ZC=F': 'Corn',
113
+ 'ZS=F': 'Soybeans', 'ZW=F': 'Wheat'
114
+ };
115
+
116
+ const COMMODITY_UNITS = {
117
+ 'GC=F': 'per oz', 'SI=F': 'per oz', 'PL=F': 'per oz', 'PA=F': 'per oz',
118
+ 'CL=F': 'per bbl', 'NG=F': 'per MMBtu', 'HG=F': 'per lb', 'ZC=F': 'per bu',
119
+ 'ZS=F': 'per bu', 'ZW=F': 'per bu'
120
+ };
121
+
122
+ let alerts = JSON.parse(localStorage.getItem('commodity_alerts') || '[]');
123
+ let history = JSON.parse(localStorage.getItem('commodity_history') || '[]');
124
+ let prices = {};
125
+ let triggered = new Set();
126
+ const debug = document.getElementById('debug');
127
+
128
+ function log(msg) {
129
+ debug.textContent = new Date().toLocaleTimeString() + ' | ' + msg + '\n' + debug.textContent.slice(0, 300);
130
+ }
131
+
132
+ function save() {
133
+ localStorage.setItem('commodity_alerts', JSON.stringify(alerts));
134
+ localStorage.setItem('commodity_history', JSON.stringify(history.slice(0, 30)));
135
+ }
136
+
137
+ function showModal() {
138
+ document.getElementById('modal').classList.add('active');
139
+ }
140
+
141
+ function hideModal() {
142
+ document.getElementById('modal').classList.remove('active');
143
+ }
144
+
145
+ function addAlert() {
146
+ const symbol = document.getElementById('assetSelect').value;
147
+ const min = parseFloat(document.getElementById('minPrice').value);
148
+ const max = parseFloat(document.getElementById('maxPrice').value);
149
+
150
+ if (!symbol || !min || !max || min >= max) {
151
+ alert('Please fill all fields correctly.\nMin must be less than Max.');
152
+ return;
153
+ }
154
+
155
+ alerts = alerts.filter(a => a.symbol !== symbol);
156
+ alerts.push({ symbol, min, max, lastInRange: false });
157
+
158
+ save();
159
+ render();
160
+ hideModal();
161
+ log('Added: ' + COMMODITY_NAMES[symbol] + ' | $' + min + ' - $' + max);
162
+ }
163
+
164
+ function removeAlert(symbol) {
165
+ alerts = alerts.filter(a => a.symbol !== symbol);
166
+ triggered.clear();
167
+ save();
168
+ render();
169
+ log('Removed: ' + symbol);
170
+ }
171
+
172
+ function triggerAlert(symbol, price, min, max) {
173
+ const key = symbol + '-' + min + '-' + max;
174
+ if (triggered.has(key)) return;
175
+ triggered.add(key);
176
+
177
+ history.unshift({ symbol, price, min, max, time: Date.now() });
178
+ save();
179
+ renderHistory();
180
+
181
+ showToast(symbol, price, min, max);
182
+
183
+ if (Notification.permission === 'granted') {
184
+ new Notification(COMMODITY_NAMES[symbol] + ' Alert!', {
185
+ body: 'Price $' + price.toLocaleString() + ' is in range ($' + min + ' - $' + max + ')',
186
+ });
187
+ }
188
+
189
+ if ('vibrate' in navigator) navigator.vibrate([200, 100, 200]);
190
+
191
+ const card = document.getElementById('card-' + symbol.replace(/[^a-z]/g, ''));
192
+ if (card) {
193
+ card.classList.add('flash');
194
+ setTimeout(() => card.classList.remove('flash'), 2000);
195
+ }
196
+ }
197
+
198
+ function showToast(symbol, price, min, max) {
199
+ const div = document.createElement('div');
200
+ div.className = 'toast';
201
+ div.innerHTML = `
202
+ <div class="toast-title">🔔 ${COMMODITY_NAMES[symbol]} Alert!</div>
203
+ <div class="toast-msg">$${price.toLocaleString()} in range ($${min.toLocaleString()} - $${max.toLocaleString()})</div>
204
+ `;
205
+ document.getElementById('toasts').appendChild(div);
206
+ setTimeout(() => div.remove(), 5000);
207
+ }
208
+
209
+ function render() {
210
+ const container = document.getElementById('alertsContainer');
211
+
212
+ if (alerts.length === 0) {
213
+ container.innerHTML = '<div class="empty">No alerts set. Click "+ Add Alert" to start.</div>';
214
+ return;
215
+ }
216
+
217
+ container.innerHTML = alerts.map(a => {
218
+ const price = prices[a.symbol];
219
+ const inRange = price >= a.min && price <= a.max;
220
+ const icon = COMMODITY_ICONS[a.symbol] || '📦';
221
+ const name = COMMODITY_NAMES[a.symbol] || a.symbol;
222
+ const unit = COMMODITY_UNITS[a.symbol] || '';
223
+
224
+ return `
225
+ <div class="card" id="card-${a.symbol.replace(/[^a-z]/g, '')}">
226
+ <div class="card-header">
227
+ <span class="asset-name"><span class="asset-icon">${icon}</span>${name}</span>
228
+ <button class="btn btn-danger" onclick="removeAlert('${a.symbol}')">Remove</button>
229
+ </div>
230
+ <div class="price">${price ? '$' + price.toLocaleString() : 'Loading...'}</div>
231
+ <div class="unit">${unit}</div>
232
+ <div class="range">Target: $${a.min.toLocaleString()} - $${a.max.toLocaleString()}</div>
233
+ <span class="state ${inRange ? 'inside' : 'outside'}">${inRange ? '✓ In Range' : '○ Waiting'}</span>
234
+ </div>
235
+ `;
236
+ }).join('');
237
+ }
238
+
239
+ function renderHistory() {
240
+ const container = document.getElementById('historyContainer');
241
+ if (history.length === 0) {
242
+ container.innerHTML = '<div class="empty" style="padding:1rem">No alerts triggered yet</div>';
243
+ return;
244
+ }
245
+ container.innerHTML = history.map(h => `
246
+ <div class="alert-item">
247
+ <span>🔔</span>
248
+ <div>
249
+ <strong>${COMMODITY_NAMES[h.symbol] || h.symbol}</strong> - $${h.price.toLocaleString()}
250
+ <div style="font-size:0.75rem;color:#64748b;margin-top:2px">
251
+ Range: $${h.min.toLocaleString()} - $${h.max.toLocaleString()} | ${new Date(h.time).toLocaleTimeString()}
252
+ </div>
253
+ </div>
254
+ </div>
255
+ `).join('');
256
+ }
257
+
258
+ async function fetchPrices() {
259
+ if (alerts.length === 0) return;
260
+
261
+ const symbols = alerts.map(a => a.symbol);
262
+ const symbolsParam = symbols.join(',');
263
+
264
+ try {
265
+ const url = `https://query1.finance.yahoo.com/v7/finance/quote?symbols=${encodeURIComponent(symbolsParam)}`;
266
+ log('Fetching commodities...');
267
+
268
+ const res = await fetch(url);
269
+
270
+ if (!res.ok) {
271
+ log('API error: ' + res.status);
272
+ return;
273
+ }
274
+
275
+ const data = await res.json();
276
+
277
+ if (data.chart && data.chart.result) {
278
+ for (const result of data.chart.result) {
279
+ const symbol = result.meta.symbol;
280
+ const price = result.meta.regularMarketPrice;
281
+ if (price) {
282
+ prices[symbol] = price;
283
+ log(symbol + ': $' + price);
284
+ }
285
+ }
286
+ }
287
+
288
+ log('Price update complete');
289
+ } catch (e) {
290
+ log('Fetch error: ' + e.message);
291
+ }
292
+ }
293
+
294
+ function checkAlerts() {
295
+ alerts.forEach(a => {
296
+ const price = prices[a.symbol];
297
+ if (!price) return;
298
+
299
+ const wasIn = a.lastInRange === true;
300
+ const isIn = price >= a.min && price <= a.max;
301
+
302
+ if (isIn && !wasIn) {
303
+ log('TRIGGER: ' + a.symbol + ' at $' + price);
304
+ triggerAlert(a.symbol, price, a.min, a.max);
305
+ }
306
+
307
+ a.lastInRange = isIn;
308
+ });
309
+ save();
310
+ render();
311
+ }
312
+
313
+ async function init() {
314
+ log('Starting Commodity Alerts...');
315
+ render();
316
+ renderHistory();
317
+
318
+ await fetchPrices();
319
+ checkAlerts();
320
+
321
+ setInterval(async () => {
322
+ await fetchPrices();
323
+ checkAlerts();
324
+ }, 30000);
325
+
326
+ if ('Notification' in window && Notification.permission === 'default') {
327
+ Notification.requestPermission();
328
+ }
329
+ }
330
+
331
+ init();
332
+ </script>
333
+ </body>
334
+ </html>
config.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ config.py — Central configuration for the Price Alert Bot.
3
+
4
+ Contains ticker mappings, default price ranges, polling intervals,
5
+ and asset categorisation.
6
+ """
7
+
8
+ import os
9
+ from dotenv import load_dotenv
10
+
11
+ load_dotenv()
12
+
13
+ # ─── Telegram ────────────────────────────────────────────────────────────────
14
+ TELEGRAM_BOT_TOKEN: str = os.getenv("TELEGRAM_BOT_TOKEN", "")
15
+ TELEGRAM_CHAT_ID: str = os.getenv("TELEGRAM_CHAT_ID", "")
16
+
17
+ # ─── Polling / streaming intervals (seconds) ────────────────────────────────
18
+ STOCK_POLL_INTERVAL: int = 15 # yfinance polling for stocks & commodities
19
+ CRYPTO_WS_RECONNECT_DELAY: int = 5 # seconds before reconnecting WebSocket
20
+ CRYPTO_REST_FALLBACK_INTERVAL: int = 10 # REST fallback poll interval
21
+
22
+ # ─── Alert behaviour ─────────────────────────────────────────────────────────
23
+ # Minimum seconds between consecutive alerts for the same asset.
24
+ # Prevents spam when price oscillates rapidly at a range boundary.
25
+ ALERT_COOLDOWN_SECONDS: int = int(os.getenv("ALERT_COOLDOWN_SECONDS", "300")) # 5 minutes
26
+
27
+ # Maximum number of alert events kept in memory for /alerts history.
28
+ ALERT_HISTORY_MAX: int = 100
29
+
30
+ # ─── Persistence ─────────────────────────────────────────────────────────────
31
+ # JSON file used to save/restore tracked asset ranges across restarts.
32
+ PERSISTENCE_FILE: str = os.getenv("PERSISTENCE_FILE", "state.json")
33
+
34
+ # ─── Asset categories ────────────────────────────────────────────────────────
35
+ # Maps a user-friendly name → yfinance ticker
36
+ YFINANCE_TICKERS: dict[str, str] = {
37
+ # Commodities
38
+ "GOLD": "GC=F",
39
+ "SILVER": "SI=F",
40
+ "CRUDE_OIL": "CL=F",
41
+ # Stocks
42
+ "NVIDIA": "NVDA",
43
+ "TESLA": "TSLA",
44
+ "GOOGLE": "GOOGL",
45
+ "AMAZON": "AMZN",
46
+ "ORACLE": "ORCL",
47
+ "APPLE": "AAPL",
48
+ "MICROSOFT": "MSFT",
49
+ "META": "META",
50
+ # Indices
51
+ "SP500": "^GSPC",
52
+ "NASDAQ": "^IXIC",
53
+ "DOW": "^DJI",
54
+ }
55
+
56
+ # Maps a user-friendly name → Binance WebSocket stream symbol
57
+ BINANCE_SYMBOLS: dict[str, str] = {
58
+ "BTC": "btcusdt",
59
+ "ETH": "ethusdt",
60
+ "XRP": "xrpusdt",
61
+ "SOL": "solusdt",
62
+ "BNB": "bnbusdt",
63
+ "DOGE": "dogeusdt",
64
+ "ADA": "adausdt",
65
+ "MATIC":"maticusdt",
66
+ }
67
+
68
+ # Reverse lookup: Binance stream symbol → user-friendly name
69
+ BINANCE_SYMBOL_TO_NAME: dict[str, str] = {v: k for k, v in BINANCE_SYMBOLS.items()}
70
+
71
+ # All supported asset names (for validation)
72
+ ALL_ASSETS: set[str] = set(YFINANCE_TICKERS.keys()) | set(BINANCE_SYMBOLS.keys())
73
+
74
+ # ─── Default price ranges (min, max) — updated to current market levels ─────
75
+ DEFAULT_RANGES: dict[str, tuple[float, float]] = {
76
+ # Commodities
77
+ "GOLD": (2900.0, 3200.0),
78
+ "SILVER": (30.0, 36.0),
79
+ "CRUDE_OIL": (65.0, 75.0),
80
+ # Crypto
81
+ "BTC": (80000.0, 95000.0),
82
+ "ETH": (1700.0, 2200.0),
83
+ "XRP": (2.00, 2.80),
84
+ "SOL": (120.0, 175.0),
85
+ "BNB": (580.0, 650.0),
86
+ "DOGE": (0.15, 0.25),
87
+ "ADA": (0.65, 0.90),
88
+ "MATIC": (0.40, 0.65),
89
+ # Stocks
90
+ "NVIDIA": (100.0, 135.0),
91
+ "TESLA": (240.0, 310.0),
92
+ "GOOGLE": (155.0, 185.0),
93
+ "AMAZON": (195.0, 225.0),
94
+ "ORACLE": (155.0, 185.0),
95
+ "APPLE": (200.0, 240.0),
96
+ "MICROSOFT": (370.0, 420.0),
97
+ "META": (520.0, 620.0),
98
+ # Indices
99
+ "SP500": (5400.0, 5800.0),
100
+ "NASDAQ": (17000.0,19000.0),
101
+ "DOW": (41000.0,44000.0),
102
+ }
103
+
104
+ # ─── Logging ─────────────────────────────────────────────────────────────────
105
+ LOG_FILE: str = "bot.log"
106
+ LOG_MAX_BYTES: int = 5 * 1024 * 1024 # 5 MB
107
+ LOG_BACKUP_COUNT: int = 3
crypto-alerts.html ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Crypto Price Alerts</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0a0a0f; color: #f8fafc; min-height: 100vh; padding: 1rem; }
10
+ .container { max-width: 800px; margin: 0 auto; }
11
+ header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #1e293b; }
12
+ h1 { font-size: 1.5rem; background: linear-gradient(135deg, #f7931a, #ff6b00); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
13
+ .debug { background: #1a1a2e; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-family: monospace; font-size: 0.75rem; white-space: pre-wrap; max-height: 80px; overflow-y: auto; color: #94a3b8; }
14
+ .card { background: #12121a; border: 1px solid #1e293b; border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; transition: all 0.3s; }
15
+ .card:hover { border-color: #f7931a; }
16
+ .card.flash { animation: flash 0.5s ease 3; }
17
+ @keyframes flash { 0%,100% { border-color: #1e293b; box-shadow: none; } 50% { border-color: #f59e0b; box-shadow: 0 0 30px #f59e0b50; } }
18
+ .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
19
+ .asset-name { font-size: 1.25rem; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
20
+ .asset-icon { font-size: 1.5rem; }
21
+ .price { font-size: 1.75rem; font-weight: 700; color: #f7931a; margin-bottom: 0.5rem; }
22
+ .range { color: #94a3b8; font-size: 0.875rem; margin-bottom: 0.75rem; }
23
+ .state { padding: 0.4rem 0.8rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; display: inline-block; }
24
+ .state.inside { background: #22c55e20; color: #22c55e; }
25
+ .state.outside { background: #374151; color: #94a3b8; }
26
+ .btn { padding: 0.5rem 1rem; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.875rem; }
27
+ .btn-primary { background: #f7931a; color: #0a0a0f; }
28
+ .btn-primary:hover { background: #ff9f2e; }
29
+ .btn-danger { background: transparent; color: #ef4444; border: 1px solid #ef4444; }
30
+ .btn-danger:hover { background: #ef4444; color: white; }
31
+ .modal { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; align-items: center; justify-content: center; z-index: 100; }
32
+ .modal.active { display: flex; }
33
+ .modal-content { background: #12121a; border: 1px solid #1e293b; border-radius: 16px; padding: 2rem; width: 90%; max-width: 400px; }
34
+ .modal h2 { margin-bottom: 1.5rem; }
35
+ .form-group { margin-bottom: 1rem; }
36
+ .form-group label { display: block; margin-bottom: 0.5rem; color: #94a3b8; font-size: 0.875rem; }
37
+ .form-group input, .form-group select { width: 100%; padding: 0.75rem; background: #0a0a0f; border: 1px solid #1e293b; border-radius: 8px; color: #f8fafc; font-size: 1rem; }
38
+ .form-group input:focus, .form-group select:focus { outline: none; border-color: #f7931a; }
39
+ .btn-block { width: 100%; padding: 1rem; margin-top: 0.5rem; }
40
+ .toast { position: fixed; top: 20px; right: 20px; background: #12121a; border: 2px solid #22c55e; border-radius: 12px; padding: 1rem 1.5rem; z-index: 1000; animation: slideIn 0.3s; }
41
+ @keyframes slideIn { from { opacity: 0; transform: translateX(120%); } to { opacity: 1; transform: translateX(0); } }
42
+ .toast-title { font-weight: 700; margin-bottom: 0.25rem; display: flex; align-items: center; gap: 0.5rem; }
43
+ .toast-msg { font-size: 0.875rem; color: #94a3b8; }
44
+ .empty { text-align: center; padding: 3rem; color: #94a3b8; }
45
+ .section-title { font-size: 1.1rem; margin: 1.5rem 0 1rem; color: #94a3b8; }
46
+ .alert-item { background: #12121a; border: 1px solid #1e293b; border-radius: 8px; padding: 1rem; margin-bottom: 0.5rem; display: flex; gap: 1rem; align-items: center; }
47
+ .status { display: flex; gap: 1rem; margin-bottom: 1rem; font-size: 0.875rem; color: #94a3b8; }
48
+ .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #22c55e; }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <div id="toasts"></div>
53
+
54
+ <div class="container">
55
+ <header>
56
+ <h1>₿ Crypto Alerts</h1>
57
+ <button class="btn btn-primary" onclick="showModal()">+ Add Alert</button>
58
+ </header>
59
+
60
+ <div class="status"><span class="status-dot"></span> Live prices from CoinGecko</div>
61
+ <div id="debug" class="debug">Initializing...</div>
62
+ <div id="alertsContainer"></div>
63
+
64
+ <div class="section-title">📋 Alert History</div>
65
+ <div id="historyContainer"></div>
66
+ </div>
67
+
68
+ <div id="modal" class="modal" onclick="if(event.target===this)hideModal()">
69
+ <div class="modal-content">
70
+ <h2>Add Crypto Alert</h2>
71
+ <div class="form-group">
72
+ <label>Cryptocurrency</label>
73
+ <select id="assetSelect">
74
+ <option value="">Select coin...</option>
75
+ <option value="bitcoin">Bitcoin (BTC)</option>
76
+ <option value="ethereum">Ethereum (ETH)</option>
77
+ <option value="solana">Solana (SOL)</option>
78
+ <option value="ripple">XRP</option>
79
+ <option value="cardano">Cardano (ADA)</option>
80
+ <option value="dogecoin">Dogecoin (DOGE)</option>
81
+ <option value="polkadot">Polkadot (DOT)</option>
82
+ <option value="chainlink">Chainlink (LINK)</option>
83
+ <option value="avalanche-2">Avalanche (AVAX)</option>
84
+ <option value="litecoin">Litecoin (LTC)</option>
85
+ </select>
86
+ </div>
87
+ <div class="form-group">
88
+ <label>Min Price (USD)</label>
89
+ <input type="number" id="minPrice" step="any" placeholder="60000">
90
+ </div>
91
+ <div class="form-group">
92
+ <label>Max Price (USD)</label>
93
+ <input type="number" id="maxPrice" step="any" placeholder="62000">
94
+ </div>
95
+ <button class="btn btn-primary btn-block" onclick="addAlert()">Add Alert</button>
96
+ <button class="btn btn-danger btn-block" onclick="hideModal()">Cancel</button>
97
+ </div>
98
+ </div>
99
+
100
+ <script>
101
+ const COIN_ICONS = {
102
+ 'bitcoin': '₿', 'ethereum': 'Ξ', 'solana': '◎', 'ripple': '✕',
103
+ 'cardano': '₳', 'dogecoin': 'Ð', 'polkadot': '●', 'chainlink': '⬡',
104
+ 'avalanche-2': '▲', 'litecoin': 'Ł'
105
+ };
106
+
107
+ let alerts = JSON.parse(localStorage.getItem('crypto_alerts') || '[]');
108
+ let history = JSON.parse(localStorage.getItem('crypto_history') || '[]');
109
+ let prices = {};
110
+ let triggered = new Set();
111
+ let retryCount = 0;
112
+ const MAX_RETRIES = 3;
113
+ const debug = document.getElementById('debug');
114
+
115
+ function log(msg) {
116
+ debug.textContent = new Date().toLocaleTimeString() + ' | ' + msg + '\n' + debug.textContent.slice(0, 300);
117
+ }
118
+
119
+ function save() {
120
+ localStorage.setItem('crypto_alerts', JSON.stringify(alerts));
121
+ localStorage.setItem('crypto_history', JSON.stringify(history.slice(0, 30)));
122
+ }
123
+
124
+ function showModal() {
125
+ document.getElementById('modal').classList.add('active');
126
+ }
127
+
128
+ function hideModal() {
129
+ document.getElementById('modal').classList.remove('active');
130
+ }
131
+
132
+ function addAlert() {
133
+ const coin = document.getElementById('assetSelect').value;
134
+ const min = parseFloat(document.getElementById('minPrice').value);
135
+ const max = parseFloat(document.getElementById('maxPrice').value);
136
+
137
+ if (!coin || !min || !max || min >= max) {
138
+ alert('Please fill all fields correctly.\nMin must be less than Max.');
139
+ return;
140
+ }
141
+
142
+ alerts = alerts.filter(a => a.coin !== coin);
143
+ alerts.push({ coin, min, max, lastInRange: false });
144
+
145
+ save();
146
+ render();
147
+ hideModal();
148
+ log('Added: ' + coin + ' | $' + min + ' - $' + max);
149
+ }
150
+
151
+ function removeAlert(coin) {
152
+ alerts = alerts.filter(a => a.coin !== coin);
153
+ triggered.clear();
154
+ save();
155
+ render();
156
+ log('Removed: ' + coin);
157
+ }
158
+
159
+ function triggerAlert(coin, price, min, max) {
160
+ const key = coin + '-' + min + '-' + max;
161
+ if (triggered.has(key)) return;
162
+ triggered.add(key);
163
+
164
+ history.unshift({ coin, price, min, max, time: Date.now() });
165
+ save();
166
+ renderHistory();
167
+
168
+ showToast(coin, price, min, max);
169
+
170
+ if (Notification.permission === 'granted') {
171
+ new Notification(coin.charAt(0).toUpperCase() + coin.slice(1) + ' Alert!', {
172
+ body: 'Price $' + price.toLocaleString() + ' is in range ($' + min + ' - $' + max + ')',
173
+ });
174
+ }
175
+
176
+ if ('vibrate' in navigator) navigator.vibrate([200, 100, 200]);
177
+
178
+ const card = document.getElementById('card-' + coin.replace(/[^a-z0-9]/g, ''));
179
+ if (card) {
180
+ card.classList.add('flash');
181
+ setTimeout(() => card.classList.remove('flash'), 2000);
182
+ }
183
+ }
184
+
185
+ function showToast(coin, price, min, max) {
186
+ const div = document.createElement('div');
187
+ div.className = 'toast';
188
+ div.innerHTML = `
189
+ <div class="toast-title">🔔 ${coin.charAt(0).toUpperCase() + coin.slice(1)} Alert!</div>
190
+ <div class="toast-msg">$${price.toLocaleString()} in range ($${min.toLocaleString()} - $${max.toLocaleString()})</div>
191
+ `;
192
+ document.getElementById('toasts').appendChild(div);
193
+ setTimeout(() => div.remove(), 5000);
194
+ }
195
+
196
+ function render() {
197
+ const container = document.getElementById('alertsContainer');
198
+
199
+ if (alerts.length === 0) {
200
+ container.innerHTML = '<div class="empty">No alerts set. Click "+ Add Alert" to start.</div>';
201
+ return;
202
+ }
203
+
204
+ container.innerHTML = alerts.map(a => {
205
+ const price = prices[a.coin];
206
+ const inRange = price >= a.min && price <= a.max;
207
+ const icon = COIN_ICONS[a.coin] || '●';
208
+ const name = a.coin.charAt(0).toUpperCase() + a.coin.slice(1).replace(/-2/, '');
209
+
210
+ return `
211
+ <div class="card" id="card-${a.coin.replace(/[^a-z0-9]/g, '')}">
212
+ <div class="card-header">
213
+ <span class="asset-name"><span class="asset-icon">${icon}</span>${name}</span>
214
+ <button class="btn btn-danger" onclick="removeAlert('${a.coin}')">Remove</button>
215
+ </div>
216
+ <div class="price">${price ? '$' + price.toLocaleString() : 'Loading...'}</div>
217
+ <div class="range">Target: $${a.min.toLocaleString()} - $${a.max.toLocaleString()}</div>
218
+ <span class="state ${inRange ? 'inside' : 'outside'}">${inRange ? '✓ In Range' : '○ Waiting'}</span>
219
+ </div>
220
+ `;
221
+ }).join('');
222
+ }
223
+
224
+ function renderHistory() {
225
+ const container = document.getElementById('historyContainer');
226
+ if (history.length === 0) {
227
+ container.innerHTML = '<div class="empty" style="padding:1rem">No alerts triggered yet</div>';
228
+ return;
229
+ }
230
+ container.innerHTML = history.map(h => {
231
+ const name = h.coin.charAt(0).toUpperCase() + h.coin.slice(1).replace(/-2/, '');
232
+ return `
233
+ <div class="alert-item">
234
+ <span>🔔</span>
235
+ <div>
236
+ <strong>${name}</strong> - $${h.price.toLocaleString()}
237
+ <div style="font-size:0.75rem;color:#64748b;margin-top:2px">
238
+ Range: $${h.min.toLocaleString()} - $${h.max.toLocaleString()} | ${new Date(h.time).toLocaleTimeString()}
239
+ </div>
240
+ </div>
241
+ </div>
242
+ `;
243
+ }).join('');
244
+ }
245
+
246
+ async function fetchPrices() {
247
+ if (alerts.length === 0) return;
248
+
249
+ const coins = alerts.map(a => a.coin).join(',');
250
+
251
+ try {
252
+ const url = `https://api.coingecko.com/api/v3/simple/price?ids=${coins}&vs_currencies=usd`;
253
+ log('Fetching prices...');
254
+
255
+ const res = await fetch(url);
256
+
257
+ if (!res.ok) {
258
+ if (res.status === 429) {
259
+ retryCount++;
260
+ if (retryCount < MAX_RETRIES) {
261
+ log('Rate limited. Retry ' + retryCount + '/' + MAX_RETRIES + ' in 15s...');
262
+ setTimeout(fetchPrices, 15000);
263
+ } else {
264
+ log('Rate limited. Waiting 60s...');
265
+ setTimeout(() => { retryCount = 0; fetchPrices(); }, 60000);
266
+ }
267
+ } else {
268
+ log('API error: ' + res.status);
269
+ }
270
+ return;
271
+ }
272
+
273
+ retryCount = 0;
274
+ const data = await res.json();
275
+
276
+ let updated = 0;
277
+ for (const coin of alerts) {
278
+ if (data[coin.coin]?.usd) {
279
+ prices[coin.coin] = data[coin.coin].usd;
280
+ updated++;
281
+ }
282
+ }
283
+
284
+ log('Updated ' + updated + ' prices at ' + new Date().toLocaleTimeString());
285
+ } catch (e) {
286
+ log('Fetch error: ' + e.message);
287
+ }
288
+ }
289
+
290
+ function checkAlerts() {
291
+ alerts.forEach(a => {
292
+ const price = prices[a.coin];
293
+ if (!price) return;
294
+
295
+ const wasIn = a.lastInRange === true;
296
+ const isIn = price >= a.min && price <= a.max;
297
+
298
+ if (isIn && !wasIn) {
299
+ log('TRIGGER: ' + a.coin + ' at $' + price);
300
+ triggerAlert(a.coin, price, a.min, a.max);
301
+ }
302
+
303
+ a.lastInRange = isIn;
304
+ });
305
+ save();
306
+ render();
307
+ }
308
+
309
+ async function init() {
310
+ log('Starting Crypto Alerts...');
311
+ render();
312
+ renderHistory();
313
+
314
+ await fetchPrices();
315
+ checkAlerts();
316
+
317
+ setInterval(async () => {
318
+ await fetchPrices();
319
+ checkAlerts();
320
+ }, 30000);
321
+
322
+ if ('Notification' in window && Notification.permission === 'default') {
323
+ Notification.requestPermission();
324
+ }
325
+ }
326
+
327
+ init();
328
+ </script>
329
+ </body>
330
+ </html>
fetchers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # fetchers package
fetchers/crypto_fetcher.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ crypto_fetcher.py — Real-time crypto prices via Binance WebSocket,
3
+ with REST API fallback.
4
+
5
+ Subscribes to Binance combined ticker streams for all active crypto assets.
6
+ """
7
+
8
+ import asyncio
9
+ import json
10
+ from typing import Callable
11
+
12
+ import aiohttp
13
+ import websockets
14
+ import websockets.exceptions
15
+
16
+ import config
17
+ from logger import get_logger
18
+
19
+ log = get_logger("crypto_fetcher")
20
+
21
+ BINANCE_WS_BASE = "wss://stream.binance.com:9443/ws"
22
+ BINANCE_REST_URL = "https://api.binance.com/api/v3/ticker/price"
23
+
24
+
25
+ async def stream_crypto(
26
+ on_price: Callable[[str, float], None],
27
+ get_active_assets: Callable[[], dict[str, tuple[float, float]]],
28
+ ) -> None:
29
+ """
30
+ Connect to Binance WebSocket for real-time crypto prices.
31
+ Falls back to REST polling if WebSocket connection fails repeatedly.
32
+ """
33
+ consecutive_ws_failures = 0
34
+ max_ws_retries = 5
35
+
36
+ while True:
37
+ try:
38
+ await _run_websocket(on_price, get_active_assets)
39
+ consecutive_ws_failures = 0 # reset on clean exit
40
+ except (
41
+ websockets.exceptions.ConnectionClosed,
42
+ websockets.exceptions.InvalidURI,
43
+ websockets.exceptions.InvalidHandshake,
44
+ OSError,
45
+ ConnectionRefusedError,
46
+ ) as exc:
47
+ consecutive_ws_failures += 1
48
+ log.warning(
49
+ "Binance WebSocket disconnected (attempt %d/%d): %s",
50
+ consecutive_ws_failures, max_ws_retries, exc,
51
+ )
52
+
53
+ if consecutive_ws_failures >= max_ws_retries:
54
+ log.warning("WebSocket failed %d times, switching to REST fallback", max_ws_retries)
55
+ await _rest_fallback(on_price, get_active_assets)
56
+ consecutive_ws_failures = 0 # reset after fallback session
57
+ else:
58
+ backoff = config.CRYPTO_WS_RECONNECT_DELAY * consecutive_ws_failures
59
+ log.info("Reconnecting WebSocket in %ds…", backoff)
60
+ await asyncio.sleep(backoff)
61
+
62
+ except Exception as exc:
63
+ log.error("Unexpected crypto fetcher error: %s", exc, exc_info=True)
64
+ await asyncio.sleep(config.CRYPTO_WS_RECONNECT_DELAY)
65
+
66
+
67
+ async def _run_websocket(
68
+ on_price: Callable[[str, float], None],
69
+ get_active_assets: Callable[[], dict[str, tuple[float, float]]],
70
+ ) -> None:
71
+ """Subscribe to Binance combined mini-ticker streams for active crypto assets."""
72
+ active = get_active_assets()
73
+ streams = [
74
+ f"{symbol}@miniTicker"
75
+ for name, symbol in config.BINANCE_SYMBOLS.items()
76
+ if name in active
77
+ ]
78
+
79
+ if not streams:
80
+ log.debug("No active crypto assets, sleeping…")
81
+ await asyncio.sleep(config.CRYPTO_REST_FALLBACK_INTERVAL)
82
+ return
83
+
84
+ stream_path = "/".join(streams)
85
+ url = f"wss://stream.binance.com:9443/stream?streams={stream_path}"
86
+ log.info("Connecting to Binance WebSocket: %d stream(s)", len(streams))
87
+
88
+ async with websockets.connect(url, ping_interval=20, ping_timeout=10) as ws:
89
+ log.info("Binance WebSocket connected ✓")
90
+ async for raw_msg in ws:
91
+ try:
92
+ msg = json.loads(raw_msg)
93
+ data = msg.get("data", {})
94
+ # 's' field is the raw symbol e.g. "BTCUSDT"
95
+ raw_lower = data.get("s", "").lower() # e.g. "btcusdt"
96
+ name = config.BINANCE_SYMBOL_TO_NAME.get(raw_lower)
97
+
98
+ if name and "c" in data:
99
+ price = float(data["c"]) # 'c' = close price
100
+ log.debug(" WS %s = $%.4f", name, price)
101
+ on_price(name, price)
102
+
103
+ except (json.JSONDecodeError, ValueError, KeyError) as exc:
104
+ log.debug("Skipping malformed WS message: %s", exc)
105
+
106
+
107
+ async def _rest_fallback(
108
+ on_price: Callable[[str, float], None],
109
+ get_active_assets: Callable[[], dict[str, tuple[float, float]]],
110
+ ) -> None:
111
+ """Poll Binance REST API as fallback when WebSocket is unavailable."""
112
+ log.info("Running Binance REST fallback poller (interval=%ds)", config.CRYPTO_REST_FALLBACK_INTERVAL)
113
+
114
+ # Run for a limited period then let the outer loop retry WebSocket (~5 minutes)
115
+ for _ in range(30):
116
+ try:
117
+ active = get_active_assets()
118
+ async with aiohttp.ClientSession() as session:
119
+ for name, symbol in config.BINANCE_SYMBOLS.items():
120
+ if name not in active:
121
+ continue
122
+ api_symbol = symbol.upper() # e.g. BTCUSDT
123
+ url = f"{BINANCE_REST_URL}?symbol={api_symbol}"
124
+ async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as resp:
125
+ if resp.status == 200:
126
+ data = await resp.json()
127
+ price = float(data["price"])
128
+ log.debug(" REST %s = $%.4f", name, price)
129
+ on_price(name, price)
130
+ else:
131
+ log.warning("Binance REST %s returned HTTP %d", api_symbol, resp.status)
132
+ except Exception as exc:
133
+ log.warning("Binance REST fallback error: %s", exc)
134
+
135
+ await asyncio.sleep(config.CRYPTO_REST_FALLBACK_INTERVAL)
fetchers/stock_fetcher.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ stock_fetcher.py — Polls yfinance for live prices of stocks, indices,
3
+ and commodities on a configurable interval.
4
+
5
+ Feeds price updates into the alert engine callback.
6
+ """
7
+
8
+ import asyncio
9
+ from typing import Callable
10
+
11
+ import yfinance as yf
12
+
13
+ import config
14
+ from logger import get_logger
15
+
16
+ log = get_logger("stock_fetcher")
17
+
18
+
19
+ async def poll_stocks(
20
+ on_price: Callable[[str, float], None],
21
+ get_active_assets: Callable[[], dict[str, tuple[float, float]]],
22
+ ) -> None:
23
+ """
24
+ Continuously poll yfinance for prices of stocks/commodities/indices.
25
+
26
+ Args:
27
+ on_price: callback(asset_name, price) invoked for every price update.
28
+ get_active_assets: returns the current dict of tracked asset ranges so
29
+ we only fetch tickers the user cares about.
30
+ """
31
+ log.info("Stock/commodity poller started (interval=%ds)", config.STOCK_POLL_INTERVAL)
32
+ consecutive_failures = 0
33
+ max_backoff = 120 # seconds
34
+
35
+ while True:
36
+ try:
37
+ # Build a list of yfinance tickers we need to fetch
38
+ active = get_active_assets()
39
+ tickers_to_fetch: dict[str, str] = {} # name → yf_ticker
40
+ for name, yf_ticker in config.YFINANCE_TICKERS.items():
41
+ if name in active:
42
+ tickers_to_fetch[name] = yf_ticker
43
+
44
+ if not tickers_to_fetch:
45
+ log.debug("No active yfinance assets to poll, sleeping…")
46
+ await asyncio.sleep(config.STOCK_POLL_INTERVAL)
47
+ continue
48
+
49
+ # Fetch all tickers in one batch call (efficient)
50
+ log.debug("Fetching yfinance tickers: %s", " ".join(tickers_to_fetch.values()))
51
+
52
+ data = await asyncio.to_thread(
53
+ _fetch_batch, list(tickers_to_fetch.values())
54
+ )
55
+
56
+ # Map results back to friendly names
57
+ yf_to_name = {v: k for k, v in tickers_to_fetch.items()}
58
+ for yf_ticker, price in data.items():
59
+ name = yf_to_name.get(yf_ticker)
60
+ if name and price is not None:
61
+ log.debug(" %s (%s) = $%.4f", name, yf_ticker, price)
62
+ on_price(name, price)
63
+
64
+ consecutive_failures = 0 # reset on success
65
+
66
+ except Exception as exc:
67
+ consecutive_failures += 1
68
+ backoff = min(config.STOCK_POLL_INTERVAL * (2 ** consecutive_failures), max_backoff)
69
+ log.warning(
70
+ "yfinance poll failed (attempt %d): %s — retrying in %ds",
71
+ consecutive_failures, exc, backoff,
72
+ )
73
+ await asyncio.sleep(backoff)
74
+ continue
75
+
76
+ await asyncio.sleep(config.STOCK_POLL_INTERVAL)
77
+
78
+
79
+ def _fetch_batch(tickers: list[str]) -> dict[str, float | None]:
80
+ """
81
+ Synchronous helper — fetches the latest price for a batch of yfinance
82
+ tickers. Returns {ticker: price}.
83
+
84
+ Strategy:
85
+ 1. Try fast_info.last_price for each ticker (fastest, works outside market hours)
86
+ 2. Fall back to batch download with 5d period if fast_info fails
87
+ """
88
+ results: dict[str, float | None] = {}
89
+
90
+ # Strategy 1: fast_info (works even on weekends/after-hours)
91
+ remaining = []
92
+ for ticker_str in tickers:
93
+ try:
94
+ ticker = yf.Ticker(ticker_str)
95
+ # fast_info is an object, not a dict — access as attribute with fallback
96
+ fi = ticker.fast_info
97
+ price = None
98
+ try:
99
+ price = fi.last_price
100
+ except AttributeError:
101
+ pass
102
+ if price is None:
103
+ try:
104
+ price = fi.lastPrice
105
+ except AttributeError:
106
+ pass
107
+ if price and float(price) > 0:
108
+ results[ticker_str] = float(price)
109
+ else:
110
+ remaining.append(ticker_str)
111
+ except Exception as exc:
112
+ log.debug("fast_info failed for %s: %s", ticker_str, exc)
113
+ remaining.append(ticker_str)
114
+
115
+ if not remaining:
116
+ return results
117
+
118
+ # Strategy 2: batch download with 5d period (wider window for weekends)
119
+ try:
120
+ data = yf.download(
121
+ tickers=remaining,
122
+ period="5d",
123
+ interval="1d",
124
+ progress=False,
125
+ threads=True,
126
+ auto_adjust=True,
127
+ )
128
+ if data.empty:
129
+ log.debug("yfinance batch download returned empty (market may be closed)")
130
+ return results
131
+
132
+ if len(remaining) == 1:
133
+ ticker = remaining[0]
134
+ if "Close" in data.columns:
135
+ last_price = data["Close"].dropna().iloc[-1]
136
+ results[ticker] = float(last_price)
137
+ else:
138
+ for ticker in remaining:
139
+ try:
140
+ close_col = data["Close"]
141
+ if ticker in close_col.columns:
142
+ series = close_col[ticker].dropna()
143
+ if not series.empty:
144
+ results[ticker] = float(series.iloc[-1])
145
+ except (KeyError, IndexError) as e:
146
+ log.debug("Could not get price for %s: %s", ticker, e)
147
+
148
+ except Exception as exc:
149
+ log.error("yfinance batch download error: %s", exc)
150
+
151
+ return results
logger.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ logger.py — Structured logging with rotating file handler + console output.
3
+
4
+ Usage:
5
+ from logger import get_logger
6
+ log = get_logger(__name__)
7
+ log.info("Bot started")
8
+ """
9
+
10
+ import logging
11
+ from logging.handlers import RotatingFileHandler
12
+
13
+ import config
14
+
15
+
16
+ def get_logger(name: str) -> logging.Logger:
17
+ """Return a configured logger with console + rotating file handlers."""
18
+ logger = logging.getLogger(name)
19
+
20
+ # Avoid adding duplicate handlers on repeated calls
21
+ if logger.handlers:
22
+ return logger
23
+
24
+ logger.setLevel(logging.DEBUG)
25
+ formatter = logging.Formatter(
26
+ fmt="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
27
+ datefmt="%Y-%m-%d %H:%M:%S",
28
+ )
29
+
30
+ # Console handler — INFO and above
31
+ console = logging.StreamHandler()
32
+ console.setLevel(logging.INFO)
33
+ console.setFormatter(formatter)
34
+ logger.addHandler(console)
35
+
36
+ # Rotating file handler — DEBUG and above
37
+ file_handler = RotatingFileHandler(
38
+ config.LOG_FILE,
39
+ maxBytes=config.LOG_MAX_BYTES,
40
+ backupCount=config.LOG_BACKUP_COUNT,
41
+ encoding="utf-8",
42
+ )
43
+ file_handler.setLevel(logging.DEBUG)
44
+ file_handler.setFormatter(formatter)
45
+ logger.addHandler(file_handler)
46
+
47
+ return logger
main.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ main.py — Entry point for the Multi-Asset Price Alert Bot.
3
+
4
+ Orchestrates four concurrent async tasks:
5
+ 1. Stock/commodity poller (yfinance)
6
+ 2. Crypto WebSocket stream (Binance)
7
+ 3. Telegram bot (commands + notifications)
8
+ 4. Alert dispatcher (queue → Telegram sender)
9
+
10
+ Usage:
11
+ python main.py # normal mode
12
+ python main.py --dry-run # no Telegram sends, console alerts only
13
+ """
14
+
15
+ import argparse
16
+ import asyncio
17
+ import signal
18
+ import sys
19
+
20
+ import config
21
+ import persistence
22
+ from alert_engine import AlertEngine, AlertEvent
23
+ from fetchers.crypto_fetcher import stream_crypto
24
+ from fetchers.stock_fetcher import poll_stocks
25
+ from logger import get_logger
26
+ from telegram_bot import TelegramBot
27
+
28
+ log = get_logger("main")
29
+
30
+
31
+ def parse_args() -> argparse.Namespace:
32
+ parser = argparse.ArgumentParser(description="Multi-Asset Price Alert Bot")
33
+ parser.add_argument(
34
+ "--dry-run",
35
+ action="store_true",
36
+ help="Run without sending Telegram messages (prints alerts to console)",
37
+ )
38
+ parser.add_argument(
39
+ "--no-restore",
40
+ action="store_true",
41
+ help="Skip restoring saved state on startup (use default ranges only)",
42
+ )
43
+ return parser.parse_args()
44
+
45
+
46
+ async def main() -> None:
47
+ args = parse_args()
48
+
49
+ log.info("=" * 50)
50
+ log.info(" Multi-Asset Price Alert Bot")
51
+ log.info(" Mode: %s", "DRY-RUN" if args.dry_run else "LIVE")
52
+ log.info("=" * 50)
53
+
54
+ # ── Validate config ──────────────────────────────────────────────────
55
+ if not args.dry_run:
56
+ if not config.TELEGRAM_BOT_TOKEN:
57
+ log.error("TELEGRAM_BOT_TOKEN not set. See .env.example")
58
+ sys.exit(1)
59
+ if not config.TELEGRAM_CHAT_ID:
60
+ log.warning("TELEGRAM_CHAT_ID not set — alerts won't be sent until configured")
61
+
62
+ # ── Initialise alert queue & engine ─────────────────────────────────
63
+ alert_queue: asyncio.Queue[AlertEvent] = asyncio.Queue(maxsize=500)
64
+
65
+ def on_alert(event: AlertEvent) -> None:
66
+ """Thread-safe callback: push alert events into the async queue."""
67
+ try:
68
+ alert_queue.put_nowait(event)
69
+ except asyncio.QueueFull:
70
+ log.warning("Alert queue full, dropping alert for %s", event.asset_name)
71
+
72
+ engine = AlertEngine(on_alert=on_alert)
73
+ bot = TelegramBot(alert_engine=engine, dry_run=args.dry_run)
74
+
75
+ # ── Load state: try persistence file first, then fall back to defaults ─
76
+ if not args.no_restore:
77
+ restored = persistence.load_state(engine)
78
+ if restored == 0:
79
+ # Nothing restored — load built-in defaults
80
+ for name, (min_p, max_p) in config.DEFAULT_RANGES.items():
81
+ engine.add_asset(name, min_p, max_p)
82
+ log.info("Loaded %d default price ranges", len(config.DEFAULT_RANGES))
83
+ else:
84
+ for name, (min_p, max_p) in config.DEFAULT_RANGES.items():
85
+ engine.add_asset(name, min_p, max_p)
86
+ log.info("--no-restore: loaded %d default price ranges", len(config.DEFAULT_RANGES))
87
+
88
+ # ── Build Telegram application ───────────────────────────────────────
89
+ app = bot.build_app() if not args.dry_run else None
90
+
91
+ # ── Alert dispatcher ─────────────────────────────────────────────────
92
+ async def dispatch_alerts() -> None:
93
+ """Consume alert events from the queue and send Telegram notifications."""
94
+ while True:
95
+ event = await alert_queue.get()
96
+ try:
97
+ await bot.send_alert(event)
98
+ except Exception as exc:
99
+ log.error("Failed to dispatch alert: %s", exc)
100
+ finally:
101
+ alert_queue.task_done()
102
+
103
+ # ── Graceful shutdown ────────────────────────────────────────────────
104
+ shutdown_event = asyncio.Event()
105
+
106
+ def _signal_handler(sig, frame):
107
+ log.info("Shutdown signal received (%s), stopping…", sig)
108
+ shutdown_event.set()
109
+
110
+ signal.signal(signal.SIGINT, _signal_handler)
111
+ if hasattr(signal, "SIGTERM"):
112
+ signal.signal(signal.SIGTERM, _signal_handler)
113
+
114
+ # ── Launch all tasks ─────────────────────────────────────────────────
115
+ log.info("Starting all subsystems…")
116
+
117
+ tasks = [
118
+ asyncio.create_task(
119
+ poll_stocks(engine.on_price_update, engine.get_tracked_assets),
120
+ name="stock_poller",
121
+ ),
122
+ asyncio.create_task(
123
+ stream_crypto(engine.on_price_update, engine.get_tracked_assets),
124
+ name="crypto_streamer",
125
+ ),
126
+ asyncio.create_task(dispatch_alerts(), name="alert_dispatcher"),
127
+ ]
128
+
129
+ if app:
130
+ async def run_telegram():
131
+ """Run the Telegram updater alongside our tasks."""
132
+ await app.initialize()
133
+ await app.start()
134
+ await app.updater.start_polling(drop_pending_updates=True)
135
+ log.info("Telegram bot started ✓")
136
+ await shutdown_event.wait()
137
+ log.info("Stopping Telegram bot…")
138
+ await app.updater.stop()
139
+ await app.stop()
140
+ await app.shutdown()
141
+
142
+ tasks.append(asyncio.create_task(run_telegram(), name="telegram_bot"))
143
+ else:
144
+ log.info("[DRY-RUN] Telegram bot not started")
145
+
146
+ # ── Wait for shutdown ────────────────────────────────────────────────
147
+ try:
148
+ if app:
149
+ await shutdown_event.wait()
150
+ else:
151
+ await asyncio.gather(*tasks)
152
+ except asyncio.CancelledError:
153
+ pass
154
+ finally:
155
+ log.info("Saving state before shutdown…")
156
+ persistence.save_state(engine)
157
+
158
+ log.info("Cancelling tasks…")
159
+ for task in tasks:
160
+ task.cancel()
161
+ await asyncio.gather(*tasks, return_exceptions=True)
162
+ log.info("Bot stopped. Goodbye! 👋")
163
+
164
+
165
+ if __name__ == "__main__":
166
+ try:
167
+ asyncio.run(main())
168
+ except KeyboardInterrupt:
169
+ print("\nBot stopped by user.")
mobile-app/App.tsx ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react'
2
+ import { StatusBar } from 'expo-status-bar'
3
+ import { NavigationContainer } from '@react-navigation/native'
4
+ import { createNativeStackNavigator } from '@react-navigation/native-stack'
5
+ import DashboardScreen from './screens/DashboardScreen'
6
+ import AddAssetScreen from './screens/AddAssetScreen'
7
+ import AlertsScreen from './screens/AlertsScreen'
8
+
9
+ const Stack = createNativeStackNavigator()
10
+
11
+ export default function App() {
12
+ return (
13
+ <NavigationContainer>
14
+ <StatusBar style="light" />
15
+ <Stack.Navigator
16
+ initialRouteName="Dashboard"
17
+ screenOptions={{
18
+ headerStyle: { backgroundColor: '#1e293b' },
19
+ headerTintColor: '#f1f5f9',
20
+ headerTitleStyle: { fontWeight: '600' },
21
+ contentStyle: { backgroundColor: '#0f172a' },
22
+ }}
23
+ >
24
+ <Stack.Screen
25
+ name="Dashboard"
26
+ component={DashboardScreen}
27
+ options={{ title: 'Price Alerts' }}
28
+ />
29
+ <Stack.Screen
30
+ name="AddAsset"
31
+ component={AddAssetScreen}
32
+ options={{ title: 'Add Asset' }}
33
+ />
34
+ <Stack.Screen
35
+ name="Alerts"
36
+ component={AlertsScreen}
37
+ options={{ title: 'Alert History' }}
38
+ />
39
+ </Stack.Navigator>
40
+ </NavigationContainer>
41
+ )
42
+ }
mobile-app/app.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "expo": {
3
+ "name": "Price Alert",
4
+ "slug": "price-alert",
5
+ "version": "1.0.0",
6
+ "orientation": "portrait",
7
+ "icon": "./assets/icon.png",
8
+ "userInterfaceStyle": "dark",
9
+ "splash": {
10
+ "image": "./assets/splash.png",
11
+ "resizeMode": "contain",
12
+ "backgroundColor": "#0f172a"
13
+ },
14
+ "assetBundlePatterns": ["**/*"],
15
+ "ios": {
16
+ "supportsTablet": true
17
+ },
18
+ "android": {
19
+ "adaptiveIcon": {
20
+ "foregroundImage": "./assets/adaptive-icon.png",
21
+ "backgroundColor": "#0f172a"
22
+ }
23
+ },
24
+ "web": {
25
+ "favicon": "./assets/favicon.png"
26
+ }
27
+ }
28
+ }
mobile-app/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
mobile-app/package.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "price-alert-mobile",
3
+ "version": "1.0.0",
4
+ "main": "node_modules/expo/AppEntry.js",
5
+ "scripts": {
6
+ "start": "expo start",
7
+ "android": "expo start --android",
8
+ "ios": "expo start --ios",
9
+ "web": "expo start --web"
10
+ },
11
+ "dependencies": {
12
+ "@react-navigation/native": "^6.1.9",
13
+ "@react-navigation/native-stack": "^6.9.17",
14
+ "expo": "~50.0.0",
15
+ "expo-status-bar": "~1.11.1",
16
+ "react": "18.2.0",
17
+ "react-native": "0.73.2",
18
+ "react-native-safe-area-context": "4.8.2",
19
+ "react-native-screens": "~3.29.0"
20
+ },
21
+ "devDependencies": {
22
+ "@babel/core": "^7.20.0",
23
+ "@types/node": "^25.5.0",
24
+ "@types/react": "~18.2.45",
25
+ "typescript": "^5.1.3"
26
+ },
27
+ "private": true
28
+ }
mobile-app/screens/AddAssetScreen.tsx ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react'
2
+ import { View, Text, TextInput, TouchableOpacity, StyleSheet, ScrollView, Alert } from 'react-native'
3
+ import { NativeStackNavigationProp } from '@react-navigation/native-stack'
4
+
5
+ type RootStackParamList = {
6
+ Dashboard: undefined
7
+ AddAsset: undefined
8
+ }
9
+
10
+ type Props = {
11
+ navigation: NativeStackNavigationProp<RootStackParamList, 'AddAsset'>
12
+ }
13
+
14
+ interface AvailableAssets {
15
+ commodities: string[]
16
+ stocks: string[]
17
+ crypto: string[]
18
+ all: string[]
19
+ }
20
+
21
+ const API_URL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8000'
22
+
23
+ export default function AddAssetScreen({ navigation }: Props) {
24
+ const [name, setName] = useState('')
25
+ const [minPrice, setMinPrice] = useState('')
26
+ const [maxPrice, setMaxPrice] = useState('')
27
+ const [available, setAvailable] = useState<AvailableAssets>({
28
+ commodities: [],
29
+ stocks: [],
30
+ crypto: [],
31
+ all: [],
32
+ })
33
+
34
+ useEffect(() => {
35
+ fetch(`${API_URL}/assets/available`)
36
+ .then(res => res.json())
37
+ .then((data: AvailableAssets) => setAvailable(data))
38
+ .catch(err => console.error('Failed to load available assets:', err))
39
+ }, [])
40
+
41
+ const handleSubmit = async () => {
42
+ if (!name) {
43
+ Alert.alert('Error', 'Please select an asset.')
44
+ return
45
+ }
46
+ const min = parseFloat(minPrice)
47
+ const max = parseFloat(maxPrice)
48
+ if (isNaN(min) || isNaN(max) || min >= max) {
49
+ Alert.alert('Error', 'Min price must be a number less than Max price.')
50
+ return
51
+ }
52
+
53
+ try {
54
+ const res = await fetch(`${API_URL}/assets`, {
55
+ method: 'POST',
56
+ headers: { 'Content-Type': 'application/json' },
57
+ body: JSON.stringify({ name, min_price: min, max_price: max }),
58
+ })
59
+
60
+ if (res.ok) {
61
+ navigation.goBack()
62
+ } else {
63
+ const err = await res.json()
64
+ Alert.alert('Error', err.detail || 'Failed to add asset.')
65
+ }
66
+ } catch {
67
+ Alert.alert('Error', 'Network error — is the backend running?')
68
+ }
69
+ }
70
+
71
+ const AssetChipGroup = ({ label, items }: { label: string; items: string[] }) => {
72
+ if (items.length === 0) return null
73
+ return (
74
+ <>
75
+ <Text style={styles.groupLabel}>{label}</Text>
76
+ <View style={styles.assetGrid}>
77
+ {items.map(a => (
78
+ <TouchableOpacity
79
+ key={a}
80
+ style={[styles.assetChip, name === a && styles.assetChipSelected]}
81
+ onPress={() => setName(a)}
82
+ >
83
+ <Text style={[styles.assetChipText, name === a && styles.assetChipTextSelected]}>{a}</Text>
84
+ </TouchableOpacity>
85
+ ))}
86
+ </View>
87
+ </>
88
+ )
89
+ }
90
+
91
+ return (
92
+ <ScrollView style={styles.container} contentContainerStyle={styles.content}>
93
+ <Text style={styles.label}>Select Asset</Text>
94
+
95
+ <AssetChipGroup label="₿ Crypto" items={available.crypto} />
96
+ <AssetChipGroup label="📦 Commodities" items={available.commodities} />
97
+ <AssetChipGroup label="📊 Stocks & Indices" items={available.stocks} />
98
+
99
+ {name !== '' && (
100
+ <View style={styles.selectedBadge}>
101
+ <Text style={styles.selectedText}>Selected: {name}</Text>
102
+ </View>
103
+ )}
104
+
105
+ <Text style={styles.label}>Min Price (USD)</Text>
106
+ <TextInput
107
+ style={styles.input}
108
+ placeholder="e.g. 80000"
109
+ placeholderTextColor="#64748b"
110
+ keyboardType="numeric"
111
+ value={minPrice}
112
+ onChangeText={setMinPrice}
113
+ />
114
+
115
+ <Text style={styles.label}>Max Price (USD)</Text>
116
+ <TextInput
117
+ style={styles.input}
118
+ placeholder="e.g. 90000"
119
+ placeholderTextColor="#64748b"
120
+ keyboardType="numeric"
121
+ value={maxPrice}
122
+ onChangeText={setMaxPrice}
123
+ />
124
+
125
+ <TouchableOpacity
126
+ style={[styles.submitBtn, !name && styles.submitBtnDisabled]}
127
+ onPress={handleSubmit}
128
+ disabled={!name}
129
+ >
130
+ <Text style={styles.submitBtnText}>Add Asset</Text>
131
+ </TouchableOpacity>
132
+ </ScrollView>
133
+ )
134
+ }
135
+
136
+ const styles = StyleSheet.create({
137
+ container: { flex: 1, backgroundColor: '#0f172a' },
138
+ content: { padding: 16, paddingBottom: 40 },
139
+ label: { color: '#f1f5f9', fontSize: 16, fontWeight: '600', marginBottom: 8, marginTop: 20 },
140
+ groupLabel: { color: '#94a3b8', fontSize: 13, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 14, marginBottom: 8 },
141
+ assetGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
142
+ assetChip: { backgroundColor: '#1e293b', paddingHorizontal: 14, paddingVertical: 8, borderRadius: 8, borderWidth: 1, borderColor: '#334155' },
143
+ assetChipSelected: { backgroundColor: '#3b82f6', borderColor: '#3b82f6' },
144
+ assetChipText: { color: '#94a3b8', fontSize: 14 },
145
+ assetChipTextSelected: { color: '#fff', fontWeight: '700' },
146
+ selectedBadge: { marginTop: 12, backgroundColor: '#1e3a5f', borderRadius: 8, padding: 10, borderLeftWidth: 3, borderLeftColor: '#3b82f6' },
147
+ selectedText: { color: '#93c5fd', fontWeight: '600' },
148
+ input: { backgroundColor: '#1e293b', borderWidth: 1, borderColor: '#334155', borderRadius: 8, padding: 14, color: '#f1f5f9', fontSize: 16 },
149
+ submitBtn: { backgroundColor: '#3b82f6', padding: 16, borderRadius: 8, alignItems: 'center', marginTop: 28 },
150
+ submitBtnDisabled: { opacity: 0.4 },
151
+ submitBtnText: { color: '#fff', fontWeight: '600', fontSize: 16 },
152
+ })
mobile-app/screens/AlertsScreen.tsx ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react'
2
+ import { View, Text, FlatList, StyleSheet, TouchableOpacity } from 'react-native'
3
+
4
+ interface AlertEvent {
5
+ asset_name: string
6
+ price: number
7
+ min_price: number
8
+ max_price: number
9
+ timestamp: string
10
+ }
11
+
12
+ const API_URL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8000'
13
+
14
+ export default function AlertsScreen() {
15
+ const [alerts, setAlerts] = useState<AlertEvent[]>([])
16
+
17
+ useEffect(() => {
18
+ // Fetch existing history from REST on mount
19
+ fetch(`${API_URL}/history`)
20
+ .then(res => res.json())
21
+ .then((data: AlertEvent[]) => setAlerts(data.slice(0, 50)))
22
+ .catch(console.error)
23
+
24
+ let ws: WebSocket | null = null
25
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null
26
+
27
+ const connect = () => {
28
+ ws = new WebSocket(`${API_URL.replace('http', 'ws')}/ws`)
29
+
30
+ ws.onmessage = (event) => {
31
+ try {
32
+ const msg = JSON.parse(event.data)
33
+ if (msg.type === 'alert') {
34
+ setAlerts((prev: AlertEvent[]) => [msg.data as AlertEvent, ...prev].slice(0, 50))
35
+ }
36
+ // Ignore snapshot and price_update on this screen
37
+ } catch {}
38
+ }
39
+
40
+ ws.onclose = () => {
41
+ reconnectTimer = setTimeout(connect, 3000)
42
+ }
43
+
44
+ ws.onerror = () => {
45
+ ws?.close()
46
+ }
47
+ }
48
+
49
+ connect()
50
+
51
+ return () => {
52
+ // Clean up both WS and any pending reconnect timer
53
+ if (reconnectTimer) clearTimeout(reconnectTimer)
54
+ ws?.close()
55
+ }
56
+ }, [])
57
+
58
+ const formatPrice = (price: number) =>
59
+ `$${price.toLocaleString(undefined, {
60
+ minimumFractionDigits: 2,
61
+ maximumFractionDigits: price < 1 ? 6 : 2,
62
+ })}`
63
+
64
+ const renderItem = ({ item }: { item: AlertEvent }) => (
65
+ <View style={styles.alertItem}>
66
+ <Text style={styles.alertIcon}>🔔</Text>
67
+ <View style={styles.alertContent}>
68
+ <Text style={styles.alertTitle}>{item.asset_name} entered range</Text>
69
+ <Text style={styles.alertMeta}>
70
+ Price: {formatPrice(item.price)}
71
+ {' | '}Range: {formatPrice(item.min_price)} – {formatPrice(item.max_price)}
72
+ </Text>
73
+ <Text style={styles.alertTime}>{new Date(item.timestamp).toLocaleString()}</Text>
74
+ </View>
75
+ </View>
76
+ )
77
+
78
+ return (
79
+ <View style={styles.container}>
80
+ {alerts.length > 0 && (
81
+ <View style={styles.countBar}>
82
+ <Text style={styles.countText}>{alerts.length} alert{alerts.length !== 1 ? 's' : ''} recorded</Text>
83
+ </View>
84
+ )}
85
+ <FlatList
86
+ data={alerts}
87
+ keyExtractor={(_: AlertEvent, i: number) => i.toString()}
88
+ renderItem={renderItem}
89
+ contentContainerStyle={styles.list}
90
+ ListEmptyComponent={
91
+ <View style={styles.emptyWrap}>
92
+ <Text style={styles.emptyIcon}>📭</Text>
93
+ <Text style={styles.empty}>No alerts yet</Text>
94
+ <Text style={styles.emptyHint}>Alerts appear here when prices enter your target ranges</Text>
95
+ </View>
96
+ }
97
+ />
98
+ </View>
99
+ )
100
+ }
101
+
102
+ const styles = StyleSheet.create({
103
+ container: { flex: 1, backgroundColor: '#0f172a' },
104
+ countBar: { backgroundColor: '#1e293b', padding: 10, alignItems: 'center' },
105
+ countText: { color: '#94a3b8', fontSize: 13 },
106
+ list: { padding: 16 },
107
+ alertItem: { flexDirection: 'row', backgroundColor: '#1e293b', borderRadius: 12, padding: 16, marginBottom: 12 },
108
+ alertIcon: { fontSize: 24, marginRight: 12 },
109
+ alertContent:{ flex: 1 },
110
+ alertTitle: { fontSize: 16, fontWeight: '600', color: '#f1f5f9', marginBottom: 4 },
111
+ alertMeta: { fontSize: 14, color: '#94a3b8' },
112
+ alertTime: { fontSize: 12, color: '#64748b', marginTop: 4 },
113
+ emptyWrap: { alignItems: 'center', marginTop: 60 },
114
+ emptyIcon: { fontSize: 40, marginBottom: 12 },
115
+ empty: { color: '#94a3b8', textAlign: 'center', fontSize: 16, fontWeight: '600' },
116
+ emptyHint: { color: '#64748b', textAlign: 'center', fontSize: 13, marginTop: 8, paddingHorizontal: 32 },
117
+ })
mobile-app/screens/DashboardScreen.tsx ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useCallback } from 'react'
2
+ import { View, Text, FlatList, TouchableOpacity, StyleSheet, RefreshControl, Alert } from 'react-native'
3
+ import { NativeStackNavigationProp } from '@react-navigation/native-stack'
4
+ import { useFocusEffect } from '@react-navigation/native'
5
+
6
+ type RootStackParamList = {
7
+ Dashboard: undefined
8
+ AddAsset: undefined
9
+ Alerts: undefined
10
+ }
11
+
12
+ type Props = {
13
+ navigation: NativeStackNavigationProp<RootStackParamList, 'Dashboard'>
14
+ }
15
+
16
+ interface Asset {
17
+ name: string
18
+ min_price: number
19
+ max_price: number
20
+ state: 'OUTSIDE' | 'INSIDE'
21
+ last_price: number | null
22
+ }
23
+
24
+ interface AlertEvent {
25
+ asset_name: string
26
+ price: number
27
+ min_price: number
28
+ max_price: number
29
+ timestamp: string
30
+ }
31
+
32
+ // 📝 Change this to your server's local IP when running on a real device.
33
+ // Use http://localhost:8000 for emulators / web preview.
34
+ const API_URL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:8000'
35
+
36
+ export default function DashboardScreen({ navigation }: Props) {
37
+ const [assets, setAssets] = useState<Asset[]>([])
38
+ const [prices, setPrices] = useState<Record<string, number>>({})
39
+ const [recentAlerts, setRecentAlerts] = useState<AlertEvent[]>([])
40
+ const [refreshing, setRefreshing] = useState(false)
41
+ const [connected, setConnected] = useState(false)
42
+
43
+ const fetchAssets = useCallback(async () => {
44
+ try {
45
+ const res = await fetch(`${API_URL}/assets`)
46
+ if (res.ok) {
47
+ const data: Asset[] = await res.json()
48
+ setAssets(data)
49
+ // Seed prices from last_price so we display something before WS
50
+ setPrices(prev => {
51
+ const updated = { ...prev }
52
+ for (const a of data) {
53
+ if (a.last_price != null) updated[a.name] = a.last_price
54
+ }
55
+ return updated
56
+ })
57
+ }
58
+ } catch (err) {
59
+ console.error('Failed to fetch assets:', err)
60
+ }
61
+ }, [])
62
+
63
+ const removeAsset = async (name: string) => {
64
+ try {
65
+ const res = await fetch(`${API_URL}/assets/${name}`, { method: 'DELETE' })
66
+ if (res.ok) {
67
+ fetchAssets()
68
+ } else {
69
+ Alert.alert('Error', `Could not remove ${name}.`)
70
+ }
71
+ } catch (err) {
72
+ Alert.alert('Error', 'Network error — is the backend running?')
73
+ }
74
+ }
75
+
76
+ useFocusEffect(
77
+ useCallback(() => {
78
+ fetchAssets()
79
+ }, [fetchAssets])
80
+ )
81
+
82
+ useEffect(() => {
83
+ let ws: WebSocket | null = null
84
+ let reconnectTimer: ReturnType<typeof setTimeout>
85
+
86
+ const connect = () => {
87
+ ws = new WebSocket(`${API_URL.replace('http', 'ws')}/ws`)
88
+
89
+ ws.onopen = () => setConnected(true)
90
+
91
+ ws.onclose = () => {
92
+ setConnected(false)
93
+ reconnectTimer = setTimeout(connect, 3000)
94
+ }
95
+
96
+ ws.onerror = () => {
97
+ ws?.close()
98
+ }
99
+
100
+ ws.onmessage = (event) => {
101
+ try {
102
+ const msg = JSON.parse(event.data)
103
+
104
+ if (msg.type === 'snapshot') {
105
+ // Backend sends current state on connect — hydrate assets & prices
106
+ const snap: Asset[] = msg.data
107
+ setAssets(snap)
108
+ setPrices(prev => {
109
+ const updated = { ...prev }
110
+ for (const a of snap) {
111
+ if (a.last_price != null) updated[a.name] = a.last_price
112
+ }
113
+ return updated
114
+ })
115
+ } else if (msg.type === 'price_update') {
116
+ setPrices(prev => ({ ...prev, [msg.data.name]: msg.data.price }))
117
+ } else if (msg.type === 'alert') {
118
+ const ev: AlertEvent = msg.data
119
+ setRecentAlerts(prev => [ev, ...prev].slice(0, 20))
120
+ // Show native alert notification
121
+ Alert.alert(
122
+ `🔔 ${ev.asset_name} Alert!`,
123
+ `Price $${ev.price.toLocaleString()} entered your range ($${ev.min_price.toLocaleString()} – $${ev.max_price.toLocaleString()})`
124
+ )
125
+ }
126
+ } catch {}
127
+ }
128
+ }
129
+
130
+ connect()
131
+
132
+ return () => {
133
+ clearTimeout(reconnectTimer)
134
+ ws?.close()
135
+ }
136
+ }, [])
137
+
138
+ const onRefresh = async () => {
139
+ setRefreshing(true)
140
+ await fetchAssets()
141
+ setRefreshing(false)
142
+ }
143
+
144
+ const formatPrice = (price: number) =>
145
+ `$${price.toLocaleString(undefined, {
146
+ minimumFractionDigits: 2,
147
+ maximumFractionDigits: price < 1 ? 6 : 2,
148
+ })}`
149
+
150
+ const renderItem = ({ item }: { item: Asset }) => (
151
+ <View style={styles.card}>
152
+ <View style={styles.cardHeader}>
153
+ <Text style={styles.assetName}>{item.name}</Text>
154
+ <TouchableOpacity onPress={() => removeAsset(item.name)}>
155
+ <Text style={styles.removeBtn}>Remove</Text>
156
+ </TouchableOpacity>
157
+ </View>
158
+ <Text style={styles.price}>
159
+ {prices[item.name] != null ? formatPrice(prices[item.name]) : '—'}
160
+ </Text>
161
+ <Text style={styles.range}>
162
+ Range: {formatPrice(item.min_price)} – {formatPrice(item.max_price)}
163
+ </Text>
164
+ <View style={[styles.stateBadge, item.state === 'INSIDE' ? styles.stateInside : styles.stateOutside]}>
165
+ <Text style={styles.stateText}>{item.state === 'INSIDE' ? '✓ In Range' : '○ Outside'}</Text>
166
+ </View>
167
+ </View>
168
+ )
169
+
170
+ return (
171
+ <View style={styles.container}>
172
+ <View style={styles.header}>
173
+ <Text style={styles.title}>📈 Price Alerts</Text>
174
+ <View style={styles.statusRow}>
175
+ <View style={[styles.statusDot, { backgroundColor: connected ? '#10b981' : '#ef4444' }]} />
176
+ <Text style={styles.statusText}>{connected ? 'Live' : 'Reconnecting…'}</Text>
177
+ </View>
178
+ </View>
179
+
180
+ {recentAlerts.length > 0 && (
181
+ <View style={styles.alertBanner}>
182
+ <Text style={styles.alertBannerText}>
183
+ 🔔 Last alert: {recentAlerts[0].asset_name} @ ${recentAlerts[0].price.toLocaleString()}
184
+ </Text>
185
+ </View>
186
+ )}
187
+
188
+ <FlatList
189
+ data={assets}
190
+ keyExtractor={(item) => item.name}
191
+ renderItem={renderItem}
192
+ contentContainerStyle={styles.list}
193
+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor="#3b82f6" />}
194
+ ListEmptyComponent={<Text style={styles.empty}>No assets tracked. Tap "+ Add Asset" to start.</Text>}
195
+ />
196
+
197
+ <View style={styles.actions}>
198
+ <TouchableOpacity style={styles.btn} onPress={() => navigation.navigate('AddAsset')}>
199
+ <Text style={styles.btnText}>+ Add Asset</Text>
200
+ </TouchableOpacity>
201
+ <TouchableOpacity style={[styles.btn, styles.btnSecondary]} onPress={() => navigation.navigate('Alerts')}>
202
+ <Text style={styles.btnText}>View Alerts {recentAlerts.length > 0 ? `(${recentAlerts.length})` : ''}</Text>
203
+ </TouchableOpacity>
204
+ </View>
205
+ </View>
206
+ )
207
+ }
208
+
209
+ const styles = StyleSheet.create({
210
+ container: { flex: 1, backgroundColor: '#0f172a' },
211
+ header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16 },
212
+ title: { fontSize: 20, fontWeight: '700', color: '#f1f5f9' },
213
+ statusRow: { flexDirection: 'row', alignItems: 'center', gap: 6 },
214
+ statusDot: { width: 8, height: 8, borderRadius: 4 },
215
+ statusText: { color: '#94a3b8', fontSize: 13 },
216
+ alertBanner: { backgroundColor: '#1e3a5f', marginHorizontal: 16, marginBottom: 8, padding: 10, borderRadius: 8, borderLeftWidth: 3, borderLeftColor: '#3b82f6' },
217
+ alertBannerText: { color: '#93c5fd', fontSize: 13 },
218
+ list: { padding: 16, paddingTop: 0 },
219
+ card: { backgroundColor: '#1e293b', borderRadius: 12, padding: 16, marginBottom: 12 },
220
+ cardHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 },
221
+ assetName: { fontSize: 18, fontWeight: '600', color: '#f1f5f9' },
222
+ removeBtn: { color: '#dc2626', fontSize: 14 },
223
+ price: { fontSize: 24, fontWeight: '700', color: '#3b82f6', marginBottom: 4 },
224
+ range: { color: '#94a3b8', fontSize: 14, marginBottom: 8 },
225
+ stateBadge: { alignSelf: 'flex-start', paddingHorizontal: 12, paddingVertical: 4, borderRadius: 9999 },
226
+ stateInside: { backgroundColor: '#065f46' },
227
+ stateOutside: { backgroundColor: '#374151' },
228
+ stateText: { color: '#fff', fontSize: 12, fontWeight: '600' },
229
+ empty: { color: '#94a3b8', textAlign: 'center', marginTop: 40, fontSize: 15 },
230
+ actions: { flexDirection: 'row', padding: 16, gap: 12 },
231
+ btn: { flex: 1, backgroundColor: '#3b82f6', padding: 14, borderRadius: 8, alignItems: 'center' },
232
+ btnSecondary: { backgroundColor: '#1e293b', borderWidth: 1, borderColor: '#334155' },
233
+ btnText: { color: '#fff', fontWeight: '600', fontSize: 15 },
234
+ })
mobile-app/tsconfig.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "strict": true,
4
+ "jsx": "react-native"
5
+ },
6
+ "extends": "expo/tsconfig.base"
7
+ }
persistence.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ persistence.py — Save and restore alert engine state to/from a JSON file.
3
+
4
+ Called from main.py on startup (load) and graceful shutdown (save),
5
+ so tracked asset ranges survive bot restarts.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ from typing import TYPE_CHECKING
11
+
12
+ import config
13
+ from logger import get_logger
14
+
15
+ if TYPE_CHECKING:
16
+ from alert_engine import AlertEngine
17
+
18
+ log = get_logger("persistence")
19
+
20
+
21
+ def save_state(engine: "AlertEngine") -> None:
22
+ """
23
+ Serialise the alert engine's tracked assets to PERSISTENCE_FILE.
24
+ Writes atomically via a temp file to avoid corruption on crash.
25
+ """
26
+ details = engine.get_asset_details()
27
+ payload = {
28
+ "version": 1,
29
+ "assets": [
30
+ {
31
+ "name": d["name"],
32
+ "min_price": d["min"],
33
+ "max_price": d["max"],
34
+ }
35
+ for d in details
36
+ ],
37
+ }
38
+
39
+ tmp_path = config.PERSISTENCE_FILE + ".tmp"
40
+ try:
41
+ with open(tmp_path, "w", encoding="utf-8") as f:
42
+ json.dump(payload, f, indent=2)
43
+ os.replace(tmp_path, config.PERSISTENCE_FILE)
44
+ log.info("State saved → %s (%d assets)", config.PERSISTENCE_FILE, len(details))
45
+ except OSError as exc:
46
+ log.error("Failed to save state: %s", exc)
47
+ finally:
48
+ # Clean up temp file if replace failed
49
+ if os.path.exists(tmp_path):
50
+ try:
51
+ os.remove(tmp_path)
52
+ except OSError:
53
+ pass
54
+
55
+
56
+ def load_state(engine: "AlertEngine") -> int:
57
+ """
58
+ Load tracked assets from PERSISTENCE_FILE into the alert engine.
59
+ Returns the number of assets restored.
60
+ Silently skips the file if it doesn't exist or is malformed.
61
+ """
62
+ if not os.path.exists(config.PERSISTENCE_FILE):
63
+ log.info("No persistence file found at %s — starting fresh", config.PERSISTENCE_FILE)
64
+ return 0
65
+
66
+ try:
67
+ with open(config.PERSISTENCE_FILE, "r", encoding="utf-8") as f:
68
+ payload = json.load(f)
69
+
70
+ assets = payload.get("assets", [])
71
+ restored = 0
72
+ for entry in assets:
73
+ name = entry.get("name", "").upper()
74
+ min_p = float(entry["min_price"])
75
+ max_p = float(entry["max_price"])
76
+ if name and min_p < max_p:
77
+ engine.add_asset(name, min_p, max_p)
78
+ restored += 1
79
+ else:
80
+ log.warning("Skipping invalid entry in state file: %s", entry)
81
+
82
+ log.info("Restored %d asset(s) from %s", restored, config.PERSISTENCE_FILE)
83
+ return restored
84
+
85
+ except (json.JSONDecodeError, KeyError, ValueError, OSError) as exc:
86
+ log.error("Failed to load state from %s: %s", config.PERSISTENCE_FILE, exc)
87
+ return 0
price_server.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ price_server.py — Tiny HTTP proxy server for the standalone HTML dashboards.
3
+
4
+ Run: python price_server.py
5
+ Then open standalone-alerts-full.html in your browser.
6
+ Proxies Yahoo Finance requests to avoid browser CORS restrictions.
7
+ """
8
+
9
+ import json
10
+ import os
11
+ from http.server import HTTPServer, SimpleHTTPRequestHandler
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ PORT = int(os.getenv("PRICE_SERVER_PORT", "8080"))
16
+
17
+ # Supported symbol → display name mapping
18
+ SYMBOL_MAP: dict[str, str] = {
19
+ # Commodities
20
+ "GC=F": "Gold",
21
+ "SI=F": "Silver",
22
+ "CL=F": "Crude Oil",
23
+ "NG=F": "Natural Gas",
24
+ "HG=F": "Copper",
25
+ # Stocks
26
+ "NVDA": "NVIDIA",
27
+ "TSLA": "Tesla",
28
+ "AAPL": "Apple",
29
+ "GOOGL": "Google",
30
+ "MSFT": "Microsoft",
31
+ "AMZN": "Amazon",
32
+ "META": "Meta",
33
+ "ORCL": "Oracle",
34
+ "NFLX": "Netflix",
35
+ # Indices
36
+ "^GSPC": "S&P 500",
37
+ "^DJI": "Dow Jones",
38
+ "^IXIC": "NASDAQ",
39
+ }
40
+
41
+
42
+ def _fetch_yahoo(symbol: str) -> float | None:
43
+ """Fetch the latest price for a symbol from Yahoo Finance."""
44
+ url = (
45
+ f"https://query1.finance.yahoo.com/v8/finance/chart/"
46
+ f"{urllib.request.quote(symbol)}?interval=1d&range=1d"
47
+ )
48
+ try:
49
+ req = urllib.request.Request(
50
+ url,
51
+ headers={"User-Agent": "Mozilla/5.0", "Accept": "application/json"},
52
+ )
53
+ with urllib.request.urlopen(req, timeout=10) as resp:
54
+ data = json.loads(resp.read())
55
+ price = (
56
+ data.get("chart", {})
57
+ .get("result", [{}])[0]
58
+ .get("meta", {})
59
+ .get("regularMarketPrice")
60
+ )
61
+ return float(price) if price is not None else None
62
+ except Exception as exc:
63
+ print(f" [price_server] Error fetching {symbol}: {exc}")
64
+ return None
65
+
66
+
67
+ def _json_response(handler, status: int, body: dict) -> None:
68
+ """Helper to write a JSON response."""
69
+ payload = json.dumps(body).encode()
70
+ handler.send_response(status)
71
+ handler.send_header("Content-Type", "application/json")
72
+ handler.send_header("Content-Length", str(len(payload)))
73
+ handler.send_header("Access-Control-Allow-Origin", "*")
74
+ handler.end_headers()
75
+ handler.wfile.write(payload)
76
+
77
+
78
+ class CORSRequestHandler(SimpleHTTPRequestHandler):
79
+ """HTTP handler that proxies /api/<SYMBOL> to Yahoo Finance."""
80
+
81
+ def log_message(self, fmt, *args):
82
+ # Suppress noisy access logs for static files; keep API logs
83
+ if self.path.startswith("/api/"):
84
+ print(f" [price_server] {fmt % args}")
85
+
86
+ def do_OPTIONS(self):
87
+ """Pre-flight CORS response."""
88
+ self.send_response(204)
89
+ self.send_header("Access-Control-Allow-Origin", "*")
90
+ self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
91
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
92
+ self.end_headers()
93
+
94
+ def do_GET(self):
95
+ if self.path == "/api/symbols":
96
+ # Return the full symbol map so the front-end can build dropdowns
97
+ _json_response(self, 200, {"symbols": SYMBOL_MAP})
98
+ return
99
+
100
+ if self.path.startswith("/api/"):
101
+ symbol = urllib.request.unquote(self.path[5:]) # strip /api/
102
+ if symbol not in SYMBOL_MAP:
103
+ _json_response(self, 404, {
104
+ "error": f"Unknown symbol '{symbol}'.",
105
+ "supported": list(SYMBOL_MAP.keys()),
106
+ })
107
+ return
108
+
109
+ price = _fetch_yahoo(symbol)
110
+ if price is None:
111
+ _json_response(self, 502, {
112
+ "error": f"Failed to fetch price for '{symbol}'. Yahoo Finance may be unavailable.",
113
+ })
114
+ return
115
+
116
+ _json_response(self, 200, {
117
+ "symbol": symbol,
118
+ "name": SYMBOL_MAP[symbol],
119
+ "price": price,
120
+ })
121
+ return
122
+
123
+ # Serve static files for everything else
124
+ super().do_GET()
125
+
126
+ def end_headers(self):
127
+ self.send_header("Access-Control-Allow-Origin", "*")
128
+ super().end_headers()
129
+
130
+
131
+ if __name__ == "__main__":
132
+ print(f" Price proxy server running at http://localhost:{PORT}")
133
+ print(" Keep this window open while using the HTML dashboards.")
134
+ print(f" Supported symbols: {', '.join(SYMBOL_MAP.keys())}")
135
+ HTTPServer(("", PORT), CORSRequestHandler).serve_forever()
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─── Telegram Bot ──────────────────────────────────────────────────────────────
2
+ python-telegram-bot>=20.7
3
+
4
+ # ─── HTTP / WebSocket ──────────────────────────────────────────────────────────
5
+ websockets>=12.0
6
+ aiohttp>=3.9.0
7
+
8
+ # ─── Price Data ────────────────────────────────────────────────────────────────
9
+ yfinance>=0.2.31
10
+
11
+ # ─── Config / Env ──────────────────────────────────────────────────────────────
12
+ python-dotenv>=1.0.0
13
+
14
+ # ─── FastAPI Backend (backend/main.py) ─────────────────────────────────────────
15
+ fastapi>=0.109.0
16
+ uvicorn[standard]>=0.27.0
17
+ pydantic>=2.5.3
standalone-alerts-full.html ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Price Alert Manager</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0a0a0f; color: #f8fafc; min-height: 100vh; padding: 1rem; }
10
+ .container { max-width: 900px; margin: 0 auto; }
11
+ header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #1e293b; flex-wrap: wrap; gap: 1rem; }
12
+ h1 { font-size: 1.5rem; background: linear-gradient(135deg, #6366f1, #22c55e); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
13
+ .tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
14
+ .tab { padding: 0.5rem 1rem; background: #1e293b; border: none; border-radius: 8px; color: #94a3b8; cursor: pointer; font-size: 0.875rem; transition: all 0.2s; }
15
+ .tab.active { background: #6366f1; color: white; }
16
+ .card { background: #12121a; border: 1px solid #1e293b; border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; transition: all 0.3s; }
17
+ .card:hover { border-color: #6366f1; }
18
+ .card.flash { animation: flash 0.5s ease 3; }
19
+ @keyframes flash { 0%,100% { border-color: #1e293b; box-shadow: none; } 50% { border-color: #f59e0b; box-shadow: 0 0 30px #f59e0b50; } }
20
+ .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
21
+ .asset-name { font-size: 1.25rem; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
22
+ .asset-icon { font-size: 1.5rem; }
23
+ .badge { font-size: 0.65rem; padding: 0.2rem 0.5rem; border-radius: 4px; font-weight: 600; text-transform: uppercase; }
24
+ .badge.crypto { background: #f59e0b30; color: #f59e0b; }
25
+ .badge.stock { background: #3b82f620; color: #60a5fa; }
26
+ .badge.commodity { background: #fbbf2430; color: #fbbf24; }
27
+ .badge.index { background: #a78bfa30; color: #a78bfa; }
28
+ .price { font-size: 1.75rem; font-weight: 700; color: #6366f1; margin-bottom: 0.5rem; }
29
+ .range { color: #94a3b8; font-size: 0.875rem; margin-bottom: 0.75rem; }
30
+ .state { padding: 0.4rem 0.8rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; display: inline-block; }
31
+ .state.inside { background: #22c55e20; color: #22c55e; }
32
+ .state.outside { background: #374151; color: #94a3b8; }
33
+ .btn { padding: 0.5rem 1rem; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.875rem; }
34
+ .btn-primary { background: #6366f1; color: white; }
35
+ .btn-primary:hover { background: #818cf8; }
36
+ .btn-danger { background: transparent; color: #ef4444; border: 1px solid #ef4444; }
37
+ .btn-danger:hover { background: #ef4444; color: white; }
38
+ .modal { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; align-items: center; justify-content: center; z-index: 100; }
39
+ .modal.active { display: flex; }
40
+ .modal-content { background: #12121a; border: 1px solid #1e293b; border-radius: 16px; padding: 2rem; width: 90%; max-width: 450px; max-height: 90vh; overflow-y: auto; }
41
+ .modal h2 { margin-bottom: 1rem; }
42
+ .form-group { margin-bottom: 1rem; }
43
+ .form-group label { display: block; margin-bottom: 0.5rem; color: #94a3b8; font-size: 0.875rem; }
44
+ .form-group input, .form-group select { width: 100%; padding: 0.75rem; background: #0a0a0f; border: 1px solid #1e293b; border-radius: 8px; color: #f8fafc; font-size: 1rem; }
45
+ .form-group input:focus, .form-group select:focus { outline: none; border-color: #6366f1; }
46
+ .btn-block { width: 100%; padding: 1rem; margin-top: 0.5rem; }
47
+ .toast { position: fixed; top: 20px; right: 20px; background: #12121a; border: 2px solid #22c55e; border-radius: 12px; padding: 1rem 1.5rem; z-index: 1000; animation: slideIn 0.3s; }
48
+ @keyframes slideIn { from { opacity: 0; transform: translateX(120%); } to { opacity: 1; transform: translateX(0); } }
49
+ .toast-title { font-weight: 700; margin-bottom: 0.25rem; display: flex; align-items: center; gap: 0.5rem; }
50
+ .toast-msg { font-size: 0.875rem; color: #94a3b8; }
51
+ .empty { text-align: center; padding: 3rem; color: #94a3b8; }
52
+ .section-title { font-size: 1.1rem; margin: 1.5rem 0 1rem; color: #94a3b8; display: flex; align-items: center; gap: 0.5rem; }
53
+ .alert-item { background: #12121a; border: 1px solid #1e293b; border-radius: 8px; padding: 1rem; margin-bottom: 0.5rem; display: flex; gap: 1rem; align-items: center; }
54
+ .server-status { font-size: 0.75rem; padding: 0.5rem 1rem; background: #1e293b; border-radius: 9999px; display: flex; align-items: center; gap: 0.5rem; }
55
+ .server-dot { width: 8px; height: 8px; border-radius: 50%; }
56
+ .server-dot.off { background: #ef4444; }
57
+ .server-dot.on { background: #22c55e; animation: pulse 2s infinite; }
58
+ @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.5; } }
59
+ .info-box { background: #1e293b; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.875rem; }
60
+ .info-box a { color: #6366f1; }
61
+ </style>
62
+ </head>
63
+ <body>
64
+ <div id="toasts"></div>
65
+
66
+ <div class="container">
67
+ <header>
68
+ <h1>Price Alert Manager</h1>
69
+ <div style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
70
+ <div class="server-status" id="serverStatus">
71
+ <span class="server-dot off" id="serverDot"></span>
72
+ <span id="serverText">Checking server...</span>
73
+ </div>
74
+ <button class="btn btn-primary" onclick="showModal()">+ Add Alert</button>
75
+ </div>
76
+ </header>
77
+
78
+ <div class="tabs">
79
+ <button class="tab active" onclick="filterType('all')">All</button>
80
+ <button class="tab" onclick="filterType('crypto')">Crypto</button>
81
+ <button class="tab" onclick="filterType('stock')">Stocks</button>
82
+ <button class="tab" onclick="filterType('commodity')">Commodities</button>
83
+ <button class="tab" onclick="filterType('index')">Indices</button>
84
+ </div>
85
+
86
+ <div id="alertsContainer"></div>
87
+
88
+ <div class="section-title">📋 Alert History</div>
89
+ <div id="historyContainer"></div>
90
+ </div>
91
+
92
+ <div id="modal" class="modal" onclick="if(event.target===this)hideModal()">
93
+ <div class="modal-content">
94
+ <h2>Add Price Alert</h2>
95
+ <div class="form-group">
96
+ <label>Asset</label>
97
+ <select id="assetSelect">
98
+ <option value="">Select asset...</option>
99
+ <optgroup label="💰 Crypto">
100
+ <option value="bitcoin">Bitcoin (BTC)</option>
101
+ <option value="ethereum">Ethereum (ETH)</option>
102
+ <option value="solana">Solana (SOL)</option>
103
+ <option value="ripple">XRP</option>
104
+ <option value="cardano">Cardano (ADA)</option>
105
+ <option value="dogecoin">Dogecoin (DOGE)</option>
106
+ <option value="polkadot">Polkadot (DOT)</option>
107
+ <option value="chainlink">Chainlink (LINK)</option>
108
+ </optgroup>
109
+ <optgroup label="🥇 Commodities">
110
+ <option value="GC=F">Gold</option>
111
+ <option value="SI=F">Silver</option>
112
+ <option value="CL=F">Crude Oil</option>
113
+ <option value="NG=F">Natural Gas</option>
114
+ </optgroup>
115
+ <optgroup label="📊 Stocks">
116
+ <option value="NVDA">NVIDIA</option>
117
+ <option value="TSLA">Tesla</option>
118
+ <option value="AAPL">Apple</option>
119
+ <option value="GOOGL">Google</option>
120
+ <option value="MSFT">Microsoft</option>
121
+ <option value="AMZN">Amazon</option>
122
+ <option value="META">Meta</option>
123
+ </optgroup>
124
+ <optgroup label="📈 Indices">
125
+ <option value="^GSPC">S&P 500</option>
126
+ <option value="^DJI">Dow Jones</option>
127
+ <option value="^IXIC">NASDAQ</option>
128
+ </optgroup>
129
+ </select>
130
+ </div>
131
+ <div class="form-group">
132
+ <label>Min Price (USD)</label>
133
+ <input type="number" id="minPrice" step="any" placeholder="60000">
134
+ </div>
135
+ <div class="form-group">
136
+ <label>Max Price (USD)</label>
137
+ <input type="number" id="maxPrice" step="any" placeholder="62000">
138
+ </div>
139
+ <button class="btn btn-primary btn-block" onclick="addAlert()">Add Alert</button>
140
+ <button class="btn btn-danger btn-block" onclick="hideModal()">Cancel</button>
141
+ </div>
142
+ </div>
143
+
144
+ <script>
145
+ const ASSETS = {
146
+ // Crypto
147
+ 'bitcoin': { name: 'Bitcoin', type: 'crypto', icon: '₿' },
148
+ 'ethereum': { name: 'Ethereum', type: 'crypto', icon: 'Ξ' },
149
+ 'solana': { name: 'Solana', type: 'crypto', icon: '◎' },
150
+ 'ripple': { name: 'XRP', type: 'crypto', icon: '✕' },
151
+ 'cardano': { name: 'Cardano', type: 'crypto', icon: '₳' },
152
+ 'dogecoin': { name: 'Dogecoin', type: 'crypto', icon: 'Ð' },
153
+ 'polkadot': { name: 'Polkadot', type: 'crypto', icon: '●' },
154
+ 'chainlink': { name: 'Chainlink', type: 'crypto', icon: '⬡' },
155
+ // Commodities
156
+ 'GC=F': { name: 'Gold', type: 'commodity', icon: '🥇' },
157
+ 'SI=F': { name: 'Silver', type: 'commodity', icon: '🥈' },
158
+ 'CL=F': { name: 'Crude Oil', type: 'commodity', icon: '🛢️' },
159
+ 'NG=F': { name: 'Natural Gas', type: 'commodity', icon: '🔥' },
160
+ // Stocks
161
+ 'NVDA': { name: 'NVIDIA', type: 'stock', icon: '📊' },
162
+ 'TSLA': { name: 'Tesla', type: 'stock', icon: '🚗' },
163
+ 'AAPL': { name: 'Apple', type: 'stock', icon: '🍎' },
164
+ 'GOOGL': { name: 'Google', type: 'stock', icon: '🔍' },
165
+ 'MSFT': { name: 'Microsoft', type: 'stock', icon: '🪟' },
166
+ 'AMZN': { name: 'Amazon', type: 'stock', icon: '📦' },
167
+ 'META': { name: 'Meta', type: 'stock', icon: '📘' },
168
+ // Indices
169
+ '^GSPC': { name: 'S&P 500', type: 'index', icon: '📈' },
170
+ '^DJI': { name: 'Dow Jones', type: 'index', icon: '📉' },
171
+ '^IXIC': { name: 'NASDAQ', type: 'index', icon: '💹' },
172
+ };
173
+
174
+ const CRYPTO_IDS = Object.keys(ASSETS).filter(k => ASSETS[k].type === 'crypto');
175
+ const STOCK_SYMBOLS = Object.keys(ASSETS).filter(k => ASSETS[k].type !== 'crypto');
176
+
177
+ let alerts = JSON.parse(localStorage.getItem('pa_alerts_full') || '[]');
178
+ let history = JSON.parse(localStorage.getItem('pa_history_full') || '[]');
179
+ let prices = {};
180
+ let triggered = new Set();
181
+ let currentFilter = 'all';
182
+ let serverOnline = false;
183
+
184
+ function save() {
185
+ localStorage.setItem('pa_alerts_full', JSON.stringify(alerts));
186
+ localStorage.setItem('pa_history_full', JSON.stringify(history.slice(0, 30)));
187
+ }
188
+
189
+ function showModal() {
190
+ document.getElementById('modal').classList.add('active');
191
+ }
192
+
193
+ function hideModal() {
194
+ document.getElementById('modal').classList.remove('active');
195
+ }
196
+
197
+ function filterType(type) {
198
+ currentFilter = type;
199
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
200
+ event.target.classList.add('active');
201
+ render();
202
+ }
203
+
204
+ function addAlert() {
205
+ const symbol = document.getElementById('assetSelect').value;
206
+ const min = parseFloat(document.getElementById('minPrice').value);
207
+ const max = parseFloat(document.getElementById('maxPrice').value);
208
+
209
+ if (!symbol || !min || !max || min >= max) {
210
+ alert('Please fill all fields correctly.\nMin must be less than Max.');
211
+ return;
212
+ }
213
+
214
+ const currentPrice = prices[symbol];
215
+ const inRange = currentPrice >= min && currentPrice <= max;
216
+
217
+ alerts = alerts.filter(a => a.symbol !== symbol);
218
+ alerts.push({ symbol, min, max, lastInRange: inRange });
219
+
220
+ save();
221
+ render();
222
+ hideModal();
223
+
224
+ if (inRange) {
225
+ triggerAlert(symbol, currentPrice, min, max);
226
+ }
227
+ }
228
+
229
+ function removeAlert(symbol) {
230
+ alerts = alerts.filter(a => a.symbol !== symbol);
231
+ triggered.clear();
232
+ save();
233
+ render();
234
+ }
235
+
236
+ function triggerAlert(symbol, price, min, max) {
237
+ const key = symbol + '-' + min + '-' + max;
238
+ if (triggered.has(key)) return;
239
+ triggered.add(key);
240
+
241
+ history.unshift({ symbol, price, min, max, time: Date.now() });
242
+ save();
243
+ renderHistory();
244
+
245
+ showToast(symbol, price, min, max);
246
+
247
+ if (Notification.permission === 'granted') {
248
+ new Notification(ASSETS[symbol]?.name + ' Alert!', {
249
+ body: 'Price $' + price.toLocaleString() + ' is in range',
250
+ icon: '🔔'
251
+ });
252
+ }
253
+
254
+ if ('vibrate' in navigator) navigator.vibrate([200, 100, 200]);
255
+
256
+ const card = document.getElementById('card-' + symbol.replace(/[^a-zA-Z]/g, ''));
257
+ if (card) {
258
+ card.classList.add('flash');
259
+ setTimeout(() => card.classList.remove('flash'), 2000);
260
+ }
261
+ }
262
+
263
+ function showToast(symbol, price, min, max) {
264
+ const asset = ASSETS[symbol] || { name: symbol };
265
+ const div = document.createElement('div');
266
+ div.className = 'toast';
267
+ div.innerHTML = `
268
+ <div class="toast-title">🔔 ${asset.name} Alert!</div>
269
+ <div class="toast-msg">$${price.toLocaleString()} in range ($${min.toLocaleString()} - $${max.toLocaleString()})</div>
270
+ `;
271
+ document.getElementById('toasts').appendChild(div);
272
+ setTimeout(() => div.remove(), 5000);
273
+ }
274
+
275
+ function render() {
276
+ const container = document.getElementById('alertsContainer');
277
+ const filtered = currentFilter === 'all'
278
+ ? alerts
279
+ : alerts.filter(a => ASSETS[a.symbol]?.type === currentFilter);
280
+
281
+ if (filtered.length === 0) {
282
+ container.innerHTML = '<div class="empty">No alerts for this category.<br>Click "+ Add Alert" to add one.</div>';
283
+ return;
284
+ }
285
+
286
+ container.innerHTML = filtered.map(a => {
287
+ const asset = ASSETS[a.symbol] || { name: a.symbol, icon: '●', type: 'unknown' };
288
+ const price = prices[a.symbol];
289
+ const inRange = price >= a.min && price <= a.max;
290
+
291
+ return `
292
+ <div class="card" id="card-${a.symbol.replace(/[^a-zA-Z]/g, '')}">
293
+ <div class="card-header">
294
+ <span class="asset-name">
295
+ <span class="asset-icon">${asset.icon}</span>
296
+ ${asset.name}
297
+ <span class="badge ${asset.type}">${asset.type}</span>
298
+ </span>
299
+ <button class="btn btn-danger" onclick="removeAlert('${a.symbol}')">Remove</button>
300
+ </div>
301
+ <div class="price">${price ? '$' + price.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: price < 1 ? 6 : 2}) : 'Loading...'}</div>
302
+ <div class="range">Target: $${a.min.toLocaleString()} - $${a.max.toLocaleString()}</div>
303
+ <span class="state ${inRange ? 'inside' : 'outside'}">${inRange ? '✓ In Range' : '○ Waiting'}</span>
304
+ </div>
305
+ `;
306
+ }).join('');
307
+ }
308
+
309
+ function renderHistory() {
310
+ const container = document.getElementById('historyContainer');
311
+ if (history.length === 0) {
312
+ container.innerHTML = '<div class="empty" style="padding:1rem">No alerts triggered yet</div>';
313
+ return;
314
+ }
315
+ container.innerHTML = history.map(h => {
316
+ const asset = ASSETS[h.symbol] || { name: h.symbol };
317
+ return `
318
+ <div class="alert-item">
319
+ <span>🔔</span>
320
+ <div>
321
+ <strong>${asset.icon} ${asset.name}</strong> - $${h.price.toLocaleString()}
322
+ <div style="font-size:0.75rem;color:#64748b;margin-top:2px">
323
+ Range: $${h.min.toLocaleString()} - $${h.max.toLocaleString()} | ${new Date(h.time).toLocaleTimeString()}
324
+ </div>
325
+ </div>
326
+ </div>
327
+ `;
328
+ }).join('');
329
+ }
330
+
331
+ async function fetchCryptoPrices() {
332
+ if (!alerts.some(a => CRYPTO_IDS.includes(a.symbol))) return;
333
+
334
+ const coins = alerts.filter(a => CRYPTO_IDS.includes(a.symbol)).map(a => a.symbol);
335
+ if (coins.length === 0) return;
336
+
337
+ try {
338
+ const ids = coins.join(',');
339
+ const res = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`);
340
+ if (res.ok) {
341
+ const data = await res.json();
342
+ for (const [coin, info] of Object.entries(data)) {
343
+ if (info.usd) prices[coin] = info.usd;
344
+ }
345
+ }
346
+ } catch (e) {
347
+ console.log('Crypto fetch error:', e);
348
+ }
349
+ }
350
+
351
+ async function fetchStockPrices() {
352
+ const stocks = alerts.filter(a => STOCK_SYMBOLS.includes(a.symbol)).map(a => a.symbol);
353
+ if (stocks.length === 0) return;
354
+
355
+ for (const symbol of stocks) {
356
+ try {
357
+ const res = await fetch(`http://localhost:8080/api/${encodeURIComponent(symbol)}`);
358
+ if (res.ok) {
359
+ const data = await res.json();
360
+ prices[symbol] = data.price;
361
+ }
362
+ } catch (e) {
363
+ // Server might not be running
364
+ }
365
+ }
366
+ }
367
+
368
+ function checkServer() {
369
+ fetch('http://localhost:8080/', { mode: 'no-cors' })
370
+ .then(() => {
371
+ serverOnline = true;
372
+ document.getElementById('serverDot').className = 'server-dot on';
373
+ document.getElementById('serverText').textContent = 'Stocks: Online';
374
+ })
375
+ .catch(() => {
376
+ serverOnline = false;
377
+ document.getElementById('serverDot').className = 'server-dot off';
378
+ document.getElementById('serverText').textContent = 'Stocks: Offline';
379
+ });
380
+ }
381
+
382
+ function checkAlerts() {
383
+ alerts.forEach(a => {
384
+ const price = prices[a.symbol];
385
+ if (!price) return;
386
+
387
+ const wasIn = a.lastInRange === true;
388
+ const isIn = price >= a.min && price <= a.max;
389
+
390
+ if (isIn && !wasIn) {
391
+ triggerAlert(a.symbol, price, a.min, a.max);
392
+ }
393
+
394
+ a.lastInRange = isIn;
395
+ });
396
+ save();
397
+ render();
398
+ }
399
+
400
+ async function init() {
401
+ render();
402
+ renderHistory();
403
+
404
+ // Check if stock server is running
405
+ checkServer();
406
+ setInterval(checkServer, 10000);
407
+
408
+ // Initial fetch
409
+ await fetchCryptoPrices();
410
+ if (serverOnline) await fetchStockPrices();
411
+ checkAlerts();
412
+
413
+ // Poll every 10 seconds
414
+ setInterval(async () => {
415
+ await fetchCryptoPrices();
416
+ if (serverOnline) await fetchStockPrices();
417
+ checkAlerts();
418
+ }, 10000);
419
+
420
+ if ('Notification' in window && Notification.permission === 'default') {
421
+ Notification.requestPermission();
422
+ }
423
+ }
424
+
425
+ init();
426
+ </script>
427
+ </body>
428
+ </html>
standalone-alerts.html ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Price Alert Manager</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0a0a0f; color: #f8fafc; min-height: 100vh; padding: 1rem; }
10
+ .container { max-width: 800px; margin: 0 auto; }
11
+ header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #1e293b; }
12
+ h1 { font-size: 1.5rem; background: linear-gradient(135deg, #6366f1, #22c55e); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
13
+ .debug { background: #1a1a2e; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-family: monospace; font-size: 0.75rem; white-space: pre-wrap; max-height: 100px; overflow-y: auto; color: #94a3b8; }
14
+ .card { background: #12121a; border: 1px solid #1e293b; border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; transition: all 0.3s; }
15
+ .card:hover { border-color: #6366f1; }
16
+ .card.flash { animation: flash 0.5s ease 3; }
17
+ @keyframes flash { 0%,100% { border-color: #1e293b; box-shadow: none; } 50% { border-color: #f59e0b; box-shadow: 0 0 30px #f59e0b50; } }
18
+ .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
19
+ .asset-name { font-size: 1.25rem; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
20
+ .asset-icon { font-size: 1.5rem; }
21
+ .price { font-size: 1.75rem; font-weight: 700; color: #6366f1; margin-bottom: 0.5rem; }
22
+ .range { color: #94a3b8; font-size: 0.875rem; margin-bottom: 0.75rem; }
23
+ .state { padding: 0.4rem 0.8rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; display: inline-block; }
24
+ .state.inside { background: #22c55e20; color: #22c55e; }
25
+ .state.outside { background: #374151; color: #94a3b8; }
26
+ .btn { padding: 0.5rem 1rem; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.875rem; }
27
+ .btn-primary { background: #6366f1; color: white; }
28
+ .btn-primary:hover { background: #818cf8; }
29
+ .btn-danger { background: transparent; color: #ef4444; border: 1px solid #ef4444; }
30
+ .btn-danger:hover { background: #ef4444; color: white; }
31
+ .modal { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; align-items: center; justify-content: center; z-index: 100; }
32
+ .modal.active { display: flex; }
33
+ .modal-content { background: #12121a; border: 1px solid #1e293b; border-radius: 16px; padding: 2rem; width: 90%; max-width: 400px; }
34
+ .modal h2 { margin-bottom: 1.5rem; }
35
+ .form-group { margin-bottom: 1rem; }
36
+ .form-group label { display: block; margin-bottom: 0.5rem; color: #94a3b8; font-size: 0.875rem; }
37
+ .form-group input, .form-group select { width: 100%; padding: 0.75rem; background: #0a0a0f; border: 1px solid #1e293b; border-radius: 8px; color: #f8fafc; font-size: 1rem; }
38
+ .form-group input:focus, .form-group select:focus { outline: none; border-color: #6366f1; }
39
+ .btn-block { width: 100%; padding: 1rem; margin-top: 0.5rem; }
40
+ .toast { position: fixed; top: 20px; right: 20px; background: #12121a; border: 2px solid #22c55e; border-radius: 12px; padding: 1rem 1.5rem; z-index: 1000; animation: slideIn 0.3s; }
41
+ @keyframes slideIn { from { opacity: 0; transform: translateX(120%); } to { opacity: 1; transform: translateX(0); } }
42
+ .toast-title { font-weight: 700; margin-bottom: 0.25rem; display: flex; align-items: center; gap: 0.5rem; }
43
+ .toast-msg { font-size: 0.875rem; color: #94a3b8; }
44
+ .empty { text-align: center; padding: 3rem; color: #94a3b8; }
45
+ .section-title { font-size: 1.1rem; margin: 1.5rem 0 1rem; color: #94a3b8; }
46
+ .alert-item { background: #12121a; border: 1px solid #1e293b; border-radius: 8px; padding: 1rem; margin-bottom: 0.5rem; display: flex; gap: 1rem; align-items: center; }
47
+ .alert-item span:first-child { font-size: 1.25rem; }
48
+ .note { background: #1e293b; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.875rem; color: #94a3b8; }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <div id="toasts"></div>
53
+
54
+ <div class="container">
55
+ <header>
56
+ <h1>Price Alerts</h1>
57
+ <button class="btn btn-primary" onclick="showModal()">+ Add Alert</button>
58
+ </header>
59
+
60
+ <div id="debug" class="debug">Initializing...</div>
61
+
62
+ <div id="alertsContainer"></div>
63
+
64
+ <div class="section-title">📋 Alert History</div>
65
+ <div id="historyContainer"></div>
66
+ </div>
67
+
68
+ <div id="modal" class="modal" onclick="if(event.target===this)hideModal()">
69
+ <div class="modal-content">
70
+ <h2>Add Price Alert</h2>
71
+ <div class="form-group">
72
+ <label>Cryptocurrency</label>
73
+ <select id="assetSelect">
74
+ <option value="">Select coin...</option>
75
+ <option value="bitcoin">Bitcoin (BTC)</option>
76
+ <option value="ethereum">Ethereum (ETH)</option>
77
+ <option value="solana">Solana (SOL)</option>
78
+ <option value="ripple">XRP</option>
79
+ <option value="cardano">Cardano (ADA)</option>
80
+ <option value="dogecoin">Dogecoin (DOGE)</option>
81
+ <option value="polkadot">Polkadot (DOT)</option>
82
+ <option value="chainlink">Chainlink (LINK)</option>
83
+ <option value="avalanche-2">Avalanche (AVAX)</option>
84
+ <option value="litecoin">Litecoin (LTC)</option>
85
+ </select>
86
+ </div>
87
+ <div class="form-group">
88
+ <label>Min Price (USD)</label>
89
+ <input type="number" id="minPrice" step="any" placeholder="60000">
90
+ </div>
91
+ <div class="form-group">
92
+ <label>Max Price (USD)</label>
93
+ <input type="number" id="maxPrice" step="any" placeholder="62000">
94
+ </div>
95
+ <button class="btn btn-primary btn-block" onclick="addAlert()">Add Alert</button>
96
+ <button class="btn btn-danger btn-block" onclick="hideModal()">Cancel</button>
97
+ </div>
98
+ </div>
99
+
100
+ <script>
101
+ const COIN_ICONS = {
102
+ 'bitcoin': '₿', 'ethereum': 'Ξ', 'solana': '◎', 'ripple': '✕',
103
+ 'cardano': '₳', 'dogecoin': 'Ð', 'polkadot': '●', 'chainlink': '⬡',
104
+ 'avalanche-2': '▲', 'litecoin': 'Ł'
105
+ };
106
+
107
+ let alerts = JSON.parse(localStorage.getItem('pa_alerts') || '[]');
108
+ let history = JSON.parse(localStorage.getItem('pa_history') || '[]');
109
+ let prices = {};
110
+ let triggered = new Set();
111
+ const debug = document.getElementById('debug');
112
+
113
+ function log(msg) {
114
+ debug.textContent = new Date().toLocaleTimeString() + ' | ' + msg + '\n' + debug.textContent.slice(0, 300);
115
+ }
116
+
117
+ function save() {
118
+ localStorage.setItem('pa_alerts', JSON.stringify(alerts));
119
+ localStorage.setItem('pa_history', JSON.stringify(history.slice(0, 30)));
120
+ }
121
+
122
+ function showModal() {
123
+ document.getElementById('modal').classList.add('active');
124
+ }
125
+
126
+ function hideModal() {
127
+ document.getElementById('modal').classList.remove('active');
128
+ }
129
+
130
+ function addAlert() {
131
+ const coin = document.getElementById('assetSelect').value;
132
+ const min = parseFloat(document.getElementById('minPrice').value);
133
+ const max = parseFloat(document.getElementById('maxPrice').value);
134
+
135
+ if (!coin || !min || !max || min >= max) {
136
+ alert('Please fill all fields correctly.\nMin must be less than Max.');
137
+ return;
138
+ }
139
+
140
+ const currentPrice = prices[coin];
141
+ const inRange = currentPrice >= min && currentPrice <= max;
142
+
143
+ alerts = alerts.filter(a => a.coin !== coin);
144
+ alerts.push({ coin, min, max, lastInRange: false });
145
+
146
+ save();
147
+ render();
148
+ hideModal();
149
+
150
+ log('Added: ' + coin + ' | $' + min + ' - $' + max + (inRange ? ' (in range)' : ''));
151
+ }
152
+
153
+ function removeAlert(coin) {
154
+ alerts = alerts.filter(a => a.coin !== coin);
155
+ triggered.clear();
156
+ save();
157
+ render();
158
+ log('Removed: ' + coin);
159
+ }
160
+
161
+ function triggerAlert(coin, price, min, max) {
162
+ const key = coin + '-' + min + '-' + max;
163
+ if (triggered.has(key)) return;
164
+ triggered.add(key);
165
+
166
+ history.unshift({ coin, price, min, max, time: Date.now() });
167
+ save();
168
+ renderHistory();
169
+
170
+ showToast(coin, price, min, max);
171
+
172
+ if (Notification.permission === 'granted') {
173
+ new Notification(coin.charAt(0).toUpperCase() + coin.slice(1) + ' Alert!', {
174
+ body: 'Price $' + price.toLocaleString() + ' is in range ($' + min + ' - $' + max + ')',
175
+ icon: '🔔'
176
+ });
177
+ }
178
+
179
+ if ('vibrate' in navigator) navigator.vibrate([200, 100, 200]);
180
+
181
+ const card = document.getElementById('card-' + coin.replace(/[^a-z]/g, ''));
182
+ if (card) {
183
+ card.classList.add('flash');
184
+ setTimeout(() => card.classList.remove('flash'), 2000);
185
+ }
186
+ }
187
+
188
+ function showToast(coin, price, min, max) {
189
+ const div = document.createElement('div');
190
+ div.className = 'toast';
191
+ div.innerHTML = `
192
+ <div class="toast-title">🔔 ${coin.charAt(0).toUpperCase() + coin.slice(1)} Alert!</div>
193
+ <div class="toast-msg">$${price.toLocaleString()} in range ($${min.toLocaleString()} - $${max.toLocaleString()})</div>
194
+ `;
195
+ document.getElementById('toasts').appendChild(div);
196
+ setTimeout(() => div.remove(), 5000);
197
+ }
198
+
199
+ function render() {
200
+ const container = document.getElementById('alertsContainer');
201
+
202
+ if (alerts.length === 0) {
203
+ container.innerHTML = '<div class="empty">No alerts set. Click "+ Add Alert" to start.</div>';
204
+ return;
205
+ }
206
+
207
+ container.innerHTML = alerts.map(a => {
208
+ const price = prices[a.coin];
209
+ const inRange = price >= a.min && price <= a.max;
210
+ const icon = COIN_ICONS[a.coin] || '●';
211
+ const name = a.coin.charAt(0).toUpperCase() + a.coin.slice(1).replace(/-2/, '');
212
+
213
+ return `
214
+ <div class="card" id="card-${a.coin.replace(/[^a-z]/g, '')}">
215
+ <div class="card-header">
216
+ <span class="asset-name"><span class="asset-icon">${icon}</span>${name}</span>
217
+ <button class="btn btn-danger" onclick="removeAlert('${a.coin}')">Remove</button>
218
+ </div>
219
+ <div class="price">${price ? '$' + price.toLocaleString() : 'Loading...'}</div>
220
+ <div class="range">Target: $${a.min.toLocaleString()} - $${a.max.toLocaleString()}</div>
221
+ <span class="state ${inRange ? 'inside' : 'outside'}">${inRange ? '✓ In Range' : '○ Waiting'}</span>
222
+ </div>
223
+ `;
224
+ }).join('');
225
+ }
226
+
227
+ function renderHistory() {
228
+ const container = document.getElementById('historyContainer');
229
+ if (history.length === 0) {
230
+ container.innerHTML = '<div class="empty" style="padding:1rem">No alerts triggered yet</div>';
231
+ return;
232
+ }
233
+ container.innerHTML = history.map(h => {
234
+ const name = h.coin.charAt(0).toUpperCase() + h.coin.slice(1).replace(/-2/, '');
235
+ return `
236
+ <div class="alert-item">
237
+ <span>🔔</span>
238
+ <div>
239
+ <strong>${name}</strong> - $${h.price.toLocaleString()}
240
+ <div style="font-size:0.75rem;color:#64748b;margin-top:2px">
241
+ Range: $${h.min.toLocaleString()} - $${h.max.toLocaleString()} | ${new Date(h.time).toLocaleTimeString()}
242
+ </div>
243
+ </div>
244
+ </div>
245
+ `;
246
+ }).join('');
247
+ }
248
+
249
+ async function fetchPrices() {
250
+ if (alerts.length === 0) return;
251
+
252
+ const coins = alerts.map(a => a.coin).join(',');
253
+
254
+ try {
255
+ const url = `https://api.coingecko.com/api/v3/simple/price?ids=${coins}&vs_currencies=usd`;
256
+ log('Fetching: ' + url.slice(0, 60) + '...');
257
+
258
+ const res = await fetch(url);
259
+
260
+ if (!res.ok) {
261
+ log('API error: ' + res.status);
262
+ return;
263
+ }
264
+
265
+ const data = await res.json();
266
+
267
+ let updated = 0;
268
+ for (const coin of alerts) {
269
+ if (data[coin.coin]?.usd) {
270
+ prices[coin.coin] = data[coin.coin].usd;
271
+ updated++;
272
+ }
273
+ }
274
+
275
+ log('Updated ' + updated + ' prices');
276
+ } catch (e) {
277
+ log('Fetch error: ' + e.message);
278
+ }
279
+ }
280
+
281
+ function checkAlerts() {
282
+ alerts.forEach(a => {
283
+ const price = prices[a.coin];
284
+ if (!price) return;
285
+
286
+ const wasIn = a.lastInRange === true;
287
+ const isIn = price >= a.min && price <= a.max;
288
+
289
+ if (isIn && !wasIn) {
290
+ log('TRIGGER: ' + a.coin + ' at $' + price);
291
+ triggerAlert(a.coin, price, a.min, a.max);
292
+ }
293
+
294
+ a.lastInRange = isIn;
295
+ });
296
+ save();
297
+ render();
298
+ }
299
+
300
+ async function init() {
301
+ log('Starting...');
302
+ render();
303
+ renderHistory();
304
+
305
+ await fetchPrices();
306
+ checkAlerts();
307
+
308
+ // Poll every 10 seconds
309
+ setInterval(async () => {
310
+ await fetchPrices();
311
+ checkAlerts();
312
+ }, 10000);
313
+
314
+ // Request notification permission
315
+ if ('Notification' in window && Notification.permission === 'default') {
316
+ Notification.requestPermission();
317
+ }
318
+ }
319
+
320
+ init();
321
+ </script>
322
+ </body>
323
+ </html>
stocks-alerts.html ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Stock Price Alerts</title>
7
+ <style>
8
+ * { box-sizing: border-box; margin: 0; padding: 0; }
9
+ body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; background: #0f1419; color: #f8fafc; min-height: 100vh; padding: 1rem; }
10
+ .container { max-width: 800px; margin: 0 auto; }
11
+ header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; padding-bottom: 1rem; border-bottom: 1px solid #2a2a2a; }
12
+ h1 { font-size: 1.5rem; background: linear-gradient(135deg, #22c55e, #10b981); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
13
+ .debug { background: #1a1a1a; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-family: monospace; font-size: 0.75rem; white-space: pre-wrap; max-height: 80px; overflow-y: auto; color: #94a3b8; }
14
+ .card { background: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; transition: all 0.3s; }
15
+ .card:hover { border-color: #22c55e; }
16
+ .card.flash { animation: flash 0.5s ease 3; }
17
+ @keyframes flash { 0%,100% { border-color: #2a2a2a; box-shadow: none; } 50% { border-color: #f59e0b; box-shadow: 0 0 30px #f59e0b50; } }
18
+ .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
19
+ .asset-name { font-size: 1.25rem; font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
20
+ .asset-icon { font-size: 1.5rem; }
21
+ .price { font-size: 1.75rem; font-weight: 700; color: #22c55e; margin-bottom: 0.5rem; }
22
+ .change { font-size: 0.875rem; margin-bottom: 0.5rem; }
23
+ .change.up { color: #22c55e; }
24
+ .change.down { color: #ef4444; }
25
+ .range { color: #94a3b8; font-size: 0.875rem; margin-bottom: 0.75rem; }
26
+ .state { padding: 0.4rem 0.8rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; display: inline-block; }
27
+ .state.inside { background: #22c55e20; color: #22c55e; }
28
+ .state.outside { background: #374151; color: #94a3b8; }
29
+ .btn { padding: 0.5rem 1rem; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; font-size: 0.875rem; }
30
+ .btn-primary { background: #22c55e; color: #0f1419; }
31
+ .btn-primary:hover { background: #34d76a; }
32
+ .btn-danger { background: transparent; color: #ef4444; border: 1px solid #ef4444; }
33
+ .btn-danger:hover { background: #ef4444; color: white; }
34
+ .modal { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: none; align-items: center; justify-content: center; z-index: 100; }
35
+ .modal.active { display: flex; }
36
+ .modal-content { background: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 16px; padding: 2rem; width: 90%; max-width: 400px; }
37
+ .modal h2 { margin-bottom: 1.5rem; }
38
+ .form-group { margin-bottom: 1rem; }
39
+ .form-group label { display: block; margin-bottom: 0.5rem; color: #94a3b8; font-size: 0.875rem; }
40
+ .form-group input, .form-group select { width: 100%; padding: 0.75rem; background: #0f1419; border: 1px solid #2a2a2a; border-radius: 8px; color: #f8fafc; font-size: 1rem; }
41
+ .form-group input:focus, .form-group select:focus { outline: none; border-color: #22c55e; }
42
+ .btn-block { width: 100%; padding: 1rem; margin-top: 0.5rem; }
43
+ .toast { position: fixed; top: 20px; right: 20px; background: #1a1a1a; border: 2px solid #22c55e; border-radius: 12px; padding: 1rem 1.5rem; z-index: 1000; animation: slideIn 0.3s; }
44
+ @keyframes slideIn { from { opacity: 0; transform: translateX(120%); } to { opacity: 1; transform: translateX(0); } }
45
+ .toast-title { font-weight: 700; margin-bottom: 0.25rem; display: flex; align-items: center; gap: 0.5rem; }
46
+ .toast-msg { font-size: 0.875rem; color: #94a3b8; }
47
+ .empty { text-align: center; padding: 3rem; color: #94a3b8; }
48
+ .section-title { font-size: 1.1rem; margin: 1.5rem 0 1rem; color: #94a3b8; }
49
+ .alert-item { background: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 8px; padding: 1rem; margin-bottom: 0.5rem; display: flex; gap: 1rem; align-items: center; }
50
+ .status { display: flex; gap: 1rem; margin-bottom: 1rem; font-size: 0.875rem; color: #94a3b8; }
51
+ .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #22c55e; }
52
+ .note { background: #2a2a2a; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: 0.875rem; color: #94a3b8; }
53
+ </style>
54
+ </head>
55
+ <body>
56
+ <div id="toasts"></div>
57
+
58
+ <div class="container">
59
+ <header>
60
+ <h1>📈 Stock Alerts</h1>
61
+ <button class="btn btn-primary" onclick="showModal()">+ Add Alert</button>
62
+ </header>
63
+
64
+ <div class="note">Free tier: 25 requests/day. Get your free API key at <strong>alphavantage.co</strong></div>
65
+ <div class="status"><span class="status-dot"></span> Live prices from Alpha Vantage</div>
66
+ <div id="debug" class="debug">Initializing...</div>
67
+ <div id="alertsContainer"></div>
68
+
69
+ <div class="section-title">📋 Alert History</div>
70
+ <div id="historyContainer"></div>
71
+ </div>
72
+
73
+ <div id="modal" class="modal" onclick="if(event.target===this)hideModal()">
74
+ <div class="modal-content">
75
+ <h2>Add Stock Alert</h2>
76
+ <div class="form-group">
77
+ <label>Stock Symbol</label>
78
+ <select id="assetSelect">
79
+ <option value="">Select stock...</option>
80
+ <option value="AAPL">Apple (AAPL)</option>
81
+ <option value="GOOGL">Google (GOOGL)</option>
82
+ <option value="MSFT">Microsoft (MSFT)</option>
83
+ <option value="AMZN">Amazon (AMZN)</option>
84
+ <option value="TSLA">Tesla (TSLA)</option>
85
+ <option value="META">Meta (META)</option>
86
+ <option value="NVDA">NVIDIA (NVDA)</option>
87
+ <option value="JPM">JPMorgan (JPM)</option>
88
+ <option value="V">Visa (V)</option>
89
+ <option value="WMT">Walmart (WMT)</option>
90
+ </select>
91
+ </div>
92
+ <div class="form-group">
93
+ <label>Min Price (USD)</label>
94
+ <input type="number" id="minPrice" step="any" placeholder="150">
95
+ </div>
96
+ <div class="form-group">
97
+ <label>Max Price (USD)</label>
98
+ <input type="number" id="maxPrice" step="any" placeholder="160">
99
+ </div>
100
+ <button class="btn btn-primary btn-block" onclick="addAlert()">Add Alert</button>
101
+ <button class="btn btn-danger btn-block" onclick="hideModal()">Cancel</button>
102
+ </div>
103
+ </div>
104
+
105
+ <script>
106
+ const STOCK_ICONS = {
107
+ 'AAPL': '🍎', 'GOOGL': '🔍', 'MSFT': '🪟', 'AMZN': '📦', 'TSLA': '🚗',
108
+ 'META': '📘', 'NVDA': '🎮', 'JPM': '🏦', 'V': '💳', 'WMT': '🛒'
109
+ };
110
+
111
+ const API_KEY = 'demo';
112
+ const CORS_PROXY = 'https://api.allorigins.win/raw?url=';
113
+
114
+ let alerts = JSON.parse(localStorage.getItem('stock_alerts') || '[]');
115
+ let history = JSON.parse(localStorage.getItem('stock_history') || '[]');
116
+ let prices = {};
117
+ let prevClose = {};
118
+ let triggered = new Set();
119
+ let retryCount = 0;
120
+ const debug = document.getElementById('debug');
121
+
122
+ function log(msg) {
123
+ debug.textContent = new Date().toLocaleTimeString() + ' | ' + msg + '\n' + debug.textContent.slice(0, 300);
124
+ }
125
+
126
+ function save() {
127
+ localStorage.setItem('stock_alerts', JSON.stringify(alerts));
128
+ localStorage.setItem('stock_history', JSON.stringify(history.slice(0, 30)));
129
+ }
130
+
131
+ function showModal() {
132
+ document.getElementById('modal').classList.add('active');
133
+ }
134
+
135
+ function hideModal() {
136
+ document.getElementById('modal').classList.remove('active');
137
+ }
138
+
139
+ function addAlert() {
140
+ const symbol = document.getElementById('assetSelect').value;
141
+ const min = parseFloat(document.getElementById('minPrice').value);
142
+ const max = parseFloat(document.getElementById('maxPrice').value);
143
+
144
+ if (!symbol || !min || !max || min >= max) {
145
+ alert('Please fill all fields correctly.\nMin must be less than Max.');
146
+ return;
147
+ }
148
+
149
+ alerts = alerts.filter(a => a.symbol !== symbol);
150
+ alerts.push({ symbol, min, max, lastInRange: false });
151
+
152
+ save();
153
+ render();
154
+ hideModal();
155
+ log('Added: ' + symbol + ' | $' + min + ' - $' + max);
156
+ }
157
+
158
+ function removeAlert(symbol) {
159
+ alerts = alerts.filter(a => a.symbol !== symbol);
160
+ triggered.clear();
161
+ save();
162
+ render();
163
+ log('Removed: ' + symbol);
164
+ }
165
+
166
+ function triggerAlert(symbol, price, min, max) {
167
+ const key = symbol + '-' + min + '-' + max;
168
+ if (triggered.has(key)) return;
169
+ triggered.add(key);
170
+
171
+ history.unshift({ symbol, price, min, max, time: Date.now() });
172
+ save();
173
+ renderHistory();
174
+
175
+ showToast(symbol, price, min, max);
176
+
177
+ if (Notification.permission === 'granted') {
178
+ new Notification(symbol + ' Alert!', {
179
+ body: 'Price $' + price.toLocaleString() + ' is in range ($' + min + ' - $' + max + ')',
180
+ });
181
+ }
182
+
183
+ if ('vibrate' in navigator) navigator.vibrate([200, 100, 200]);
184
+
185
+ const card = document.getElementById('card-' + symbol);
186
+ if (card) {
187
+ card.classList.add('flash');
188
+ setTimeout(() => card.classList.remove('flash'), 2000);
189
+ }
190
+ }
191
+
192
+ function showToast(symbol, price, min, max) {
193
+ const div = document.createElement('div');
194
+ div.className = 'toast';
195
+ div.innerHTML = `
196
+ <div class="toast-title">🔔 ${symbol} Alert!</div>
197
+ <div class="toast-msg">$${price.toLocaleString()} in range ($${min.toLocaleString()} - $${max.toLocaleString()})</div>
198
+ `;
199
+ document.getElementById('toasts').appendChild(div);
200
+ setTimeout(() => div.remove(), 5000);
201
+ }
202
+
203
+ function render() {
204
+ const container = document.getElementById('alertsContainer');
205
+
206
+ if (alerts.length === 0) {
207
+ container.innerHTML = '<div class="empty">No alerts set. Click "+ Add Alert" to start.</div>';
208
+ return;
209
+ }
210
+
211
+ container.innerHTML = alerts.map(a => {
212
+ const price = prices[a.symbol];
213
+ const prev = prevClose[a.symbol];
214
+ const inRange = price >= a.min && price <= a.max;
215
+ const icon = STOCK_ICONS[a.symbol] || '📊';
216
+ const change = prev ? ((price - prev) / prev * 100).toFixed(2) : null;
217
+
218
+ return `
219
+ <div class="card" id="card-${a.symbol}">
220
+ <div class="card-header">
221
+ <span class="asset-name"><span class="asset-icon">${icon}</span>${a.symbol}</span>
222
+ <button class="btn btn-danger" onclick="removeAlert('${a.symbol}')">Remove</button>
223
+ </div>
224
+ <div class="price">${price ? '$' + price.toLocaleString() : 'Loading...'}</div>
225
+ ${change !== null ? `<div class="change ${change >= 0 ? 'up' : 'down'}">${change >= 0 ? '▲' : '▼'} ${Math.abs(change)}%</div>` : ''}
226
+ <div class="range">Target: $${a.min.toLocaleString()} - $${a.max.toLocaleString()}</div>
227
+ <span class="state ${inRange ? 'inside' : 'outside'}">${inRange ? '✓ In Range' : '○ Waiting'}</span>
228
+ </div>
229
+ `;
230
+ }).join('');
231
+ }
232
+
233
+ function renderHistory() {
234
+ const container = document.getElementById('historyContainer');
235
+ if (history.length === 0) {
236
+ container.innerHTML = '<div class="empty" style="padding:1rem">No alerts triggered yet</div>';
237
+ return;
238
+ }
239
+ container.innerHTML = history.map(h => `
240
+ <div class="alert-item">
241
+ <span>🔔</span>
242
+ <div>
243
+ <strong>${h.symbol}</strong> - $${h.price.toLocaleString()}
244
+ <div style="font-size:0.75rem;color:#64748b;margin-top:2px">
245
+ Range: $${h.min.toLocaleString()} - $${h.max.toLocaleString()} | ${new Date(h.time).toLocaleTimeString()}
246
+ </div>
247
+ </div>
248
+ </div>
249
+ `).join('');
250
+ }
251
+
252
+ async function fetchPrices() {
253
+ if (alerts.length === 0) return;
254
+
255
+ for (const alert of alerts) {
256
+ try {
257
+ const url = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${alert.symbol}&apikey=${API_KEY}`;
258
+ log('Fetching ' + alert.symbol + '...');
259
+
260
+ const res = await fetch(CORS_PROXY + encodeURIComponent(url));
261
+
262
+ if (!res.ok) {
263
+ log('API error: ' + res.status);
264
+ continue;
265
+ }
266
+
267
+ const data = await res.json();
268
+
269
+ if (data['Global Quote'] && data['Global Quote']['05. price']) {
270
+ const price = parseFloat(data['Global Quote']['05. price']);
271
+ if (!prevClose[alert.symbol]) {
272
+ prevClose[alert.symbol] = parseFloat(data['Global Quote']['08. previous close']) || price;
273
+ }
274
+ prices[alert.symbol] = price;
275
+ log(alert.symbol + ': $' + price);
276
+ }
277
+ } catch (e) {
278
+ log('Error: ' + alert.symbol + ' - ' + e.message);
279
+ }
280
+
281
+ await new Promise(r => setTimeout(r, 1000));
282
+ }
283
+
284
+ log('Price update complete');
285
+ }
286
+
287
+ function checkAlerts() {
288
+ alerts.forEach(a => {
289
+ const price = prices[a.symbol];
290
+ if (!price) return;
291
+
292
+ const wasIn = a.lastInRange === true;
293
+ const isIn = price >= a.min && price <= a.max;
294
+
295
+ if (isIn && !wasIn) {
296
+ log('TRIGGER: ' + a.symbol + ' at $' + price);
297
+ triggerAlert(a.symbol, price, a.min, a.max);
298
+ }
299
+
300
+ a.lastInRange = isIn;
301
+ });
302
+ save();
303
+ render();
304
+ }
305
+
306
+ async function init() {
307
+ log('Starting Stock Alerts...');
308
+ render();
309
+ renderHistory();
310
+
311
+ await fetchPrices();
312
+ checkAlerts();
313
+
314
+ setInterval(async () => {
315
+ await fetchPrices();
316
+ checkAlerts();
317
+ }, 60000);
318
+
319
+ if ('Notification' in window && Notification.permission === 'default') {
320
+ Notification.requestPermission();
321
+ }
322
+ }
323
+
324
+ init();
325
+ </script>
326
+ </body>
327
+ </html>
telegram_bot.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ telegram_bot.py — Telegram integration for notifications and user commands.
3
+
4
+ Sends formatted alert messages and handles interactive commands:
5
+ /add <ASSET> <MIN> <MAX> — set a price range alert
6
+ /remove <ASSET> — stop tracking an asset
7
+ /list — show all tracked assets
8
+ /price <ASSET> — get last known price for an asset
9
+ /alerts — show last 10 triggered alerts
10
+ /pause — silence all alert notifications
11
+ /resume — re-enable alert notifications
12
+ /status — bot health check
13
+ /help — this message
14
+ """
15
+
16
+ import asyncio
17
+ from datetime import datetime, timezone
18
+
19
+ from telegram import Update
20
+ from telegram.constants import ParseMode
21
+ from telegram.ext import (
22
+ Application,
23
+ CommandHandler,
24
+ ContextTypes,
25
+ )
26
+
27
+ import config
28
+ from alert_engine import AlertEngine, AlertEvent
29
+ from logger import get_logger
30
+
31
+ log = get_logger("telegram_bot")
32
+
33
+ # Rate-limit: minimum seconds between Telegram messages
34
+ _MIN_SEND_INTERVAL = 1.0
35
+ _last_send_time: float = 0.0
36
+
37
+ # ── Markdown V2 escape helper ─────────────────────────────────────────────────
38
+ _MD2_SPECIAL = r"\_*[]()~`>#+-=|{}.!"
39
+
40
+ def _esc(text: str) -> str:
41
+ """Escape special characters for Telegram MarkdownV2."""
42
+ for ch in _MD2_SPECIAL:
43
+ text = text.replace(ch, f"\\{ch}")
44
+ return text
45
+
46
+
47
+ class TelegramBot:
48
+ """Wraps python-telegram-bot to provide both commands and alert sending."""
49
+
50
+ def __init__(self, alert_engine: AlertEngine, dry_run: bool = False) -> None:
51
+ self.engine = alert_engine
52
+ self.dry_run = dry_run
53
+ self._app: Application | None = None
54
+ self._start_time = datetime.now(timezone.utc)
55
+
56
+ # ── Initialise the bot application ───────────────────────────────────
57
+
58
+ def build_app(self) -> Application:
59
+ """Create and configure the Telegram Application."""
60
+ if not config.TELEGRAM_BOT_TOKEN:
61
+ raise ValueError(
62
+ "TELEGRAM_BOT_TOKEN is not set. "
63
+ "Add it to your .env file (see .env.example)."
64
+ )
65
+
66
+ builder = Application.builder().token(config.TELEGRAM_BOT_TOKEN)
67
+ self._app = builder.build()
68
+
69
+ # Register command handlers
70
+ self._app.add_handler(CommandHandler("start", self._cmd_help))
71
+ self._app.add_handler(CommandHandler("help", self._cmd_help))
72
+ self._app.add_handler(CommandHandler("add", self._cmd_add))
73
+ self._app.add_handler(CommandHandler("remove", self._cmd_remove))
74
+ self._app.add_handler(CommandHandler("list", self._cmd_list))
75
+ self._app.add_handler(CommandHandler("price", self._cmd_price))
76
+ self._app.add_handler(CommandHandler("alerts", self._cmd_alerts))
77
+ self._app.add_handler(CommandHandler("pause", self._cmd_pause))
78
+ self._app.add_handler(CommandHandler("resume", self._cmd_resume))
79
+ self._app.add_handler(CommandHandler("status", self._cmd_status))
80
+
81
+ return self._app
82
+
83
+ # ── Send alert notification ──────────────────────────────────────────
84
+
85
+ async def send_alert(self, event: AlertEvent) -> None:
86
+ """Send a price-alert message to the configured Telegram chat."""
87
+ asset = _esc(event.asset_name)
88
+ price = _esc(f"${event.price:,.4f}")
89
+ rng = _esc(f"${event.min_price:,.4f} – ${event.max_price:,.4f}")
90
+ ts = _esc(event.timestamp.strftime("%Y-%m-%d %H:%M:%S"))
91
+
92
+ text = (
93
+ f"🔔 *Price Alert — {asset}*\n"
94
+ f"━━━━━━━━━━━━━━━━━━━━━━━\n"
95
+ f"💰 *Current Price:* `{price}`\n"
96
+ f"📊 *Target Range:* `{rng}`\n"
97
+ f"🕐 *Time \\(UTC\\):* `{ts}`\n"
98
+ f"━━━━━━━━━━━━━━━━━━━━━━━\n"
99
+ f"_Price has entered your defined range\\!_"
100
+ )
101
+
102
+ if self.dry_run:
103
+ log.info("[DRY-RUN] Would send alert:\n%s", text)
104
+ return
105
+
106
+ await self._send_message(text)
107
+
108
+ async def _send_message(self, text: str, chat_id: str | None = None) -> None:
109
+ """Send a MarkdownV2 message with simple rate-limiting."""
110
+ global _last_send_time
111
+
112
+ target_chat = chat_id or config.TELEGRAM_CHAT_ID
113
+ if not target_chat:
114
+ log.warning("No TELEGRAM_CHAT_ID configured, skipping message send")
115
+ return
116
+
117
+ # Simple rate limiting using running loop time
118
+ loop = asyncio.get_running_loop()
119
+ now = loop.time()
120
+ elapsed = now - _last_send_time
121
+ if elapsed < _MIN_SEND_INTERVAL:
122
+ await asyncio.sleep(_MIN_SEND_INTERVAL - elapsed)
123
+
124
+ try:
125
+ if self._app and self._app.bot:
126
+ await self._app.bot.send_message(
127
+ chat_id=target_chat,
128
+ text=text,
129
+ parse_mode=ParseMode.MARKDOWN_V2,
130
+ )
131
+ _last_send_time = asyncio.get_running_loop().time()
132
+ log.debug("Telegram message sent to chat %s", target_chat)
133
+ except Exception as exc:
134
+ log.error("Failed to send Telegram message: %s", exc)
135
+
136
+ # ── Command handlers ─────────────────────────────────────────────────
137
+
138
+ async def _cmd_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
139
+ """Handle /help and /start."""
140
+ commodities = sorted(k for k in config.YFINANCE_TICKERS if k in ("GOLD","SILVER","CRUDE_OIL"))
141
+ stocks = sorted(k for k in config.YFINANCE_TICKERS if k not in commodities)
142
+ crypto = sorted(config.BINANCE_SYMBOLS.keys())
143
+
144
+ text = (
145
+ "📈 *Multi\\-Asset Price Alert Bot*\n\n"
146
+ "*Commands:*\n"
147
+ "`/add <ASSET> <MIN> <MAX>` — Track an asset\n"
148
+ "`/remove <ASSET>` — Stop tracking\n"
149
+ "`/list` — Show all tracked assets\n"
150
+ "`/price <ASSET>` — Get current price\n"
151
+ "`/alerts` — Last 10 triggered alerts\n"
152
+ "`/pause` — Mute all notifications\n"
153
+ "`/resume` — Unmute notifications\n"
154
+ "`/status` — Bot health check\n"
155
+ "`/help` — This message\n\n"
156
+ f"*📦 Commodities:* `{', '.join(commodities)}`\n"
157
+ f"*₿ Crypto:* `{', '.join(crypto)}`\n"
158
+ f"*📊 Stocks/Indices:* `{', '.join(stocks)}`\n\n"
159
+ "_Example:_ `/add BTC 80000 90000`"
160
+ )
161
+ await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
162
+
163
+ async def _cmd_add(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
164
+ """Handle /add <ASSET> <MIN> <MAX>."""
165
+ args = context.args
166
+ if not args or len(args) != 3:
167
+ await update.message.reply_text(
168
+ "⚠️ Usage: `/add <ASSET> <MIN_PRICE> <MAX_PRICE>`\n"
169
+ "Example: `/add BTC 80000 90000`",
170
+ parse_mode=ParseMode.MARKDOWN_V2,
171
+ )
172
+ return
173
+
174
+ asset_name = args[0].upper()
175
+ try:
176
+ min_price = float(args[1])
177
+ max_price = float(args[2])
178
+ except ValueError:
179
+ await update.message.reply_text("⚠️ MIN and MAX must be numbers\\.")
180
+ return
181
+
182
+ if min_price >= max_price:
183
+ await update.message.reply_text("⚠️ MIN must be less than MAX\\.", parse_mode=ParseMode.MARKDOWN_V2)
184
+ return
185
+
186
+ if asset_name not in config.ALL_ASSETS:
187
+ supported = _esc(", ".join(sorted(config.ALL_ASSETS)))
188
+ await update.message.reply_text(
189
+ f"⚠️ Unknown asset `{_esc(asset_name)}`\\.\n\nSupported: `{supported}`",
190
+ parse_mode=ParseMode.MARKDOWN_V2,
191
+ )
192
+ return
193
+
194
+ self.engine.add_asset(asset_name, min_price, max_price)
195
+ min_str = _esc(f"${min_price:,.4f}")
196
+ max_str = _esc(f"${max_price:,.4f}")
197
+ await update.message.reply_text(
198
+ f"✅ Tracking *{_esc(asset_name)}*\n"
199
+ f"Range: `{min_str}` \u2013 `{max_str}`",
200
+ parse_mode=ParseMode.MARKDOWN_V2,
201
+ )
202
+
203
+ async def _cmd_remove(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
204
+ """Handle /remove <ASSET>."""
205
+ args = context.args
206
+ if not args or len(args) != 1:
207
+ await update.message.reply_text("⚠️ Usage: `/remove <ASSET>`", parse_mode=ParseMode.MARKDOWN_V2)
208
+ return
209
+
210
+ asset_name = args[0].upper()
211
+ if self.engine.remove_asset(asset_name):
212
+ await update.message.reply_text(
213
+ f"🗑️ Stopped tracking *{_esc(asset_name)}*\\.",
214
+ parse_mode=ParseMode.MARKDOWN_V2,
215
+ )
216
+ else:
217
+ await update.message.reply_text(
218
+ f"⚠️ `{_esc(asset_name)}` is not being tracked\\.",
219
+ parse_mode=ParseMode.MARKDOWN_V2,
220
+ )
221
+
222
+ async def _cmd_list(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
223
+ """Handle /list — show all tracked assets."""
224
+ details = self.engine.get_asset_details()
225
+ if not details:
226
+ await update.message.reply_text(
227
+ "📭 No assets tracked\\. Use `/add` to start\\.",
228
+ parse_mode=ParseMode.MARKDOWN_V2,
229
+ )
230
+ return
231
+
232
+ lines = ["📋 *Tracked Assets:*\n"]
233
+ for d in sorted(details, key=lambda x: x["name"]):
234
+ state_emoji = "🟢" if d["state"] == "INSIDE" else "⚪"
235
+ pause_tag = " ⏸" if d.get("paused") else ""
236
+ price_str = _esc(f"${d['last_price']:,.4f}") if d["last_price"] else "N/A"
237
+ rng_min = _esc(f"${d['min']:,.4f}")
238
+ rng_max = _esc(f"${d['max']:,.4f}")
239
+ lines.append(
240
+ f"{state_emoji} *{_esc(d['name'])}*{_esc(pause_tag)}\n"
241
+ f" Range: `{rng_min}` \u2013 `{rng_max}`\n"
242
+ f" Last: `{price_str}` \\| State: `{_esc(d['state'])}`"
243
+ )
244
+
245
+ await update.message.reply_text("\n".join(lines), parse_mode=ParseMode.MARKDOWN_V2)
246
+
247
+ async def _cmd_price(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
248
+ """Handle /price <ASSET> — show last known price."""
249
+ args = context.args
250
+ if not args or len(args) != 1:
251
+ await update.message.reply_text(
252
+ "⚠️ Usage: `/price <ASSET>`\nExample: `/price BTC`",
253
+ parse_mode=ParseMode.MARKDOWN_V2,
254
+ )
255
+ return
256
+
257
+ asset_name = args[0].upper()
258
+ price = self.engine.get_asset_price(asset_name)
259
+
260
+ if price is None:
261
+ await update.message.reply_text(
262
+ f"❓ No price data for `{_esc(asset_name)}` yet\\.\n"
263
+ "_Make sure it's tracked with_ `/add`\\.",
264
+ parse_mode=ParseMode.MARKDOWN_V2,
265
+ )
266
+ else:
267
+ await update.message.reply_text(
268
+ f"💰 *{_esc(asset_name)}* latest price: `{_esc(f'${price:,.4f}')}`",
269
+ parse_mode=ParseMode.MARKDOWN_V2,
270
+ )
271
+
272
+ async def _cmd_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
273
+ """Handle /alerts — show last 10 triggered alerts."""
274
+ history = self.engine.get_alert_history(limit=10)
275
+ if not history:
276
+ await update.message.reply_text(
277
+ "📭 No alerts have been triggered yet\\.",
278
+ parse_mode=ParseMode.MARKDOWN_V2,
279
+ )
280
+ return
281
+
282
+ lines = ["🔔 *Recent Alerts \\(newest first\\):*\n"]
283
+ for event in history:
284
+ ts = _esc(event.timestamp.strftime("%m/%d %H:%M UTC"))
285
+ name = _esc(event.asset_name)
286
+ px = _esc(f"${event.price:,.4f}")
287
+ lines.append(f"• *{name}* — `{px}` at {ts}")
288
+
289
+ await update.message.reply_text("\n".join(lines), parse_mode=ParseMode.MARKDOWN_V2)
290
+
291
+ async def _cmd_pause(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
292
+ """Handle /pause — silence all alert notifications."""
293
+ self.engine.pause_all()
294
+ await update.message.reply_text(
295
+ "⏸️ *Alerts paused\\.* You won't receive notifications until you send `/resume`\\.",
296
+ parse_mode=ParseMode.MARKDOWN_V2,
297
+ )
298
+
299
+ async def _cmd_resume(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
300
+ """Handle /resume — re-enable alert notifications."""
301
+ self.engine.resume_all()
302
+ await update.message.reply_text(
303
+ "▶️ *Alerts resumed\\.* You will now receive notifications again\\.",
304
+ parse_mode=ParseMode.MARKDOWN_V2,
305
+ )
306
+
307
+ async def _cmd_status(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
308
+ """Handle /status — bot health check."""
309
+ now = datetime.now(timezone.utc)
310
+ uptime = now - self._start_time
311
+ hours, remainder = divmod(int(uptime.total_seconds()), 3600)
312
+ minutes, seconds = divmod(remainder, 60)
313
+
314
+ tracked = self.engine.get_tracked_assets()
315
+ crypto_cnt = sum(1 for n in tracked if n in config.BINANCE_SYMBOLS)
316
+ stock_cnt = len(tracked) - crypto_cnt
317
+ paused_flag = "⏸️ YES" if self.engine.is_paused() else "▶️ NO"
318
+ alert_cnt = len(self.engine.get_alert_history(limit=config.ALERT_HISTORY_MAX))
319
+
320
+ text = (
321
+ "🤖 *Bot Status*\n"
322
+ f"━━━━━━━━━━━━━━━━━━━━━━━\n"
323
+ f"⏱️ Uptime: `{_esc(f'{hours}h {minutes}m {seconds}s')}`\n"
324
+ f"📊 Tracking: `{len(tracked)}` assets "
325
+ f"\\(`{crypto_cnt}` crypto, `{stock_cnt}` stocks/commodities\\)\n"
326
+ f"🔔 Alerts fired: `{alert_cnt}`\n"
327
+ f"⏸️ Paused: {_esc(paused_flag)}\n"
328
+ f"🔄 Stock poll: `{config.STOCK_POLL_INTERVAL}s`\n"
329
+ f"⏳ Cooldown: `{config.ALERT_COOLDOWN_SECONDS}s`\n"
330
+ f"📡 Crypto: WebSocket streaming\n"
331
+ f"━━━━━━━━━━━━━━━━━━━━━━━"
332
+ )
333
+ await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
tests/test_alert_engine.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ tests/test_alert_engine.py — Unit tests for the alert engine state machine.
3
+
4
+ Run with:
5
+ python -m pytest tests/test_alert_engine.py -v
6
+ """
7
+
8
+ import sys
9
+ import os
10
+ from datetime import datetime, timezone, timedelta
11
+ from unittest.mock import patch
12
+
13
+ # Add project root to path
14
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15
+
16
+ from alert_engine import AlertEngine, AlertEvent, RangeState
17
+ import config
18
+
19
+
20
+ class TestAlertEngine:
21
+ """Tests for AlertEngine state transitions and dedup logic."""
22
+
23
+ def setup_method(self):
24
+ """Fresh engine + captured alerts for each test.
25
+
26
+ Cooldown is patched to 0 for most tests so re-entry is always allowed.
27
+ Use TestAlertEngineCooldown for cooldown-specific tests.
28
+ """
29
+ self.alerts: list[AlertEvent] = []
30
+ self.engine = AlertEngine(on_alert=lambda e: self.alerts.append(e))
31
+
32
+ # ── Basic state transitions ──────────────────────────────────────────
33
+
34
+ def test_outside_to_inside_triggers_alert(self):
35
+ """Price entering the range should fire exactly one alert."""
36
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
37
+ self.engine.add_asset("BTC", 80000, 90000)
38
+ self.engine.on_price_update("BTC", 85000) # enters range
39
+
40
+ assert len(self.alerts) == 1
41
+ assert self.alerts[0].asset_name == "BTC"
42
+ assert self.alerts[0].price == 85000
43
+
44
+ def test_inside_to_inside_no_duplicate(self):
45
+ """Price staying inside range should NOT fire additional alerts."""
46
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
47
+ self.engine.add_asset("BTC", 80000, 90000)
48
+ self.engine.on_price_update("BTC", 85000) # enter → alert
49
+ self.engine.on_price_update("BTC", 86000) # still inside → no alert
50
+ self.engine.on_price_update("BTC", 89999) # still inside → no alert
51
+
52
+ assert len(self.alerts) == 1
53
+
54
+ def test_inside_to_outside_resets(self):
55
+ """Price exiting range should reset state so re-entry triggers again."""
56
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
57
+ self.engine.add_asset("BTC", 80000, 90000)
58
+ self.engine.on_price_update("BTC", 85000) # enter → alert
59
+ self.engine.on_price_update("BTC", 95000) # exit → reset
60
+ self.engine.on_price_update("BTC", 82000) # re-enter → alert again
61
+
62
+ assert len(self.alerts) == 2
63
+
64
+ def test_outside_to_outside_no_alert(self):
65
+ """Price staying outside should produce no alerts."""
66
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
67
+ self.engine.add_asset("BTC", 80000, 90000)
68
+ self.engine.on_price_update("BTC", 50000)
69
+ self.engine.on_price_update("BTC", 55000)
70
+ self.engine.on_price_update("BTC", 95000)
71
+
72
+ assert len(self.alerts) == 0
73
+
74
+ # ── Boundary conditions ──────────────────────────────────────────────
75
+
76
+ def test_price_at_min_boundary_is_inside(self):
77
+ """Price exactly at min_price should be considered inside."""
78
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
79
+ self.engine.add_asset("ETH", 1700, 2200)
80
+ self.engine.on_price_update("ETH", 1700)
81
+
82
+ assert len(self.alerts) == 1
83
+
84
+ def test_price_at_max_boundary_is_inside(self):
85
+ """Price exactly at max_price should be considered inside."""
86
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
87
+ self.engine.add_asset("ETH", 1700, 2200)
88
+ self.engine.on_price_update("ETH", 2200)
89
+
90
+ assert len(self.alerts) == 1
91
+
92
+ def test_price_just_below_min_is_outside(self):
93
+ """Price just below min should not trigger."""
94
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
95
+ self.engine.add_asset("ETH", 1700, 2200)
96
+ self.engine.on_price_update("ETH", 1699.99)
97
+
98
+ assert len(self.alerts) == 0
99
+
100
+ def test_price_just_above_max_is_outside(self):
101
+ """Price just above max should not trigger."""
102
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
103
+ self.engine.add_asset("ETH", 1700, 2200)
104
+ self.engine.on_price_update("ETH", 2200.01)
105
+
106
+ assert len(self.alerts) == 0
107
+
108
+ # ── Asset management ─────────────────────────────────────────────────
109
+
110
+ def test_add_asset(self):
111
+ self.engine.add_asset("GOLD", 2900, 3200)
112
+ tracked = self.engine.get_tracked_assets()
113
+ assert "GOLD" in tracked
114
+ assert tracked["GOLD"] == (2900, 3200)
115
+
116
+ def test_remove_asset(self):
117
+ self.engine.add_asset("GOLD", 2900, 3200)
118
+ assert self.engine.remove_asset("GOLD") is True
119
+ assert self.engine.remove_asset("GOLD") is False # already removed
120
+ assert "GOLD" not in self.engine.get_tracked_assets()
121
+
122
+ def test_update_range_resets_state(self):
123
+ """Updating an asset's range should reset state to OUTSIDE."""
124
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
125
+ self.engine.add_asset("BTC", 80000, 90000)
126
+ self.engine.on_price_update("BTC", 85000) # inside → INSIDE state
127
+ assert len(self.alerts) == 1
128
+
129
+ # Update range — state resets to OUTSIDE
130
+ self.engine.add_asset("BTC", 80000, 88000)
131
+ self.engine.on_price_update("BTC", 85000) # re-enters → alert again
132
+ assert len(self.alerts) == 2
133
+
134
+ def test_untracked_asset_ignored(self):
135
+ """Price update for an untracked asset should be silently ignored."""
136
+ self.engine.on_price_update("UNKNOWN", 100)
137
+ assert len(self.alerts) == 0
138
+
139
+ def test_case_insensitive_names(self):
140
+ """Asset names should be case-insensitive."""
141
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
142
+ self.engine.add_asset("btc", 80000, 90000)
143
+ self.engine.on_price_update("Btc", 85000)
144
+
145
+ assert len(self.alerts) == 1
146
+ assert self.alerts[0].asset_name == "BTC"
147
+
148
+ # ── Multiple assets ──────────────────────────────────────────────────
149
+
150
+ def test_multiple_assets_independent(self):
151
+ """Alerts for different assets should be independent."""
152
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
153
+ self.engine.add_asset("BTC", 80000, 90000)
154
+ self.engine.add_asset("ETH", 1700, 2200)
155
+
156
+ self.engine.on_price_update("BTC", 85000) # BTC enters
157
+ self.engine.on_price_update("ETH", 1500) # ETH outside
158
+ self.engine.on_price_update("ETH", 2000) # ETH enters
159
+
160
+ assert len(self.alerts) == 2
161
+ assert self.alerts[0].asset_name == "BTC"
162
+ assert self.alerts[1].asset_name == "ETH"
163
+
164
+ def test_get_asset_details(self):
165
+ """get_asset_details should return comprehensive info."""
166
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
167
+ self.engine.add_asset("BTC", 80000, 90000)
168
+ self.engine.on_price_update("BTC", 85000)
169
+
170
+ details = self.engine.get_asset_details()
171
+ assert len(details) == 1
172
+ d = details[0]
173
+ assert d["name"] == "BTC"
174
+ assert d["state"] == "INSIDE"
175
+ assert d["last_price"] == 85000
176
+ assert d["last_alert"] is not None
177
+
178
+ # ── Alert history ────────────────────────────────────────────────────
179
+
180
+ def test_alert_stored_in_history(self):
181
+ """Triggered alerts should appear in get_alert_history()."""
182
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
183
+ self.engine.add_asset("BTC", 80000, 90000)
184
+ self.engine.on_price_update("BTC", 85000)
185
+
186
+ history = self.engine.get_alert_history(limit=10)
187
+ assert len(history) == 1
188
+ assert history[0].asset_name == "BTC"
189
+
190
+ def test_history_newest_first(self):
191
+ """get_alert_history should return newest events first."""
192
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
193
+ self.engine.add_asset("BTC", 80000, 90000)
194
+ self.engine.add_asset("ETH", 1700, 2200)
195
+ self.engine.on_price_update("BTC", 85000)
196
+ self.engine.on_price_update("ETH", 2000)
197
+
198
+ history = self.engine.get_alert_history(limit=10)
199
+ assert history[0].asset_name == "ETH"
200
+ assert history[1].asset_name == "BTC"
201
+
202
+ # ── Pause / Resume ───────────────────────────────────────────────────
203
+
204
+ def test_pause_suppresses_alerts(self):
205
+ """Paused engine should not fire alert callbacks."""
206
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
207
+ self.engine.add_asset("BTC", 80000, 90000)
208
+ self.engine.pause_all()
209
+ self.engine.on_price_update("BTC", 85000)
210
+
211
+ assert len(self.alerts) == 0
212
+
213
+ def test_resume_re_enables_alerts(self):
214
+ """Resuming after pause should allow alerts to fire again."""
215
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
216
+ self.engine.add_asset("BTC", 80000, 90000)
217
+ self.engine.pause_all()
218
+ self.engine.on_price_update("BTC", 85000) # paused → no alert, state=INSIDE
219
+ self.engine.on_price_update("BTC", 95000) # exits → OUTSIDE
220
+ self.engine.resume_all()
221
+ self.engine.on_price_update("BTC", 85000) # re-enters → alert fires
222
+
223
+ assert len(self.alerts) == 1
224
+
225
+
226
+ class TestAlertEngineCooldown:
227
+ """Tests specifically for the cooldown behaviour."""
228
+
229
+ def setup_method(self):
230
+ self.alerts: list[AlertEvent] = []
231
+ self.engine = AlertEngine(on_alert=lambda e: self.alerts.append(e))
232
+
233
+ def test_cooldown_blocks_rapid_reentry(self):
234
+ """Re-entry within cooldown period should NOT fire another alert."""
235
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 300):
236
+ self.engine.add_asset("BTC", 80000, 90000)
237
+ self.engine.on_price_update("BTC", 85000) # alert fires
238
+ self.engine.on_price_update("BTC", 95000) # exits
239
+ self.engine.on_price_update("BTC", 85000) # re-enters — blocked by cooldown
240
+
241
+ assert len(self.alerts) == 1
242
+
243
+ def test_cooldown_zero_allows_immediate_reentry(self):
244
+ """With cooldown=0, re-entry should always fire."""
245
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 0):
246
+ self.engine.add_asset("BTC", 80000, 90000)
247
+ self.engine.on_price_update("BTC", 85000) # alert
248
+ self.engine.on_price_update("BTC", 95000) # exit
249
+ self.engine.on_price_update("BTC", 85000) # re-enter → alert
250
+
251
+ assert len(self.alerts) == 2
252
+
253
+ def test_cooldown_expired_allows_reentry(self):
254
+ """After cooldown expires, re-entry should fire again."""
255
+ with patch.object(config, "ALERT_COOLDOWN_SECONDS", 300):
256
+ self.engine.add_asset("BTC", 80000, 90000)
257
+ self.engine.on_price_update("BTC", 85000) # alert fires
258
+ # Manually backdate the last_alert_time past cooldown
259
+ asset = self.engine._assets["BTC"]
260
+ asset.last_alert_time = datetime.now(timezone.utc) - timedelta(seconds=301)
261
+ self.engine.on_price_update("BTC", 95000) # exits
262
+ self.engine.on_price_update("BTC", 85000) # re-enters after cooldown
263
+
264
+ assert len(self.alerts) == 2
web-app/next.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ /** @type {import('next').NextConfig} */
2
+ const nextConfig = {
3
+ reactStrictMode: true,
4
+ }
5
+
6
+ module.exports = nextConfig
web-app/package.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "price-alert-web",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "scripts": {
6
+ "dev": "next dev",
7
+ "build": "next build",
8
+ "start": "next start",
9
+ "lint": "next lint"
10
+ },
11
+ "dependencies": {
12
+ "next": "14.1.0",
13
+ "react": "^18.2.0",
14
+ "react-dom": "^18.2.0"
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^20",
18
+ "@types/react": "^18",
19
+ "@types/react-dom": "^18",
20
+ "typescript": "^5"
21
+ }
22
+ }
web-app/src/app/globals.css ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg: #0f172a;
3
+ --card-bg: #1e293b;
4
+ --primary: #3b82f6;
5
+ --accent: #10b981;
6
+ --text: #f1f5f9;
7
+ --text-muted: #94a3b8;
8
+ --border: #334155;
9
+ }
10
+
11
+ * {
12
+ box-sizing: border-box;
13
+ margin: 0;
14
+ padding: 0;
15
+ }
16
+
17
+ body {
18
+ font-family: system-ui, -apple-system, sans-serif;
19
+ background: var(--bg);
20
+ color: var(--text);
21
+ min-height: 100vh;
22
+ }
23
+
24
+ .container {
25
+ max-width: 1200px;
26
+ margin: 0 auto;
27
+ padding: 2rem;
28
+ }
29
+
30
+ header {
31
+ display: flex;
32
+ justify-content: space-between;
33
+ align-items: center;
34
+ margin-bottom: 2rem;
35
+ padding-bottom: 1rem;
36
+ border-bottom: 1px solid var(--border);
37
+ }
38
+
39
+ h1 {
40
+ font-size: 1.5rem;
41
+ font-weight: 700;
42
+ }
43
+
44
+ .status-badge {
45
+ display: flex;
46
+ align-items: center;
47
+ gap: 0.5rem;
48
+ padding: 0.5rem 1rem;
49
+ background: var(--card-bg);
50
+ border-radius: 9999px;
51
+ font-size: 0.875rem;
52
+ }
53
+
54
+ .status-dot {
55
+ width: 8px;
56
+ height: 8px;
57
+ border-radius: 50%;
58
+ background: var(--accent);
59
+ animation: pulse 2s infinite;
60
+ }
61
+
62
+ @keyframes pulse {
63
+ 0%, 100% { opacity: 1; }
64
+ 50% { opacity: 0.5; }
65
+ }
66
+
67
+ .grid {
68
+ display: grid;
69
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
70
+ gap: 1rem;
71
+ margin-bottom: 2rem;
72
+ }
73
+
74
+ .card {
75
+ background: var(--card-bg);
76
+ border: 1px solid var(--border);
77
+ border-radius: 0.75rem;
78
+ padding: 1.25rem;
79
+ transition: border-color 0.2s;
80
+ }
81
+
82
+ .card:hover {
83
+ border-color: var(--primary);
84
+ }
85
+
86
+ .card-header {
87
+ display: flex;
88
+ justify-content: space-between;
89
+ align-items: center;
90
+ margin-bottom: 1rem;
91
+ }
92
+
93
+ .asset-name {
94
+ font-size: 1.125rem;
95
+ font-weight: 600;
96
+ }
97
+
98
+ .asset-price {
99
+ font-size: 1.5rem;
100
+ font-weight: 700;
101
+ color: var(--primary);
102
+ margin-bottom: 0.5rem;
103
+ }
104
+
105
+ .range-info {
106
+ font-size: 0.875rem;
107
+ color: var(--text-muted);
108
+ }
109
+
110
+ .state-indicator {
111
+ padding: 0.25rem 0.75rem;
112
+ border-radius: 9999px;
113
+ font-size: 0.75rem;
114
+ font-weight: 600;
115
+ text-transform: uppercase;
116
+ }
117
+
118
+ .state-outside { background: #374151; color: #9ca3af; }
119
+ .state-inside { background: #065f46; color: #34d399; }
120
+
121
+ .add-form {
122
+ background: var(--card-bg);
123
+ border: 1px solid var(--border);
124
+ border-radius: 0.75rem;
125
+ padding: 1.5rem;
126
+ margin-bottom: 2rem;
127
+ }
128
+
129
+ .form-title {
130
+ font-size: 1.125rem;
131
+ font-weight: 600;
132
+ margin-bottom: 1rem;
133
+ }
134
+
135
+ .form-row {
136
+ display: grid;
137
+ grid-template-columns: 1fr 1fr 1fr auto;
138
+ gap: 1rem;
139
+ align-items: end;
140
+ }
141
+
142
+ .form-group {
143
+ display: flex;
144
+ flex-direction: column;
145
+ gap: 0.5rem;
146
+ }
147
+
148
+ label {
149
+ font-size: 0.875rem;
150
+ color: var(--text-muted);
151
+ }
152
+
153
+ input, select {
154
+ padding: 0.625rem;
155
+ background: var(--bg);
156
+ border: 1px solid var(--border);
157
+ border-radius: 0.5rem;
158
+ color: var(--text);
159
+ font-size: 1rem;
160
+ }
161
+
162
+ input:focus, select:focus {
163
+ outline: none;
164
+ border-color: var(--primary);
165
+ }
166
+
167
+ button {
168
+ padding: 0.625rem 1.25rem;
169
+ background: var(--primary);
170
+ color: white;
171
+ border: none;
172
+ border-radius: 0.5rem;
173
+ font-weight: 600;
174
+ cursor: pointer;
175
+ transition: opacity 0.2s;
176
+ }
177
+
178
+ button:hover {
179
+ opacity: 0.9;
180
+ }
181
+
182
+ button:disabled {
183
+ opacity: 0.5;
184
+ cursor: not-allowed;
185
+ }
186
+
187
+ button.remove {
188
+ background: #dc2626;
189
+ padding: 0.5rem;
190
+ font-size: 0.875rem;
191
+ }
192
+
193
+ .alerts-section {
194
+ background: var(--card-bg);
195
+ border: 1px solid var(--border);
196
+ border-radius: 0.75rem;
197
+ padding: 1.5rem;
198
+ }
199
+
200
+ .section-title {
201
+ font-size: 1.125rem;
202
+ font-weight: 600;
203
+ margin-bottom: 1rem;
204
+ }
205
+
206
+ .alert-item {
207
+ display: flex;
208
+ align-items: center;
209
+ gap: 1rem;
210
+ padding: 1rem;
211
+ background: var(--bg);
212
+ border-radius: 0.5rem;
213
+ margin-bottom: 0.5rem;
214
+ }
215
+
216
+ .alert-icon {
217
+ font-size: 1.5rem;
218
+ }
219
+
220
+ .alert-details {
221
+ flex: 1;
222
+ }
223
+
224
+ .alert-title {
225
+ font-weight: 600;
226
+ margin-bottom: 0.25rem;
227
+ }
228
+
229
+ .alert-meta {
230
+ font-size: 0.875rem;
231
+ color: var(--text-muted);
232
+ }
233
+
234
+ .empty-state {
235
+ text-align: center;
236
+ padding: 2rem;
237
+ color: var(--text-muted);
238
+ }
239
+
240
+ @media (max-width: 768px) {
241
+ .container { padding: 1rem; }
242
+ .form-row { grid-template-columns: 1fr; }
243
+ }
244
+
245
+ /* ── Form feedback ───────────────────────────────────────────────────────── */
246
+ .form-error {
247
+ margin-top: 0.75rem;
248
+ padding: 0.625rem 0.875rem;
249
+ background: #451a1a;
250
+ border: 1px solid #dc2626;
251
+ border-radius: 0.5rem;
252
+ color: #fca5a5;
253
+ font-size: 0.875rem;
254
+ }
255
+
256
+ .form-success {
257
+ margin-top: 0.75rem;
258
+ padding: 0.625rem 0.875rem;
259
+ background: #052e16;
260
+ border: 1px solid #16a34a;
261
+ border-radius: 0.5rem;
262
+ color: #86efac;
263
+ font-size: 0.875rem;
264
+ }
265
+
266
+ /* ── In-range card highlight ─────────────────────────────────────────────── */
267
+ .card-in-range {
268
+ border-color: #10b981;
269
+ box-shadow: 0 0 0 1px #10b98140;
270
+ }
web-app/src/app/layout.tsx ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Metadata } from 'next'
2
+ import './globals.css'
3
+
4
+ export const metadata: Metadata = {
5
+ title: 'Price Alert Dashboard',
6
+ description: 'Track crypto, stocks, and commodities with real-time alerts',
7
+ }
8
+
9
+ export default function RootLayout({
10
+ children,
11
+ }: {
12
+ children: React.ReactNode
13
+ }) {
14
+ return (
15
+ <html lang="en">
16
+ <body>{children}</body>
17
+ </html>
18
+ )
19
+ }
web-app/src/app/page.tsx ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useState, useEffect, useCallback } from 'react'
4
+
5
+ interface Asset {
6
+ name: string
7
+ min_price: number
8
+ max_price: number
9
+ state: 'OUTSIDE' | 'INSIDE'
10
+ last_price: number | null
11
+ last_alert_time: string | null
12
+ }
13
+
14
+ interface AlertEvent {
15
+ asset_name: string
16
+ price: number
17
+ min_price: number
18
+ max_price: number
19
+ timestamp: string
20
+ }
21
+
22
+ interface AvailableAssets {
23
+ commodities: string[]
24
+ stocks: string[]
25
+ crypto: string[]
26
+ all: string[]
27
+ }
28
+
29
+ const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
30
+
31
+ export default function Dashboard() {
32
+ const [assets, setAssets] = useState<Asset[]>([])
33
+ const [prices, setPrices] = useState<Record<string, number>>({})
34
+ const [alerts, setAlerts] = useState<AlertEvent[]>([])
35
+ const [available, setAvailable] = useState<AvailableAssets>({
36
+ commodities: [],
37
+ stocks: [],
38
+ crypto: [],
39
+ all: [],
40
+ })
41
+ const [newAsset, setNewAsset] = useState({ name: '', min_price: '', max_price: '' })
42
+ const [connected, setConnected] = useState(false)
43
+ const [addError, setAddError] = useState<string | null>(null)
44
+ const [addSuccess, setAddSuccess] = useState(false)
45
+
46
+ const fetchAssets = useCallback(async () => {
47
+ try {
48
+ const res = await fetch(`${API_URL}/assets`)
49
+ if (res.ok) {
50
+ const data = await res.json()
51
+ setAssets(data)
52
+ // Populate prices map from last_price field
53
+ setPrices(prev => {
54
+ const updated = { ...prev }
55
+ for (const a of data as Asset[]) {
56
+ if (a.last_price != null) updated[a.name] = a.last_price
57
+ }
58
+ return updated
59
+ })
60
+ }
61
+ } catch (err) {
62
+ console.error('Failed to fetch assets:', err)
63
+ }
64
+ }, [])
65
+
66
+ const fetchAvailable = useCallback(async () => {
67
+ try {
68
+ const res = await fetch(`${API_URL}/assets/available`)
69
+ if (res.ok) {
70
+ const data = await res.json()
71
+ setAvailable(data)
72
+ }
73
+ } catch (err) {
74
+ console.error('Failed to fetch available assets:', err)
75
+ }
76
+ }, [])
77
+
78
+ const fetchHistory = useCallback(async () => {
79
+ try {
80
+ const res = await fetch(`${API_URL}/history`)
81
+ if (res.ok) {
82
+ const data: AlertEvent[] = await res.json()
83
+ setAlerts(data.slice(0, 50))
84
+ }
85
+ } catch (err) {
86
+ console.error('Failed to fetch history:', err)
87
+ }
88
+ }, [])
89
+
90
+ useEffect(() => {
91
+ fetchAssets()
92
+ fetchAvailable()
93
+ fetchHistory()
94
+
95
+ let ws: WebSocket | null = null
96
+ let reconnectTimer: NodeJS.Timeout
97
+
98
+ const connect = () => {
99
+ ws = new WebSocket(`${API_URL.replace('http', 'ws')}/ws`)
100
+
101
+ ws.onopen = () => {
102
+ setConnected(true)
103
+ console.log('WebSocket connected')
104
+ }
105
+
106
+ ws.onmessage = (event) => {
107
+ try {
108
+ const msg = JSON.parse(event.data)
109
+
110
+ if (msg.type === 'snapshot') {
111
+ // Initial state snapshot sent by backend on connect
112
+ const snap = msg.data as Asset[]
113
+ setAssets(snap)
114
+ setPrices(prev => {
115
+ const updated = { ...prev }
116
+ for (const a of snap) {
117
+ if (a.last_price != null) updated[a.name] = a.last_price
118
+ }
119
+ return updated
120
+ })
121
+ } else if (msg.type === 'price_update') {
122
+ setPrices(prev => ({ ...prev, [msg.data.name]: msg.data.price }))
123
+ } else if (msg.type === 'alert') {
124
+ setAlerts(prev => [msg.data as AlertEvent, ...prev].slice(0, 50))
125
+ }
126
+ } catch (err) {
127
+ console.error('Failed to parse WS message:', err)
128
+ }
129
+ }
130
+
131
+ ws.onclose = () => {
132
+ setConnected(false)
133
+ reconnectTimer = setTimeout(connect, 3000)
134
+ }
135
+
136
+ ws.onerror = () => {
137
+ ws?.close()
138
+ }
139
+ }
140
+
141
+ connect()
142
+
143
+ return () => {
144
+ clearTimeout(reconnectTimer)
145
+ ws?.close()
146
+ }
147
+ }, [fetchAssets, fetchAvailable, fetchHistory])
148
+
149
+ const handleAddAsset = async (e: React.FormEvent) => {
150
+ e.preventDefault()
151
+ setAddError(null)
152
+ setAddSuccess(false)
153
+
154
+ if (!newAsset.name || !newAsset.min_price || !newAsset.max_price) {
155
+ setAddError('Please fill in all fields.')
156
+ return
157
+ }
158
+
159
+ const min = parseFloat(newAsset.min_price)
160
+ const max = parseFloat(newAsset.max_price)
161
+ if (isNaN(min) || isNaN(max) || min >= max) {
162
+ setAddError('Min price must be a number less than Max price.')
163
+ return
164
+ }
165
+
166
+ try {
167
+ const res = await fetch(`${API_URL}/assets`, {
168
+ method: 'POST',
169
+ headers: { 'Content-Type': 'application/json' },
170
+ body: JSON.stringify({ name: newAsset.name, min_price: min, max_price: max }),
171
+ })
172
+
173
+ if (res.ok) {
174
+ setNewAsset({ name: '', min_price: '', max_price: '' })
175
+ setAddSuccess(true)
176
+ setTimeout(() => setAddSuccess(false), 3000)
177
+ fetchAssets()
178
+ } else {
179
+ const err = await res.json()
180
+ setAddError(err.detail || 'Failed to add asset.')
181
+ }
182
+ } catch (err) {
183
+ setAddError('Network error — is the backend running?')
184
+ }
185
+ }
186
+
187
+ const handleRemoveAsset = async (name: string) => {
188
+ try {
189
+ const res = await fetch(`${API_URL}/assets/${name}`, { method: 'DELETE' })
190
+ if (res.ok) fetchAssets()
191
+ } catch (err) {
192
+ console.error('Failed to remove asset:', err)
193
+ }
194
+ }
195
+
196
+ return (
197
+ <div className="container">
198
+ <header>
199
+ <h1>Price Alert Dashboard</h1>
200
+ <div className="status-badge">
201
+ <div className="status-dot" style={{ background: connected ? '#10b981' : '#ef4444' }} />
202
+ {connected ? 'Live' : 'Disconnected'}
203
+ </div>
204
+ </header>
205
+
206
+ <form className="add-form" onSubmit={handleAddAsset}>
207
+ <div className="form-title">Add Asset to Track</div>
208
+ <div className="form-row">
209
+ <div className="form-group">
210
+ <label>Asset</label>
211
+ <select
212
+ value={newAsset.name}
213
+ onChange={e => setNewAsset({ ...newAsset, name: e.target.value })}
214
+ >
215
+ <option value="">Select asset...</option>
216
+ <optgroup label="₿ Crypto">
217
+ {available.crypto.map(a => <option key={a} value={a}>{a}</option>)}
218
+ </optgroup>
219
+ <optgroup label="📦 Commodities">
220
+ {available.commodities.map(a => <option key={a} value={a}>{a}</option>)}
221
+ </optgroup>
222
+ <optgroup label="📊 Stocks & Indices">
223
+ {available.stocks.map(a => <option key={a} value={a}>{a}</option>)}
224
+ </optgroup>
225
+ </select>
226
+ </div>
227
+ <div className="form-group">
228
+ <label>Min Price</label>
229
+ <input
230
+ type="number"
231
+ step="any"
232
+ placeholder="e.g. 80000"
233
+ value={newAsset.min_price}
234
+ onChange={e => setNewAsset({ ...newAsset, min_price: e.target.value })}
235
+ />
236
+ </div>
237
+ <div className="form-group">
238
+ <label>Max Price</label>
239
+ <input
240
+ type="number"
241
+ step="any"
242
+ placeholder="e.g. 90000"
243
+ value={newAsset.max_price}
244
+ onChange={e => setNewAsset({ ...newAsset, max_price: e.target.value })}
245
+ />
246
+ </div>
247
+ <button type="submit">Add</button>
248
+ </div>
249
+ {addError && <div className="form-error">⚠️ {addError}</div>}
250
+ {addSuccess && <div className="form-success">✅ Asset added successfully!</div>}
251
+ </form>
252
+
253
+ <div className="grid">
254
+ {assets.length === 0 ? (
255
+ <div className="card empty-state">
256
+ No assets being tracked. Add one above!
257
+ </div>
258
+ ) : (
259
+ assets.map(asset => (
260
+ <div key={asset.name} className={`card ${asset.state === 'INSIDE' ? 'card-in-range' : ''}`}>
261
+ <div className="card-header">
262
+ <span className="asset-name">{asset.name}</span>
263
+ <button className="remove" onClick={() => handleRemoveAsset(asset.name)}>
264
+ Remove
265
+ </button>
266
+ </div>
267
+ <div className="asset-price">
268
+ {prices[asset.name] != null
269
+ ? `$${prices[asset.name].toLocaleString(undefined, {
270
+ minimumFractionDigits: 2,
271
+ maximumFractionDigits: prices[asset.name] < 1 ? 6 : 2,
272
+ })}`
273
+ : '—'}
274
+ </div>
275
+ <div className="range-info">
276
+ Range: ${asset.min_price.toLocaleString()} – ${asset.max_price.toLocaleString()}
277
+ </div>
278
+ <div style={{ marginTop: '0.5rem' }}>
279
+ <span className={`state-indicator state-${asset.state.toLowerCase()}`}>
280
+ {asset.state === 'INSIDE' ? '✓ In Range' : '○ Outside Range'}
281
+ </span>
282
+ </div>
283
+ </div>
284
+ ))
285
+ )}
286
+ </div>
287
+
288
+ <div className="alerts-section">
289
+ <div className="section-title">🔔 Recent Alerts</div>
290
+ {alerts.length === 0 ? (
291
+ <div className="empty-state">No alerts yet. Prices will trigger when they enter your target range.</div>
292
+ ) : (
293
+ alerts.map((alert, i) => (
294
+ <div key={i} className="alert-item">
295
+ <span className="alert-icon">🔔</span>
296
+ <div className="alert-details">
297
+ <div className="alert-title">{alert.asset_name} entered range</div>
298
+ <div className="alert-meta">
299
+ Price: ${alert.price.toLocaleString(undefined, { maximumFractionDigits: 4 })} &nbsp;|&nbsp;
300
+ Range: ${alert.min_price.toLocaleString()} – ${alert.max_price.toLocaleString()} &nbsp;|&nbsp;
301
+ {new Date(alert.timestamp).toLocaleString()}
302
+ </div>
303
+ </div>
304
+ </div>
305
+ ))
306
+ )}
307
+ </div>
308
+ </div>
309
+ )
310
+ }
web-app/tsconfig.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["dom", "dom.iterable", "esnext"],
4
+ "allowJs": true,
5
+ "skipLibCheck": true,
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "esModuleInterop": true,
9
+ "module": "esnext",
10
+ "moduleResolution": "bundler",
11
+ "resolveJsonModule": true,
12
+ "isolatedModules": true,
13
+ "jsx": "preserve",
14
+ "incremental": true,
15
+ "plugins": [{"name": "next"}],
16
+ "paths": {"@/*": ["./src/*"]}
17
+ },
18
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
19
+ "exclude": ["node_modules"]
20
+ }