File size: 18,740 Bytes
d6d843f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 |
# Professional Crypto Intelligence Dashboard
## π― Overview
A **professional, production-ready cryptocurrency intelligence dashboard** with:
β
**Backend Integration** - Full REST API + WebSocket real-time updates
β
**User Query System** - Natural language queries for crypto data
β
**Real-time Synchronization** - Live price updates every 10 seconds
β
**Professional UI** - Modern design with charts and visualizations
β
**Comprehensive Data** - Prices, market cap, news, sentiment, DeFi, NFTs
---
## ποΈ Architecture
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend (HTML/JS/CSS) β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Query System β β Price Charts β β News Feed β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP/WebSocket
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Backend API (Python/FastAPI) β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β REST API β β WebSocket β β Query Parser β β
β β Endpoints β β Real-time β β NLP Engine β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Data Sources & Providers β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β CoinGecko β β DeFiLlama β β News APIs β β
β β Binance β β Etherscan β β Sentiment β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## π¦ Files Provided
| File | Purpose | Size |
|------|---------|------|
| `crypto_dashboard_pro.html` | Professional frontend dashboard | 35 KB |
| `api_dashboard_backend.py` | Complete backend API server | 18 KB |
| `PROFESSIONAL_DASHBOARD_GUIDE.md` | This comprehensive guide | 15 KB |
---
## π Quick Start (3 Steps)
### Step 1: Install Dependencies
```bash
# Install required Python packages
pip install fastapi uvicorn websockets
```
### Step 2: Start Backend Server
```bash
# Start the API server
python3 api_dashboard_backend.py
```
Server starts on: **http://localhost:7860**
### Step 3: Open Dashboard
```bash
# Open in browser
http://localhost:7860
```
**Done!** Dashboard is now running with full backend integration.
---
## π¨ Dashboard Features
### 1. **Query Interface** π
Users can ask questions in natural language:
```
Example Queries:
π° "Bitcoin price" β Shows current BTC price
π "Top 10 coins" β Lists top 10 cryptocurrencies
π "Ethereum trend" β Shows ETH price trend
π "Market sentiment" β Shows bullish/bearish sentiment
π "DeFi TVL" β Total Value Locked in DeFi
πΌοΈ "NFT volume" β Daily NFT trading volume
β½ "Gas prices" β Current Ethereum gas fees
π° "Latest news" β Recent crypto news
```
**How It Works:**
1. User types query in search box
2. Backend parses natural language using regex patterns
3. API fetches relevant data from providers
4. Results displayed in real-time
### 2. **Real-time Price Updates** π
- WebSocket connection for live data
- Updates every 10 seconds automatically
- Connection status indicator
- Top cryptocurrencies table with:
- Current price
- 24h change percentage
- Market capitalization
- Trading volume
### 3. **Interactive Charts** π
**Price Trend Chart:**
- Line chart showing historical prices
- Timeframe options: 1D, 7D, 30D, 90D
- Smooth animations
- Responsive design
**Sentiment Analysis Chart:**
- Doughnut chart
- Shows Bullish/Neutral/Bearish percentages
- Real-time market sentiment
### 4. **Market Statistics** π
Four key metrics displayed as cards:
1. **Total Market Cap** - Combined value of all cryptocurrencies
2. **24h Volume** - Total trading volume
3. **Bitcoin Dominance** - BTC market share
4. **Fear & Greed Index** - Market sentiment indicator
### 5. **Latest News Feed** π°
- Real-time crypto news
- Source attribution
- Timestamp
- Clickable links
- Sentiment indicators
### 6. **Data Export** πΎ
- Export all data as JSON
- One-click download
- Includes: prices, news, stats, sentiment
---
## π§ Backend API Endpoints
### REST API
#### **GET /api/health**
Health check endpoint
```json
{
"status": "healthy",
"version": "1.0.0",
"service": "Crypto Intelligence Dashboard API"
}
```
#### **GET /api/coins/top?limit=10**
Get top cryptocurrencies by market cap
```json
{
"success": true,
"coins": [
{
"name": "Bitcoin",
"symbol": "BTC",
"price": 43250.50,
"change_24h": 2.34,
"market_cap": 845000000000,
"volume_24h": 25000000000
}
],
"count": 10
}
```
#### **GET /api/coins/{symbol}**
Get detailed information about a specific coin
```json
{
"success": true,
"coin": {
"name": "Bitcoin",
"symbol": "BTC",
"price": 43250.50,
"circulating_supply": 19500000,
"max_supply": 21000000,
"ath": 69000,
"atl": 100
}
}
```
#### **GET /api/market/stats**
Get overall market statistics
```json
{
"success": true,
"stats": {
"total_market_cap": 2100000000000,
"total_volume_24h": 89500000000,
"btc_dominance": 48.2,
"fear_greed_index": 65,
"active_cryptocurrencies": 10523
}
}
```
#### **GET /api/news/latest?limit=10**
Get latest cryptocurrency news
```json
{
"success": true,
"news": [
{
"title": "Bitcoin reaches new milestone",
"source": "CoinDesk",
"time": "2 hours ago",
"url": "https://coindesk.com/...",
"sentiment": "positive"
}
]
}
```
#### **POST /api/query**
Process natural language queries
**Request:**
```json
{
"query": "Bitcoin price"
}
```
**Response:**
```json
{
"success": true,
"type": "price",
"coin": "Bitcoin",
"symbol": "BTC",
"price": 43250.50,
"message": "Bitcoin (BTC) is currently $43,250.50"
}
```
#### **GET /api/charts/price/{symbol}?timeframe=7d**
Get historical price data for charts
```json
{
"success": true,
"symbol": "BTC",
"timeframe": "7d",
"data": [
{
"timestamp": "2024-01-01T00:00:00",
"price": 43000.00
}
]
}
```
### WebSocket
#### **WS /ws**
Real-time data stream
**Connection:**
```javascript
const ws = new WebSocket('ws://localhost:7860/ws');
```
**Received Messages:**
```json
{
"type": "price_update",
"payload": [...coins],
"timestamp": "2024-01-15T12:00:00"
}
```
**Message Types:**
- `connected` - Initial connection established
- `price_update` - Real-time price updates
- `news_update` - New news articles
- `sentiment_update` - Market sentiment changes
---
## π» Query System Details
### Supported Query Types
1. **Price Queries**
- Pattern: "price of {coin}", "{coin} price"
- Example: "Bitcoin price", "ETH price"
- Response: Current price with 24h change
2. **Top Coins**
- Pattern: "top {number}", "best {number} coins"
- Example: "top 10", "best 20 coins"
- Response: List of top cryptocurrencies
3. **Market Cap**
- Pattern: "market cap of {coin}"
- Example: "Bitcoin market cap"
- Response: Current market capitalization
4. **Trend Analysis**
- Pattern: "{coin} trend", "trend of {coin}"
- Example: "Ethereum trend"
- Response: Historical price trend chart
5. **Sentiment**
- Pattern: "sentiment", "market feeling"
- Example: "market sentiment"
- Response: Bullish/bearish/neutral analysis
6. **DeFi Queries**
- Pattern: "defi", "tvl", "total value locked"
- Example: "DeFi TVL"
- Response: Total Value Locked statistics
7. **NFT Queries**
- Pattern: "nft", "non fungible"
- Example: "NFT volume"
- Response: NFT market statistics
8. **Gas Prices**
- Pattern: "gas price", "transaction fee"
- Example: "Ethereum gas prices"
- Response: Current gas fees
### Adding Custom Queries
Edit `api_dashboard_backend.py`:
```python
# In parse_query() function
patterns = {
'your_query_type': [r'your regex pattern', r'alternative pattern'],
}
# In process_query() function
elif parsed['type'] == 'your_query_type':
return {
"success": True,
"type": "info",
"message": "Your custom response",
"data": {...}
}
```
---
## π¨ Frontend Customization
### Change Colors
Edit CSS variables in `crypto_dashboard_pro.html`:
```css
:root {
--primary: #6366f1; /* Main theme color */
--success: #10b981; /* Positive values */
--danger: #ef4444; /* Negative values */
--warning: #f59e0b; /* Warnings */
--bg-dark: #0f172a; /* Background */
--bg-card: #1e293b; /* Card background */
}
```
### Add Quick Query Buttons
```html
<button class="quick-query-btn" onclick="quickQuery('your query')">
π₯ Your Query
</button>
```
### Modify Charts
```javascript
// In initializeCharts() function
priceChart = new Chart(priceCtx, {
type: 'line', // Change to: 'bar', 'pie', 'doughnut'
data: { ... },
options: {
// Customize chart options
}
});
```
---
## π Integration with Existing Providers
### Connect to Real Data Sources
Edit `api_dashboard_backend.py` to integrate with your providers:
```python
async def fetch_real_coin_data():
"""Fetch from actual API providers"""
# Load your provider configuration
config = load_providers_config()
# Use CoinGecko provider
coingecko = config['providers']['coingecko']
url = f"{coingecko['base_url']}/coins/markets"
# Make request
async with aiohttp.ClientSession() as session:
async with session.get(url, params={
'vs_currency': 'usd',
'order': 'market_cap_desc',
'per_page': 10
}) as response:
return await response.json()
```
### Add New Data Sources
```python
# In generate_mock_news() - replace with real news API
async def fetch_real_news():
news_provider = config['providers']['cryptopanic']
url = f"{news_provider['base_url']}/posts/"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
```
---
## π± Mobile Responsive Design
Dashboard automatically adapts to screen sizes:
**Desktop** (>1024px):
- Two-column layout
- Full-width charts
- All features visible
**Tablet** (768px-1024px):
- Single column for some cards
- Scrollable tables
- Touch-friendly buttons
**Mobile** (<768px):
- Single column layout
- Stacked statistics cards
- Horizontal scroll for tables
- Larger touch targets
---
## π Security Considerations
### Production Deployment
1. **Enable HTTPS**
```python
uvicorn.run(
app,
host="0.0.0.0",
port=443,
ssl_keyfile="./key.pem",
ssl_certfile="./cert.pem"
)
```
2. **Rate Limiting**
```python
from slowapi import Limiter
limiter = Limiter(key_func=get_remote_address)
@app.get("/api/query")
@limiter.limit("10/minute")
async def process_query(...):
...
```
3. **API Authentication**
```python
from fastapi.security import HTTPBearer
security = HTTPBearer()
@app.get("/api/coins/top")
async def get_top_coins(credentials: HTTPAuthorizationCredentials = Depends(security)):
# Verify token
verify_token(credentials.credentials)
...
```
4. **CORS Configuration**
```python
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourdomain.com"], # Specific domains
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
```
---
## π Deployment Options
### Option 1: Hugging Face Spaces
1. Create `requirements.txt`:
```
fastapi==0.104.1
uvicorn[standard]==0.24.0
websockets==12.0
```
2. Create `app.py`:
```python
from api_dashboard_backend import app
```
3. Push to Hugging Face:
```bash
git add .
git commit -m "Deploy crypto dashboard"
git push origin main
```
### Option 2: Docker
1. Create `Dockerfile`:
```dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "api_dashboard_backend.py"]
```
2. Build and run:
```bash
docker build -t crypto-dashboard .
docker run -p 7860:7860 crypto-dashboard
```
### Option 3: Cloud Platforms
**AWS/GCP/Azure:**
```bash
# Install platform CLI
# Deploy as serverless function or container
```
---
## π Performance Optimization
### Backend
1. **Caching**
```python
from functools import lru_cache
@lru_cache(maxsize=100)
def get_cached_coin_data():
return fetch_coin_data()
```
2. **Async Operations**
```python
async def fetch_multiple_sources():
results = await asyncio.gather(
fetch_coingecko(),
fetch_binance(),
fetch_defillama()
)
return results
```
3. **Connection Pooling**
```python
import aiohttp
connector = aiohttp.TCPConnector(limit=100)
session = aiohttp.ClientSession(connector=connector)
```
### Frontend
1. **Lazy Loading**
```javascript
// Load charts only when visible
if (element.isIntersecting) {
loadChart();
}
```
2. **Debouncing**
```javascript
const debouncedQuery = debounce(executeQuery, 300);
```
3. **Data Pagination**
```javascript
// Load data in chunks
loadMore() {
offset += 10;
fetchCoins(offset, 10);
}
```
---
## π Troubleshooting
### Issue: WebSocket not connecting
**Solution:**
1. Check server is running: `curl http://localhost:7860/api/health`
2. Verify WebSocket URL in browser console
3. Check firewall settings
4. For HTTPS, use `wss://` instead of `ws://`
### Issue: Queries not working
**Solution:**
1. Check backend logs: `tail -f logs/api.log`
2. Verify query patterns in `parse_query()`
3. Test API endpoint: `curl -X POST http://localhost:7860/api/query -d '{"query":"bitcoin price"}'`
### Issue: Charts not displaying
**Solution:**
1. Check Chart.js is loaded: Browser dev tools β Network
2. Verify canvas element exists: `document.getElementById('priceChart')`
3. Check data format matches chart requirements
### Issue: Slow performance
**Solution:**
1. Enable caching for API responses
2. Reduce WebSocket update frequency
3. Limit number of coins displayed
4. Optimize database queries
---
## π Feature Roadmap
**Planned Features:**
- [ ] Historical data analysis
- [ ] Portfolio tracking
- [ ] Price alerts
- [ ] Advanced charting (candlesticks, indicators)
- [ ] Social media sentiment analysis
- [ ] AI-powered predictions
- [ ] Multi-language support
- [ ] Dark/Light theme toggle
- [ ] Mobile app version
- [ ] Desktop notifications
---
## π€ Contributing
To add features:
1. Fork the repository
2. Create feature branch: `git checkout -b feature/amazing-feature`
3. Commit changes: `git commit -m 'Add amazing feature'`
4. Push to branch: `git push origin feature/amazing-feature`
5. Open Pull Request
---
## π Support
**Documentation:** This guide
**API Reference:** See REST API Endpoints section
**Examples:** Check `crypto_dashboard_pro.html` for frontend examples
**Backend:** See `api_dashboard_backend.py` for API implementation
---
## β
Summary
You now have a **complete, professional cryptocurrency intelligence dashboard**:
β
**Professional UI** - Modern design with gradients, animations, SVG icons
β
**Backend Integration** - Full REST API + WebSocket real-time updates
β
**Query System** - Natural language processing for user queries
β
**Real-time Data** - Live price updates every 10 seconds
β
**Comprehensive Features** - Prices, charts, news, sentiment, stats
β
**Mobile Responsive** - Works on all devices
β
**Production Ready** - Security, optimization, deployment guides
β
**Extensible** - Easy to add new features and data sources
**Start Command:**
```bash
python3 api_dashboard_backend.py
```
**Access Dashboard:**
```
http://localhost:7860
```
---
**Ready for production deployment! π**
|