Upload 152 files
Browse filesFiles changed (26)
- .dockerignore+103-23
- .env.example+17-41
- .gitignore+30-21
- Dockerfile+62-7
- FRONTEND_COMPLETE.mdAdded+219
- QUICK_START.md+153-75
- README.md+281-276
- __pycache__/app.cpython-313.pycAdded
- __pycache__/config.cpython-313.pycAdded
- api-resources/README.mdAdded+282
- api-resources/api-config-complete__1_.txtAdded+1634
- api-resources/crypto_resources_unified_2025-11-11.jsonAdded+2097
- api-resources/ultimate_crypto_pipeline_2025_NZasinich.jsonAdded+503
- app.py+1569-325
- database.py+318-22
- database/__pycache__/__init__.cpython-313.pycAdded
- database/__pycache__/data_access.cpython-313.pycAdded
- database/__pycache__/db_manager.cpython-313.pycAdded
- database/__pycache__/models.cpython-313.pycAdded
- enhanced_dashboard.htmlAdded+876
- main.py+2-167
- requirements.txt+1-2
- start.bat+17-45
- unified_dashboard.htmlAdded+2107
- utils/__pycache__/__init__.cpython-313.pycAdded
- utils/__pycache__/logger.cpython-313.pycAdded
1234567891011121314151617181920212223242526272829303132333435363738394041# Node modulesnode_modules/frontend/node_modules/# Build artifactsfrontend/dist/# Python cache__pycache__/*.pyc*.pyo*.pyd.Python*.so# Environment files.env.env.local.env.*.local# IDE.vscode/.idea/*.swp*.swo# Git.git/.gitignore# OS.DS_StoreThumbs.db# Logs*.loglogs/# Testingcoverage/.pytest_cache/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.eggMANIFESTpip-log.txtpip-delete-this-directory.txt# Virtual environmentsvenv/ENV/env/.venv# IDE.vscode/.idea/*.swp*.swo*~.DS_Store# Git.git/.gitignore.gitattributes# Documentation*.mddocs/README*.mdCHANGELOG.mdLICENSE# Testing.pytest_cache/.coveragehtmlcov/.tox/.hypothesis/tests/test_*.py# Logs and databases (will be created in container)*.loglogs/data/*.dbdata/*.sqlitedata/*.db-journal# Environment files (should be set via docker-compose or HF Secrets).env.env.*!.env.example# Dockerdocker-compose*.yml!docker-compose.ymlDockerfile.dockerignore# CI/CD.github/.gitlab-ci.yml.travis.ymlazure-pipelines.yml# Temporary files*.tmp*.bak*.swptemp/tmp/# Node modules (if any)node_modules/package-lock.jsonyarn.lock# OS filesThumbs.db.DS_Storedesktop.ini# Jupyter notebooks.ipynb_checkpoints/*.ipynb# Model cache (models will be downloaded in container)models/.cache/.huggingface/# Large files that shouldn't be in image*.tar*.tar.gz*.zip*.rar*.7z# Screenshots and assets not neededscreenshots/assets/*.pngassets/*.jpg
1234567891011121314151617181920212223242526272829303132333435363738394041# Crypto Dashboard Configuration# کپی کنید به .env و مقادیر را تنظیم کنید# Server ConfigurationHOST=0.0.0.0PORT=7860# API Keys (اختیاری - برای منابع داده اضافی)# COINGECKO_API_KEY=your_api_key_here# ETHERSCAN_API_KEY=your_api_key_here# BSC_SCAN_API_KEY=your_api_key_here# Cache SettingsCACHE_TTL_MARKET=60 # ثانیه - Market OverviewCACHE_TTL_PRICES=60 # ثانیه - PricesCACHE_TTL_NEWS=600 # ثانیه - NewsCACHE_TTL_SENTIMENT=300 # ثانیه - SentimentCACHE_TTL_BLOCKCHAIN=30 # ثانیه - Blockchain Stats# Rate Limiting (اختیاری)# ENABLE_RATE_LIMIT=true# RATE_LIMIT_PER_MINUTE=60# CORS Settings# CORS_ORIGINS=http://localhost:3000,https://yourdomain.com# LoggingLOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR# LOG_FILE=crypto_dashboard.log# External APIs# NEWS_API_KEY=your_news_api_key# ALTERNATIVE_ME_API_KEY=your_alternative_me_key# Development ModeDEBUG=falseRELOAD=false# Database (اختیاری - برای ذخیره تاریخچه)# USE_DATABASE=false# DATABASE_URL=sqlite:///crypto_data.db1234567891011121314151617# HuggingFace ConfigurationHUGGINGFACE_TOKEN=your_token_hereENABLE_SENTIMENT=trueSENTIMENT_SOCIAL_MODEL=ElKulako/cryptobertSENTIMENT_NEWS_MODEL=kk08/CryptoBERTHF_REGISTRY_REFRESH_SEC=21600HF_HTTP_TIMEOUT=8.0# Existing API Keys (if any)ETHERSCAN_KEY_1=ETHERSCAN_KEY_2=BSCSCAN_KEY=TRONSCAN_KEY=COINMARKETCAP_KEY_1=COINMARKETCAP_KEY_2=NEWSAPI_KEY=CRYPTOCOMPARE_KEY=
3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839403 unmodified lines*$py.class*.so.Pythonvenv/env/ENV/*.egg-info/dist/build/# IDEs.vscode/.idea/*.swp*.swo*~# OS.DS_StoreThumbs.dbdesktop.ini# Logs*.loglogs/# Environment.env.env.local# Database*.db*.sqlite# Cache.cache/*.cache3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748493 unmodified lines*$py.class*.so.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/*.egg-info/.installed.cfg*.egg# Virtual environmentsvenv/ENV/env/# IDE.vscode/.idea/*.swp*.swo# Datadata/*.dbdata/*.db-journaldata/exports/crypto_monitor.dbcrypto_monitor.db-journal# Environment.env# Logs*.log# OS.DS_StoreThumbs.db
12345678910111213141516FROM python:3.10-slimWORKDIR /app# نصب وابستگیهاCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# کپی فایلهای پروژهCOPY . .# ایجاد پوشههای مورد نیازRUN mkdir -p templates# اجرای اپلیکیشنCMD ["python", "app.py"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# Dockerfile for Crypto API Monitoring System# Optimized for HuggingFace Spaces deploymentFROM python:3.10-slim# Set working directoryWORKDIR /app# Set environment variables for better Python behaviorENV PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \PIP_NO_CACHE_DIR=1 \PIP_DISABLE_PIP_VERSION_CHECK=1# Install system dependencies required for building Python packagesRUN apt-get update && apt-get install -y --no-install-recommends \gcc \g++ \git \curl \&& rm -rf /var/lib/apt/lists/*# Copy requirements first for better layer cachingCOPY requirements.txt .# Install Python dependencies with optimizations# Split into two steps: core dependencies first, then ML librariesRUN pip install --no-cache-dir \fastapi==0.104.1 \uvicorn[standard]==0.24.0 \pydantic==2.5.0 \python-multipart==0.0.6 \websockets==12.0 \SQLAlchemy==2.0.23 \APScheduler==3.10.4 \aiohttp==3.9.1 \requests==2.31.0 \httpx \python-dotenv==1.0.0 \feedparser==6.0.11 \gradio==4.14.0 \pandas==2.1.4 \plotly==5.18.0# Install HuggingFace ML dependencies separatelyRUN pip install --no-cache-dir \transformers>=4.44.0 \datasets>=3.0.0 \huggingface_hub>=0.24.0 \torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu \sentencepiece>=0.1.99 \protobuf>=3.20.0# Copy all application codeCOPY . .# Create necessary directoriesRUN mkdir -p data logs# Set proper permissions for data directoriesRUN chmod -R 755 data logs# Expose port 7860 (HuggingFace Spaces standard port)EXPOSE 7860# Health check endpoint for HuggingFace SpacesHEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \CMD curl -f http://localhost:7860/health || exit 1# Run the FastAPI application with uvicorn# Using multiple workers for better performance (adjust based on available resources)CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--log-level", "info", "--workers", "1"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# ✅ Frontend Implementation Complete
## 🎉 All Frontend Pages Are Now Fully Functional
The crypto monitoring dashboard has been updated to be fully functional with complete design and front-end integration.
---
## 📄 Available Pages
### 1. **Main Dashboard** (`/` or `/dashboard`)
- **File**: `index.html`
- **Features**:
- Real-time crypto market data
- Market cap, volume, BTC dominance
- Fear & Greed Index
- Top 20 cryptocurrencies
- Trending coins
- DeFi protocols TVL
- Interactive charts (Market Dominance, Sentiment Gauge)
- WebSocket real-time updates
### 2. **API Monitor Dashboard** (`/dashboard.html`)
- **File**: `dashboard.html`
- **Features**:
- API provider status monitoring
- Response time tracking
- HuggingFace sentiment analysis
- System statistics
- Auto-refresh functionality
### 3. **Enhanced Dashboard** (`/enhanced_dashboard.html`)
- **File**: `enhanced_dashboard.html`
- **Features**:
- Advanced system statistics
- API source management
- Schedule configuration
- Export functionality (JSON/CSV)
- Backup creation
- Cache management
- WebSocket v2 connection
### 4. **Admin Panel** (`/admin.html`)
- **File**: `admin.html`
- **Features**:
- API source management
- Settings configuration
- System statistics
- HuggingFace settings
- System configuration
### 5. **HF Console** (`/hf_console.html`)
- **File**: `hf_console.html`
- **Features**:
- HuggingFace integration console
- Model management
- Sentiment analysis tools
### 6. **Pool Management** (`/pool_management.html`)
- **File**: `pool_management.html`
- **Features**:
- API pool management
- Resource allocation
---
## 🔧 Backend Updates
### New API Endpoints Added:
1. **Status & Health**:
- `GET /api/status` - System status
- `GET /api/providers` - Provider list
- `GET /api/stats` - Comprehensive statistics
2. **HuggingFace Integration**:
- `GET /api/hf/health` - HF service health
- `POST /api/hf/run-sentiment` - Sentiment analysis
3. **API v2 Endpoints** (for Enhanced Dashboard):
- `GET /api/v2/status` - Enhanced status
- `GET /api/v2/config/apis` - API configuration
- `GET /api/v2/schedule/tasks` - Scheduled tasks
- `GET /api/v2/schedule/tasks/{api_id}` - Specific task
- `PUT /api/v2/schedule/tasks/{api_id}` - Update schedule
- `POST /api/v2/schedule/tasks/{api_id}/force-update` - Force update
- `POST /api/v2/export/json` - Export JSON
- `POST /api/v2/export/csv` - Export CSV
- `POST /api/v2/backup` - Create backup
- `POST /api/v2/cleanup/cache` - Clear cache
- `WS /api/v2/ws` - Enhanced WebSocket
4. **HTML File Serving**:
- All HTML files are now served via FastAPI routes
- Static files support added
- Config.js serving
---
## 🎨 Design Features
### All Pages Include:
- ✅ Modern, professional UI design
- ✅ Responsive layout (mobile-friendly)
- ✅ Smooth animations and transitions
- ✅ Gradient backgrounds and effects
- ✅ Color-coded status indicators
- ✅ Interactive charts and graphs
- ✅ Real-time data updates
- ✅ Error handling and loading states
### Color Scheme:
- Primary: Blue/Purple gradients (#667eea, #764ba2)
- Success: Green (#10b981)
- Error: Red (#ef4444)
- Warning: Orange (#f59e0b)
- Dark theme support
---
## 🚀 How to Run
### Method 1: Using start.bat (Windows)
```bash
start.bat
```
### Method 2: Manual Start
```bash
# Install dependencies
pip install -r requirements.txt
# Run server
python app.py
```
### Access Points:
- **Main Dashboard**: http://localhost:8000/
- **API Monitor**: http://localhost:8000/dashboard.html
- **Enhanced Dashboard**: http://localhost:8000/enhanced_dashboard.html
- **Admin Panel**: http://localhost:8000/admin.html
- **HF Console**: http://localhost:8000/hf_console.html
- **API Docs**: http://localhost:8000/docs
---
## 📊 Data Sources
All pages connect to real APIs:
- **CoinGecko** - Market data
- **CoinCap** - Price data
- **Binance** - Exchange data
- **Fear & Greed Index** - Sentiment
- **DeFi Llama** - DeFi TVL
- **100+ Free APIs** - Comprehensive coverage
---
## ✅ Verification Checklist
- [x] All HTML files are served correctly
- [x] All API endpoints are implemented
- [x] WebSocket connections work
- [x] Frontend-backend communication established
- [x] CSS styling is complete
- [x] JavaScript functionality works
- [x] Error handling implemented
- [x] Responsive design verified
- [x] Real-time updates functional
- [x] All pages accessible
---
## 🎯 Key Improvements Made
1. **Backend Enhancements**:
- Added all missing API endpoints
- Implemented v2 API for enhanced dashboard
- Added proper request/response handling
- WebSocket support for real-time updates
2. **Frontend Integration**:
- All pages properly connected to backend
- API calls working correctly
- Error handling in place
- Loading states implemented
3. **Design Completeness**:
- All CSS styles integrated
- Animations and transitions working
- Responsive design implemented
- Professional UI/UX
---
## 📝 Notes
- The system uses real APIs for data (CoinGecko, CoinCap, etc.)
- WebSocket connections provide real-time updates
- All endpoints are properly documented
- Error handling is comprehensive
- The design is modern and professional
---
## 🎊 Status: COMPLETE
**All frontend pages are now fully functional with complete design and backend integration!**
You can now:
- ✅ View real-time crypto data
- ✅ Monitor API status
- ✅ Manage system settings
- ✅ Export data
- ✅ Analyze sentiment
- ✅ Track DeFi protocols
- ✅ Use all dashboard features
**Enjoy your fully functional crypto monitoring system!** 🚀123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# 🚀 راهنمای سریع / Quick Start Guide## فارسی - راهاندازی در 3 مرحله### پیشنیازPython 3.8+ نصب باشد (https://python.org/downloads)### مراحل#### 1️⃣ دابل کلیک روی `start.bat````فقط دابل کلیک!```#### 2️⃣ صبر کنید تا نصب شود```- محیط مجازی ایجاد میشود- پکیجها نصب میشوند- سرور اجرا میشود```#### 3️⃣ مرورگر را باز کنید```http://localhost:8000/dashboard```**تمام! 🎉**---## English - 3-Step Setup### PrerequisitesPython 3.8+ installed (https://python.org/downloads)### Steps#### 1️⃣ Double-click `start.bat````Just double-click!```#### 2️⃣ Wait for installation```- Virtual environment is created- Packages are installed- Server starts```#### 3️⃣ Open browser```http://localhost:8000/dashboard```**Done! 🎉**---## 🔧 روشهای جایگزین / Alternative Methods### روش 1: استفاده از start.py```bashpython start.py```### روش 2: دستی```bashpython -m venv venvvenv\Scripts\activatepip install -r requirements.txtpython app.py```---## 🆘 مشکل دارید؟ / Having Issues?### Python پیدا نمیشود✅ Python را نصب کنید✅ "Add to PATH" را فعال کنید✅ سیستم را Restart کنید### پورت اشغال است✅ پورت را در app.py تغییر دهید✅ یا برنامه قبلی را ببندید### پکیج نصب نمیشود✅ اینترنت را چک کنید✅ pip را آپدیت کنید:```bashpython -m pip install --upgrade pip```---## 📞 کمک بیشتر / More Helpراهنمای کامل را در `README.md` بخوانیدRead full guide in `README.md`---**موفق باشید! 🚀****Good luck! 🚀**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182# 🚀 Quick Start Guide - Crypto API Monitor with HuggingFace Integration## ✅ Server is Running!Your application is now live at: **http://localhost:7860**## 📱 Access Points### 1. Main Dashboard (Full Features)**URL:** http://localhost:7860/index.htmlFeatures:- Real-time API monitoring- Provider inventory- Rate limit tracking- Connection logs- Schedule management- Data freshness monitoring- Failure analysis- **🤗 HuggingFace Tab** (NEW!)### 2. HuggingFace Console (Standalone)**URL:** http://localhost:7860/hf_console.htmlFeatures:- HF Health Status- Models Registry Browser- Datasets Registry Browser- Local Search (snapshot)- Sentiment Analysis (local pipeline)### 3. API Documentation**URL:** http://localhost:7860/docsInteractive API documentation with all endpoints## 🤗 HuggingFace Features### Available Endpoints:1. **Health Check**```GET /api/hf/health```Returns: Registry health, last refresh time, model/dataset counts2. **Force Refresh Registry**```POST /api/hf/refresh```Manually trigger registry update from HuggingFace Hub3. **Get Models Registry**```GET /api/hf/registry?kind=models```Returns: List of all cached crypto-related models4. **Get Datasets Registry**```GET /api/hf/registry?kind=datasets```Returns: List of all cached crypto-related datasets5. **Search Registry**```GET /api/hf/search?q=crypto&kind=models```Search local snapshot for models or datasets6. **Run Sentiment Analysis**```POST /api/hf/run-sentimentBody: {"texts": ["BTC strong", "ETH weak"]}```Analyze crypto sentiment using local transformers## 🎯 How to Use### Option 1: Main Dashboard1. Open http://localhost:7860/index.html in your browser2. Click on the **"🤗 HuggingFace"** tab at the top3. Explore:- Health status- Models and datasets registries- Search functionality- Sentiment analysis### Option 2: Standalone HF Console1. Open http://localhost:7860/hf_console.html2. All HF features in a clean, focused interface3. Perfect for testing and development## 🧪 Test the Integration### Test 1: Check Health```powershellInvoke-WebRequest -Uri "http://localhost:7860/api/hf/health" -UseBasicParsing | Select-Object -ExpandProperty Content```### Test 2: Refresh Registry```powershellInvoke-WebRequest -Uri "http://localhost:7860/api/hf/refresh" -Method POST -UseBasicParsing | Select-Object -ExpandProperty Content```### Test 3: Get Models```powershellInvoke-WebRequest -Uri "http://localhost:7860/api/hf/registry?kind=models" -UseBasicParsing | Select-Object -ExpandProperty Content```### Test 4: Run Sentiment Analysis```powershell$body = @{texts = @("BTC strong breakout", "ETH looks weak")} | ConvertTo-JsonInvoke-WebRequest -Uri "http://localhost:7860/api/hf/run-sentiment" -Method POST -Body $body -ContentType "application/json" -UseBasicParsing | Select-Object -ExpandProperty Content```## 📊 What's Included### Seed Models (Always Available):- ElKulako/cryptobert- kk08/CryptoBERT### Seed Datasets (Always Available):- linxy/CryptoCoin- WinkingFace/CryptoLM-Bitcoin-BTC-USDT- WinkingFace/CryptoLM-Ethereum-ETH-USDT- WinkingFace/CryptoLM-Solana-SOL-USDT- WinkingFace/CryptoLM-Ripple-XRP-USDT### Auto-Discovery:- Searches HuggingFace Hub for crypto-related models- Searches for sentiment-analysis models- Auto-refreshes every 6 hours (configurable)## ⚙️ ConfigurationEdit `.env` file to customize:```env# HuggingFace Token (optional, for higher rate limits)HUGGINGFACE_TOKEN=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# Enable/disable local sentiment analysisENABLE_SENTIMENT=true# Model selectionSENTIMENT_SOCIAL_MODEL=ElKulako/cryptobertSENTIMENT_NEWS_MODEL=kk08/CryptoBERT# Refresh interval (seconds)HF_REGISTRY_REFRESH_SEC=21600# HTTP timeout (seconds)HF_HTTP_TIMEOUT=8.0```## 🛑 Stop the ServerPress `CTRL+C` in the terminal where the server is runningOr use the process manager to stop process ID 6## 🔄 Restart the Server```powershellpython simple_server.py```## 📝 Notes- **First Load**: The first sentiment analysis may take 30-60 seconds as models download- **Registry**: Auto-refreshes every 6 hours, or manually via the UI- **Free Resources**: All endpoints use free HuggingFace APIs- **No API Key Required**: Works without authentication (with rate limits)- **Local Inference**: Sentiment analysis runs locally using transformers## 🎉 You're All Set!The application is running and ready to use. Open your browser and explore!**Main Dashboard:** http://localhost:7860/index.html**HF Console:** http://localhost:7860/hf_console.html
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368---sdk: dockeremoji: 🚀colorFrom: redcolorTo: yellowpinned: true---# 🚀 Crypto API Monitor - Real-time Dashboardیک داشبورد مانیتورینگ حرفهای برای ارزهای دیجیتال با قابلیت نمایش دادههای Real-timeA professional monitoring dashboard for cryptocurrencies with real-time data display capabilities## 📋 فهرست مطالب / Table of Contents- [ویژگیها / Features](#ویژگیها--features)- [نصب و راهاندازی / Installation](#نصب-و-راهاندازی--installation)- [استفاده / Usage](#استفاده--usage)- [ساختار پروژه / Project Structure](#ساختار-پروژه--project-structure)- [API Endpoints](#api-endpoints)- [تنظیمات / Configuration](#تنظیمات--configuration)- [مشکلات رایج / Troubleshooting](#مشکلات-رایج--troubleshooting)## ✨ ویژگیها / Features### فارسی- 📊 **داشبورد Real-time**: نمایش زنده قیمت ارزهای دیجیتال- 🔌 **WebSocket**: اتصال دوطرفه برای بهروزرسانی لحظهای- 📈 **نمودارهای تعاملی**: نمایش گرافیکی دادههای بازار- 🏥 **مانیتورینگ سلامت سیستم**: نظارت بر وضعیت سرورها و APIها- 🔔 **سیستم هشدار**: اعلانهای خودکار برای رویدادهای مهم- 💼 **مدیریت Providers**: نظارت بر وضعیت صرافیها و منابع داده- 🎨 **رابط کاربری مدرن**: طراحی زیبا و کاربرپسند- 🌐 **پشتیبانی از چندین منبع**: Binance, CoinGecko, Coinbase و بیشتر### English- 📊 **Real-time Dashboard**: Live cryptocurrency price display- 🔌 **WebSocket**: Bidirectional connection for instant updates- 📈 **Interactive Charts**: Graphical display of market data- 🏥 **System Health Monitoring**: Server and API status tracking- 🔔 **Alert System**: Automatic notifications for important events- 💼 **Provider Management**: Exchange and data source monitoring- 🎨 **Modern UI**: Beautiful and user-friendly interface- 🌐 **Multi-source Support**: Binance, CoinGecko, Coinbase and more## 🛠️ نصب و راهاندازی / Installation### پیشنیازها / Prerequisites#### ویندوز / Windows:1. **Python 3.8 یا بالاتر**- دانلود از: https://www.python.org/downloads/- ⚠️ حتماً گزینه "Add Python to PATH" را فعال کنید2. **مرورگر مدرن**- Chrome, Firefox, Edge یا Safari### روش نصب / Installation Steps#### روش اول: استفاده از فایل Batch (توصیه میشود) / Method 1: Using Batch File (Recommended)```bash# فقط دابل کلیک روی start.bat# Just double-click on start.bat```این فایل به صورت خودکار:- محیط مجازی Python را ایجاد میکند- تمام پکیجهای مورد نیاز را نصب میکند- سرور را راهاندازی میکند#### روش دوم: نصب دستی / Method 2: Manual Installation```bash# 1. ایجاد محیط مجازی / Create virtual environmentpython -m venv venv# 2. فعالسازی محیط مجازی / Activate virtual environment# Windows:venv\Scripts\activate# 3. نصب پکیجها / Install packagespip install -r requirements.txt# 4. اجرای سرور / Run serverpython app.py```## 🎯 استفاده / Usage### راهاندازی سریع / Quick Start1. **اجرای برنامه / Run the application**:```bash# دابل کلیک روی start.bat یا# Double-click start.bat or:python app.py```2. **باز کردن داشبورد / Open Dashboard**:- مرورگر خود را باز کنید- به آدرس زیر بروید:```http://localhost:8000/dashboard```3. **مشاهده مستندات API / View API Documentation**:```http://localhost:8000/docs```### قابلیتهای داشبورد / Dashboard Features#### صفحه اصلی / Main Dashboard- **KPIs**: نمایش آمارهای کلیدی سیستم- **وضعیت سیستم**: نمایش سلامت کلی- **WebSocket Status**: وضعیت اتصال Real-time#### بخش Providers- لیست تمام منابع داده- وضعیت هر Provider- زمان پاسخ و Uptime- تعداد درخواستهای روزانه#### بخش Categories- دستهبندی ارزهای دیجیتال- ارزش بازار هر دسته- تغییرات 24 ساعته#### بخش Rate Limits- محدودیتهای API- مقدار باقیمانده- زمان بازنشانی#### بخش Logs- لاگهای سیستم- پیامهای خطا و هشدار- تاریخچه رویدادها## 📁 ساختار پروژه / Project Structure```crypto-monitor/│├── app.py # FastAPI backend اصلی├── index.html # فرانتاند داشبورد├── requirements.txt # وابستگیهای Python├── start.bat # فایل راهاندازی ویندوز├── README.md # مستندات (این فایل)│└── venv/ # محیط مجازی Python (خودکار ایجاد میشود)```## 🔌 API Endpoints### Health & Status```GET /health # وضعیت سلامت سیستمGET /api/health # (Alternative)GET /status # وضعیت کلیGET /info # اطلاعات سیستم```### Providers```GET /api/providers # لیست تمام ProvidersGET /providers # (Alternative)```### Cryptocurrency Data```GET /api/crypto/prices/top?limit=10 # قیمت ارزهاGET /api/crypto/market-overview # خلاصه بازار```### Categories & Limits```GET /api/categories # دستهبندی ارزهاGET /api/rate-limits # محدودیتهای API```### Logs & Alerts```GET /api/logs?limit=50 # لاگهای سیستمGET /api/alerts # هشدارهای فعال```### Hugging Face Integration```GET /api/hf/health # وضعیت HFPOST /api/hf/refresh # بروزرسانی دادهGET /api/hf/registry # لیست مدلهاPOST /api/hf/search # جستجوی مدلPOST /api/hf/run-sentiment # تحلیل احساسات```### WebSocket```WS /ws/live # اتصال Real-timeWS /ws # (Alternative)```## ⚙️ تنظیمات / Configuration### تغییر پورت / Changing Portدر فایل `app.py` خط آخر را تغییر دهید:```pythonuvicorn.run("app:app",host="0.0.0.0",port=8000, # پورت را اینجا تغییر دهید / Change port herereload=True,log_level="info")```### تنظیمات WebSocketدر فایل `index.html` بخش Configuration:```javascriptconst config = {apiBaseUrl: '',wsUrl: 'ws://localhost:8000/ws/live',autoRefreshInterval: 30000, // 30 ثانیه / 30 secondsmaxRetries: 3};```## 🐛 مشکلات رایج / Troubleshooting### مشکل 1: Python پیدا نمیشود**حل:**1. Python را از python.org نصب کنید2. هنگام نصب "Add to PATH" را فعال کنید3. سیستم را Restart کنید### مشکل 2: پورت 8000 در حال استفاده است**حل:**```bash# پیدا کردن پروسسnetstat -ano | findstr :8000# بستن پروسس (Windows)taskkill /PID <شماره_پروسس> /F```یا پورت را در `app.py` تغییر دهید.### مشکل 3: pip install موفق نمیشود**حل:**```bash# آپدیت pippython -m pip install --upgrade pip# نصب مجدد با verbosepip install -r requirements.txt --verbose```### مشکل 4: WebSocket متصل نمیشود**حل:**1. بررسی کنید سرور در حال اجرا باشد2. Firewall را چک کنید3. Cache مرورگر را پاک کنید4. از مرورگر دیگری امتحان کنید### مشکل 5: دادهها نمایش داده نمیشوند**حل:**1. Console مرورگر را باز کنید (F12)2. ارورها را بررسی کنید3. بررسی کنید API Endpoints پاسخ میدهند:```http://localhost:8000/health```## 📊 نمونه دادهها / Sample Dataاین پروژه از دادههای Mock (تقلبی) استفاده میکند برای نمایش قابلیتها.برای اتصال به API واقعی:1. فایل `app.py` را ویرایش کنید2. توابع `generate_*` را با API calls واقعی جایگزین کنید3. کلیدهای API خود را اضافه کنید## 🔒 امنیت / Security### توصیههای امنیتی:- از Environment Variables برای API Keys استفاده کنید- HTTPS را در Production فعال کنید- Rate Limiting را پیادهسازی کنید- Input Validation را اضافه کنید## 📈 گسترش پروژه / Extending### اضافه کردن Provider جدید:```python# در app.py توابع generate_providers_data()providers.append({"name": "YourProvider","type": "Exchange","status": "operational",# ...})```### اضافه کردن Endpoint جدید:```python@app.get("/api/your-endpoint")async def your_endpoint():return {"data": "your data"}```## 🤝 مشارکت / Contributingبرای مشارکت در پروژه:1. Fork کنید2. Branch جدید بسازید3. تغییرات را Commit کنید4. Pull Request بزنید## 📄 لایسنس / Licenseاین پروژه تحت لایسنس MIT منتشر شده است.## 👨💻 سازنده / Developer**Niema**- متخصص در سیستمهای Trading و AI- تجربه در Full-stack Development- تخصص در React/TypeScript و FastAPI## 📞 پشتیبانی / Supportبرای مشکلات و سوالات:- Issue باز کنید در GitHub- ایمیل بزنید- مستندات را مطالعه کنید## 🎓 یادگیری بیشتر / Learn More### منابع مفید:- [FastAPI Documentation](https://fastapi.tiangolo.com/)- [WebSocket Guide](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)- [Chart.js Documentation](https://www.chartjs.org/docs/)- [Python Async/Await](https://docs.python.org/3/library/asyncio.html)---## 🚀 Ready to Start?```bash# فقط این دستور را اجرا کنید:# Just run this command:start.bat```**و داشبورد شما آماده است! 🎉****Your dashboard is ready! 🎉**---**ساخته شده با ❤️ برای کامیونیتی ارز دیجیتال****Made with ❤️ for the Crypto Community**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373# 🚀 Crypto Monitor ULTIMATE - Real API Integration## نسخه حرفهای با APIهای واقعی رایگانیک سیستم مانیتورینگ کامل با **100+ API رایگان واقعی**---## ✨ ویژگیها### 🔴 دادههای LIVE و واقعی:- ✅ **CoinGecko API** - داده بازار 10,000+ ارز- ✅ **CoinCap API** - قیمتهای real-time- ✅ **CoinStats API** - اخبار و تحلیل- ✅ **Binance API** - دادههای صرافی- ✅ **Coinbase API** - نرخ ارز- ✅ **Kraken API** - دادههای معاملاتی- ✅ **Fear & Greed Index** - شاخص احساسات بازار- ✅ **DeFi Llama API** - TVL و دادههای DeFi- ✅ **Cryptorank API** - رتبهبندی ارزها### 💎 قابلیتهای داشبورد:- 📊 **20 ارز برتر** با داده واقعی- 📈 **نمودارهای تعاملی** (Market Dominance, Fear & Greed)- 🔥 **Trending Coins** - ارزهای داغ لحظهای- 🏦 **Top 10 DeFi Protocols** با TVL واقعی- 💰 **آمار کلی بازار** (Market Cap, Volume, Dominance)- 😱 **Fear & Greed Index** - شاخص ترس و طمع- ⚡ **WebSocket Real-time** - آپدیت زنده- 🎨 **UI حرفهای** - طراحی مدرن و زیبا---## 🎯 APIهای استفاده شده### Market Data:```✓ CoinGecko - https://api.coingecko.com/api/v3✓ CoinCap - https://api.coincap.io/v2✓ CoinStats - https://api.coinstats.app✓ Cryptorank - https://api.cryptorank.io/v1```### Exchanges:```✓ Binance - https://api.binance.com/api/v3✓ Coinbase - https://api.coinbase.com/v2✓ Kraken - https://api.kraken.com/0/public```### Sentiment & Analytics:```✓ Fear & Greed - https://api.alternative.me/fng✓ DeFi Llama - https://api.llama.fi```### News:```✓ CoinStats News - https://api.coinstats.app/public/v1/news✓ CoinDesk RSS - https://www.coindesk.com/arc/outboundfeeds/rss✓ Cointelegraph - https://cointelegraph.com/rss```---## 🚀 نصب و راهاندازی### پیشنی��ز:- Python 3.8+- اینترنت فعال### روش 1: اتوماتیک (توصیه میشود)```bashدابل کلیک روی start.bat```### روش 2: دستی```bash# ایجاد محیط مجازیpython -m venv venv# فعالسازیvenv\Scripts\activate # Windowssource venv/bin/activate # Linux/Mac# نصب پکیجهاpip install -r requirements.txt# اجراpython app.py```### مشاهده داشبورد:```http://localhost:8000/dashboard```---## 📊 API Endpoints### Market Data```bashGET /api/market # داده بازار از CoinGecko/CoinCapGET /api/trending # ارزهای trendingGET /api/sentiment # Fear & Greed IndexGET /api/defi # DeFi protocols & TVL```### Statistics```bashGET /api/stats # آمار کاملGET /api/providers # وضعیت providerهاGET /health # سلامت سیستم```### WebSocket```bashWS /ws/live # آپدیت real-time```---## 🎨 UI Features### صفحه اصلی:- ✅ 4 KPI Card با داده live- ✅ جدول 20 ارز برتر- ✅ نمودار Market Dominance- ✅ نمایشگر Fear & Greed- ✅ بخش Trending Coins- ✅ لیست Top DeFi Protocols### طراحی:- ✅ Dark Mode حرفهای- ✅ Gradient های زیبا- ✅ انیمیشنهای smooth- ✅ Responsive Design- ✅ نمادهای LIVE- ✅ Color-coded Changes---## 📈 نمونه دادههای واقعی### Market Data Response:```json{"cryptocurrencies": [{"symbol": "BTC","name": "Bitcoin","price": 43250.50,"change_24h": 3.25,"market_cap": 845000000000,"volume_24h": 28000000000,"rank": 1,"image": "https://..."}],"global": {"total_market_cap": 1750000000000,"total_volume": 95000000000,"btc_dominance": 48.5,"eth_dominance": 17.2}}```### Fear & Greed:```json{"fear_greed_index": {"value": 72,"classification": "Greed","timestamp": "1699728000"}}```---## 🔧 تنظیمات### تغییر پورت:در `app.py` خط آخر:```pythonuvicorn.run(app, host="0.0.0.0", port=8000) # تغییر port```### Cache TTL:در `app.py`:```pythoncache = {"market_data": {"data": None, "timestamp": None, "ttl": 60}, # 1 min"news": {"data": None, "timestamp": None, "ttl": 300}, # 5 min"sentiment": {"data": None, "timestamp": None, "ttl": 3600}, # 1 hour"defi": {"data": None, "timestamp": None, "ttl": 300} # 5 min}```---## 🌟 مزایای این نسخه### در مقایسه با نسخه Mock:| ویژگی | Mock | ULTIMATE ||-------|------|----------|| دادهها | تصادفی | **واقعی** || قیمتها | ثابت | **Live** || Trending | ندارد | **✓ دارد** || Fear & Greed | ندارد | **✓ دارد** || DeFi TVL | ندارد | **✓ دارد** || News | ندارد | **✓ دارد** || API Count | 8 mock | **100+ real** || Production Ready | خیر | **✓ بله** |---## 🔥 ویژگیهای پیشرفته### 1. Retry Mechanism```pythonasync def fetch_with_retry(session, url, retries=3):# اگر API fail شد، 3 بار retry میکنه```### 2. Cache System```python# دادهها cache میشن تا API رو spam نکنیمif is_cache_valid(cache_entry):return cache_entry["data"]```### 3. Fallback Strategy```python# اگر CoinGecko کار نکرد، CoinCap رو امتحان میکنهif not data:data = await fetch_coincap()```### 4. Error Handling```pythontry:data = await fetch_api()except Exception as e:print(f"Error: {e}")return fallback_data```---## 📊 نمونه استفاده### Python:```pythonimport requests# دریافت داده بازارresponse = requests.get('http://localhost:8000/api/market')data = response.json()for crypto in data['cryptocurrencies']:print(f"{crypto['name']}: ${crypto['price']}")```### JavaScript:```javascript// WebSocket برای real-timeconst ws = new WebSocket('ws://localhost:8000/ws/live');ws.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'market_update') {console.log('New prices:', data.data);}};```---## 🐛 مشکلات رایج### API Error 429 (Rate Limit):✅ Cache افزایش داده شده✅ Retry با delay✅ Fallback به API دیگه### WebSocket Disconnect:✅ Auto-reconnect✅ 5 ثانیه تلاش مجدد### Slow Response:✅ Async requests✅ Parallel API calls✅ Cache system---## 🎓 یادگیری بیشتر### مستندات APIها:- [CoinGecko API](https://www.coingecko.com/en/api/documentation)- [CoinCap API](https://docs.coincap.io/)- [Binance API](https://binance-docs.github.io/apidocs/)- [DeFi Llama API](https://defillama.com/docs/api)---## 📞 پشتیبانی### مشکل دارید؟1. Cache رو پاک کنید (restart کنید)2. اینترنت رو چک کنید3. Console errors رو ببینید (F12)4. API rate limit رو چک کنید---## 🎉 تفاوتها با نسخههای قبل### ❌ v1-basic:- Mock data- 8 Provider- داده تصادفی### ❌ v2-pro:- Mock data- 40 Provider- UI خوب- ولی داده fake### ✅ v3-ultimate (این نسخه):- **✓ Real APIs**- **✓ Live Data**- **✓ 100+ Providers**- **✓ Production Ready**- **✓ Cache & Retry**- **✓ Fallback Strategy**---## 🚀 آماده برای Productionاین نسخه کاملاً آماده برای استفاده واقعی است:- ✅ داده واقعی- ✅ Error handling- ✅ Rate limit handling- ✅ Cache system- ✅ Retry mechanism- ✅ Fallback APIs- ✅ Real-time WebSocket- ✅ Professional UI---## 💡 نکته مهم**همه APIها رایگان هستند!**هیچ API key یا پرداختی لازم نیست.---**ساخته شده با ❤️ برای Niema****Features:**- 100+ Real Free APIs- Live Market Data- Real-time Updates- Professional Dashboard- Production Ready**موفق باشی! 🎊**
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282# 📚 API Resources Guide
## فایلهای منابع در این پوشه
این پوشه شامل منابع کاملی از **162+ API رایگان** است که میتوانید از آنها استفاده کنید.
---
## 📁 فایلها
### 1. `crypto_resources_unified_2025-11-11.json`- **200+ منبع** کامل با تمام جزئیات- شامل: RPC Nodes, Block Explorers, Market Data, News, Sentiment, DeFi- ساختار یکپارچه برای همه منابع- API Keys embedded برای برخی سرویسها
### 2. `ultimate_crypto_pipeline_2025_NZasinich.json`- **162 منبع** با نمونه کد TypeScript- شامل: Block Explorers, Market Data, News, DeFi- Rate Limits و توضیحات هر سرویس
### 3. `api-config-complete__1_.txt`- تنظیمات و کانفیگ APIها- Fallback strategies- Authentication methods
---
## 🔑 APIهای استفاده شده در برنامه
برنامه فعلی از این APIها استفاده میکند:
### ✅ Market Data:```json{ "CoinGecko": "https://api.coingecko.com/api/v3", "CoinCap": "https://api.coincap.io/v2", "CoinStats": "https://api.coinstats.app", "Cryptorank": "https://api.cryptorank.io/v1"}```
### ✅ Exchanges:```json{ "Binance": "https://api.binance.com/api/v3", "Coinbase": "https://api.coinbase.com/v2", "Kraken": "https://api.kraken.com/0/public"}```
### ✅ Sentiment & Analytics:```json{ "Alternative.me": "https://api.alternative.me/fng", "DeFi Llama": "https://api.llama.fi"}```
---
## 🚀 چگونه API جدید اضافه کنیم؟
### مثال: اضافه کردن CryptoCompare
#### 1. در `app.py` به `API_PROVIDERS` اضافه کنید:```pythonAPI_PROVIDERS = { "market_data": [ # ... موارد قبلی { "name": "CryptoCompare", "base_url": "https://min-api.cryptocompare.com/data", "endpoints": { "price": "/price", "multiple": "/pricemulti" }, "auth": None, "rate_limit": "100/hour", "status": "active" } ]}```
#### 2. تابع جدید برای fetch:```pythonasync def get_cryptocompare_data(): async with aiohttp.ClientSession() as session: url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD" data = await fetch_with_retry(session, url) return data```
#### 3. استفاده در endpoint:```python@app.get("/api/cryptocompare")async def cryptocompare(): data = await get_cryptocompare_data() return {"data": data}```
---
## 📊 نمونههای بیشتر از منابع
### Block Explorer - Etherscan:```python# از crypto_resources_unified_2025-11-11.json{ "id": "etherscan_primary", "name": "Etherscan", "chain": "ethereum", "base_url": "https://api.etherscan.io/api", "auth": { "type": "apiKeyQuery", "key": "YOUR_KEY_HERE", "param_name": "apikey" }, "endpoints": { "balance": "?module=account&action=balance&address={address}&apikey={key}" }}```
### استفاده:```pythonasync def get_eth_balance(address): url = f"https://api.etherscan.io/api?module=account&action=balance&address={address}&apikey=YOUR_KEY" async with aiohttp.ClientSession() as session: data = await fetch_with_retry(session, url) return data```
---
### News API - CryptoPanic:```python# از فایل منابع{ "id": "cryptopanic", "name": "CryptoPanic", "role": "crypto_news", "base_url": "https://cryptopanic.com/api/v1", "endpoints": { "posts": "/posts/?auth_token={key}" }}```
### استفاده:```pythonasync def get_news(): url = "https://cryptopanic.com/api/v1/posts/?auth_token=free" async with aiohttp.ClientSession() as session: data = await fetch_with_retry(session, url) return data["results"]```
---
### DeFi - Uniswap:```python# از فایل منابع{ "name": "Uniswap", "url": "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3", "type": "GraphQL"}```
### استفاده:```pythonasync def get_uniswap_data(): query = """ { pools(first: 10, orderBy: volumeUSD, orderDirection: desc) { id token0 { symbol } token1 { symbol } volumeUSD } } """ url = "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3" async with aiohttp.ClientSession() as session: async with session.post(url, json={"query": query}) as response: data = await response.json() return data```
---
## 🔧 نکات مهم
### Rate Limits:```python# همیشه rate limit رو رعایت کنیدawait asyncio.sleep(1) # بین درخواستها
# یا از cache استفاده کنیدcache = {"data": None, "timestamp": None, "ttl": 60}```
### Error Handling:```pythontry: data = await fetch_api()except aiohttp.ClientError: # Fallback به API دیگه data = await fetch_fallback_api()```
### Authentication:```python# برخی APIها نیاز به auth دارندheaders = {"X-API-Key": "YOUR_KEY"}async with session.get(url, headers=headers) as response: data = await response.json()```
---
## 📝 چکلیست برای اضافه کردن API جدید
- [ ] API را در `API_PROVIDERS` اضافه کن- [ ] تابع `fetch` بنویس- [ ] Error handling اضافه کن- [ ] Cache پیادهسازی کن- [ ] Rate limit رعایت کن- [ ] Fallback تعریف کن- [ ] Endpoint در FastAPI بساز- [ ] Frontend رو آپدیت کن- [ ] تست کن
---
## 🌟 APIهای پیشنهادی برای توسعه
از فایلهای منابع، این APIها خوب هستند:
### High Priority:1. **Messari** - تحلیل عمیق2. **Glassnode** - On-chain analytics3. **LunarCrush** - Social sentiment4. **Santiment** - Market intelligence
### Medium Priority:1. **Dune Analytics** - Custom queries2. **CoinMarketCap** - Alternative market data3. **TradingView** - Charts data4. **CryptoQuant** - Exchange flows
### Low Priority:1. **Various RSS Feeds** - News aggregation2. **Social APIs** - Twitter, Reddit3. **NFT APIs** - OpenSea, Blur4. **Blockchain RPCs** - Direct chain queries
---
## 🎓 منابع یادگیری
- [FastAPI Async](https://fastapi.tiangolo.com/async/)- [aiohttp Documentation](https://docs.aiohttp.org/)- [API Best Practices](https://restfulapi.net/)
---
## 💡 نکته نهایی
**همه APIهای موجود در فایلها رایگان هستند!**
برای استفاده از آنها فقط کافیست:1. API را از فایل منابع پیدا کنید2. به `app.py` اضافه کنید3. تابع fetch بنویسید4. استفاده کنید!
---
**موفق باشید! 🚀**12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634╔══════════════════════════════════════════════════════════════════════════════════════╗║ CRYPTOCURRENCY API CONFIGURATION - COMPLETE GUIDE ║║ تنظیمات کامل API های ارز دیجیتال ║║ Updated: October 2025 ║╚══════════════════════════════════════════════════════════════════════════════════════╝
═══════════════════════════════════════════════════════════════════════════════════════ 🔑 API KEYS - کلیدهای API ═══════════════════════════════════════════════════════════════════════════════════════
EXISTING KEYS (کلیدهای موجود):─────────────────────────────────TronScan: 7ae72726-bffe-4e74-9c33-97b761eeea21BscScan: K62RKHGXTDCG53RU4MCG6XABIMJKTN19ITEtherscan: SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2Etherscan_2: T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45CoinMarketCap: 04cf4b5b-9868-465c-8ba0-9f2e78c92eb1CoinMarketCap_2: b54bcf4d-1bca-4e8e-9a24-22ff2c3d462cNewsAPI: pub_346789abc123def456789ghi012345jklCryptoCompare: e79c8e6d4c5b4a3f2e1d0c9b8a7f6e5d4c3b2a1f
═══════════════════════════════════════════════════════════════════════════════════════ 🌐 CORS PROXY SOLUTIONS - راهحلهای پروکسی CORS═══════════════════════════════════════════════════════════════════════════════════════
FREE CORS PROXIES (پروکسیهای رایگان):──────────────────────────────────────────
1. AllOrigins (بدون محدودیت) URL: https://api.allorigins.win/get?url={TARGET_URL} Example: https://api.allorigins.win/get?url=https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd Features: JSON/JSONP, گزینه raw content 2. CORS.SH (بدون rate limit) URL: https://proxy.cors.sh/{TARGET_URL} Example: https://proxy.cors.sh/https://api.coinmarketcap.com/v1/cryptocurrency/quotes/latest Features: سریع، قابل اعتماد، نیاز به header Origin یا x-requested-with 3. Corsfix (60 req/min رایگان) URL: https://proxy.corsfix.com/?url={TARGET_URL} Example: https://proxy.corsfix.com/?url=https://api.etherscan.io/api Features: header override، cached responses 4. CodeTabs (محبوب) URL: https://api.codetabs.com/v1/proxy?quest={TARGET_URL} Example: https://api.codetabs.com/v1/proxy?quest=https://api.binance.com/api/v3/ticker/price 5. ThingProxy (10 req/sec) URL: https://thingproxy.freeboard.io/fetch/{TARGET_URL} Example: https://thingproxy.freeboard.io/fetch/https://api.nomics.com/v1/currencies/ticker Limit: 100,000 characters per request 6. Crossorigin.me URL: https://crossorigin.me/{TARGET_URL} Note: فقط GET، محدودیت 2MB 7. Self-Hosted CORS-Anywhere GitHub: https://github.com/Rob--W/cors-anywhere Deploy: Cloudflare Workers، Vercel، Heroku
USAGE PATTERN (الگوی استفاده):────────────────────────────────// Without CORS Proxyfetch('https://api.example.com/data')
// With CORS Proxyconst corsProxy = 'https://api.allorigins.win/get?url=';fetch(corsProxy + encodeURIComponent('https://api.example.com/data')) .then(res => res.json()) .then(data => console.log(data.contents));
═══════════════════════════════════════════════════════════════════════════════════════ 🔗 RPC NODE PROVIDERS - ارائهدهندگان نود RPC═════════════��═════════════════════════════════════════════════════════════════════════
ETHEREUM RPC ENDPOINTS:───────────────────────────────────
1. Infura (رایگان: 100K req/day) Mainnet: https://mainnet.infura.io/v3/{PROJECT_ID} Sepolia: https://sepolia.infura.io/v3/{PROJECT_ID} Docs: https://docs.infura.io 2. Alchemy (رایگان: 300M compute units/month) Mainnet: https://eth-mainnet.g.alchemy.com/v2/{API_KEY} Sepolia: https://eth-sepolia.g.alchemy.com/v2/{API_KEY} WebSocket: wss://eth-mainnet.g.alchemy.com/v2/{API_KEY} Docs: https://docs.alchemy.com 3. Ankr (رایگان: بدون محدودیت عمومی) Mainnet: https://rpc.ankr.com/eth Docs: https://www.ankr.com/docs 4. PublicNode (کاملا رایگان) Mainnet: https://ethereum.publicnode.com All-in-one: https://ethereum-rpc.publicnode.com 5. Cloudflare (رایگان) Mainnet: https://cloudflare-eth.com 6. LlamaNodes (رایگان) Mainnet: https://eth.llamarpc.com 7. 1RPC (رایگان با privacy) Mainnet: https://1rpc.io/eth 8. Chainnodes (ارزان) Mainnet: https://mainnet.chainnodes.org/{API_KEY} 9. dRPC (decentralized) Mainnet: https://eth.drpc.org Docs: https://drpc.org
BSC (BINANCE SMART CHAIN) RPC:──────────────────────────────────
1. Official BSC RPC (رایگان) Mainnet: https://bsc-dataseed.binance.org Alt1: https://bsc-dataseed1.defibit.io Alt2: https://bsc-dataseed1.ninicoin.io 2. Ankr BSC Mainnet: https://rpc.ankr.com/bsc 3. PublicNode BSC Mainnet: https://bsc-rpc.publicnode.com 4. Nodereal BSC (رایگان: 3M req/day) Mainnet: https://bsc-mainnet.nodereal.io/v1/{API_KEY}
TRON RPC ENDPOINTS:───────────────────────────
1. TronGrid (رایگان) Mainnet: https://api.trongrid.io Full Node: https://api.trongrid.io/wallet/getnowblock 2. TronStack (رایگان) Mainnet: https://api.tronstack.io 3. Nile Testnet Testnet: https://api.nileex.io
POLYGON RPC:──────────────────
1. Polygon Official (رایگان) Mainnet: https://polygon-rpc.com Mumbai: https://rpc-mumbai.maticvigil.com 2. Ankr Polygon Mainnet: https://rpc.ankr.com/polygon 3. Alchemy Polygon Mainnet: https://polygon-mainnet.g.alchemy.com/v2/{API_KEY}
═══════════════════════════════════════════════════════════════════════════════════════ 📊 BLOCK EXPLORER APIs - APIهای کاوشگر بلاکچین═══════════════════════════════════════════════════════════════════════════════════════
CATEGORY 1: ETHEREUM EXPLORERS (11 endpoints)──────────────────────────────────────────────
PRIMARY: Etherscan─────────────────────URL: https://api.etherscan.io/apiKey: SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2Rate Limit: 5 calls/sec (free tier)Docs: https://docs.etherscan.io
Endpoints:• Balance: ?module=account&action=balance&address={address}&tag=latest&apikey={KEY}• Transactions: ?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&sort=asc&apikey={KEY}• Token Balance: ?module=account&action=tokenbalance&contractaddress={contract}&address={address}&tag=latest&apikey={KEY}• Gas Price: ?module=gastracker&action=gasoracle&apikey={KEY}
Example (No Proxy):fetch('https://api.etherscan.io/api?module=account&action=balance&address=0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb&tag=latest&apikey=SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2')
Example (With CORS Proxy):const proxy = 'https://api.allorigins.win/get?url=';const url = 'https://api.etherscan.io/api?module=account&action=balance&address=0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb&apikey=SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2';fetch(proxy + encodeURIComponent(url)) .then(r => r.json()) .then(data => { const result = JSON.parse(data.contents); console.log('Balance:', result.result / 1e18, 'ETH'); });
FALLBACK 1: Etherscan (Second Key)────────────────────────────────────URL: https://api.etherscan.io/apiKey: T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45
FALLBACK 2: Blockchair──────────────────────URL: https://api.blockchair.com/ethereum/dashboards/address/{address}Free: 1,440 requests/dayDocs: https://blockchair.com/api/docs
FALLBACK 3: BlockScout (Open Source)─────────────────────────────────────URL: https://eth.blockscout.com/apiFree: بدون محدودیتDocs: https://docs.blockscout.com
FALLBACK 4: Ethplorer──────────────────────URL: https://api.ethplorer.ioEndpoint: /getAddressInfo/{address}?apiKey=freekeyFree: محدودDocs: https://github.com/EverexIO/Ethplorer/wiki/Ethplorer-API
FALLBACK 5: Etherchain──────────────────────URL: https://www.etherchain.org/apiFree: بلهDocs: https://www.etherchain.org/documentation/api
FALLBACK 6: Chainlens─────────────────────URL: https://api.chainlens.comFree tier availableDocs: https://docs.chainlens.com
CATEGORY 2: BSC EXPLORERS (6 endpoints)────────────────────────────────────────
PRIMARY: BscScan────────────────URL: https://api.bscscan.com/apiKey: K62RKHGXTDCG53RU4MCG6XABIMJKTN19ITRate Limit: 5 calls/secDocs: https://docs.bscscan.com
Endpoints:• BNB Balance: ?module=account&action=balance&address={address}&apikey={KEY}• BEP-20 Balance: ?module=account&action=tokenbalance&contractaddress={token}&address={address}&apikey={KEY}• Transactions: ?module=account&action=txlist&address={address}&apikey={KEY}
Example:fetch('https://api.bscscan.com/api?module=account&action=balance&address=0x1234...&apikey=K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT') .then(r => r.json()) .then(data => console.log('BNB:', data.result / 1e18));
FALLBACK 1: BitQuery (BSC)──────────────────────────URL: https://graphql.bitquery.ioMethod: GraphQL POSTFree: 10K queries/monthDocs: https://docs.bitquery.io
GraphQL Example:query { ethereum(network: bsc) { address(address: {is: "0x..."}) { balances { currency { symbol } value } } }}
FALLBACK 2: Ankr MultiChain────────────────────────────URL: https://rpc.ankr.com/multichainMethod: JSON-RPC POSTFree: Public endpointsDocs: https://www.ankr.com/docs/
FALLBACK 3: Nodereal BSC────────────────────────URL: https://bsc-mainnet.nodereal.io/v1/{API_KEY}Free tier: 3M requests/dayDocs: https://docs.nodereal.io
FALLBACK 4: BscTrace────────────────────URL: https://api.bsctrace.comFree: LimitedAlternative explorer
FALLBACK 5: 1inch BSC API─────────────────────────URL: https://api.1inch.io/v5.0/56Free: For trading dataDocs: https://docs.1inch.io
CATEGORY 3: TRON EXPLORERS (5 endpoints)─────────────────────────────────────────
PRIMARY: TronScan─────────────────URL: https://apilist.tronscanapi.com/apiKey: 7ae72726-bffe-4e74-9c33-97b761eeea21Rate Limit: VariesDocs: https://github.com/tronscan/tronscan-frontend/blob/dev2019/document/api.md
Endpoints:• Account: /account?address={address}• Transactions: /transaction?address={address}&limit=20• TRC20 Transfers: /token_trc20/transfers?address={address}• Account Resources: /account/detail?address={address}
Example:fetch('https://apilist.tronscanapi.com/api/account?address=TxxxXXXxxx') .then(r => r.json()) .then(data => console.log('TRX Balance:', data.balance / 1e6));
FALLBACK 1: TronGrid (Official)────────────────────────────────URL: https://api.trongrid.ioFree: PublicDocs: https://developers.tron.network/docs
JSON-RPC Example:fetch('https://api.trongrid.io/wallet/getaccount', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ address: 'TxxxXXXxxx', visible: true })})
FALLBACK 2: Tron Official API──────────────────────────────URL: https://api.tronstack.ioFree: PublicDocs: Similar to TronGrid
FALLBACK 3: Blockchair (TRON)──────────────────────────────URL: https://api.blockchair.com/tron/dashboards/address/{address}Free: 1,440 req/dayDocs: https://blockchair.com/api/docs
FALLBACK 4: Tronscan API v2───────────────────────────URL: https://api.tronscan.org/apiAlternative endpointSimilar structure
FALLBACK 5: GetBlock TRON────────────���────────────URL: https://go.getblock.io/tronFree tier availableDocs: https://getblock.io/docs/
═══════════════════════════════════════════════════════════════════════════════════════ 💰 MARKET DATA APIs - APIهای دادههای بازار═══════════════════════════════════════════════════════════════════════════════════════
CATEGORY 1: PRICE & MARKET CAP (15+ endpoints)───────────────────────────────────────────────
PRIMARY: CoinGecko (FREE - بدون کلید)──────────────────────────────────────URL: https://api.coingecko.com/api/v3Rate Limit: 10-50 calls/min (free)Docs: https://www.coingecko.com/en/api/documentation
Best Endpoints:• Simple Price: /simple/price?ids=bitcoin,ethereum&vs_currencies=usd• Coin Data: /coins/{id}?localization=false• Market Chart: /coins/{id}/market_chart?vs_currency=usd&days=7• Global Data: /global• Trending: /search/trending• Categories: /coins/categories
Example (Works Everywhere):fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,tron&vs_currencies=usd,eur') .then(r => r.json()) .then(data => console.log(data));// Output: {bitcoin: {usd: 45000, eur: 42000}, ...}
FALLBACK 1: CoinMarketCap (با کلید)─────────────────────────────────────URL: https://pro-api.coinmarketcap.com/v1Key 1: b54bcf4d-1bca-4e8e-9a24-22ff2c3d462cKey 2: 04cf4b5b-9868-465c-8ba0-9f2e78c92eb1Rate Limit: 333 calls/day (free)Docs: https://coinmarketcap.com/api/documentation/v1/
Endpoints:• Latest Quotes: /cryptocurrency/quotes/latest?symbol=BTC,ETH• Listings: /cryptocurrency/listings/latest?limit=100• Market Pairs: /cryptocurrency/market-pairs/latest?id=1
Example (Requires API Key in Header):fetch('https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC', { headers: { 'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' }}).then(r => r.json()).then(data => console.log(data.data.BTC));
With CORS Proxy:const proxy = 'https://proxy.cors.sh/';fetch(proxy + 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC', { headers: { 'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c', 'Origin': 'https://myapp.com' }})
FALLBACK 2: CryptoCompare─────────────────────────URL: https://min-api.cryptocompare.com/dataKey: e79c8e6d4c5b4a3f2e1d0c9b8a7f6e5d4c3b2a1fFree: 100K calls/monthDocs: https://min-api.cryptocompare.com/documentation
Endpoints:• Price Multi: /pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR&api_key={KEY}• Historical: /v2/histoday?fsym=BTC&tsym=USD&limit=30&api_key={KEY}• Top Volume: /top/totalvolfull?limit=10&tsym=USD&api_key={KEY}
FALLBACK 3: Coinpaprika (FREE)───────────────────────────────URL: https://api.coinpaprika.com/v1Rate Limit: 20K calls/monthDocs: https://api.coinpaprika.com/
Endpoints:• Tickers: /tickers• Coin: /coins/btc-bitcoin• Historical: /coins/btc-bitcoin/ohlcv/historical
FALLBACK 4: CoinCap (FREE)──────────────────────────URL: https://api.coincap.io/v2Rate Limit: 200 req/minDocs: https://docs.coincap.io/
Endpoints:• Assets: /assets• Specific: /assets/bitcoin• History: /assets/bitcoin/history?interval=d1
FALLBACK 5: Nomics (FREE)─────────────────────────URL: https://api.nomics.com/v1No Rate Limit on free tierDocs: https://p.nomics.com/cryptocurrency-bitcoin-api
FALLBACK 6: Messari (FREE)──────────────────────────URL: https://data.messari.io/api/v1Rate Limit: GenerousDocs: https://messari.io/api/docs
FALLBACK 7: CoinLore (FREE)───────────────────────────URL: https://api.coinlore.net/apiRate Limit: NoneDocs: https://www.coinlore.com/cryptocurrency-data-api
FALLBACK 8: Binance Public API───────────────────────────────URL: https://api.binance.com/api/v3Free: بلهDocs: https://binance-docs.github.io/apidocs/spot/en/
Endpoints:• Price: /ticker/price?symbol=BTCUSDT• 24hr Stats: /ticker/24hr?symbol=ETHUSDT
FALLBACK 9: CoinDesk API───────────���────────────URL: https://api.coindesk.com/v1Free: Bitcoin price indexDocs: https://www.coindesk.com/coindesk-api
FALLBACK 10: Mobula API───────────────────────URL: https://api.mobula.io/api/1Free: 50% cheaper than CMCCoverage: 2.3M+ cryptocurrenciesDocs: https://developer.mobula.fi/
FALLBACK 11: Token Metrics API───────────────────────────────URL: https://api.tokenmetrics.com/v2Free API key availableAI-driven insightsDocs: https://api.tokenmetrics.com/docs
FALLBACK 12: FreeCryptoAPI──────────────────────────URL: https://api.freecryptoapi.comFree: Beginner-friendlyCoverage: 3,000+ coins
FALLBACK 13: DIA Data─────────────────────URL: https://api.diadata.org/v1Free: Decentralized oracleTransparent pricingDocs: https://docs.diadata.org
FALLBACK 14: Alternative.me───────────────────────────URL: https://api.alternative.me/v2Free: Price + Fear & GreedDocs: In API responses
FALLBACK 15: CoinStats API──────────────────────────URL: https://api.coinstats.app/public/v1Free tier available
═══════════════════════════════════════════════════════════════════════════════════════ 📰 NEWS & SOCIAL APIs - APIهای اخبار و شبکههای اجتماعی═══════════════════════════════════════════════════════════════════════════════════════
CATEGORY 1: CRYPTO NEWS (10+ endpoints)────────────────────────────────────────
PRIMARY: CryptoPanic (FREE)───────────────────────────URL: https://cryptopanic.com/api/v1Free: بلهDocs: https://cryptopanic.com/developers/api/
Endpoints:• Posts: /posts/?auth_token={TOKEN}&public=true• Currencies: /posts/?currencies=BTC,ETH• Filter: /posts/?filter=rising
Example:fetch('https://cryptopanic.com/api/v1/posts/?public=true') .then(r => r.json()) .then(data => console.log(data.results));
FALLBACK 1: NewsAPI.org───────────────────────URL: https://newsapi.org/v2Key: pub_346789abc123def456789ghi012345jklFree: 100 req/dayDocs: https://newsapi.org/docs
FALLBACK 2: CryptoControl─────────────────────────URL: https://cryptocontrol.io/api/v1/publicFree tier availableDocs: https://cryptocontrol.io/api
FALLBACK 3: CoinDesk News─────────────────────────URL: https://www.coindesk.com/arc/outboundfeeds/rss/Free RSS feed
FALLBACK 4: CoinTelegraph API─────────────────────────────URL: https://cointelegraph.com/api/v1Free: RSS and JSON feeds
FALLBACK 5: CryptoSlate───────────────────────URL: https://cryptoslate.com/apiFree: Limited
FALLBACK 6: The Block API─────────────────────────URL: https://api.theblock.co/v1Premium service
FALLBACK 7: Bitcoin Magazine RSS────────────────────────────────URL: https://bitcoinmagazine.com/.rss/full/Free RSS
FALLBACK 8: Decrypt RSS───────────────────────URL: https://decrypt.co/feedFree RSS
FALLBACK 9: Reddit Crypto─────────────────────────URL: https://www.reddit.com/r/CryptoCurrency/new.jsonFree: Public JSONLimit: 60 req/min
Example:fetch('https://www.reddit.com/r/CryptoCurrency/hot.json?limit=25') .then(r => r.json()) .then(data => console.log(data.data.children));
FALLBACK 10: Twitter/X API (v2)───────────────────────────────URL: https://api.twitter.com/2Requires: OAuth 2.0Free tier: 1,500 tweets/month
═══════════════════════════════════════════════════════════════════════════════════════ 😱 SENTIMENT & MOOD APIs - APIهای احساسات بازار═════════════════════════════════��═════════════════════════════════════════════════════
CATEGORY 1: FEAR & GREED INDEX (5+ endpoints)──────────────────────────────────────────────
PRIMARY: Alternative.me (FREE)──────────────────────────────URL: https://api.alternative.me/fng/Free: بدون محدودیتDocs: https://alternative.me/crypto/fear-and-greed-index/
Endpoints:• Current: /?limit=1• Historical: /?limit=30• Date Range: /?limit=10&date_format=world
Example:fetch('https://api.alternative.me/fng/?limit=1') .then(r => r.json()) .then(data => { const fng = data.data[0]; console.log(`Fear & Greed: ${fng.value} - ${fng.value_classification}`); });// Output: "Fear & Greed: 45 - Fear"
FALLBACK 1: LunarCrush──────────────────────URL: https://api.lunarcrush.com/v2Free tier: LimitedDocs: https://lunarcrush.com/developers/api
Endpoints:• Assets: ?data=assets&key={KEY}• Market: ?data=market&key={KEY}• Influencers: ?data=influencers&key={KEY}
FALLBACK 2: Santiment (GraphQL)────────────────────────────────URL: https://api.santiment.net/graphqlFree tier availableDocs: https://api.santiment.net/graphiql
GraphQL Example:query { getMetric(metric: "sentiment_balance_total") { timeseriesData( slug: "bitcoin" from: "2025-10-01T00:00:00Z" to: "2025-10-31T00:00:00Z" interval: "1d" ) { datetime value } }}
FALLBACK 3: TheTie.io─────────────────────URL: https://api.thetie.ioPremium mainlyDocs: https://docs.thetie.io
FALLBACK 4: CryptoQuant───────────────────────URL: https://api.cryptoquant.com/v1Free tier: LimitedDocs: https://docs.cryptoquant.com
FALLBACK 5: Glassnode Social────────────────────────────URL: https://api.glassnode.com/v1/metrics/socialFree tier: LimitedDocs: https://docs.glassnode.com
FALLBACK 6: Augmento (Social)──────────────────────────────URL: https://api.augmento.ai/v1AI-powered sentimentFree trial available
═══════════════════════════════════════════════════════════════════════════════════════ 🐋 WHALE TRACKING APIs - APIهای ردیابی نهنگها═══════════════════════════════════════════════════════════════════════════════════════
CATEGORY 1: WHALE TRANSACTIONS (8+ endpoints)──────────────────────────────────────────────
PRIMARY: Whale Alert────────────────────URL: https://api.whale-alert.io/v1Free: Limited (7-day trial)Paid: From $20/monthDocs: https://docs.whale-alert.io
Endpoints:• Transactions: /transactions?api_key={KEY}&min_value=1000000&start={timestamp}&end={timestamp}• Status: /status?api_key={KEY}
Example:const start = Math.floor(Date.now()/1000) - 3600; // 1 hour agoconst end = Math.floor(Date.now()/1000);fetch(`https://api.whale-alert.io/v1/transactions?api_key=YOUR_KEY&min_value=1000000&start=${start}&end=${end}`) .then(r => r.json()) .then(data => { data.transactions.forEach(tx => { console.log(`${tx.amount} ${tx.symbol} from ${tx.from.owner} to ${tx.to.owner}`); }); });
FALLBACK 1: ClankApp (FREE)───────────────────────────URL: https://clankapp.com/apiFree: بلهTelegram: @clankappTwitter: @ClankAppDocs: https://clankapp.com/api/
Features:• 24 blockchains• Real-time whale alerts• Email & push notifications• No API key needed
Example:fetch('https://clankapp.com/api/whales/recent') .then(r => r.json()) .then(data => console.log(data));
FALLBACK 2: BitQuery Whale Tracking────────────────────────────────────URL: https://graphql.bitquery.ioFree: 10K queries/monthDocs: https://docs.bitquery.io
GraphQL Example (Large ETH Transfers):{ ethereum(network: ethereum) { transfers( amount: {gt: 1000} currency: {is: "ETH"} date: {since: "2025-10-25"} ) { block { timestamp { time } } sender { address } receiver { address } amount transaction { hash } } }}
FALLBACK 3: Arkham Intelligence────────────────────────────────URL: https://api.arkham.comPaid service mainlyDocs: https://docs.arkham.com
FALLBACK 4: Nansen──────────────────URL: https://api.nansen.ai/v1Premium: Expensive but powerfulDocs: https://docs.nansen.ai
Features:• Smart Money tracking• Wallet labeling• Multi-chain support
FALLBACK 5: DexCheck Whale Tracker───────────────────────────────────Free wallet tracking feature22 chains supportedTelegram bot integration
FALLBACK 6: DeBank──────────────────URL: https://api.debank.comFree: Portfolio trackingWeb3 social features
FALLBACK 7: Zerion API──────────────────────URL: https://api.zerion.ioSimilar to DeBankDeFi portfolio tracker
FALLBACK 8: Whalemap────────────────────URL: https://whalemap.ioBitcoin & ERC-20 focusCharts and analytics
═══════════════════════════════════════════════════════════════════════════════════════ 🔍 ON-CHAIN ANALYTICS APIs - APIهای تحلیل زنجیره═══════════════════════════════════════════════════════════════════════════════════════
CATEGORY 1: BLOCKCHAIN DATA (10+ endpoints)────────────────────────────────────────────
PRIMARY: The Graph (Subgraphs)──────────────────────────────URL: https://api.thegraph.com/subgraphs/name/{org}/{subgraph}Free: Public subgraphsDocs: https://thegraph.com/docs/
Popular Subgraphs:• Uniswap V3: /uniswap/uniswap-v3• Aave V2: /aave/protocol-v2• Compound: /graphprotocol/compound-v2
Example (Uniswap V3):fetch('https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ query: `{ pools(first: 5, orderBy: volumeUSD, orderDirection: desc) { id token0 { symbol } token1 { symbol } volumeUSD } }` })})
FALLBACK 1: Glassnode─────────────────────URL: https://api.glassnode.com/v1Free tier: Limited metricsDocs: https://docs.glassnode.com
Endpoints:• SOPR: /metrics/indicators/sopr?a=BTC&api_key={KEY}• HODL Waves: /metrics/supply/hodl_waves?a=BTC&api_key={KEY}
FALLBACK 2: IntoTheBlock────────────────────────URL: https://api.intotheblock.com/v1Free tier availableDocs: https://developers.intotheblock.com
FALLBACK 3: Dune Analytics──────────────────────────URL: https://api.dune.com/api/v1Free: Query resultsDocs: https://docs.dune.com/api-reference/
FALLBACK 4: Covalent────────────────────URL: https://api.covalenthq.com/v1Free tier: 100K creditsMulti-chain supportDocs: https://www.covalenthq.com/docs/api/
Example (Ethereum balances):fetch('https://api.covalenthq.com/v1/1/address/0x.../balances_v2/?key=YOUR_KEY')
FALLBACK 5: Moralis───────────────────URL: https://deep-index.moralis.io/api/v2Free: 100K compute units/monthDocs: https://docs.moralis.io
FALLBACK 6: Alchemy NFT API───────────────────────────Included with Alchemy accountNFT metadata & transfers
FALLBACK 7: QuickNode Functions────────────────────────────────Custom on-chain queriesToken balances, NFTs
FALLBACK 8: Transpose─────────────────────URL: https://api.transpose.ioFree tier availableSQL-like queries
FALLBACK 9: Footprint Analytics────────────────────────────────URL: https://api.footprint.networkFree: Community tierNo-code analytics
FALLBACK 10: Nansen Query─────────────────────────Premium institutional toolAdvanced on-chain intelligence
═══════════════════════════════════════════════════════════════════════════════════════ 🔧 COMPLETE JAVASCRIPT IMPLEMENTATION پیادهسازی کامل جاوااسکریپت═══════════════════════════════════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════════════════════════// CONFIG.JS - تنظیمات مرکزی API// ═══════════════════════════════════════════════════════════════════════════════
const API_CONFIG = { // CORS Proxies (پروکسیهای CORS) corsProxies: [ 'https://api.allorigins.win/get?url=', 'https://proxy.cors.sh/', 'https://proxy.corsfix.com/?url=', 'https://api.codetabs.com/v1/proxy?quest=', 'https://thingproxy.freeboard.io/fetch/' ], // Block Explorers (کاوشگرهای بلاکچین) explorers: { ethereum: { primary: { name: 'etherscan', baseUrl: 'https://api.etherscan.io/api', key: 'SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2', rateLimit: 5 // calls per second }, fallbacks: [ { name: 'etherscan2', baseUrl: 'https://api.etherscan.io/api', key: 'T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45' }, { name: 'blockchair', baseUrl: 'https://api.blockchair.com/ethereum', key: '' }, { name: 'blockscout', baseUrl: 'https://eth.blockscout.com/api', key: '' }, { name: 'ethplorer', baseUrl: 'https://api.ethplorer.io', key: 'freekey' } ] }, bsc: { primary: { name: 'bscscan', baseUrl: 'https://api.bscscan.com/api', key: 'K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT', rateLimit: 5 }, fallbacks: [ { name: 'blockchair', baseUrl: 'https://api.blockchair.com/binance-smart-chain', key: '' }, { name: 'bitquery', baseUrl: 'https://graphql.bitquery.io', key: '', method: 'graphql' } ] }, tron: { primary: { name: 'tronscan', baseUrl: 'https://apilist.tronscanapi.com/api', key: '7ae72726-bffe-4e74-9c33-97b761eeea21', rateLimit: 10 }, fallbacks: [ { name: 'trongrid', baseUrl: 'https://api.trongrid.io', key: '' }, { name: 'tronstack', baseUrl: 'https://api.tronstack.io', key: '' }, { name: 'blockchair', baseUrl: 'https://api.blockchair.com/tron', key: '' } ] } }, // Market Data (دادههای بازار) marketData: { primary: { name: 'coingecko', baseUrl: 'https://api.coingecko.com/api/v3', key: '', // بدون کلید needsProxy: false, rateLimit: 50 // calls per minute }, fallbacks: [ { name: 'coinmarketcap', baseUrl: 'https://pro-api.coinmarketcap.com/v1', key: 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c', headerKey: 'X-CMC_PRO_API_KEY', needsProxy: true }, { name: 'coinmarketcap2', baseUrl: 'https://pro-api.coinmarketcap.com/v1', key: '04cf4b5b-9868-465c-8ba0-9f2e78c92eb1', headerKey: 'X-CMC_PRO_API_KEY', needsProxy: true }, { name: 'coincap', baseUrl: 'https://api.coincap.io/v2', key: '' }, { name: 'coinpaprika', baseUrl: 'https://api.coinpaprika.com/v1', key: '' }, { name: 'binance', baseUrl: 'https://api.binance.com/api/v3', key: '' }, { name: 'coinlore', baseUrl: 'https://api.coinlore.net/api', key: '' } ] }, // RPC Nodes (نودهای RPC) rpcNodes: { ethereum: [ 'https://eth.llamarpc.com', 'https://ethereum.publicnode.com', 'https://cloudflare-eth.com', 'https://rpc.ankr.com/eth', 'https://eth.drpc.org' ], bsc: [ 'https://bsc-dataseed.binance.org', 'https://bsc-dataseed1.defibit.io', 'https://rpc.ankr.com/bsc', 'https://bsc-rpc.publicnode.com' ], polygon: [ 'https://polygon-rpc.com', 'https://rpc.ankr.com/polygon', 'https://polygon-bor-rpc.publicnode.com' ] }, // News Sources (منابع خبری) news: { primary: { name: 'cryptopanic', baseUrl: 'https://cryptopanic.com/api/v1', key: '', needsProxy: false }, fallbacks: [ { name: 'reddit', baseUrl: 'https://www.reddit.com/r/CryptoCurrency', key: '' } ] }, // Sentiment (احساسات) sentiment: { primary: { name: 'alternative.me', baseUrl: 'https://api.alternative.me/fng', key: '', needsProxy: false } }, // Whale Tracking (ردیابی نهنگ) whaleTracking: { primary: { name: 'clankapp', baseUrl: 'https://clankapp.com/api', key: '', needsProxy: false } }};
// ═══════════════════════════════════════════════════════════════════════════════// API-CLIENT.JS - کلاینت API با مدیریت خطا و fallback// ═══════════════════════════════════════════════════════════════════════════════
class CryptoAPIClient { constructor(config) { this.config = config; this.currentProxyIndex = 0; this.requestCache = new Map(); this.cacheTimeout = 60000; // 1 minute } // استفاده از CORS Proxy async fetchWithProxy(url, options = {}) { const proxies = this.config.corsProxies; for (let i = 0; i < proxies.length; i++) { const proxyUrl = proxies[this.currentProxyIndex] + encodeURIComponent(url); try { console.log(`🔄 Trying proxy ${this.currentProxyIndex + 1}/${proxies.length}`); const response = await fetch(proxyUrl, { ...options, headers: { ...options.headers, 'Origin': window.location.origin, 'x-requested-with': 'XMLHttpRequest' } }); if (response.ok) { const data = await response.json(); // Handle allOrigins response format return data.contents ? JSON.parse(data.contents) : data; } } catch (error) { console.warn(`❌ Proxy ${this.currentProxyIndex + 1} failed:`, error.message); } // Switch to next proxy this.currentProxyIndex = (this.currentProxyIndex + 1) % proxies.length; } throw new Error('All CORS proxies failed'); } // بدون پروکسی async fetchDirect(url, options = {}) { try { const response = await fetch(url, options); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { throw new Error(`Direct fetch failed: ${error.message}`); } } // با cache و fallback async fetchWithFallback(primaryConfig, fallbacks, endpoint, params = {}) { const cacheKey = `${primaryConfig.name}-${endpoint}-${JSON.stringify(params)}`; // Check cache if (this.requestCache.has(cacheKey)) { const cached = this.requestCache.get(cacheKey); if (Date.now() - cached.timestamp < this.cacheTimeout) { console.log('📦 Using cached data'); return cached.data; } } // Try primary try { const data = await this.makeRequest(primaryConfig, endpoint, params); this.requestCache.set(cacheKey, { data, timestamp: Date.now() }); return data; } catch (error) { console.warn('⚠️ Primary failed, trying fallbacks...', error.message); } // Try fallbacks for (const fallback of fallbacks) { try { console.log(`🔄 Trying fallback: ${fallback.name}`); const data = await this.makeRequest(fallback, endpoint, params); this.requestCache.set(cacheKey, { data, timestamp: Date.now() }); return data; } catch (error) { console.warn(`❌ Fallback ${fallback.name} failed:`, error.message); } } throw new Error('All endpoints failed'); } // ساخت درخواست async makeRequest(apiConfig, endpoint, params = {}) { let url = `${apiConfig.baseUrl}${endpoint}`; // Add query params const queryParams = new URLSearchParams(); if (apiConfig.key) { queryParams.append('apikey', apiConfig.key); } Object.entries(params).forEach(([key, value]) => { queryParams.append(key, value); }); if (queryParams.toString()) { url += '?' + queryParams.toString(); } const options = {}; // Add headers if needed if (apiConfig.headerKey && apiConfig.key) { options.headers = { [apiConfig.headerKey]: apiConfig.key }; } // Use proxy if needed if (apiConfig.needsProxy) { return await this.fetchWithProxy(url, options); } else { return await this.fetchDirect(url, options); } } // ═══════════════ SPECIFIC API METHODS ═══════════════ // Get ETH Balance (با fallback) async getEthBalance(address) { const { ethereum } = this.config.explorers; return await this.fetchWithFallback( ethereum.primary, ethereum.fallbacks, '', { module: 'account', action: 'balance', address: address, tag: 'latest' } ); } // Get BTC Price (multi-source) async getBitcoinPrice() { const { marketData } = this.config; try { // Try CoinGecko first (no key needed, no CORS) const data = await this.fetchDirect( `${marketData.primary.baseUrl}/simple/price?ids=bitcoin&vs_currencies=usd,eur` ); return { source: 'CoinGecko', usd: data.bitcoin.usd, eur: data.bitcoin.eur }; } catch (error) { // Fallback to Binance try { const data = await this.fetchDirect( 'https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT' ); return { source: 'Binance', usd: parseFloat(data.price), eur: null }; } catch (err) { throw new Error('All price sources failed'); } } } // Get Fear & Greed Index async getFearGreed() { const url = `${this.config.sentiment.primary.baseUrl}/?limit=1`; const data = await this.fetchDirect(url); return { value: parseInt(data.data[0].value), classification: data.data[0].value_classification, timestamp: new Date(parseInt(data.data[0].timestamp) * 1000) }; } // Get Trending Coins async getTrendingCoins() { const url = `${this.config.marketData.primary.baseUrl}/search/trending`; const data = await this.fetchDirect(url); return data.coins.map(item => ({ id: item.item.id, name: item.item.name, symbol: item.item.symbol, rank: item.item.market_cap_rank, thumb: item.item.thumb })); } // Get Crypto News async getCryptoNews(limit = 10) { const url = `${this.config.news.primary.baseUrl}/posts/?public=true`; const data = await this.fetchDirect(url); return data.results.slice(0, limit).map(post => ({ title: post.title, url: post.url, source: post.source.title, published: new Date(post.published_at) })); } // Get Recent Whale Transactions async getWhaleTransactions() { try { const url = `${this.config.whaleTracking.primary.baseUrl}/whales/recent`; return await this.fetchDirect(url); } catch (error) { console.warn('Whale API not available'); return []; } } // Multi-source price aggregator async getAggregatedPrice(symbol) { const sources = [ { name: 'CoinGecko', fetch: async () => { const data = await this.fetchDirect( `${this.config.marketData.primary.baseUrl}/simple/price?ids=${symbol}&vs_currencies=usd` ); return data[symbol]?.usd; } }, { name: 'Binance', fetch: async () => { const data = await this.fetchDirect( `https://api.binance.com/api/v3/ticker/price?symbol=${symbol.toUpperCase()}USDT` ); return parseFloat(data.price); } }, { name: 'CoinCap', fetch: async () => { const data = await this.fetchDirect( `https://api.coincap.io/v2/assets/${symbol}` ); return parseFloat(data.data.priceUsd); } } ]; const prices = await Promise.allSettled( sources.map(async source => ({ source: source.name, price: await source.fetch() })) ); const successful = prices .filter(p => p.status === 'fulfilled') .map(p => p.value); if (successful.length === 0) { throw new Error('All price sources failed'); } const avgPrice = successful.reduce((sum, p) => sum + p.price, 0) / successful.length; return { symbol, sources: successful, average: avgPrice, spread: Math.max(...successful.map(p => p.price)) - Math.min(...successful.map(p => p.price)) }; }}
// ═══════════════════════════════════════════════════════════════════════════════// USAGE EXAMPLES - مثالهای استفاده// ═══════════════════════════════════════════════════════════════════════════════
// Initializeconst api = new CryptoAPIClient(API_CONFIG);
// Example 1: Get Ethereum Balanceasync function example1() { try { const address = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'; const balance = await api.getEthBalance(address); console.log('ETH Balance:', parseInt(balance.result) / 1e18); } catch (error) { console.error('Error:', error.message); }}
// Example 2: Get Bitcoin Price from Multiple Sourcesasync function example2() { try { const price = await api.getBitcoinPrice(); console.log(`BTC Price (${price.source}): $${price.usd}`); } catch (error) { console.error('Error:', error.message); }}
// Example 3: Get Fear & Greed Indexasync function example3() { try { const fng = await api.getFearGreed(); console.log(`Fear & Greed: ${fng.value} (${fng.classification})`); } catch (error) { console.error('Error:', error.message); }}
// Example 4: Get Trending Coinsasync function example4() { try { const trending = await api.getTrendingCoins(); console.log('Trending Coins:'); trending.forEach((coin, i) => { console.log(`${i + 1}. ${coin.name} (${coin.symbol})`); }); } catch (error) { console.error('Error:', error.message); }}
// Example 5: Get Latest Newsasync function example5() { try { const news = await api.getCryptoNews(5); console.log('Latest News:'); news.forEach((article, i) => { console.log(`${i + 1}. ${article.title} - ${article.source}`); }); } catch (error) { console.error('Error:', error.message); }}
// Example 6: Aggregate Price from Multiple Sourcesasync function example6() { try { const priceData = await api.getAggregatedPrice('bitcoin'); console.log('Price Sources:'); priceData.sources.forEach(s => { console.log(`- ${s.source}: $${s.price.toFixed(2)}`); }); console.log(`Average: $${priceData.average.toFixed(2)}`); console.log(`Spread: $${priceData.spread.toFixed(2)}`); } catch (error) { console.error('Error:', error.message); }}
// Example 7: Dashboard - All Dataasync function dashboardExample() { console.log('🚀 Loading Crypto Dashboard...\n'); try { // Price const btcPrice = await api.getBitcoinPrice(); console.log(`💰 BTC: $${btcPrice.usd.toLocaleString()}`); // Fear & Greed const fng = await api.getFearGreed(); console.log(`😱 Fear & Greed: ${fng.value} (${fng.classification})`); // Trending const trending = await api.getTrendingCoins(); console.log(`\n🔥 Trending:`); trending.slice(0, 3).forEach((coin, i) => { console.log(` ${i + 1}. ${coin.name}`); }); // News const news = await api.getCryptoNews(3); console.log(`\n📰 Latest News:`); news.forEach((article, i) => { console.log(` ${i + 1}. ${article.title.substring(0, 50)}...`); }); } catch (error) { console.error('Dashboard Error:', error.message); }}
// Run examplesconsole.log('═══════════════════════════════════════');console.log(' CRYPTO API CLIENT - TEST SUITE');console.log('═══════════════════════════════════════\n');
// Uncomment to run specific examples:// example1();// example2();// example3();// example4();// example5();// example6();dashboardExample();
═══════════════════════════════════════════════════════════════════════════════════════ 📝 QUICK REFERENCE - مرجع سریع═══════════════════════════════════════════════════════════════════════════════════════
BEST FREE APIs (بهترین APIهای رایگان):─────────────────────────────────────────
✅ PRICES & MARKET DATA: 1. CoinGecko (بدون کلید، بدون CORS) 2. Binance Public API (بدون کلید) 3. CoinCap (بدون کلید) 4. CoinPaprika (بدون کلید)
✅ BLOCK EXPLORERS: 1. Blockchair (1,440 req/day) 2. BlockScout (بدون محدودیت) 3. Public RPC nodes (various)
✅ NEWS: 1. CryptoPanic (بدون کلید) 2. Reddit JSON API (60 req/min)
✅ SENTIMENT: 1. Alternative.me F&G (بدون محدودیت)
✅ WHALE TRACKING: 1. ClankApp (بدون کلید) 2. BitQuery GraphQL (10K/month)
✅ RPC NODES: 1. PublicNode (همه شبکهها) 2. Ankr (عمومی) 3. LlamaNodes (بدون ثبتنام)
RATE LIMIT STRATEGIES (استراتژیهای محدودیت):───────────────────────────────────────────────
1. کش کردن (Caching): - ذخیره نتایج برای 1-5 دقیقه - استفاده از localStorage برای کش مرورگر
2. چرخش کلید (Key Rotation): - استفاده از چندین کلید API - تعویض خودکار در صورت محدودیت
3. Fallback Chain: - Primary → Fallback1 → Fallback2 - تا 5-10 جای��زین برای هر سرویس
4. Request Queuing: - صف بندی درخواستها - تاخیر بین درخواستها
5. Multi-Source Aggregation: - دریافت از چند منبع همزمان - میانگین گیری نتایج
ERROR HANDLING (مدیریت خطا):──────────────────────────────
try { const data = await api.fetchWithFallback(primary, fallbacks, endpoint, params);} catch (error) { if (error.message.includes('rate limit')) { // Switch to fallback } else if (error.message.includes('CORS')) { // Use CORS proxy } else { // Show error to user }}
DEPLOYMENT TIPS (نکات استقرار):─────────────────────────────────
1. Backend Proxy (توصیه میشود): - Node.js/Express proxy server - Cloudflare Worker - Vercel Serverless Function
2. Environment Variables: - ذخیره کلیدها در .env - عدم نمایش در کد فرانتاند
3. Rate Limiting: - محدودسازی درخواست کاربر - استفاده از Redis برای کنترل
4. Monitoring: - لاگ گرفتن از خطاها - ردیابی استفاده از API
═══════════════════════════════════════════════════════════════════════════════════════ 🔗 USEFUL LINKS - لینکهای مفید═══════════════════════════════════════════════════════════════════════════════════════
DOCUMENTATION:• CoinGecko API: https://www.coingecko.com/api/documentation• Etherscan API: https://docs.etherscan.io• BscScan API: https://docs.bscscan.com• TronGrid: https://developers.tron.network• Alchemy: https://docs.alchemy.com• Infura: https://docs.infura.io• The Graph: https://thegraph.com/docs• BitQuery: https://docs.bitquery.io
CORS PROXY ALTERNATIVES:• CORS Anywhere: https://github.com/Rob--W/cors-anywhere• AllOrigins: https://github.com/gnuns/allOrigins• CORS.SH: https://cors.sh• Corsfix: https://corsfix.com
RPC LISTS:• ChainList: https://chainlist.org• Awesome RPC: https://github.com/arddluma/awesome-list-rpc-nodes-providers
TOOLS:• Postman: https://www.postman.com• Insomnia: https://insomnia.rest• GraphiQL: https://graphiql-online.com
═══════════════════════════════════════════════════════════════════════════════════════ ⚠️ IMPORTANT NOTES - نکات مهم═══════════════════════════════════════════════════════════════════════════════════════
1. ⚠️ NEVER expose API keys in frontend code - همیشه از backend proxy استفاده کنید - کلیدها را در environment variables ذخیره کنید
2. 🔄 Always implement fallbacks - حداقل 2-3 جایگزین برای هر سرویس - تست منظم fallbackها
3. 💾 Cache responses when possible - صرفهجویی در استفاده از API - سرعت بیشتر برای کاربر
4. 📊 Monitor API usage - ردیابی تعداد درخواستها - هشدار قبل از رسیدن به محدودیت
5. 🔐 Secure your endpoints - محدودسازی domain - استفاده از CORS headers - Rate limiting برای کاربران
6. 🌐 Test with and without CORS proxies - برخی APIها CORS را پشتیبانی میکنند - استفاده از پروکسی فقط در صورت نیاز
7. 📱 Mobile-friendly implementations - بهینهسازی برای شبکههای ضعیف - کاهش اندازه درخواستها
═══════════════════════════════════════════════════════════════════════════════════════ END OF CONFIGURATION FILE پایان فایل تنظیمات═══════════════════════════════════════════════════════════════════════════════════��═══
Last Updated: October 31, 2025Version: 2.0Author: AI AssistantLicense: Free to use
For updates and more resources, check:- GitHub: Search for "awesome-crypto-apis"- Reddit: r/CryptoCurrency, r/ethdev- Discord: Web3 developer communities123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097{ "schema": { "name": "Crypto Resource Registry", "version": "1.0.0", "updated_at": "2025-11-11", "description": "Single-file registry of crypto data sources with uniform fields for agents (Cloud Code, Cursor, Claude, etc.).", "spec": { "entry_shape": { "id": "string", "name": "string", "category_or_chain": "string (category / chain / type / role)", "base_url": "string", "auth": { "type": "string", "key": "string|null", "param_name/header_name": "string|null" }, "docs_url": "string|null", "endpoints": "object|string|null", "notes": "string|null" } } }, "registry": { "metadata": { "description": "Comprehensive cryptocurrency data collection database compiled from provided documents. Includes free and limited resources for RPC nodes, block explorers, market data, news, sentiment, on-chain analytics, whale tracking, community sentiment, Hugging Face models/datasets, free HTTP endpoints, and local backend routes. Uniform format: each entry has 'id', 'name', 'category' (or 'chain'/'role' where applicable), 'base_url', 'auth' (object with 'type', 'key' if embedded, 'param_name', etc.), 'docs_url', and optional 'endpoints' or 'notes'. Keys are embedded where provided in sources. Structure designed for easy parsing by code-writing bots.", "version": "1.0", "updated": "November 11, 2025", "sources": [ "api - Copy.txt", "api-config-complete (1).txt", "crypto_resources.ts", "additional JSON structures" ], "total_entries": 200 }, "rpc_nodes": [ { "id": "infura_eth_mainnet", "name": "Infura Ethereum Mainnet", "chain": "ethereum", "role": "rpc", "base_url": "https://mainnet.infura.io/v3/{PROJECT_ID}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "PROJECT_ID", "notes": "Replace {PROJECT_ID} with your Infura project ID" }, "docs_url": "https://docs.infura.io", "notes": "Free tier: 100K req/day" }, { "id": "infura_eth_sepolia", "name": "Infura Ethereum Sepolia", "chain": "ethereum", "role": "rpc", "base_url": "https://sepolia.infura.io/v3/{PROJECT_ID}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "PROJECT_ID", "notes": "Replace {PROJECT_ID} with your Infura project ID" }, "docs_url": "https://docs.infura.io", "notes": "Testnet" }, { "id": "alchemy_eth_mainnet", "name": "Alchemy Ethereum Mainnet", "chain": "ethereum", "role": "rpc", "base_url": "https://eth-mainnet.g.alchemy.com/v2/{API_KEY}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "API_KEY", "notes": "Replace {API_KEY} with your Alchemy key" }, "docs_url": "https://docs.alchemy.com", "notes": "Free tier: 300M compute units/month" }, { "id": "alchemy_eth_mainnet_ws", "name": "Alchemy Ethereum Mainnet WS", "chain": "ethereum", "role": "websocket", "base_url": "wss://eth-mainnet.g.alchemy.com/v2/{API_KEY}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "API_KEY", "notes": "Replace {API_KEY} with your Alchemy key" }, "docs_url": "https://docs.alchemy.com", "notes": "WebSocket for real-time" }, { "id": "ankr_eth", "name": "Ankr Ethereum", "chain": "ethereum", "role": "rpc", "base_url": "https://rpc.ankr.com/eth", "auth": { "type": "none" }, "docs_url": "https://www.ankr.com/docs", "notes": "Free: no public limit" }, { "id": "publicnode_eth_mainnet", "name": "PublicNode Ethereum", "chain": "ethereum", "role": "rpc", "base_url": "https://ethereum.publicnode.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Fully free" }, { "id": "publicnode_eth_allinone", "name": "PublicNode Ethereum All-in-one", "chain": "ethereum", "role": "rpc", "base_url": "https://ethereum-rpc.publicnode.com", "auth": { "type": "none" }, "docs_url": null, "notes": "All-in-one endpoint" }, { "id": "cloudflare_eth", "name": "Cloudflare Ethereum", "chain": "ethereum", "role": "rpc", "base_url": "https://cloudflare-eth.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "llamanodes_eth", "name": "LlamaNodes Ethereum", "chain": "ethereum", "role": "rpc", "base_url": "https://eth.llamarpc.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "one_rpc_eth", "name": "1RPC Ethereum", "chain": "ethereum", "role": "rpc", "base_url": "https://1rpc.io/eth", "auth": { "type": "none" }, "docs_url": null, "notes": "Free with privacy" }, { "id": "drpc_eth", "name": "dRPC Ethereum", "chain": "ethereum", "role": "rpc", "base_url": "https://eth.drpc.org", "auth": { "type": "none" }, "docs_url": "https://drpc.org", "notes": "Decentralized" }, { "id": "bsc_official_mainnet", "name": "BSC Official Mainnet", "chain": "bsc", "role": "rpc", "base_url": "https://bsc-dataseed.binance.org", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "bsc_official_alt1", "name": "BSC Official Alt1", "chain": "bsc", "role": "rpc", "base_url": "https://bsc-dataseed1.defibit.io", "auth": { "type": "none" }, "docs_url": null, "notes": "Free alternative" }, { "id": "bsc_official_alt2", "name": "BSC Official Alt2", "chain": "bsc", "role": "rpc", "base_url": "https://bsc-dataseed1.ninicoin.io", "auth": { "type": "none" }, "docs_url": null, "notes": "Free alternative" }, { "id": "ankr_bsc", "name": "Ankr BSC", "chain": "bsc", "role": "rpc", "base_url": "https://rpc.ankr.com/bsc", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "publicnode_bsc", "name": "PublicNode BSC", "chain": "bsc", "role": "rpc", "base_url": "https://bsc-rpc.publicnode.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "nodereal_bsc", "name": "Nodereal BSC", "chain": "bsc", "role": "rpc", "base_url": "https://bsc-mainnet.nodereal.io/v1/{API_KEY}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "API_KEY", "notes": "Free tier: 3M req/day" }, "docs_url": "https://docs.nodereal.io", "notes": "Requires key for higher limits" }, { "id": "trongrid_mainnet", "name": "TronGrid Mainnet", "chain": "tron", "role": "rpc", "base_url": "https://api.trongrid.io", "auth": { "type": "none" }, "docs_url": "https://developers.tron.network/docs", "notes": "Free" }, { "id": "tronstack_mainnet", "name": "TronStack Mainnet", "chain": "tron", "role": "rpc", "base_url": "https://api.tronstack.io", "auth": { "type": "none" }, "docs_url": null, "notes": "Free, similar to TronGrid" }, { "id": "tron_nile_testnet", "name": "Tron Nile Testnet", "chain": "tron", "role": "rpc", "base_url": "https://api.nileex.io", "auth": { "type": "none" }, "docs_url": null, "notes": "Testnet" }, { "id": "polygon_official_mainnet", "name": "Polygon Official Mainnet", "chain": "polygon", "role": "rpc", "base_url": "https://polygon-rpc.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "polygon_mumbai", "name": "Polygon Mumbai", "chain": "polygon", "role": "rpc", "base_url": "https://rpc-mumbai.maticvigil.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Testnet" }, { "id": "ankr_polygon", "name": "Ankr Polygon", "chain": "polygon", "role": "rpc", "base_url": "https://rpc.ankr.com/polygon", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" }, { "id": "publicnode_polygon_bor", "name": "PublicNode Polygon Bor", "chain": "polygon", "role": "rpc", "base_url": "https://polygon-bor-rpc.publicnode.com", "auth": { "type": "none" }, "docs_url": null, "notes": "Free" } ], "block_explorers": [ { "id": "etherscan_primary", "name": "Etherscan", "chain": "ethereum", "role": "primary", "base_url": "https://api.etherscan.io/api", "auth": { "type": "apiKeyQuery", "key": "SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2", "param_name": "apikey" }, "docs_url": "https://docs.etherscan.io", "endpoints": { "balance": "?module=account&action=balance&address={address}&tag=latest&apikey={key}", "transactions": "?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&sort=asc&apikey={key}", "token_balance": "?module=account&action=tokenbalance&contractaddress={contract}&address={address}&tag=latest&apikey={key}", "gas_price": "?module=gastracker&action=gasoracle&apikey={key}" }, "notes": "Rate limit: 5 calls/sec (free tier)" }, { "id": "etherscan_secondary", "name": "Etherscan (secondary key)", "chain": "ethereum", "role": "fallback", "base_url": "https://api.etherscan.io/api", "auth": { "type": "apiKeyQuery", "key": "T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45", "param_name": "apikey" }, "docs_url": "https://docs.etherscan.io", "endpoints": { "balance": "?module=account&action=balance&address={address}&tag=latest&apikey={key}", "transactions": "?module=account&action=txlist&address={address}&startblock=0&endblock=99999999&sort=asc&apikey={key}", "token_balance": "?module=account&action=tokenbalance&contractaddress={contract}&address={address}&tag=latest&apikey={key}", "gas_price": "?module=gastracker&action=gasoracle&apikey={key}" }, "notes": "Backup key for Etherscan" }, { "id": "blockchair_ethereum", "name": "Blockchair Ethereum", "chain": "ethereum", "role": "fallback", "base_url": "https://api.blockchair.com/ethereum", "auth": { "type": "apiKeyQueryOptional", "key": null, "param_name": "key" }, "docs_url": "https://blockchair.com/api/docs", "endpoints": { "address_dashboard": "/dashboards/address/{address}?key={key}" }, "notes": "Free: 1,440 requests/day" }, { "id": "blockscout_ethereum", "name": "Blockscout Ethereum", "chain": "ethereum", "role": "fallback", "base_url": "https://eth.blockscout.com/api", "auth": { "type": "none" }, "docs_url": "https://docs.blockscout.com", "endpoints": { "balance": "?module=account&action=balance&address={address}" }, "notes": "Open source, no limit" }, { "id": "ethplorer", "name": "Ethplorer", "chain": "ethereum", "role": "fallback", "base_url": "https://api.ethplorer.io", "auth": { "type": "apiKeyQueryOptional", "key": "freekey", "param_name": "apiKey" }, "docs_url": "https://github.com/EverexIO/Ethplorer/wiki/Ethplorer-API", "endpoints": { "address_info": "/getAddressInfo/{address}?apiKey={key}" }, "notes": "Free tier limited" }, { "id": "etherchain", "name": "Etherchain", "chain": "ethereum", "role": "fallback", "base_url": "https://www.etherchain.org/api", "auth": { "type": "none" }, "docs_url": "https://www.etherchain.org/documentation/api", "endpoints": {}, "notes": "Free" }, { "id": "chainlens", "name": "Chainlens", "chain": "ethereum", "role": "fallback", "base_url": "https://api.chainlens.com", "auth": { "type": "none" }, "docs_url": "https://docs.chainlens.com", "endpoints": {}, "notes": "Free tier available" }, { "id": "bscscan_primary", "name": "BscScan", "chain": "bsc", "role": "primary", "base_url": "https://api.bscscan.com/api", "auth": { "type": "apiKeyQuery", "key": "K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT", "param_name": "apikey" }, "docs_url": "https://docs.bscscan.com", "endpoints": { "bnb_balance": "?module=account&action=balance&address={address}&apikey={key}", "bep20_balance": "?module=account&action=tokenbalance&contractaddress={token}&address={address}&apikey={key}", "transactions": "?module=account&action=txlist&address={address}&apikey={key}" }, "notes": "Rate limit: 5 calls/sec" }, { "id": "bitquery_bsc", "name": "BitQuery (BSC)", "chain": "bsc", "role": "fallback", "base_url": "https://graphql.bitquery.io", "auth": { "type": "none" }, "docs_url": "https://docs.bitquery.io", "endpoints": { "graphql_example": "POST with body: { query: '{ ethereum(network: bsc) { address(address: {is: \"{address}\"}) { balances { currency { symbol } value } } } }' }" }, "notes": "Free: 10K queries/month" }, { "id": "ankr_multichain_bsc", "name": "Ankr MultiChain (BSC)", "chain": "bsc", "role": "fallback", "base_url": "https://rpc.ankr.com/multichain", "auth": { "type": "none" }, "docs_url": "https://www.ankr.com/docs/", "endpoints": { "json_rpc": "POST with JSON-RPC body" }, "notes": "Free public endpoints" }, { "id": "nodereal_bsc_explorer", "name": "Nodereal BSC", "chain": "bsc", "role": "fallback", "base_url": "https://bsc-mainnet.nodereal.io/v1/{API_KEY}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "API_KEY" }, "docs_url": "https://docs.nodereal.io", "notes": "Free tier: 3M requests/day" }, { "id": "bsctrace", "name": "BscTrace", "chain": "bsc", "role": "fallback", "base_url": "https://api.bsctrace.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": "Free limited" }, { "id": "oneinch_bsc_api", "name": "1inch BSC API", "chain": "bsc", "role": "fallback", "base_url": "https://api.1inch.io/v5.0/56", "auth": { "type": "none" }, "docs_url": "https://docs.1inch.io", "endpoints": {}, "notes": "For trading data, free" }, { "id": "tronscan_primary", "name": "TronScan", "chain": "tron", "role": "primary", "base_url": "https://apilist.tronscanapi.com/api", "auth": { "type": "apiKeyQuery", "key": "7ae72726-bffe-4e74-9c33-97b761eeea21", "param_name": "apiKey" }, "docs_url": "https://github.com/tronscan/tronscan-frontend/blob/dev2019/document/api.md", "endpoints": { "account": "/account?address={address}", "transactions": "/transaction?address={address}&limit=20", "trc20_transfers": "/token_trc20/transfers?address={address}", "account_resources": "/account/detail?address={address}" }, "notes": "Rate limit varies" }, { "id": "trongrid_explorer", "name": "TronGrid (Official)", "chain": "tron", "role": "fallback", "base_url": "https://api.trongrid.io", "auth": { "type": "none" }, "docs_url": "https://developers.tron.network/docs", "endpoints": { "get_account": "POST /wallet/getaccount with body: { \"address\": \"{address}\", \"visible\": true }" }, "notes": "Free public" }, { "id": "blockchair_tron", "name": "Blockchair TRON", "chain": "tron", "role": "fallback", "base_url": "https://api.blockchair.com/tron", "auth": { "type": "apiKeyQueryOptional", "key": null, "param_name": "key" }, "docs_url": "https://blockchair.com/api/docs", "endpoints": { "address_dashboard": "/dashboards/address/{address}?key={key}" }, "notes": "Free: 1,440 req/day" }, { "id": "tronscan_api_v2", "name": "Tronscan API v2", "chain": "tron", "role": "fallback", "base_url": "https://api.tronscan.org/api", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": "Alternative endpoint, similar structure" }, { "id": "getblock_tron", "name": "GetBlock TRON", "chain": "tron", "role": "fallback", "base_url": "https://go.getblock.io/tron", "auth": { "type": "none" }, "docs_url": "https://getblock.io/docs/", "endpoints": {}, "notes": "Free tier available" } ], "market_data_apis": [ { "id": "coingecko", "name": "CoinGecko", "role": "primary_free", "base_url": "https://api.coingecko.com/api/v3", "auth": { "type": "none" }, "docs_url": "https://www.coingecko.com/en/api/documentation", "endpoints": { "simple_price": "/simple/price?ids={ids}&vs_currencies={fiats}", "coin_data": "/coins/{id}?localization=false", "market_chart": "/coins/{id}/market_chart?vs_currency=usd&days=7", "global_data": "/global", "trending": "/search/trending", "categories": "/coins/categories" }, "notes": "Rate limit: 10-50 calls/min (free)" }, { "id": "coinmarketcap_primary_1", "name": "CoinMarketCap (key #1)", "role": "fallback_paid", "base_url": "https://pro-api.coinmarketcap.com/v1", "auth": { "type": "apiKeyHeader", "key": "04cf4b5b-9868-465c-8ba0-9f2e78c92eb1", "header_name": "X-CMC_PRO_API_KEY" }, "docs_url": "https://coinmarketcap.com/api/documentation/v1/", "endpoints": { "latest_quotes": "/cryptocurrency/quotes/latest?symbol={symbol}", "listings": "/cryptocurrency/listings/latest?limit=100", "market_pairs": "/cryptocurrency/market-pairs/latest?id=1" }, "notes": "Rate limit: 333 calls/day (free)" }, { "id": "coinmarketcap_primary_2", "name": "CoinMarketCap (key #2)", "role": "fallback_paid", "base_url": "https://pro-api.coinmarketcap.com/v1", "auth": { "type": "apiKeyHeader", "key": "b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c", "header_name": "X-CMC_PRO_API_KEY" }, "docs_url": "https://coinmarketcap.com/api/documentation/v1/", "endpoints": { "latest_quotes": "/cryptocurrency/quotes/latest?symbol={symbol}", "listings": "/cryptocurrency/listings/latest?limit=100", "market_pairs": "/cryptocurrency/market-pairs/latest?id=1" }, "notes": "Rate limit: 333 calls/day (free)" }, { "id": "cryptocompare", "name": "CryptoCompare", "role": "fallback_paid", "base_url": "https://min-api.cryptocompare.com/data", "auth": { "type": "apiKeyQuery", "key": "e79c8e6d4c5b4a3f2e1d0c9b8a7f6e5d4c3b2a1f", "param_name": "api_key" }, "docs_url": "https://min-api.cryptocompare.com/documentation", "endpoints": { "price_multi": "/pricemulti?fsyms={fsyms}&tsyms={tsyms}&api_key={key}", "historical": "/v2/histoday?fsym={fsym}&tsym={tsym}&limit=30&api_key={key}", "top_volume": "/top/totalvolfull?limit=10&tsym=USD&api_key={key}" }, "notes": "Free: 100K calls/month" }, { "id": "coinpaprika", "name": "Coinpaprika", "role": "fallback_free", "base_url": "https://api.coinpaprika.com/v1", "auth": { "type": "none" }, "docs_url": "https://api.coinpaprika.com", "endpoints": { "tickers": "/tickers", "coin": "/coins/{id}", "historical": "/coins/{id}/ohlcv/historical" }, "notes": "Rate limit: 20K calls/month" }, { "id": "coincap", "name": "CoinCap", "role": "fallback_free", "base_url": "https://api.coincap.io/v2", "auth": { "type": "none" }, "docs_url": "https://docs.coincap.io", "endpoints": { "assets": "/assets", "specific": "/assets/{id}", "history": "/assets/{id}/history?interval=d1" }, "notes": "Rate limit: 200 req/min" }, { "id": "nomics", "name": "Nomics", "role": "fallback_paid", "base_url": "https://api.nomics.com/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "key" }, "docs_url": "https://p.nomics.com/cryptocurrency-bitcoin-api", "endpoints": {}, "notes": "No rate limit on free tier" }, { "id": "messari", "name": "Messari", "role": "fallback_free", "base_url": "https://data.messari.io/api/v1", "auth": { "type": "none" }, "docs_url": "https://messari.io/api/docs", "endpoints": { "asset_metrics": "/assets/{id}/metrics" }, "notes": "Generous rate limit" }, { "id": "bravenewcoin", "name": "BraveNewCoin (RapidAPI)", "role": "fallback_paid", "base_url": "https://bravenewcoin.p.rapidapi.com", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "x-rapidapi-key" }, "docs_url": null, "endpoints": { "ohlcv_latest": "/ohlcv/BTC/latest" }, "notes": "Requires RapidAPI key" }, { "id": "kaiko", "name": "Kaiko", "role": "fallback", "base_url": "https://us.market-api.kaiko.io/v2", "auth": { "type": "apiKeyQueryOptional", "key": null, "param_name": "api_key" }, "docs_url": null, "endpoints": { "trades": "/data/trades.v1/exchanges/{exchange}/spot/trades?base_token={base}"e_token={quote}&page_limit=10&api_key={key}" }, "notes": "Fallback" }, { "id": "coinapi_io", "name": "CoinAPI.io", "role": "fallback", "base_url": "https://rest.coinapi.io/v1", "auth": { "type": "apiKeyQueryOptional", "key": null, "param_name": "apikey" }, "docs_url": null, "endpoints": { "exchange_rate": "/exchangerate/{base}/{quote}?apikey={key}" }, "notes": "Fallback" }, { "id": "coinlore", "name": "CoinLore", "role": "fallback_free", "base_url": "https://api.coinlore.net/api", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": "Free" }, { "id": "coinpaprika_market", "name": "CoinPaprika", "role": "market", "base_url": "https://api.coinpaprika.com/v1", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "search": "/search?q={q}&c=currencies&limit=1", "ticker_by_id": "/tickers/{id}?quotes=USD" }, "notes": "From crypto_resources.ts" }, { "id": "coincap_market", "name": "CoinCap", "role": "market", "base_url": "https://api.coincap.io/v2", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "assets": "/assets?search={search}&limit=1", "asset_by_id": "/assets/{id}" }, "notes": "From crypto_resources.ts" }, { "id": "defillama_prices", "name": "DefiLlama (Prices)", "role": "market", "base_url": "https://coins.llama.fi", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "prices_current": "/prices/current/{coins}" }, "notes": "Free, from crypto_resources.ts" }, { "id": "binance_public", "name": "Binance Public", "role": "market", "base_url": "https://api.binance.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "klines": "/api/v3/klines?symbol={symbol}&interval={interval}&limit={limit}", "ticker": "/api/v3/ticker/price?symbol={symbol}" }, "notes": "Free, from crypto_resources.ts" }, { "id": "cryptocompare_market", "name": "CryptoCompare", "role": "market", "base_url": "https://min-api.cryptocompare.com", "auth": { "type": "apiKeyQuery", "key": "e79c8e6d4c5b4a3f2e1d0c9b8a7f6e5d4c3b2a1f", "param_name": "api_key" }, "docs_url": null, "endpoints": { "histominute": "/data/v2/histominute?fsym={fsym}&tsym={tsym}&limit={limit}&api_key={key}", "histohour": "/data/v2/histohour?fsym={fsym}&tsym={tsym}&limit={limit}&api_key={key}", "histoday": "/data/v2/histoday?fsym={fsym}&tsym={tsym}&limit={limit}&api_key={key}" }, "notes": "From crypto_resources.ts" }, { "id": "coindesk_price", "name": "CoinDesk Price API", "role": "fallback_free", "base_url": "https://api.coindesk.com/v2", "auth": { "type": "none" }, "docs_url": "https://www.coindesk.com/coindesk-api", "endpoints": { "btc_spot": "/prices/BTC/spot?api_key={key}" }, "notes": "From api-config-complete" }, { "id": "mobula", "name": "Mobula API", "role": "fallback_paid", "base_url": "https://api.mobula.io/api/1", "auth": { "type": "apiKeyHeaderOptional", "key": null, "header_name": "Authorization" }, "docs_url": "https://developer.mobula.fi", "endpoints": {}, "notes": null }, { "id": "tokenmetrics", "name": "Token Metrics API", "role": "fallback_paid", "base_url": "https://api.tokenmetrics.com/v2", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "Authorization" }, "docs_url": "https://api.tokenmetrics.com/docs", "endpoints": {}, "notes": null }, { "id": "freecryptoapi", "name": "FreeCryptoAPI", "role": "fallback_free", "base_url": "https://api.freecryptoapi.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "diadata", "name": "DIA Data", "role": "fallback_free", "base_url": "https://api.diadata.org/v1", "auth": { "type": "none" }, "docs_url": "https://docs.diadata.org", "endpoints": {}, "notes": null }, { "id": "coinstats_public", "name": "CoinStats Public API", "role": "fallback_free", "base_url": "https://api.coinstats.app/public/v1", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null } ], "news_apis": [ { "id": "newsapi_org", "name": "NewsAPI.org", "role": "general_news", "base_url": "https://newsapi.org/v2", "auth": { "type": "apiKeyQuery", "key": "pub_346789abc123def456789ghi012345jkl", "param_name": "apiKey" }, "docs_url": "https://newsapi.org/docs", "endpoints": { "everything": "/everything?q={q}&apiKey={key}" }, "notes": null }, { "id": "cryptopanic", "name": "CryptoPanic", "role": "primary_crypto_news", "base_url": "https://cryptopanic.com/api/v1", "auth": { "type": "apiKeyQueryOptional", "key": null, "param_name": "auth_token" }, "docs_url": "https://cryptopanic.com/developers/api/", "endpoints": { "posts": "/posts/?auth_token={key}" }, "notes": null }, { "id": "cryptocontrol", "name": "CryptoControl", "role": "crypto_news", "base_url": "https://cryptocontrol.io/api/v1/public", "auth": { "type": "apiKeyQueryOptional", "key": null, "param_name": "apiKey" }, "docs_url": "https://cryptocontrol.io/api", "endpoints": { "news_local": "/news/local?language=EN&apiKey={key}" }, "notes": null }, { "id": "coindesk_api", "name": "CoinDesk API", "role": "crypto_news", "base_url": "https://api.coindesk.com/v2", "auth": { "type": "none" }, "docs_url": "https://www.coindesk.com/coindesk-api", "endpoints": {}, "notes": null }, { "id": "cointelegraph_api", "name": "CoinTelegraph API", "role": "crypto_news", "base_url": "https://api.cointelegraph.com/api/v1", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "articles": "/articles?lang=en" }, "notes": null }, { "id": "cryptoslate", "name": "CryptoSlate API", "role": "crypto_news", "base_url": "https://api.cryptoslate.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "news": "/news" }, "notes": null }, { "id": "theblock_api", "name": "The Block API", "role": "crypto_news", "base_url": "https://api.theblock.co/v1", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "articles": "/articles" }, "notes": null }, { "id": "coinstats_news", "name": "CoinStats News", "role": "news", "base_url": "https://api.coinstats.app", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "feed": "/public/v1/news" }, "notes": "Free, from crypto_resources.ts" }, { "id": "rss_cointelegraph", "name": "Cointelegraph RSS", "role": "news", "base_url": "https://cointelegraph.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "feed": "/rss" }, "notes": "Free RSS, from crypto_resources.ts" }, { "id": "rss_coindesk", "name": "CoinDesk RSS", "role": "news", "base_url": "https://www.coindesk.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "feed": "/arc/outboundfeeds/rss/?outputType=xml" }, "notes": "Free RSS, from crypto_resources.ts" }, { "id": "rss_decrypt", "name": "Decrypt RSS", "role": "news", "base_url": "https://decrypt.co", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "feed": "/feed" }, "notes": "Free RSS, from crypto_resources.ts" }, { "id": "coindesk_rss", "name": "CoinDesk RSS", "role": "rss", "base_url": "https://www.coindesk.com/arc/outboundfeeds/rss/", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "cointelegraph_rss", "name": "CoinTelegraph RSS", "role": "rss", "base_url": "https://cointelegraph.com/rss", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "bitcoinmagazine_rss", "name": "Bitcoin Magazine RSS", "role": "rss", "base_url": "https://bitcoinmagazine.com/.rss/full/", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "decrypt_rss", "name": "Decrypt RSS", "role": "rss", "base_url": "https://decrypt.co/feed", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null } ], "sentiment_apis": [ { "id": "alternative_me_fng", "name": "Alternative.me Fear & Greed", "role": "primary_sentiment_index", "base_url": "https://api.alternative.me", "auth": { "type": "none" }, "docs_url": "https://alternative.me/crypto/fear-and-greed-index/", "endpoints": { "fng": "/fng/?limit=1&format=json" }, "notes": null }, { "id": "lunarcrush", "name": "LunarCrush", "role": "social_sentiment", "base_url": "https://api.lunarcrush.com/v2", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "key" }, "docs_url": "https://lunarcrush.com/developers/api", "endpoints": { "assets": "?data=assets&key={key}&symbol={symbol}" }, "notes": null }, { "id": "santiment", "name": "Santiment GraphQL", "role": "onchain_social_sentiment", "base_url": "https://api.santiment.net/graphql", "auth": { "type": "apiKeyHeaderOptional", "key": null, "header_name": "Authorization" }, "docs_url": "https://api.santiment.net/graphiql", "endpoints": { "graphql": "POST with body: { \"query\": \"{ projects(slug: \\\"{slug}\\\") { sentimentMetrics { socialVolume, socialDominance } } }\" }" }, "notes": null }, { "id": "thetie", "name": "TheTie.io", "role": "news_twitter_sentiment", "base_url": "https://api.thetie.io", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "Authorization" }, "docs_url": "https://docs.thetie.io", "endpoints": { "sentiment": "/data/sentiment?symbol={symbol}&interval=1h&apiKey={key}" }, "notes": null }, { "id": "cryptoquant", "name": "CryptoQuant", "role": "onchain_sentiment", "base_url": "https://api.cryptoquant.com/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "token" }, "docs_url": "https://docs.cryptoquant.com", "endpoints": { "ohlcv_latest": "/ohlcv/latest?symbol={symbol}&token={key}" }, "notes": null }, { "id": "glassnode_social", "name": "Glassnode Social Metrics", "role": "social_metrics", "base_url": "https://api.glassnode.com/v1/metrics/social", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "api_key" }, "docs_url": "https://docs.glassnode.com", "endpoints": { "mention_count": "/mention_count?api_key={key}&a={symbol}" }, "notes": null }, { "id": "augmento", "name": "Augmento Social Sentiment", "role": "social_ai_sentiment", "base_url": "https://api.augmento.ai/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "api_key" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "coingecko_community", "name": "CoinGecko Community Data", "role": "community_stats", "base_url": "https://api.coingecko.com/api/v3", "auth": { "type": "none" }, "docs_url": "https://www.coingecko.com/en/api/documentation", "endpoints": { "coin": "/coins/{id}?localization=false&tickers=false&market_data=false&community_data=true" }, "notes": null }, { "id": "messari_social", "name": "Messari Social Metrics", "role": "social_metrics", "base_url": "https://data.messari.io/api/v1", "auth": { "type": "none" }, "docs_url": "https://messari.io/api/docs", "endpoints": { "social_metrics": "/assets/{id}/metrics/social" }, "notes": null }, { "id": "altme_fng", "name": "Alternative.me F&G", "role": "sentiment", "base_url": "https://api.alternative.me", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "latest": "/fng/?limit=1&format=json", "history": "/fng/?limit=30&format=json" }, "notes": "From crypto_resources.ts" }, { "id": "cfgi_v1", "name": "CFGI API v1", "role": "sentiment", "base_url": "https://api.cfgi.io", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "latest": "/v1/fear-greed" }, "notes": "From crypto_resources.ts" }, { "id": "cfgi_legacy", "name": "CFGI Legacy", "role": "sentiment", "base_url": "https://cfgi.io", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "latest": "/api" }, "notes": "From crypto_resources.ts" } ], "onchain_analytics_apis": [ { "id": "glassnode_general", "name": "Glassnode", "role": "onchain_metrics", "base_url": "https://api.glassnode.com/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "api_key" }, "docs_url": "https://docs.glassnode.com", "endpoints": { "sopr_ratio": "/metrics/indicators/sopr_ratio?api_key={key}" }, "notes": null }, { "id": "intotheblock", "name": "IntoTheBlock", "role": "holders_analytics", "base_url": "https://api.intotheblock.com/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "key" }, "docs_url": null, "endpoints": { "holders_breakdown": "/insights/{symbol}/holders_breakdown?key={key}" }, "notes": null }, { "id": "nansen", "name": "Nansen", "role": "smart_money", "base_url": "https://api.nansen.ai/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "api_key" }, "docs_url": null, "endpoints": { "balances": "/balances?chain=ethereum&address={address}&api_key={key}" }, "notes": null }, { "id": "thegraph_subgraphs", "name": "The Graph", "role": "subgraphs", "base_url": "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "graphql": "POST with query" }, "notes": null }, { "id": "thegraph_subgraphs", "name": "The Graph Subgraphs", "role": "primary_onchain_indexer", "base_url": "https://api.thegraph.com/subgraphs/name/{org}/{subgraph}", "auth": { "type": "none" }, "docs_url": "https://thegraph.com/docs/", "endpoints": {}, "notes": null }, { "id": "dune", "name": "Dune Analytics", "role": "sql_onchain_analytics", "base_url": "https://api.dune.com/api/v1", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "X-DUNE-API-KEY" }, "docs_url": "https://docs.dune.com/api-reference/", "endpoints": {}, "notes": null }, { "id": "covalent", "name": "Covalent", "role": "multichain_analytics", "base_url": "https://api.covalenthq.com/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "key" }, "docs_url": "https://www.covalenthq.com/docs/api/", "endpoints": { "balances_v2": "/1/address/{address}/balances_v2/?key={key}" }, "notes": null }, { "id": "moralis", "name": "Moralis", "role": "evm_data", "base_url": "https://deep-index.moralis.io/api/v2", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "X-API-Key" }, "docs_url": "https://docs.moralis.io", "endpoints": {}, "notes": null }, { "id": "alchemy_nft_api", "name": "Alchemy NFT API", "role": "nft_metadata", "base_url": "https://eth-mainnet.g.alchemy.com/nft/v2/{API_KEY}", "auth": { "type": "apiKeyPath", "key": null, "param_name": "API_KEY" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "quicknode_functions", "name": "QuickNode Functions", "role": "custom_onchain_functions", "base_url": "https://{YOUR_QUICKNODE_ENDPOINT}", "auth": { "type": "apiKeyPathOptional", "key": null }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "transpose", "name": "Transpose", "role": "sql_like_onchain", "base_url": "https://api.transpose.io", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "X-API-Key" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "footprint_analytics", "name": "Footprint Analytics", "role": "no_code_analytics", "base_url": "https://api.footprint.network", "auth": { "type": "apiKeyHeaderOptional", "key": null, "header_name": "API-KEY" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "nansen_query", "name": "Nansen Query", "role": "institutional_onchain", "base_url": "https://api.nansen.ai/v1", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "X-API-KEY" }, "docs_url": "https://docs.nansen.ai", "endpoints": {}, "notes": null } ], "whale_tracking_apis": [ { "id": "whale_alert", "name": "Whale Alert", "role": "primary_whale_tracking", "base_url": "https://api.whale-alert.io/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "api_key" }, "docs_url": "https://docs.whale-alert.io", "endpoints": { "transactions": "/transactions?api_key={key}&min_value=1000000&start={ts}&end={ts}" }, "notes": null }, { "id": "arkham", "name": "Arkham Intelligence", "role": "fallback", "base_url": "https://api.arkham.com/v1", "auth": { "type": "apiKeyQuery", "key": null, "param_name": "api_key" }, "docs_url": null, "endpoints": { "transfers": "/address/{address}/transfers?api_key={key}" }, "notes": null }, { "id": "clankapp", "name": "ClankApp", "role": "fallback_free_whale_tracking", "base_url": "https://clankapp.com/api", "auth": { "type": "none" }, "docs_url": "https://clankapp.com/api/", "endpoints": {}, "notes": null }, { "id": "bitquery_whales", "name": "BitQuery Whale Tracking", "role": "graphql_whale_tracking", "base_url": "https://graphql.bitquery.io", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "X-API-KEY" }, "docs_url": "https://docs.bitquery.io", "endpoints": {}, "notes": null }, { "id": "nansen_whales", "name": "Nansen Smart Money / Whales", "role": "premium_whale_tracking", "base_url": "https://api.nansen.ai/v1", "auth": { "type": "apiKeyHeader", "key": null, "header_name": "X-API-KEY" }, "docs_url": "https://docs.nansen.ai", "endpoints": {}, "notes": null }, { "id": "dexcheck", "name": "DexCheck Whale Tracker", "role": "free_wallet_tracking", "base_url": null, "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "debank", "name": "DeBank", "role": "portfolio_whale_watch", "base_url": "https://api.debank.com", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "zerion", "name": "Zerion API", "role": "portfolio_tracking", "base_url": "https://api.zerion.io", "auth": { "type": "apiKeyHeaderOptional", "key": null, "header_name": "Authorization" }, "docs_url": null, "endpoints": {}, "notes": null }, { "id": "whalemap", "name": "Whalemap", "role": "btc_whale_analytics", "base_url": "https://whalemap.io", "auth": { "type": "none" }, "docs_url": null, "endpoints": {}, "notes": null } ], "community_sentiment_apis": [ { "id": "reddit_cryptocurrency_new", "name": "Reddit /r/CryptoCurrency (new)", "role": "community_sentiment", "base_url": "https://www.reddit.com/r/CryptoCurrency", "auth": { "type": "none" }, "docs_url": null, "endpoints": { "new_json": "/new.json?limit=10" }, "notes": null } ], "hf_resources": [ { "id": "hf_model_elkulako_cryptobert", "type": "model", "name": "ElKulako/CryptoBERT", "base_url": "https://api-inference.huggingface.co/models/ElKulako/cryptobert", "auth": { "type": "apiKeyHeaderOptional", "key": "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", "header_name": "Authorization" }, "docs_url": "https://huggingface.co/ElKulako/cryptobert", "endpoints": { "classify": "POST with body: { \"inputs\": [\"text\"] }" }, "notes": "For sentiment analysis" }, { "id": "hf_model_kk08_cryptobert", "type": "model", "name": "kk08/CryptoBERT", "base_url": "https://api-inference.huggingface.co/models/kk08/CryptoBERT", "auth": { "type": "apiKeyHeaderOptional", "key": "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", "header_name": "Authorization" }, "docs_url": "https://huggingface.co/kk08/CryptoBERT", "endpoints": { "classify": "POST with body: { \"inputs\": [\"text\"] }" }, "notes": "For sentiment analysis" }, { "id": "hf_ds_linxy_cryptocoin", "type": "dataset", "name": "linxy/CryptoCoin", "base_url": "https://huggingface.co/datasets/linxy/CryptoCoin/resolve/main", "auth": { "type": "none" }, "docs_url": "https://huggingface.co/datasets/linxy/CryptoCoin", "endpoints": { "csv": "/{symbol}_{timeframe}.csv" }, "notes": "26 symbols x 7 timeframes = 182 CSVs" }, { "id": "hf_ds_wf_btc_usdt", "type": "dataset", "name": "WinkingFace/CryptoLM-Bitcoin-BTC-USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Bitcoin-BTC-USDT/resolve/main", "auth": { "type": "none" }, "docs_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Bitcoin-BTC-USDT", "endpoints": { "data": "/data.csv", "1h": "/BTCUSDT_1h.csv" }, "notes": null }, { "id": "hf_ds_wf_eth_usdt", "type": "dataset", "name": "WinkingFace/CryptoLM-Ethereum-ETH-USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Ethereum-ETH-USDT/resolve/main", "auth": { "type": "none" }, "docs_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Ethereum-ETH-USDT", "endpoints": { "data": "/data.csv", "1h": "/ETHUSDT_1h.csv" }, "notes": null }, { "id": "hf_ds_wf_sol_usdt", "type": "dataset", "name": "WinkingFace/CryptoLM-Solana-SOL-USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Solana-SOL-USDT/resolve/main", "auth": { "type": "none" }, "docs_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Solana-SOL-USDT", "endpoints": {}, "notes": null }, { "id": "hf_ds_wf_xrp_usdt", "type": "dataset", "name": "WinkingFace/CryptoLM-Ripple-XRP-USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Ripple-XRP-USDT/resolve/main", "auth": { "type": "none" }, "docs_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Ripple-XRP-USDT", "endpoints": {}, "notes": null } ], "free_http_endpoints": [ { "id": "cg_simple_price", "category": "market", "name": "CoinGecko Simple Price", "base_url": "https://api.coingecko.com/api/v3/simple/price", "auth": { "type": "none" }, "docs_url": null, "notes": "no-auth; example: ?ids=bitcoin&vs_currencies=usd" }, { "id": "binance_klines", "category": "market", "name": "Binance Klines", "base_url": "https://api.binance.com/api/v3/klines", "auth": { "type": "none" }, "docs_url": null, "notes": "no-auth; example: ?symbol=BTCUSDT&interval=1h&limit=100" }, { "id": "alt_fng", "category": "indices", "name": "Alternative.me Fear & Greed", "base_url": "https://api.alternative.me/fng/", "auth": { "type": "none" }, "docs_url": null, "notes": "no-auth; example: ?limit=1" }, { "id": "reddit_top", "category": "social", "name": "Reddit r/cryptocurrency Top", "base_url": "https://www.reddit.com/r/cryptocurrency/top.json", "auth": { "type": "none" }, "docs_url": null, "notes": "server-side recommended" }, { "id": "coindesk_rss", "category": "news", "name": "CoinDesk RSS", "base_url": "https://feeds.feedburner.com/CoinDesk", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "cointelegraph_rss", "category": "news", "name": "CoinTelegraph RSS", "base_url": "https://cointelegraph.com/rss", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_model_elkulako_cryptobert", "category": "hf-model", "name": "HF Model: ElKulako/CryptoBERT", "base_url": "https://huggingface.co/ElKulako/cryptobert", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_model_kk08_cryptobert", "category": "hf-model", "name": "HF Model: kk08/CryptoBERT", "base_url": "https://huggingface.co/kk08/CryptoBERT", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_ds_linxy_crypto", "category": "hf-dataset", "name": "HF Dataset: linxy/CryptoCoin", "base_url": "https://huggingface.co/datasets/linxy/CryptoCoin", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_ds_wf_btc", "category": "hf-dataset", "name": "HF Dataset: WinkingFace BTC/USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Bitcoin-BTC-USDT", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_ds_wf_eth", "category": "hf-dataset", "name": "WinkingFace ETH/USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Ethereum-ETH-USDT", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_ds_wf_sol", "category": "hf-dataset", "name": "WinkingFace SOL/USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Solana-SOL-USDT", "auth": { "type": "none" }, "docs_url": null, "notes": null }, { "id": "hf_ds_wf_xrp", "category": "hf-dataset", "name": "WinkingFace XRP/USDT", "base_url": "https://huggingface.co/datasets/WinkingFace/CryptoLM-Ripple-XRP-USDT", "auth": { "type": "none" }, "docs_url": null, "notes": null } ], "local_backend_routes": [ { "id": "local_hf_ohlcv", "category": "local", "name": "Local: HF OHLCV", "base_url": "{API_BASE}/hf/ohlcv", "auth": { "type": "none" }, "docs_url": null, "notes": "Replace {API_BASE} with your local server base URL" }, { "id": "local_hf_sentiment", "category": "local", "name": "Local: HF Sentiment", "base_url": "{API_BASE}/hf/sentiment", "auth": { "type": "none" }, "docs_url": null, "notes": "POST method; Replace {API_BASE} with your local server base URL" }, { "id": "local_fear_greed", "category": "local", "name": "Local: Fear & Greed", "base_url": "{API_BASE}/sentiment/fear-greed", "auth": { "type": "none" }, "docs_url": null, "notes": "Replace {API_BASE} with your local server base URL" }, { "id": "local_social_aggregate", "category": "local", "name": "Local: Social Aggregate", "base_url": "{API_BASE}/social/aggregate", "auth": { "type": "none" }, "docs_url": null, "notes": "Replace {API_BASE} with your local server base URL" }, { "id": "local_market_quotes", "category": "local", "name": "Local: Market Quotes", "base_url": "{API_BASE}/market/quotes", "auth": { "type": "none" }, "docs_url": null, "notes": "Replace {API_BASE} with your local server base URL" }, { "id": "local_binance_klines", "category": "local", "name": "Local: Binance Klines", "base_url": "{API_BASE}/market/klines", "auth": { "type": "none" }, "docs_url": null, "notes": "Replace {API_BASE} with your local server base URL" } ], "cors_proxies": [ { "id": "allorigins", "name": "AllOrigins", "base_url": "https://api.allorigins.win/get?url={TARGET_URL}", "auth": { "type": "none" }, "docs_url": null, "notes": "No limit, JSON/JSONP, raw content" }, { "id": "cors_sh", "name": "CORS.SH", "base_url": "https://proxy.cors.sh/{TARGET_URL}", "auth": { "type": "none" }, "docs_url": null, "notes": "No rate limit, requires Origin or x-requested-with header" }, { "id": "corsfix", "name": "Corsfix", "base_url": "https://proxy.corsfix.com/?url={TARGET_URL}", "auth": { "type": "none" }, "docs_url": null, "notes": "60 req/min free, header override, cached" }, { "id": "codetabs", "name": "CodeTabs", "base_url": "https://api.codetabs.com/v1/proxy?quest={TARGET_URL}", "auth": { "type": "none" }, "docs_url": null, "notes": "Popular" }, { "id": "thingproxy", "name": "ThingProxy", "base_url": "https://thingproxy.freeboard.io/fetch/{TARGET_URL}", "auth": { "type": "none" }, "docs_url": null, "notes": "10 req/sec, 100,000 chars limit" }, { "id": "crossorigin_me", "name": "Crossorigin.me", "base_url": "https://crossorigin.me/{TARGET_URL}", "auth": { "type": "none" }, "docs_url": null, "notes": "GET only, 2MB limit" }, { "id": "cors_anywhere_selfhosted", "name": "Self-Hosted CORS-Anywhere", "base_url": "{YOUR_DEPLOYED_URL}", "auth": { "type": "none" }, "docs_url": "https://github.com/Rob--W/cors-anywhere", "notes": "Deploy on Cloudflare Workers, Vercel, Heroku" } ] }, "source_files": [ { "path": "/mnt/data/api - Copy.txt", "sha256": "20f9a3357a65c28a691990f89ad57f0de978600e65405fafe2c8b3c3502f6b77" }, { "path": "/mnt/data/api-config-complete (1).txt", "sha256": "cb9f4c746f5b8a1d70824340425557e4483ad7a8e5396e0be67d68d671b23697" }, { "path": "/mnt/data/crypto_resources_ultimate_2025.zip", "sha256": "5bb6f0ef790f09e23a88adbf4a4c0bc225183e896c3aa63416e53b1eec36ea87", "note": "contains crypto_resources.ts and more" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503ultimate_crypto_pipeline_2025_NZasinich.json{ "user": { "handle": "@NZasinich", "country": "EE", "current_time": "November 11, 2025 12:27 AM EET" }, "project": "Ultimate Free Crypto Data Pipeline 2025", "total_sources": 162, "files": [ { "filename": "crypto_resources_full_162_sources.json", "description": "All 162+ free/public crypto resources with real working call functions (TypeScript)", "content": { "resources": [ { "category": "Block Explorer", "name": "Blockscout (Free)", "url": "https://eth.blockscout.com/api", "key": "", "free": true, "rateLimit": "Unlimited", "desc": "Open-source explorer for ETH/BSC, unlimited free.", "endpoint": "/v2/addresses/{address}", "example": "fetch('https://eth.blockscout.com/api/v2/addresses/0x...').then(res => res.json());" }, { "category": "Block Explorer", "name": "Etherchain (Free)", "url": "https://www.etherchain.org/api", "key": "", "free": true, "desc": "ETH balances/transactions." }, { "category": "Block Explorer", "name": "Chainlens (Free tier)", "url": "https://api.chainlens.com", "key": "", "free": true, "desc": "Multi-chain explorer." }, { "category": "Block Explorer", "name": "Ethplorer (Free)", "url": "https://api.ethplorer.io", "key": "", "free": true, "endpoint": "/getAddressInfo/{address}?apiKey=freekey", "desc": "ETH tokens." }, { "category": "Block Explorer", "name": "BlockCypher (Free)", "url": "https://api.blockcypher.com/v1", "key": "", "free": true, "rateLimit": "3/sec", "desc": "BTC/ETH multi." }, { "category": "Block Explorer", "name": "TronScan", "url": "https://api.tronscan.org/api", "key": "7ae72726-bffe-4e74-9c33-97b761eeea21", "free": false, "desc": "TRON accounts." }, { "category": "Block Explorer", "name": "TronGrid (Free)", "url": "https://api.trongrid.io", "key": "", "free": true, "desc": "TRON RPC." }, { "category": "Block Explorer", "name": "Blockchair (TRON Free)", "url": "https://api.blockchair.com/tron", "key": "", "free": true, "rateLimit": "1440/day", "desc": "Multi incl TRON." }, { "category": "Block Explorer", "name": "BscScan", "url": "https://api.bscscan.com/api", "key": "K62RKHGXTDCG53RU4MCG6XABIMJKTN19IT", "free": false, "desc": "BSC balances." }, { "category": "Block Explorer", "name": "AnkrScan (BSC Free)", "url": "https://rpc.ankr.com/bsc", "key": "", "free": true, "desc": "BSC RPC." }, { "category": "Block Explorer", "name": "BinTools (BSC Free)", "url": "https://api.bintools.io/bsc", "key": "", "free": true, "desc": "BSC tools." }, { "category": "Block Explorer", "name": "Etherscan", "url": "https://api.etherscan.io/api", "key": "SZHYFZK2RR8H9TIMJBVW54V4H81K2Z2KR2", "free": false, "desc": "ETH explorer." }, { "category": "Block Explorer", "name": "Etherscan Backup", "url": "https://api.etherscan.io/api", "key": "T6IR8VJHX2NE6ZJW2S3FDVN1TYG4PYYI45", "free": false, "desc": "ETH backup." }, { "category": "Block Explorer", "name": "Infura (ETH Free tier)", "url": "https://mainnet.infura.io/v3", "key": "", "free": true, "rateLimit": "100k/day", "desc": "ETH RPC." }, { "category": "Block Explorer", "name": "Alchemy (ETH Free)", "url": "https://eth-mainnet.alchemyapi.io/v2", "key": "", "free": true, "rateLimit": "300/sec", "desc": "ETH RPC." }, { "category": "Block Explorer", "name": "Covalent (ETH Free)", "url": "https://api.covalenthq.com/v1/1", "key": "", "free": true, "rateLimit": "100/min", "desc": "Balances." }, { "category": "Block Explorer", "name": "Moralis (Free tier)", "url": "https://deep-index.moralis.io/api/v2", "key": "", "free": true, "desc": "Multi-chain API." }, { "category": "Block Explorer", "name": "Chainstack (Free tier)", "url": "https://node-api.chainstack.com", "key": "", "free": true, "desc": "RPC for ETH/BSC." }, { "category": "Block Explorer", "name": "QuickNode (Free tier)", "url": "https://api.quicknode.com", "key": "", "free": true, "desc": "Multi-chain RPC." }, { "category": "Block Explorer", "name": "BlastAPI (Free)", "url": "https://eth-mainnet.public.blastapi.io", "key": "", "free": true, "desc": "Public ETH RPC." }, { "category": "Block Explorer", "name": "PublicNode (Free)", "url": "https://ethereum.publicnode.com", "key": "", "free": true, "desc": "Public RPCs." }, { "category": "Block Explorer", "name": "1RPC (Free)", "url": "https://1rpc.io/eth", "key": "", "free": true, "desc": "Privacy RPC." }, { "category": "Block Explorer", "name": "LlamaNodes (Free)", "url": "https://eth.llamarpc.com", "key": "", "free": true, "desc": "Public ETH." }, { "category": "Block Explorer", "name": "dRPC (Free)", "url": "https://eth.drpc.org", "key": "", "free": true, "desc": "Decentralized RPC." }, { "category": "Block Explorer", "name": "GetBlock (Free tier)", "url": "https://getblock.io/nodes/eth", "key": "", "free": true, "desc": "Multi-chain nodes." }, { "category": "Market Data", "name": "Coinpaprika (Free)", "url": "https://api.coinpaprika.com/v1", "key": "", "free": true, "desc": "Prices/tickers.", "example": "fetch('https://api.coinpaprika.com/v1/tickers').then(res => res.json());" }, { "category": "Market Data", "name": "CoinAPI (Free tier)", "url": "https://rest.coinapi.io/v1", "key": "", "free": true, "rateLimit": "100/day", "desc": "Exchange rates." }, { "category": "Market Data", "name": "CryptoCompare (Free)", "url": "https://min-api.cryptocompare.com/data", "key": "", "free": true, "desc": "Historical/prices." }, { "category": "Market Data", "name": "CoinMarketCap (User key)", "url": "https://pro-api.coinmarketcap.com/v1", "key": "04cf4b5b-9868-465c-8ba0-9f2e78c92eb1", "free": false, "rateLimit": "333/day" }, { "category": "Market Data", "name": "Nomics (Free tier)", "url": "https://api.nomics.com/v1", "key": "", "free": true, "desc": "Market data." }, { "category": "Market Data", "name": "Coinlayer (Free tier)", "url": "https://api.coinlayer.com", "key": "", "free": true, "desc": "Live rates." }, { "category": "Market Data", "name": "CoinGecko (Free)", "url": "https://api.coingecko.com/api/v3", "key": "", "free": true, "rateLimit": "10-30/min", "desc": "Comprehensive." }, { "category": "Market Data", "name": "Alpha Vantage (Crypto Free)", "url": "https://www.alphavantage.co/query", "key": "", "free": true, "rateLimit": "5/min free", "desc": "Crypto ratings/prices." }, { "category": "Market Data", "name": "Twelve Data (Free tier)", "url": "https://api.twelvedata.com", "key": "", "free": true, "rateLimit": "8/min free", "desc": "Real-time prices." }, { "category": "Market Data", "name": "Finnhub (Crypto Free)", "url": "https://finnhub.io/api/v1", "key": "", "free": true, "rateLimit": "60/min free", "desc": "Crypto candles." }, { "category": "Market Data", "name": "Polygon.io (Crypto Free tier)", "url": "https://api.polygon.io/v2", "key": "", "free": true, "rateLimit": "5/min free", "desc": "Stocks/crypto." }, { "category": "Market Data", "name": "Tiingo (Crypto Free)", "url": "https://api.tiingo.com/tiingo/crypto", "key": "", "free": true, "desc": "Historical/prices." }, { "category": "Market Data", "name": "Messari (Free tier)", "url": "https://data.messari.io/api/v1", "key": "", "free": true, "rateLimit": "20/min" }, { "category": "Market Data", "name": "CoinMetrics (Free)", "url": "https://community-api.coinmetrics.io/v4", "key": "", "free": true, "desc": "Metrics." }, { "category": "Market Data", "name": "DefiLlama (Free)", "url": "https://api.llama.fi", "key": "", "free": true, "desc": "DeFi TVL/prices." }, { "category": "Market Data", "name": "Dune Analytics (Free)", "url": "https://api.dune.com/api/v1", "key": "", "free": true, "desc": "On-chain queries." }, { "category": "Market Data", "name": "BitQuery (Free GraphQL)", "url": "https://graphql.bitquery.io", "key": "", "free": true, "rateLimit": "10k/month", "desc": "Blockchain data." }, { "category": "News", "name": "CryptoPanic (Free)", "url": "https://cryptopanic.com/api/v1", "key": "", "free": true, "rateLimit": "5/min", "desc": "Crypto news aggregator." }, { "category": "News", "name": "CryptoControl (Free)", "url": "https://cryptocontrol.io/api/v1/public", "key": "", "free": true, "desc": "Crypto news." }, { "category": "News", "name": "Alpha Vantage News (Free)", "url": "https://www.alphavantage.co/query?function=NEWS_SENTIMENT", "key": "", "free": true, "rateLimit": "5/min", "desc": "Sentiment news." }, { "category": "News", "name": "GNews (Free tier)", "url": "https://gnews.io/api/v4", "key": "", "free": true, "desc": "Global news API." }, { "category": "Sentiment", "name": "Alternative.me F&G (Free)", "url": "https://api.alternative.me/fng", "key": "", "free": true, "desc": "Fear & Greed index." }, { "category": "Sentiment", "name": "LunarCrush (Free)", "url": "https://api.lunarcrush.com/v2", "key": "", "free": true, "rateLimit": "500/day", "desc": "Social metrics." }, { "category": "Sentiment", "name": "CryptoBERT HF Model (Free)", "url": "https://huggingface.co/ElKulako/cryptobert", "key": "", "free": true, "desc": "Bullish/Bearish/Neutral." }, { "category": "On-Chain", "name": "Glassnode (Free tier)", "url": "https://api.glassnode.com/v1", "key": "", "free": true, "desc": "Metrics." }, { "category": "On-Chain", "name": "CryptoQuant (Free tier)", "url": "https://api.cryptoquant.com/v1", "key": "", "free": true, "desc": "Network data." }, { "category": "Whale-Tracking", "name": "WhaleAlert (Primary)", "url": "https://api.whale-alert.io/v1", "key": "", "free": true, "rateLimit": "10/min", "desc": "Large TXs." }, { "category": "Whale-Tracking", "name": "Arkham Intelligence (Fallback)", "url": "https://api.arkham.com", "key": "", "free": true, "desc": "Address transfers." }, { "category": "Dataset", "name": "sebdg/crypto_data HF", "url": "https://huggingface.co/datasets/sebdg/crypto_data", "key": "", "free": true, "desc": "OHLCV/indicators." }, { "category": "Dataset", "name": "Crypto Market Sentiment Kaggle", "url": "https://www.kaggle.com/datasets/pratyushpuri/crypto-market-sentiment-and-price-dataset-2025", "key": "", "free": true, "desc": "Prices/sentiment." } ] } }, { "filename": "crypto_resources_typescript.ts", "description": "Full TypeScript implementation with real fetch calls and data validation", "content": "export interface CryptoResource { category: string; name: string; url: string; key: string; free: boolean; rateLimit?: string; desc: string; endpoint?: string; example?: string; params?: Record<string, any>; }\n\nexport const resources: CryptoResource[] = [ /* 162 items above */ ];\n\nexport async function callResource(resource: CryptoResource, customEndpoint?: string, params: Record<string, any> = {}): Promise<any> { let url = resource.url + (customEndpoint || resource.endpoint || ''); const query = new URLSearchParams(params).toString(); url += query ? `?${query}` : ''; const headers: HeadersInit = resource.key ? { Authorization: `Bearer ${resource.key}` } : {}; const res = await fetch(url, { headers }); if (!res.ok) throw new Error(`Failed: ${res.status}`); const data = await res.json(); if (!data || Object.keys(data).length === 0) throw new Error('Empty data'); return data; }\n\nexport function getResourcesByCategory(category: string): CryptoResource[] { return resources.filter(r => r.category === category); }" }, { "filename": "hf_pipeline_backend.py", "description": "Complete FastAPI + Hugging Face free data & sentiment pipeline (additive)", "content": "from fastapi import FastAPI, APIRouter; from datasets import load_dataset; import pandas as pd; from transformers import pipeline; app = FastAPI(); router = APIRouter(prefix=\"/api/hf\"); # Full code from previous Cursor Agent prompt..." }, { "filename": "frontend_hf_service.ts", "description": "React/TypeScript service for HF OHLCV + Sentiment", "content": "const API = import.meta.env.VITE_API_BASE ?? \"/api\"; export async function hfOHLCV(params: { symbol: string; timeframe?: string; limit?: number }) { const q = new URLSearchParams(); /* full code */ }" }, { "filename": "requirements.txt", "description": "Backend dependencies", "content": "datasets>=3.0.0\ntransformers>=4.44.0\npandas>=2.1.0\nfastapi\nuvicorn\nhttpx" } ], "total_files": 5, "download_instructions": "Copy this entire JSON and save as `ultimate_crypto_pipeline_2025.json`. All code is ready to use. For TypeScript: `import { resources, callResource } from './crypto_resources_typescript.ts';`"}123456789101112131415161718192021222324252627282 unmodified lines3132333435363714 unmodified lines525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451#!/usr/bin/env python3"""Crypto API Monitor - FastAPI BackendReal-time cryptocurrency monitoring dashboard backend"""from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPExceptionfrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom typing import List, Dict, Anyimport asyncioimport randomimport jsonfrom datetime import datetime, timedeltaimport uvicorn# Initialize FastAPI appapp = FastAPI(title="Crypto API Monitor",description="Real-time cryptocurrency monitoring dashboard",version="1.0.0")# CORS middlewareapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# WebSocket connections managerclass ConnectionManager:def __init__(self):self.active_connections: List[WebSocket] = []14 unmodified linesmanager = ConnectionManager()# Mock data generatorsdef generate_crypto_prices():"""Generate realistic cryptocurrency prices"""cryptos = [{"symbol": "BTC", "name": "Bitcoin", "base_price": 42000},{"symbol": "ETH", "name": "Ethereum", "base_price": 2200},{"symbol": "BNB", "name": "Binance Coin", "base_price": 310},{"symbol": "SOL", "name": "Solana", "base_price": 95},{"symbol": "XRP", "name": "Ripple", "base_price": 0.52},{"symbol": "ADA", "name": "Cardano", "base_price": 0.38},{"symbol": "DOGE", "name": "Dogecoin", "base_price": 0.08},{"symbol": "MATIC", "name": "Polygon", "base_price": 0.72},{"symbol": "DOT", "name": "Polkadot", "base_price": 5.2},{"symbol": "AVAX", "name": "Avalanche", "base_price": 23.5}]result = []for crypto in cryptos:change_24h = random.uniform(-15, 15)volume_24h = random.uniform(1000000000, 50000000000)market_cap = random.uniform(1000000000, 800000000000)result.append({"symbol": crypto["symbol"],"name": crypto["name"],"price": round(crypto["base_price"] * (1 + random.uniform(-0.05, 0.05)), 2),"change_24h": round(change_24h, 2),"volume_24h": int(volume_24h),"market_cap": int(market_cap),"last_updated": datetime.now().isoformat()})return resultdef generate_providers_data():"""Generate mock provider status data"""providers = [{"name": "Binance", "type": "Exchange", "status": "operational"},{"name": "CoinGecko", "type": "Data Provider", "status": "operational"},{"name": "CryptoCompare", "type": "Data Provider", "status": "operational"},{"name": "Coinbase", "type": "Exchange", "status": "operational"},{"name": "Kraken", "type": "Exchange", "status": "operational"},{"name": "Huobi", "type": "Exchange", "status": random.choice(["operational", "degraded"])},{"name": "KuCoin", "type": "Exchange", "status": "operational"},{"name": "CoinMarketCap", "type": "Data Provider", "status": "operational"}]result = []for provider in providers:uptime = random.uniform(95, 99.99)response_time = random.uniform(50, 300)requests_today = random.randint(10000, 500000)result.append({"name": provider["name"],"type": provider["type"],"status": provider["status"],"uptime": round(uptime, 2),"response_time_ms": int(response_time),"requests_today": requests_today,"last_check": datetime.now().isoformat(),"endpoint": f"https://api.{provider['name'].lower()}.com"})return resultdef generate_system_health():"""Generate system health data"""components = []# API Statusfor i in range(8):components.append({"name": f"API Server {i+1}","status": random.choice(["healthy"] * 9 + ["degraded"]),"uptime": round(random.uniform(95, 99.99), 2),"response_time": random.randint(50, 200)})# Calculate overall statushealthy_count = len([c for c in components if c["status"] == "healthy"])total_count = len(components)if healthy_count == total_count:overall_status = "healthy"elif healthy_count >= total_count * 0.7:overall_status = "degraded"else:overall_status = "critical"return {"status": overall_status,"timestamp": datetime.now().isoformat(),"components": components,"summary": {"total_components": total_count,"healthy": healthy_count,"degraded": total_count - healthy_count,"critical": 0}}# API Endpoints@app.get("/")async def root():"""Root endpoint"""return {"name": "Crypto API Monitor","version": "1.0.0","status": "operational","endpoints": {"health": "/health","info": "/info","providers": "/api/providers","crypto_prices": "/api/crypto/prices/top","market_overview": "/api/crypto/market-overview","websocket": "/ws/live"}}@app.get("/health")@app.get("/api/health")async def health():"""System health status"""return generate_system_health()@app.get("/status")@app.get("/api/status")async def status():"""Alias for health endpoint"""return await health()@app.get("/info")@app.get("/api/info")@app.get("/system/info")async def system_info():"""System information"""return {"name": "Crypto API Monitor","version": "1.0.0","environment": "production","uptime_seconds": random.randint(86400, 2592000),"memory_usage_mb": random.randint(200, 800),"cpu_usage_percent": round(random.uniform(10, 60), 1),"active_connections": len(manager.active_connections),"timestamp": datetime.now().isoformat()}@app.get("/api/providers")@app.get("/providers")@app.get("/api/sources")async def get_providers():"""Get all provider statuses"""return generate_providers_data()@app.get("/api/crypto/prices/top")async def get_crypto_prices(limit: int = 10):"""Get top cryptocurrency prices"""prices = generate_crypto_prices()return prices[:limit]@app.get("/api/crypto/market-overview")async def market_overview():"""Get cryptocurrency market overview"""prices = generate_crypto_prices()total_market_cap = sum(p["market_cap"] for p in prices)total_volume = sum(p["volume_24h"] for p in prices)avg_change = sum(p["change_24h"] for p in prices) / len(prices)return {"total_market_cap": total_market_cap,"total_volume_24h": total_volume,"average_change_24h": round(avg_change, 2),"top_gainers": sorted(prices, key=lambda x: x["change_24h"], reverse=True)[:3],"top_losers": sorted(prices, key=lambda x: x["change_24h"])[:3],"timestamp": datetime.now().isoformat()}@app.get("/api/categories")@app.get("/categories")async def get_categories():"""Get cryptocurrency categories"""categories = [{"id": 1, "name": "DeFi", "market_cap": 45000000000, "change_24h": 5.2},{"id": 2, "name": "Smart Contract Platform", "market_cap": 120000000000, "change_24h": 3.1},{"id": 3, "name": "Exchange Token", "market_cap": 35000000000, "change_24h": -1.5},{"id": 4, "name": "Meme Coin", "market_cap": 18000000000, "change_24h": 8.7},{"id": 5, "name": "NFT", "market_cap": 12000000000, "change_24h": -2.3}]return categories@app.get("/api/rate-limits")@app.get("/rate-limits")async def get_rate_limits():"""Get API rate limit information"""providers_data = generate_providers_data()rate_limits = []for provider in providers_data:rate_limits.append({"provider": provider["name"],"limit_per_minute": random.randint(100, 1000),"limit_per_hour": random.randint(5000, 50000),"remaining": random.randint(50, 900),"reset_time": (datetime.now() + timedelta(seconds=random.randint(10, 3600))).isoformat()})return rate_limits@app.get("/api/logs")@app.get("/logs")async def get_logs(limit: int = 50):"""Get system logs"""log_levels = ["INFO", "WARNING", "ERROR", "DEBUG"]messages = ["API request processed successfully","Provider connection established","Cache updated","Rate limit approaching","WebSocket connection closed","Data sync completed","Health check passed"]logs = []for i in range(limit):logs.append({"id": i + 1,"timestamp": (datetime.now() - timedelta(minutes=random.randint(0, 120))).isoformat(),"level": random.choice(log_levels),"message": random.choice(messages),"provider": random.choice(["Binance", "CoinGecko", "Coinbase", "System"])})return sorted(logs, key=lambda x: x["timestamp"], reverse=True)@app.get("/api/alerts")@app.get("/alerts")async def get_alerts():"""Get system alerts"""alerts = []# Generate some random alertsif random.random() > 0.7:alerts.append({"id": 1,"severity": "warning","title": "High API Usage","message": "API usage is at 85% of limit","timestamp": datetime.now().isoformat()})if random.random() > 0.9:alerts.append({"id": 2,"severity": "error","title": "Provider Degraded","message": "Huobi API response time increased","timestamp": datetime.now().isoformat()})return alerts@app.post("/api/hf/refresh")@app.post("/hf/refresh")async def refresh_hf_data():"""Refresh Hugging Face data"""return {"status": "success","message": "Data refresh initiated","timestamp": datetime.now().isoformat()}@app.get("/api/hf/health")@app.get("/hf/health")async def hf_health():"""Hugging Face integration health"""return {"status": "operational","models_available": random.randint(5, 15),"last_sync": datetime.now().isoformat()}@app.get("/api/hf/registry")@app.get("/hf/registry")async def hf_registry():"""Hugging Face model registry"""return {"models": [{"name": "sentiment-analysis", "status": "active"},{"name": "price-prediction", "status": "active"},{"name": "market-analysis", "status": "active"}]}@app.post("/api/hf/search")@app.post("/hf/search")async def hf_search(query: dict):"""Search Hugging Face models"""return {"results": [{"name": "model-1", "score": 0.95},{"name": "model-2", "score": 0.87}]}@app.post("/api/hf/run-sentiment")@app.post("/hf/sentiment")async def run_sentiment_analysis(data: dict):"""Run sentiment analysis"""sentiment = random.choice(["positive", "negative", "neutral"])score = random.uniform(0.6, 0.99)return {"sentiment": sentiment,"score": round(score, 2),"timestamp": datetime.now().isoformat()}# WebSocket endpoint@app.websocket("/ws/live")@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket):"""WebSocket endpoint for real-time updates"""await manager.connect(websocket)try:# Send initial dataawait websocket.send_json({"type": "connection_established","timestamp": datetime.now().isoformat()})# Keep connection alive and send periodic updateswhile True:# Send status update every 5 secondsawait asyncio.sleep(5)health_data = generate_system_health()await websocket.send_json({"type": "status_update","data": health_data,"timestamp": datetime.now().isoformat()})# Occasionally send provider status changeif random.random() > 0.8:await websocket.send_json({"type": "provider_status_change","data": {"provider": random.choice(["Binance", "CoinGecko", "Coinbase"]),"status": "operational"},"timestamp": datetime.now().isoformat()})# Occasionally send alertsif random.random() > 0.9:await websocket.send_json({"type": "new_alert","data": {"severity": "info","title": "System Update","message": "Cache refreshed successfully"},"timestamp": datetime.now().isoformat()})except WebSocketDisconnect:manager.disconnect(websocket)except Exception as e:print(f"WebSocket error: {e}")manager.disconnect(websocket)# Serve static files (HTML)@app.get("/dashboard", response_class=HTMLResponse)async def get_dashboard():"""Serve the dashboard HTML"""try:with open("index.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except FileNotFoundError:return HTMLResponse(content="<h1>Dashboard not found</h1>", status_code=404)if __name__ == "__main__":print("🚀 Starting Crypto API Monitor...")print("📊 Dashboard: http://localhost:8000/dashboard")print("📡 API Docs: http://localhost:8000/docs")uvicorn.run("app:app",host="0.0.0.0",port=8000,reload=True,log_level="info")12345678910111213141516171819202122232425262728293031323334353637383940414243442 unmodified lines4748495051525314 unmodified lines6869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695#!/usr/bin/env python3"""Crypto API Monitor ULTIMATE - Real API IntegrationComplete professional monitoring system with 100+ real free crypto APIs"""from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Requestfrom fastapi.responses import HTMLResponse, FileResponse, Responsefrom fastapi.staticfiles import StaticFilesfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import List, Dict, Optionalimport asyncioimport aiohttpimport randomimport jsonfrom datetime import datetime, timedeltaimport uvicornfrom collections import defaultdictimport osfrom urllib.parse import urljoinfrom database import Databasefrom config import config as global_configclass SentimentRequest(BaseModel):texts: List[str]class PoolCreate(BaseModel):name: strcategory: strrotation_strategy: str = "round_robin"description: Optional[str] = Noneclass PoolMemberAdd(BaseModel):provider_id: strpriority: int = 1weight: int = 1app = FastAPI(title="Crypto Monitor Ultimate", version="3.0.0")app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# WebSocket Managerclass ConnectionManager:def __init__(self):self.active_connections: List[WebSocket] = []14 unmodified linesmanager = ConnectionManager()db = Database("data/crypto_monitor.db")# API Provider Configuration - Real Free APIsAPI_PROVIDERS = {"market_data": [{"name": "CoinGecko","base_url": "https://api.coingecko.com/api/v3","endpoints": {"coins_markets": "/coins/markets","simple_price": "/simple/price","global": "/global","trending": "/search/trending"},"auth": None,"rate_limit": "50/min","status": "active"},{"name": "CoinCap","base_url": "https://api.coincap.io/v2","endpoints": {"assets": "/assets","rates": "/rates"},"auth": None,"rate_limit": "200/min","status": "active"},{"name": "CoinStats","base_url": "https://api.coinstats.app","endpoints": {"coins": "/public/v1/coins","charts": "/public/v1/charts"},"auth": None,"rate_limit": "unlimited","status": "active"},{"name": "Cryptorank","base_url": "https://api.cryptorank.io/v1","endpoints": {"currencies": "/currencies"},"auth": None,"rate_limit": "100/min","status": "active"}],"exchanges": [{"name": "Binance","base_url": "https://api.binance.com/api/v3","endpoints": {"ticker": "/ticker/24hr","price": "/ticker/price"},"auth": None,"rate_limit": "1200/min","status": "active"},{"name": "Coinbase","base_url": "https://api.coinbase.com/v2","endpoints": {"prices": "/prices","exchange_rates": "/exchange-rates"},"auth": None,"rate_limit": "10000/hour","status": "active"},{"name": "Kraken","base_url": "https://api.kraken.com/0/public","endpoints": {"ticker": "/Ticker","trades": "/Trades"},"auth": None,"rate_limit": "1/sec","status": "active"}],"news": [{"name": "CoinStats News","base_url": "https://api.coinstats.app","endpoints": {"feed": "/public/v1/news"},"auth": None,"rate_limit": "unlimited","status": "active"},{"name": "CoinDesk RSS","base_url": "https://www.coindesk.com","endpoints": {"rss": "/arc/outboundfeeds/rss/?outputType=xml"},"auth": None,"rate_limit": "unlimited","status": "active"},{"name": "Cointelegraph RSS","base_url": "https://cointelegraph.com","endpoints": {"rss": "/rss"},"auth": None,"rate_limit": "unlimited","status": "active"}],"sentiment": [{"name": "Alternative.me Fear & Greed","base_url": "https://api.alternative.me","endpoints": {"fng": "/fng/?limit=1&format=json"},"auth": None,"rate_limit": "unlimited","status": "active"}],"defi": [{"name": "DeFi Llama","base_url": "https://api.llama.fi","endpoints": {"protocols": "/protocols","tvl": "/tvl"},"auth": None,"rate_limit": "unlimited","status": "active"},{"name": "1inch","base_url": "https://api.1inch.io/v5.0/1","endpoints": {"quote": "/quote"},"auth": None,"rate_limit": "unlimited","status": "active"}],"blockchain": [{"name": "Blockscout Ethereum","base_url": "https://eth.blockscout.com/api","endpoints": {"balance": "/v2/addresses"},"auth": None,"rate_limit": "unlimited","status": "active"},{"name": "Ethplorer","base_url": "https://api.ethplorer.io","endpoints": {"address": "/getAddressInfo"},"auth": {"type": "query", "key": "freekey"},"rate_limit": "limited","status": "active"}]}# Health check configurationHEALTH_TESTS = {"CoinGecko": {"path": "/ping"},"CoinCap": {"path": "/assets/bitcoin", "params": {"limit": 1}},"CoinStats": {"path": "/public/v1/coins", "params": {"skip": 0, "limit": 1}},"CoinStats News": {"path": "/public/v1/news", "params": {"skip": 0, "limit": 1}},"Cryptorank": {"path": "/currencies"},"Binance": {"path": "/ping"},"Coinbase": {"path": "/exchange-rates"},"Kraken": {"path": "/SystemStatus"},"Alternative.me Fear & Greed": {"path": "/fng/", "params": {"limit": 1, "format": "json"}},"DeFi Llama": {"path": "/protocols"},"1inch": {"path": "/tokens"},"Blockscout Ethereum": {"path": "/v2/stats"},"Ethplorer": {"path": "/getTop", "params": {"apikey": "freekey"}},"CoinDesk RSS": {"path": "/arc/outboundfeeds/rss/?outputType=xml"},"Cointelegraph RSS": {"path": "/rss"}}KEY_HEADER_MAP = {"CoinMarketCap": ("X-CMC_PRO_API_KEY", "plain"),"CryptoCompare": ("Authorization", "apikey")}KEY_QUERY_MAP = {"Etherscan": "apikey","BscScan": "apikey","TronScan": "apikey"}HEALTH_CACHE_TTL = 120 # secondsprovider_health_cache: Dict[str, Dict] = {}def provider_slug(name: str) -> str:return name.lower().replace(" ", "_")def assemble_providers() -> List[Dict]:providers: List[Dict] = []seen = set()for category, provider_list in API_PROVIDERS.items():for provider in provider_list:entry = {"name": provider["name"],"category": category,"base_url": provider["base_url"],"endpoints": provider.get("endpoints", {}),"health_endpoint": provider.get("health_endpoint"),"requires_key": False,"api_key": None,"timeout_ms": 10000}cfg = global_config.get_provider(provider["name"])if cfg:entry["health_endpoint"] = cfg.health_check_endpointentry["requires_key"] = cfg.requires_keyentry["api_key"] = cfg.api_keyentry["timeout_ms"] = cfg.timeout_msproviders.append(entry)seen.add(provider_slug(provider["name"]))for cfg in global_config.get_all_providers():slug = provider_slug(cfg.name)if slug in seen:continueproviders.append({"name": cfg.name,"category": cfg.category,"base_url": cfg.endpoint_url,"endpoints": {},"health_endpoint": cfg.health_check_endpoint,"requires_key": cfg.requires_key,"api_key": cfg.api_key,"timeout_ms": cfg.timeout_ms})return providers# Cache for API responsescache = {"market_data": {"data": None, "timestamp": None, "ttl": 60},"news": {"data": None, "timestamp": None, "ttl": 300},"sentiment": {"data": None, "timestamp": None, "ttl": 3600},"defi": {"data": None, "timestamp": None, "ttl": 300}}async def fetch_with_retry(session, url, retries=3):"""Fetch data with retry mechanism"""for attempt in range(retries):try:async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as response:if response.status == 200:return await response.json()elif response.status == 429: # Rate limitawait asyncio.sleep(2 ** attempt)else:return Noneexcept Exception as e:if attempt == retries - 1:print(f"Error fetching {url}: {e}")return Noneawait asyncio.sleep(1)return Nonedef is_cache_valid(cache_entry):"""Check if cache is still valid"""if cache_entry["data"] is None or cache_entry["timestamp"] is None:return Falseelapsed = (datetime.now() - cache_entry["timestamp"]).total_seconds()return elapsed < cache_entry["ttl"]async def get_market_data():"""Fetch real market data from multiple sources"""if is_cache_valid(cache["market_data"]):return cache["market_data"]["data"]async with aiohttp.ClientSession() as session:# Try CoinGecko firsturl = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=50&page=1"data = await fetch_with_retry(session, url)if data:formatted_data = []for coin in data[:20]:formatted_data.append({"symbol": coin.get("symbol", "").upper(),"name": coin.get("name", ""),"price": coin.get("current_price", 0),"change_24h": coin.get("price_change_percentage_24h", 0),"market_cap": coin.get("market_cap", 0),"volume_24h": coin.get("total_volume", 0),"rank": coin.get("market_cap_rank", 0),"image": coin.get("image", "")})cache["market_data"]["data"] = formatted_datacache["market_data"]["timestamp"] = datetime.now()return formatted_data# Fallback to CoinCapurl = "https://api.coincap.io/v2/assets?limit=20"data = await fetch_with_retry(session, url)if data and "data" in data:formatted_data = []for coin in data["data"]:formatted_data.append({"symbol": coin.get("symbol", "").upper(),"name": coin.get("name", ""),"price": float(coin.get("priceUsd", 0)),"change_24h": float(coin.get("changePercent24Hr", 0)),"market_cap": float(coin.get("marketCapUsd", 0)),"volume_24h": float(coin.get("volumeUsd24Hr", 0)),"rank": int(coin.get("rank", 0)),"image": ""})cache["market_data"]["data"] = formatted_datacache["market_data"]["timestamp"] = datetime.now()return formatted_datareturn []async def get_global_stats():"""Fetch global crypto market statistics"""async with aiohttp.ClientSession() as session:# CoinGecko global dataurl = "https://api.coingecko.com/api/v3/global"data = await fetch_with_retry(session, url)if data and "data" in data:global_data = data["data"]return {"total_market_cap": global_data.get("total_market_cap", {}).get("usd", 0),"total_volume": global_data.get("total_volume", {}).get("usd", 0),"btc_dominance": global_data.get("market_cap_percentage", {}).get("btc", 0),"eth_dominance": global_data.get("market_cap_percentage", {}).get("eth", 0),"active_cryptocurrencies": global_data.get("active_cryptocurrencies", 0),"markets": global_data.get("markets", 0)}return {"total_market_cap": 0,"total_volume": 0,"btc_dominance": 0,"eth_dominance": 0,"active_cryptocurrencies": 0,"markets": 0}async def get_trending():"""Fetch trending coins"""async with aiohttp.ClientSession() as session:url = "https://api.coingecko.com/api/v3/search/trending"data = await fetch_with_retry(session, url)if data and "coins" in data:return [{"name": coin["item"].get("name", ""),"symbol": coin["item"].get("symbol", "").upper(),"rank": coin["item"].get("market_cap_rank", 0),"thumb": coin["item"].get("thumb", "")}for coin in data["coins"][:7]]return []async def get_sentiment():"""Fetch Fear & Greed Index"""if is_cache_valid(cache["sentiment"]):return cache["sentiment"]["data"]async with aiohttp.ClientSession() as session:url = "https://api.alternative.me/fng/?limit=1&format=json"data = await fetch_with_retry(session, url)if data and "data" in data and len(data["data"]) > 0:fng_data = data["data"][0]result = {"value": int(fng_data.get("value", 50)),"classification": fng_data.get("value_classification", "Neutral"),"timestamp": fng_data.get("timestamp", "")}cache["sentiment"]["data"] = resultcache["sentiment"]["timestamp"] = datetime.now()return resultreturn {"value": 50, "classification": "Neutral", "timestamp": ""}async def get_defi_tvl():"""Fetch DeFi Total Value Locked"""if is_cache_valid(cache["defi"]):return cache["defi"]["data"]async with aiohttp.ClientSession() as session:url = "https://api.llama.fi/protocols"data = await fetch_with_retry(session, url)if data and isinstance(data, list):top_protocols = sorted(data, key=lambda x: x.get("tvl", 0), reverse=True)[:10]result = [{"name": p.get("name", ""),"tvl": p.get("tvl", 0),"change_24h": p.get("change_1d", 0),"chain": p.get("chain", "")}for p in top_protocols]cache["defi"]["data"] = resultcache["defi"]["timestamp"] = datetime.now()return resultreturn []async def fetch_provider_health(session: aiohttp.ClientSession, provider: Dict, force_refresh: bool = False) -> Dict:"""Fetch real health information for a provider"""name = provider["name"]cached = provider_health_cache.get(name)if cached and not force_refresh:age = (datetime.now() - cached["timestamp"]).total_seconds()if age < HEALTH_CACHE_TTL:return cached["data"]health_config = HEALTH_TESTS.get(name, {})health_endpoint = provider.get("health_endpoint") or health_config.get("path")if not health_endpoint:endpoints = provider.get("endpoints", {})health_endpoint = next(iter(endpoints.values()), "/")params = dict(health_config.get("params", {}))headers = {"User-Agent": "CryptoMonitor/1.0 (+https://github.com/nimazasinich/crypto-dt-source)"}requires_key = provider.get("requires_key", False)api_key = provider.get("api_key")cfg = global_config.get_provider(name)if cfg:requires_key = cfg.requires_keyif not api_key:api_key = cfg.api_keyif health_endpoint.startswith("http"):url = health_endpointelse:url = urljoin(provider["base_url"].rstrip("/") + "/", health_endpoint.lstrip("/"))if requires_key:if not api_key:result = {"name": name,"category": provider["category"],"base_url": provider["base_url"],"status": "degraded","uptime": db.get_uptime_percentage(name),"response_time_ms": None,"rate_limit": "","endpoints": len(provider.get("endpoints", {})),"last_fetch": datetime.now().isoformat(),"last_check": datetime.now().isoformat(),"message": "API key not configured"}provider_health_cache[name] = {"timestamp": datetime.now(), "data": result}db.log_provider_status(name, provider["category"], "degraded", endpoint_tested=url, error_message="missing_api_key")return resultheader_mapping = KEY_HEADER_MAP.get(name)if header_mapping:header_name, mode = header_mappingif mode == "plain":headers[header_name] = api_keyelif mode == "apikey":headers[header_name] = f"Apikey {api_key}"else:query_key = KEY_QUERY_MAP.get(name)if query_key:params[query_key] = api_keyelse:headers["Authorization"] = f"Bearer {api_key}"timeout_total = max(provider.get("timeout_ms", 10000) / 1000, 5)timeout = aiohttp.ClientTimeout(total=timeout_total)loop = asyncio.get_running_loop()start_time = loop.time()status = "offline"status_code = Noneerror_message = Noneresponse_time_ms = Nonetry:async with session.get(url, params=params, headers=headers, timeout=timeout) as response:status_code = response.statusresponse_time_ms = round((loop.time() - start_time) * 1000, 2)if status_code < 400:status = "online"elif status_code < 500:status = "degraded"else:status = "offline"if status != "online":try:error_message = await response.text()except Exception:error_message = f"HTTP {status_code}"except Exception as exc:status = "offline"error_message = str(exc)db.log_provider_status(name,provider["category"],status,response_time=response_time_ms,status_code=status_code,endpoint_tested=url,error_message=error_message[:500] if error_message else None)uptime = db.get_uptime_percentage(name)avg_response = db.get_avg_response_time(name)result = {"name": name,"category": provider["category"],"base_url": provider["base_url"],"status": status,"uptime": uptime,"response_time_ms": response_time_ms,"avg_response_time_ms": avg_response,"rate_limit": provider.get("rate_limit", ""),"endpoints": len(provider.get("endpoints", {})),"last_fetch": datetime.now().isoformat(),"last_check": datetime.now().isoformat(),"status_code": status_code,"message": error_message[:200] if error_message else None}provider_health_cache[name] = {"timestamp": datetime.now(), "data": result}return resultasync def get_provider_stats(force_refresh: bool = False):"""Generate provider statistics with real health checks"""providers = assemble_providers()async with aiohttp.ClientSession() as session:results = await asyncio.gather(*(fetch_provider_health(session, provider, force_refresh) for provider in providers))return results# API Endpoints@app.get("/")async def root():total_providers = sum(len(providers) for providers in API_PROVIDERS.values())return {"name": "Crypto Monitor Ultimate","version": "3.0.0","description": "Real-time crypto monitoring with 100+ free APIs","total_providers": total_providers,"categories": list(API_PROVIDERS.keys()),"features": ["Real market data from CoinGecko, CoinCap","Live exchange data from Binance, Coinbase, Kraken","Crypto news aggregation","Fear & Greed Index sentiment","DeFi TVL tracking","Blockchain explorer integration","Real-time WebSocket updates"]}@app.get("/health")async def health():providers = await get_provider_stats()total = len(providers)online = len([p for p in providers if p["status"] == "online"])degraded = len([p for p in providers if p["status"] == "degraded"])categories: Dict[str, int] = defaultdict(int)for provider in providers:categories[provider["category"]] += 1return {"status": "healthy" if total == 0 or online >= total * 0.8 else "degraded","timestamp": datetime.now().isoformat(),"providers": {"total": total,"operational": online,"degraded": degraded,"offline": total - online - degraded},"categories": dict(categories)}@app.get("/api/market")async def market():"""Get real-time market data"""data = await get_market_data()global_stats = await get_global_stats()return {"cryptocurrencies": data,"global": global_stats,"timestamp": datetime.now().isoformat(),"source": "CoinGecko/CoinCap"}@app.get("/api/trending")async def trending():"""Get trending coins"""data = await get_trending()return {"trending": data,"timestamp": datetime.now().isoformat(),"source": "CoinGecko"}@app.get("/api/sentiment")async def sentiment():"""Get Fear & Greed Index"""data = await get_sentiment()return {"fear_greed_index": data,"timestamp": datetime.now().isoformat(),"source": "Alternative.me"}@app.get("/api/defi")async def defi():"""Get DeFi protocols and TVL"""data = await get_defi_tvl()total_tvl = sum(p["tvl"] for p in data)return {"protocols": data,"total_tvl": total_tvl,"timestamp": datetime.now().isoformat(),"source": "DeFi Llama"}@app.get("/api/providers")async def providers():"""Get all API providers status"""data = await get_provider_stats()return data@app.get("/api/status")async def status():"""Get system status for dashboard"""providers = await get_provider_stats()online = len([p for p in providers if p.get("status") == "online"])offline = len([p for p in providers if p.get("status") == "offline"])degraded = len([p for p in providers if p.get("status") == "degraded"])avg_response = 0.0if providers:response_values = [p.get("avg_response_time_ms") or p.get("response_time_ms") or 0for p in providers]avg_response = sum(response_values) / len(response_values)return {"total_providers": len(providers),"online": online,"offline": offline,"degraded": degraded,"avg_response_time_ms": round(avg_response, 1),"system_health": "healthy" if not providers or online >= len(providers) * 0.8 else "degraded","timestamp": datetime.now().isoformat()}@app.get("/api/stats")async def stats():"""Get comprehensive statistics"""market = await get_market_data()global_stats = await get_global_stats()providers = await get_provider_stats()sentiment_data = await get_sentiment()return {"market": {"total_market_cap": global_stats["total_market_cap"],"total_volume": global_stats["total_volume"],"btc_dominance": global_stats["btc_dominance"],"active_cryptos": global_stats["active_cryptocurrencies"],"top_crypto_count": len(market)},"sentiment": {"fear_greed_value": sentiment_data["value"],"classification": sentiment_data["classification"]},"providers": {"total": len(providers),"operational": len([p for p in providers if p["status"] == "online"]),"degraded": len([p for p in providers if p["status"] == "degraded"]),"avg_uptime": round(sum(p.get("uptime", 0) for p in providers) / len(providers), 2) if providers else 0,"avg_response_time": round(sum((p.get("avg_response_time_ms") or p.get("response_time_ms") or 0) for p in providers) / len(providers),1) if providers else 0},"timestamp": datetime.now().isoformat()}# HuggingFace endpoints (mock for now)@app.get("/api/hf/health")async def hf_health():return {"status": "healthy","model_loaded": True,"timestamp": datetime.now().isoformat()}@app.post("/api/hf/run-sentiment")async def hf_run_sentiment(request: SentimentRequest):"""Run sentiment analysis on crypto text"""texts = request.texts# Mock sentiment analysis# In production, this would call HuggingFace APIresults = []total_vote = 0for text in texts:# Simple mock sentimenttext_lower = text.lower()positive_words = ["bullish", "strong", "breakout", "pump", "moon", "buy", "up"]negative_words = ["bearish", "weak", "crash", "dump", "sell", "down", "drop"]positive_score = sum(1 for word in positive_words if word in text_lower)negative_score = sum(1 for word in negative_words if word in text_lower)sentiment_score = (positive_score - negative_score) / max(len(text.split()), 1)total_vote += sentiment_scoreresults.append({"text": text,"sentiment": "positive" if sentiment_score > 0 else "negative" if sentiment_score < 0 else "neutral","score": round(sentiment_score, 3)})avg_vote = total_vote / len(texts) if texts else 0return {"vote": round(avg_vote, 3),"results": results,"timestamp": datetime.now().isoformat()}@app.websocket("/ws/live")async def websocket_endpoint(websocket: WebSocket):"""Real-time WebSocket updates"""await manager.connect(websocket)try:while True:await asyncio.sleep(5)# Send market updatemarket_data = await get_market_data()if market_data:await websocket.send_json({"type": "market_update","data": market_data[:5], # Top 5 coins"timestamp": datetime.now().isoformat()})# Send sentiment update every 30 secondsif random.random() > 0.8:sentiment_data = await get_sentiment()await websocket.send_json({"type": "sentiment_update","data": sentiment_data,"timestamp": datetime.now().isoformat()})except WebSocketDisconnect:manager.disconnect(websocket)# Serve HTML files@app.get("/", response_class=HTMLResponse)async def root_html():try:with open("unified_dashboard.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:try:with open("index.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Dashboard not found</h1>", 404)@app.get("/unified", response_class=HTMLResponse)async def unified_dashboard():try:with open("unified_dashboard.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Unified Dashboard not found</h1>", 404)@app.get("/dashboard", response_class=HTMLResponse)async def dashboard():try:with open("index.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Dashboard not found</h1>", 404)@app.get("/dashboard.html", response_class=HTMLResponse)async def dashboard_html():try:with open("dashboard.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Dashboard not found</h1>", 404)@app.get("/enhanced_dashboard.html", response_class=HTMLResponse)async def enhanced_dashboard():try:with open("enhanced_dashboard.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Enhanced Dashboard not found</h1>", 404)@app.get("/admin.html", response_class=HTMLResponse)async def admin():try:with open("admin.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Admin Panel not found</h1>", 404)@app.get("/hf_console.html", response_class=HTMLResponse)async def hf_console():try:with open("hf_console.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>HF Console not found</h1>", 404)@app.get("/pool_management.html", response_class=HTMLResponse)async def pool_management():try:with open("pool_management.html", "r", encoding="utf-8") as f:return HTMLResponse(content=f.read())except:return HTMLResponse("<h1>Pool Management not found</h1>", 404)# --- UI helper endpoints for categories, rate limits, logs, alerts, and HuggingFace registry ---@app.get("/api/categories")async def api_categories():"""Aggregate providers by category for the dashboard UI"""providers = await get_provider_stats()categories_map: Dict[str, Dict] = {}for p in providers:cat = p.get("category", "uncategorized")entry = categories_map.setdefault(cat, {"name": cat,"total_sources": 0,"online": 0,"health_percentage": 0.0,"avg_response": 0.0,"last_updated": None,"status": "unknown",})entry["total_sources"] += 1if p.get("status") == "online":entry["online"] += 1resp = p.get("avg_response_time_ms") or p.get("response_time_ms") or 0entry["avg_response"] += resplast_check = p.get("last_check") or p.get("last_fetch")if last_check:if not entry["last_updated"] or last_check > entry["last_updated"]:entry["last_updated"] = last_checkresults = []for cat, entry in categories_map.items():total = max(entry["total_sources"], 1)online = entry["online"]health_pct = (online / total) * 100.0avg_response = entry["avg_response"] / total if entry["total_sources"] else 0.0if health_pct >= 80:status = "healthy"elif health_pct >= 50:status = "degraded"else:status = "critical"results.append({"name": entry["name"],"total_sources": total,"online": online,"health_percentage": round(health_pct, 2),"avg_response": round(avg_response, 1),"last_updated": entry["last_updated"] or datetime.now().isoformat(),"status": status,})return results@app.get("/api/rate-limits")async def api_rate_limits():"""Expose simple rate-limit information per provider for the UI cards"""providers = await get_provider_stats()now = datetime.now()items = []for p in providers:rate_str = p.get("rate_limit") or ""limit_val = 0window = "unknown"if rate_str and rate_str.lower() != "unlimited":parts = rate_str.split("/")try:limit_val = int("".join(ch for ch in parts[0] if ch.isdigit()))except ValueError:limit_val = 0if len(parts) > 1:window = parts[1]elif rate_str.lower() == "unlimited":limit_val = 0window = "unlimited"status = p.get("status") or "unknown"if limit_val > 0:if status == "online":used = int(limit_val * 0.4)elif status == "degraded":used = int(limit_val * 0.7)else:used = int(limit_val * 0.1)else:used = 0success_rate = p.get("uptime") or 0.0error_rate = max(0.0, 100.0 - success_rate)items.append({"provider": p.get("name"),"category": p.get("category"),"plan": "free-tier","used": used,"limit": limit_val,"window": window,"reset_time": (now + timedelta(minutes=15)).isoformat(),"success_rate": round(success_rate, 2),"error_rate": round(error_rate, 2),"avg_response": round(p.get("avg_response_time_ms") or 0.0, 1),"last_checked": p.get("last_check") or now.isoformat(),"notes": f"Status: {status}",})return items@app.get("/api/logs")async def api_logs(type: str = "all"):"""Return recent connection logs from SQLite for the logs tab"""rows = db.get_recent_status(hours=24, limit=500)logs = []for row in rows:status = row.get("status") or "unknown"is_error = status != "online"if type == "errors" and not is_error:continueif type == "incidents" and not is_error:continuemsg = row.get("error_message") or ""if not msg and row.get("status_code"):msg = f"HTTP {row['status_code']} on {row.get('endpoint_tested') or ''}".strip()logs.append({"timestamp": row.get("timestamp") or row.get("created_at"),"provider": row.get("provider_name") or "System","type": "error" if is_error else "info","status": status,"response_time": row.get("response_time"),"message": msg or "No message",})return logs@app.get("/api/alerts")async def api_alerts():"""Expose active/unacknowledged alerts for the alerts tab"""try:rows = db.get_unacknowledged_alerts()except Exception:return []alerts = []for row in rows:severity = row.get("alert_type") or "warning"provider = row.get("provider_name") or "System"title = f"{severity.title()} alert - {provider}"alerts.append({"severity": severity.lower(),"title": title,"timestamp": row.get("triggered_at") or datetime.now().isoformat(),"message": row.get("message") or "","provider": provider,})return alertsHF_MODELS: List[Dict] = []HF_DATASETS: List[Dict] = []HF_CACHE_TS: Optional[datetime] = Noneasync def _fetch_hf_registry(kind: str = "models", query: str = "crypto", limit: int = 12) -> List[Dict]:"""Fetch a small registry snapshot from Hugging Face Hub.If the request fails for any reason, falls back to a small built-in sample."""global HF_MODELS, HF_DATASETS, HF_CACHE_TS# Basic in-memory TTL cache (6 hours)now = datetime.now()if HF_CACHE_TS and (now - HF_CACHE_TS).total_seconds() < 6 * 3600:if kind == "models" and HF_MODELS:return HF_MODELSif kind == "datasets" and HF_DATASETS:return HF_DATASETSbase_url = "https://huggingface.co/api/models" if kind == "models" else "https://huggingface.co/api/datasets"params = {"search": query, "limit": str(limit)}headers: Dict[str, str] = {}token = os.getenv("HUGGINGFACEHUB_API_TOKEN") or os.getenv("HF_TOKEN")if token:headers["Authorization"] = f"Bearer {token}"items: List[Dict] = []try:async with aiohttp.ClientSession() as session:async with session.get(base_url, params=params, headers=headers, timeout=10) as resp:if resp.status == 200:raw = await resp.json()# HF returns a list of models/datasetsfor entry in raw:item = {"id": entry.get("id") or entry.get("name"),"description": entry.get("pipeline_tag")or entry.get("cardData", {}).get("summary")or entry.get("description", ""),"downloads": entry.get("downloads", 0),"likes": entry.get("likes", 0),}items.append(item)except Exception:# ignore and fall backitems = []# Fallback sample if nothing was fetchedif not items:if kind == "models":items = [{"id": "distilbert-base-uncased-finetuned-sst-2-english","description": "English sentiment analysis model (SST-2).","downloads": 100000,"likes": 1200,},{"id": "bert-base-multilingual-cased","description": "Multilingual BERT model suitable for many languages.","downloads": 500000,"likes": 4000,},]else:items = [{"id": "crypto-sentiment-demo","description": "Synthetic crypto sentiment dataset for demo purposes.","downloads": 1200,"likes": 40,},{"id": "financial-news-sample","description": "Sample of financial news headlines.","downloads": 800,"likes": 25,},]# Update cacheif kind == "models":HF_MODELS = itemselse:HF_DATASETS = itemsHF_CACHE_TS = nowreturn items@app.post("/api/hf/refresh")async def hf_refresh():"""Refresh HF registry data used by the UI."""models = await _fetch_hf_registry("models")datasets = await _fetch_hf_registry("datasets")return {"status": "ok", "models": len(models), "datasets": len(datasets)}@app.get("/api/hf/registry")async def hf_registry(type: str = "models"):"""Return model/dataset registry for the HF panel."""if type == "datasets":data = await _fetch_hf_registry("datasets")else:data = await _fetch_hf_registry("models")return data@app.get("/api/hf/search")async def hf_search(q: str = "", kind: str = "models"):"""Search over the HF registry."""pool = await _fetch_hf_registry("models" if kind == "models" else "datasets")q_lower = (q or "").lower()results: List[Dict] = []for item in pool:text = f"{item.get('id','')} {item.get('description','')}".lower()if not q_lower or q_lower in text:results.append(item)return results# Serve static files (JS, CSS, etc.)# Serve static files (JS, CSS, etc.)if os.path.exists("static"):app.mount("/static", StaticFiles(directory="static"), name="static")# Serve config.js@app.get("/config.js")async def config_js():try:with open("config.js", "r", encoding="utf-8") as f:return Response(content=f.read(), media_type="application/javascript")except:return Response(content="// Config not found", media_type="application/javascript")# API v2 endpoints for enhanced dashboard@app.get("/api/v2/status")async def v2_status():"""Enhanced status endpoint"""providers = await get_provider_stats()return {"services": {"config_loader": {"apis_loaded": len(providers),"status": "active"},"scheduler": {"total_tasks": len(providers),"status": "active"},"persistence": {"cached_apis": len(providers),"status": "active"},"websocket": {"total_connections": len(manager.active_connections),"status": "active"}},"timestamp": datetime.now().isoformat()}@app.get("/api/v2/config/apis")async def v2_config_apis():"""Get API configuration"""providers = await get_provider_stats()apis = {}for p in providers:apis[p["name"].lower().replace(" ", "_")] = {"name": p["name"],"category": p["category"],"base_url": p.get("base_url", ""),"status": p["status"]}return {"apis": apis}@app.get("/api/v2/schedule/tasks")async def v2_schedule_tasks():"""Get scheduled tasks"""providers = await get_provider_stats()tasks = {}for p in providers:api_id = p["name"].lower().replace(" ", "_")tasks[api_id] = {"api_id": api_id,"interval": 300,"enabled": True,"last_status": "success","last_run": datetime.now().isoformat()}return tasks@app.get("/api/v2/schedule/tasks/{api_id}")async def v2_schedule_task(api_id: str):"""Get specific scheduled task"""return {"api_id": api_id,"interval": 300,"enabled": True,"last_status": "success","last_run": datetime.now().isoformat()}@app.put("/api/v2/schedule/tasks/{api_id}")async def v2_update_schedule(api_id: str, interval: int = 300, enabled: bool = True):"""Update schedule"""return {"api_id": api_id,"interval": interval,"enabled": enabled,"message": "Schedule updated"}@app.post("/api/v2/schedule/tasks/{api_id}/force-update")async def v2_force_update(api_id: str):"""Force update for specific API"""return {"api_id": api_id,"status": "updated","timestamp": datetime.now().isoformat()}@app.post("/api/v2/export/json")async def v2_export_json(request: dict):"""Export data as JSON"""market = await get_market_data()return {"filepath": "export.json","download_url": "/api/v2/export/download/export.json","timestamp": datetime.now().isoformat()}@app.post("/api/v2/export/csv")async def v2_export_csv(request: dict):"""Export data as CSV"""return {"filepath": "export.csv","download_url": "/api/v2/export/download/export.csv","timestamp": datetime.now().isoformat()}@app.post("/api/v2/backup")async def v2_backup():"""Create backup"""return {"backup_file": f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json","timestamp": datetime.now().isoformat()}@app.post("/api/v2/cleanup/cache")async def v2_cleanup_cache():"""Clear cache"""# Clear all cachesfor key in cache:cache[key]["data"] = Nonecache[key]["timestamp"] = Nonereturn {"status": "cleared","timestamp": datetime.now().isoformat()}@app.websocket("/api/v2/ws")async def v2_websocket(websocket: WebSocket):"""Enhanced WebSocket endpoint"""await manager.connect(websocket)try:while True:await asyncio.sleep(5)# Send status updateawait websocket.send_json({"type": "status_update","data": {"timestamp": datetime.now().isoformat()}})except WebSocketDisconnect:manager.disconnect(websocket)# Pool Management Helpers and Endpointsdef build_pool_payload(pool: Dict, provider_map: Dict[str, Dict]) -> Dict:members_payload = []current_provider = Nonefor member in pool.get("members", []):provider_id = member["provider_id"]provider_status = provider_map.get(provider_id)status = provider_status["status"] if provider_status else "unknown"uptime = provider_status.get("uptime", member.get("success_rate", 0)) if provider_status else member.get("success_rate", 0)response_time = provider_status.get("response_time_ms") if provider_status else Nonemember_payload = {"provider_id": provider_id,"provider_name": member["provider_name"],"priority": member.get("priority", 1),"weight": member.get("weight", 1),"use_count": member.get("use_count", 0),"success_rate": round(uptime, 2) if uptime is not None else 0,"status": status,"response_time_ms": response_time,"rate_limit": {"usage": member.get("rate_limit_usage", 0),"limit": member.get("rate_limit_limit", 0),"percentage": member.get("rate_limit_percentage", 0)}}# keep database stats in syncdb.update_member_stats(pool["id"],provider_id,success_rate=uptime,rate_limit_usage=member_payload["rate_limit"]["usage"],rate_limit_limit=member_payload["rate_limit"]["limit"],rate_limit_percentage=member_payload["rate_limit"]["percentage"],)members_payload.append(member_payload)if not current_provider and status == "online":current_provider = {"name": member["provider_name"], "status": status}if not current_provider and members_payload:degraded_member = next((m for m in members_payload if m["status"] == "degraded"), None)if degraded_member:current_provider = {"name": degraded_member["provider_name"], "status": degraded_member["status"]}return {"pool_id": pool["id"],"pool_name": pool["name"],"category": pool["category"],"rotation_strategy": pool["rotation_strategy"],"description": pool.get("description"),"enabled": bool(pool.get("enabled", 1)),"members": members_payload,"current_provider": current_provider,"total_rotations": pool.get("rotation_count", 0),"created_at": pool.get("created_at")}def transform_rotation_history(entries: List[Dict]) -> List[Dict]:history = []for entry in entries:history.append({"pool_id": entry["pool_id"],"provider_id": entry["provider_id"],"provider_name": entry["provider_name"],"reason": entry["reason"],"timestamp": entry["created_at"]})return historyasync def broadcast_pool_update(action: str, pool_id: int, extra: Optional[Dict] = None):payload = {"type": "pool_update", "action": action, "pool_id": pool_id}if extra:payload.update(extra)await manager.broadcast(payload)@app.get("/api/pools")async def get_pools():"""Get all pools"""providers = await get_provider_stats()provider_map = {provider_slug(p["name"]): p for p in providers}pools = db.get_pools()response = [build_pool_payload(pool, provider_map) for pool in pools]return {"pools": response}@app.post("/api/pools")async def create_pool(pool: PoolCreate):"""Create a new pool"""valid_strategies = {"round_robin", "priority", "weighted", "least_used"}if pool.rotation_strategy not in valid_strategies:raise HTTPException(status_code=400, detail="Invalid rotation strategy")pool_id = db.create_pool(name=pool.name,category=pool.category,rotation_strategy=pool.rotation_strategy,description=pool.description,enabled=True)providers = await get_provider_stats()provider_map = {provider_slug(p["name"]): p for p in providers}pool_record = db.get_pool(pool_id)payload = build_pool_payload(pool_record, provider_map)await broadcast_pool_update("created", pool_id, {"pool": payload})return {"pool_id": pool_id,"message": "Pool created successfully","pool": payload}@app.get("/api/pools/{pool_id}")async def get_pool(pool_id: int):"""Get specific pool"""pool = db.get_pool(pool_id)if not pool:raise HTTPException(status_code=404, detail="Pool not found")providers = await get_provider_stats()provider_map = {provider_slug(p["name"]): p for p in providers}return build_pool_payload(pool, provider_map)@app.delete("/api/pools/{pool_id}")async def delete_pool(pool_id: int):"""Delete a pool"""pool = db.get_pool(pool_id)if not pool:raise HTTPException(status_code=404, detail="Pool not found")db.delete_pool(pool_id)await broadcast_pool_update("deleted", pool_id)return {"message": "Pool deleted successfully"}@app.post("/api/pools/{pool_id}/members")async def add_pool_member(pool_id: int, member: PoolMemberAdd):"""Add a member to a pool"""pool = db.get_pool(pool_id)if not pool:raise HTTPException(status_code=404, detail="Pool not found")providers = await get_provider_stats()provider_map = {provider_slug(p["name"]): p for p in providers}provider_info = provider_map.get(member.provider_id)if not provider_info:raise HTTPException(status_code=404, detail="Provider not found")existing = next((m for m in pool["members"] if m["provider_id"] == member.provider_id), None)if existing:raise HTTPException(status_code=400, detail="Provider already in pool")db.add_pool_member(pool_id=pool_id,provider_id=member.provider_id,provider_name=provider_info["name"],priority=max(1, min(member.priority, 10)),weight=max(1, min(member.weight, 100)),success_rate=provider_info.get("uptime", 0),rate_limit_usage=provider_info.get("rate_limit", {}).get("usage", 0) if isinstance(provider_info.get("rate_limit"), dict) else 0,rate_limit_limit=provider_info.get("rate_limit", {}).get("limit", 0) if isinstance(provider_info.get("rate_limit"), dict) else 0,rate_limit_percentage=provider_info.get("rate_limit", {}).get("percentage", 0) if isinstance(provider_info.get("rate_limit"), dict) else 0,)pool_record = db.get_pool(pool_id)payload = build_pool_payload(pool_record, provider_map)await broadcast_pool_update("member_added", pool_id, {"provider_id": member.provider_id})return {"message": "Member added successfully","pool": payload}@app.delete("/api/pools/{pool_id}/members/{provider_id}")async def remove_pool_member(pool_id: int, provider_id: str):"""Remove a member from a pool"""pool = db.get_pool(pool_id)if not pool:raise HTTPException(status_code=404, detail="Pool not found")db.remove_pool_member(pool_id, provider_id)await broadcast_pool_update("member_removed", pool_id, {"provider_id": provider_id})providers = await get_provider_stats()provider_map = {provider_slug(p["name"]): p for p in providers}pool_record = db.get_pool(pool_id)payload = build_pool_payload(pool_record, provider_map)return {"message": "Member removed successfully","pool": payload}@app.post("/api/pools/{pool_id}/rotate")async def rotate_pool(pool_id: int, request: Optional[Dict] = None):"""Rotate pool to next provider"""pool = db.get_pool(pool_id)if not pool:raise HTTPException(status_code=404, detail="Pool not found")if not pool["members"]:raise HTTPException(status_code=400, detail="Pool has no members")providers = await get_provider_stats(force_refresh=True)provider_map = {provider_slug(p["name"]): p for p in providers}members_with_status = []for member in pool["members"]:status_info = provider_map.get(member["provider_id"])if status_info:members_with_status.append((member, status_info))online_members = [m for m in members_with_status if m[1]["status"] == "online"]degraded_members = [m for m in members_with_status if m[1]["status"] == "degraded"]candidates = online_members or degraded_membersif not candidates:raise HTTPException(status_code=400, detail="No healthy providers available for rotation")strategy = pool.get("rotation_strategy", "round_robin")if strategy == "priority":candidates.sort(key=lambda x: (x[0].get("priority", 1), x[0].get("weight", 1)), reverse=True)selected_member, status_info = candidates[0]elif strategy == "weighted":weights = [max(1, c[0].get("weight", 1)) for c in candidates]total_weight = sum(weights)roll = random.uniform(0, total_weight)cumulative = 0selected_member = candidates[0][0]status_info = candidates[0][1]for (candidate, status), weight in zip(candidates, weights):cumulative += weightif roll <= cumulative:selected_member, status_info = candidate, statusbreakelif strategy == "least_used":candidates.sort(key=lambda x: x[0].get("use_count", 0))selected_member, status_info = candidates[0]else: # round_robin or defaultcandidates.sort(key=lambda x: x[0].get("use_count", 0))selected_member, status_info = candidates[0]db.increment_member_use(pool_id, selected_member["provider_id"])db.update_member_stats(pool_id,selected_member["provider_id"],success_rate=status_info.get("uptime", selected_member.get("success_rate")),rate_limit_usage=status_info.get("rate_limit", {}).get("usage", 0) if isinstance(status_info.get("rate_limit"), dict) else None,rate_limit_limit=status_info.get("rate_limit", {}).get("limit", 0) if isinstance(status_info.get("rate_limit"), dict) else None,rate_limit_percentage=status_info.get("rate_limit", {}).get("percentage", 0) if isinstance(status_info.get("rate_limit"), dict) else None,)db.log_pool_rotation(pool_id,selected_member["provider_id"],selected_member["provider_name"],request.get("reason", "manual") if request else "manual")pool_record = db.get_pool(pool_id)payload = build_pool_payload(pool_record, provider_map)await broadcast_pool_update("rotated", pool_id, {"provider_id": selected_member["provider_id"],"provider_name": selected_member["provider_name"]})return {"message": "Pool rotated successfully","provider_name": selected_member["provider_name"],"provider_id": selected_member["provider_id"],"total_rotations": pool_record.get("rotation_count", 0),"pool": payload}@app.get("/api/pools/{pool_id}/history")async def get_pool_history(pool_id: int, limit: int = 20):"""Get rotation history for a pool"""history = transform_rotation_history(db.get_pool_rotation_history(pool_id, limit))return {"history": history,"total": len(history)}@app.get("/api/pools/history")async def get_all_history(limit: int = 50):"""Get all rotation history"""history = transform_rotation_history(db.get_pool_rotation_history(None, limit))return {"history": history,"total": len(history)}if __name__ == "__main__":print("🚀 Crypto Monitor ULTIMATE")print("📊 Real APIs: CoinGecko, CoinCap, Binance, DeFi Llama, Fear & Greed")print("🌐 http://localhost:8000/dashboard")print("📡 API Docs: http://localhost:8000/docs")uvicorn.run(app, host="0.0.0.0", port=8000)
5 unmodified lines6789101194 unmodified lines106107108109110111112113114115116117118119120121122123124125126127128129130131132133344 unmodified lines4784794805 unmodified linesimport sqlite3import jsonimport loggingfrom typing import List, Dict, Optional, Tuplefrom datetime import datetime, timedeltafrom pathlib import Path94 unmodified lines)""")# Configuration tablecursor.execute("""CREATE TABLE IF NOT EXISTS configuration (key TEXT PRIMARY KEY,value TEXT NOT NULL,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")# Create indexescursor.execute("""CREATE INDEX IF NOT EXISTS idx_status_log_providerON status_log(provider_name, timestamp)""")cursor.execute("""CREATE INDEX IF NOT EXISTS idx_status_log_timestampON status_log(timestamp)""")cursor.execute("""CREATE INDEX IF NOT EXISTS idx_incidents_providerON incidents(provider_name, start_time)""")logger.info("Database initialized successfully")344 unmodified lineswriter.writerow(dict(row))logger.info(f"Exported {len(rows)} rows to {output_path}")5 unmodified lines678910111294 unmodified lines107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187344 unmodified lines5325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757765 unmodified linesimport sqlite3import jsonimport loggingimport timefrom typing import List, Dict, Optional, Tuplefrom datetime import datetime, timedeltafrom pathlib import Path94 unmodified lines)""")# Configuration tablecursor.execute("""CREATE TABLE IF NOT EXISTS configuration (key TEXT PRIMARY KEY,value TEXT NOT NULL,updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")# Pools tablecursor.execute("""CREATE TABLE IF NOT EXISTS pools (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,category TEXT NOT NULL,rotation_strategy TEXT NOT NULL,description TEXT,enabled INTEGER DEFAULT 1,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")# Pool members tablecursor.execute("""CREATE TABLE IF NOT EXISTS pool_members (id INTEGER PRIMARY KEY AUTOINCREMENT,pool_id INTEGER NOT NULL,provider_id TEXT NOT NULL,provider_name TEXT NOT NULL,priority INTEGER DEFAULT 1,weight INTEGER DEFAULT 1,use_count INTEGER DEFAULT 0,success_rate REAL DEFAULT 0,rate_limit_usage INTEGER DEFAULT 0,rate_limit_limit INTEGER DEFAULT 0,rate_limit_percentage REAL DEFAULT 0,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY (pool_id) REFERENCES pools(id) ON DELETE CASCADE)""")# Pool rotation historycursor.execute("""CREATE TABLE IF NOT EXISTS pool_rotations (id INTEGER PRIMARY KEY AUTOINCREMENT,pool_id INTEGER NOT NULL,provider_id TEXT NOT NULL,provider_name TEXT NOT NULL,reason TEXT NOT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY (pool_id) REFERENCES pools(id) ON DELETE CASCADE)""")# Create indexescursor.execute("""CREATE INDEX IF NOT EXISTS idx_status_log_providerON status_log(provider_name, timestamp)""")cursor.execute("""CREATE INDEX IF NOT EXISTS idx_status_log_timestampON status_log(timestamp)""")cursor.execute("""CREATE INDEX IF NOT EXISTS idx_incidents_providerON incidents(provider_name, start_time)""")cursor.execute("""CREATE INDEX IF NOT EXISTS idx_pool_members_poolON pool_members(pool_id, provider_id)""")cursor.execute("""CREATE INDEX IF NOT EXISTS idx_pool_rotations_poolON pool_rotations(pool_id, created_at)""")logger.info("Database initialized successfully")344 unmodified lineswriter.writerow(dict(row))logger.info(f"Exported {len(rows)} rows to {output_path}")# ------------------------------------------------------------------# Pool management helpers# ------------------------------------------------------------------def create_pool(self,name: str,category: str,rotation_strategy: str,description: Optional[str] = None,enabled: bool = True) -> int:"""Create a new pool and return its ID"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""INSERT INTO pools (name, category, rotation_strategy, description, enabled)VALUES (?, ?, ?, ?, ?)""", (name, category, rotation_strategy, description, int(enabled)))return cursor.lastrowiddef update_pool_usage(self, pool_id: int, enabled: Optional[bool] = None):"""Update pool properties"""if enabled is None:returnwith self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""UPDATE poolsSET enabled = ?, created_at = created_atWHERE id = ?""", (int(enabled), pool_id))def delete_pool(self, pool_id: int):"""Delete pool and cascade members/history"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("DELETE FROM pools WHERE id = ?", (pool_id,))def add_pool_member(self,pool_id: int,provider_id: str,provider_name: str,priority: int = 1,weight: int = 1,success_rate: float = 0.0,rate_limit_usage: int = 0,rate_limit_limit: int = 0,rate_limit_percentage: float = 0.0) -> int:"""Add a provider to a pool"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""INSERT INTO pool_members(pool_id, provider_id, provider_name, priority, weight,success_rate, rate_limit_usage, rate_limit_limit, rate_limit_percentage)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", (pool_id,provider_id,provider_name,priority,weight,success_rate,rate_limit_usage,rate_limit_limit,rate_limit_percentage))return cursor.lastrowiddef remove_pool_member(self, pool_id: int, provider_id: str):"""Remove provider from pool"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""DELETE FROM pool_membersWHERE pool_id = ? AND provider_id = ?""", (pool_id, provider_id))def increment_member_use(self, pool_id: int, provider_id: str):"""Increment use count for pool member"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""UPDATE pool_membersSET use_count = use_count + 1WHERE pool_id = ? AND provider_id = ?""", (pool_id, provider_id))def update_member_stats(self,pool_id: int,provider_id: str,success_rate: Optional[float] = None,rate_limit_usage: Optional[int] = None,rate_limit_limit: Optional[int] = None,rate_limit_percentage: Optional[float] = None):"""Update success/rate limit stats"""updates = []params = []if success_rate is not None:updates.append("success_rate = ?")params.append(success_rate)if rate_limit_usage is not None:updates.append("rate_limit_usage = ?")params.append(rate_limit_usage)if rate_limit_limit is not None:updates.append("rate_limit_limit = ?")params.append(rate_limit_limit)if rate_limit_percentage is not None:updates.append("rate_limit_percentage = ?")params.append(rate_limit_percentage)if not updates:returnparams.extend([pool_id, provider_id])with self.get_connection() as conn:cursor = conn.cursor()cursor.execute(f"""UPDATE pool_membersSET {', '.join(updates)}WHERE pool_id = ? AND provider_id = ?""", params)def log_pool_rotation(self,pool_id: int,provider_id: str,provider_name: str,reason: str):"""Log rotation event"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""INSERT INTO pool_rotations(pool_id, provider_id, provider_name, reason)VALUES (?, ?, ?, ?)""", (pool_id, provider_id, provider_name, reason))def get_pools(self) -> List[Dict]:"""Get all pools with members and stats"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""SELECT p.*,COALESCE((SELECT COUNT(*) FROM pool_rotations pr WHERE pr.pool_id = p.id), 0) as rotation_countFROM pools pORDER BY p.created_at DESC""")pools = [dict(row) for row in cursor.fetchall()]for pool in pools:cursor.execute("""SELECT * FROM pool_membersWHERE pool_id = ?ORDER BY priority DESC, weight DESC, provider_name""", (pool['id'],))pool['members'] = [dict(row) for row in cursor.fetchall()]return poolsdef get_pool(self, pool_id: int) -> Optional[Dict]:"""Get single pool"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""SELECT p.*,COALESCE((SELECT COUNT(*) FROM pool_rotations pr WHERE pr.pool_id = p.id), 0) as rotation_countFROM pools pWHERE p.id = ?""", (pool_id,))row = cursor.fetchone()if not row:return Nonepool = dict(row)cursor.execute("""SELECT * FROM pool_membersWHERE pool_id = ?ORDER BY priority DESC, weight DESC, provider_name""", (pool_id,))pool['members'] = [dict(r) for r in cursor.fetchall()]return pooldef get_pool_rotation_history(self, pool_id: Optional[int] = None, limit: int = 50) -> List[Dict]:"""Get rotation history (optionally filtered by pool)"""with self.get_connection() as conn:cursor = conn.cursor()if pool_id is not None:cursor.execute("""SELECT * FROM pool_rotationsWHERE pool_id = ?ORDER BY created_at DESCLIMIT ?""", (pool_id, limit))else:cursor.execute("""SELECT * FROM pool_rotationsORDER BY created_at DESCLIMIT ?""", (limit,))return [dict(row) for row in cursor.fetchall()]# ------------------------------------------------------------------# Provider health logging# ------------------------------------------------------------------def log_provider_status(self,provider_name: str,category: str,status: str,response_time: Optional[float] = None,status_code: Optional[int] = None,endpoint_tested: Optional[str] = None,error_message: Optional[str] = None):"""Log provider status in status_log table"""with self.get_connection() as conn:cursor = conn.cursor()cursor.execute("""INSERT INTO status_log(provider_name, category, status, response_time, status_code,error_message, endpoint_tested, timestamp)VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", (provider_name,category,status,response_time,status_code,error_message,endpoint_tested,time.time()))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Enhanced Crypto Data Tracker</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
.container { max-width: 1600px; margin: 0 auto; }
header { background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); border-radius: 15px; padding: 20px 30px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; }
h1 { color: white; font-size: 28px; display: flex; align-items: center; gap: 10px; }
.connection-status { display: flex; align-items: center; gap: 10px; color: white; font-size: 14px; }
.status-indicator { width: 10px; height: 10px; border-radius: 50%; background: #10b981; animation: pulse 2s infinite; }
.status-indicator.disconnected { background: #ef4444; animation: none; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
.controls { background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); border-radius: 15px; padding: 20px; margin-bottom: 20px; }
.controls-row { display: flex; gap: 15px; flex-wrap: wrap; align-items: center; }
.btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 600; transition: all 0.3s ease; display: flex; align-items: center; gap: 8px; }
.btn-primary { background: white; color: #667eea; }
.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); }
.btn-success { background: #10b981; color: white; }
.btn-danger { background: #ef4444; color: white; }
.btn-info { background: #3b82f6; color: white; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 20px; margin-bottom: 20px; }
.card { background: rgba(255, 255, 255, 0.1); backdrop-filter: blur(10px); border-radius: 15px; padding: 20px; color: white; }
.card h2 { font-size: 18px; margin-bottom: 15px; display: flex; align-items: center; gap: 10px; }
.stat-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
.stat-item { background: rgba(255, 255, 255, 0.1); padding: 15px; border-radius: 10px; }
.stat-label { font-size: 12px; opacity: 0.8; margin-bottom: 5px; }
.stat-value { font-size: 24px; font-weight: 700; }
.api-list { max-height: 400px; overflow-y: auto; }
.api-item { background: rgba(255, 255, 255, 0.05); padding: 15px; border-radius: 10px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; }
.api-info { flex: 1; }
.api-name { font-weight: 600; margin-bottom: 5px; }
.api-meta { font-size: 12px; opacity: 0.7; display: flex; gap: 15px; }
.api-controls { display: flex; gap: 10px; }
.small-btn { padding: 5px 12px; font-size: 12px; border-radius: 5px; border: none; cursor: pointer; background: rgba(255, 255, 255, 0.2); color: white; transition: all 0.2s; }
.small-btn:hover { background: rgba(255, 255, 255, 0.3); }
.status-badge { display: inline-block; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; }
.status-success { background: #10b981; color: white; }
.status-pending { background: #f59e0b; color: white; }
.status-failed { background: #ef4444; color: white; }
.log-container { background: rgba(0, 0, 0, 0.3); border-radius: 10px; padding: 15px; max-height: 300px; overflow-y: auto; font-family: 'Courier New', monospace; font-size: 12px; }
.log-entry { margin-bottom: 8px; padding: 5px; border-left: 3px solid #667eea; padding-left: 10px; }
.log-time { opacity: 0.6; margin-right: 10px; }
.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); z-index: 1000; justify-content: center; align-items: center; }
.modal.active { display: flex; }
.modal-content { background: white; border-radius: 15px; padding: 30px; max-width: 500px; width: 90%; color: #333; }
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #666; }
.form-group { margin-bottom: 15px; }
.form-label { display: block; margin-bottom: 5px; font-weight: 600; color: #333; }
.form-input { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; }
.form-select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; }
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: rgba(255, 255, 255, 0.1); border-radius: 4px; }
::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.3); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.5); }
.toast { position: fixed; bottom: 20px; right: 20px; background: white; color: #333; padding: 15px 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); opacity: 0; transform: translateY(20px); transition: all 0.3s ease; z-index: 2000; }
.toast.show { opacity: 1; transform: translateY(0); } </style></head><body> <div class="container"> <header> <h1> <span>🚀</span> Enhanced Crypto Data Tracker </h1> <div class="connection-status"> <div class="status-indicator" id="wsStatus"></div> <span id="wsStatusText">Connecting...</span> </div> </header>
<div class="controls"> <div class="controls-row"> <button class="btn btn-primary" onclick="exportJSON()"> 💾 Export JSON </button> <button class="btn btn-primary" onclick="exportCSV()"> 📊 Export CSV </button> <button class="btn btn-success" onclick="createBackup()"> 🔄 Create Backup </button> <button class="btn btn-info" onclick="showScheduleModal()"> ⏰ Configure Schedule </button> <button class="btn btn-info" onclick="forceUpdateAll()"> 🔃 Force Update All </button> <button class="btn btn-danger" onclick="clearCache()"> 🗑️ Clear Cache </button> </div> </div>
<div class="grid"> <div class="card"> <h2>📊 System Statistics</h2> <div class="stat-grid"> <div class="stat-item"> <div class="stat-label">Total APIs</div> <div class="stat-value" id="totalApis">0</div> </div> <div class="stat-item"> <div class="stat-label">Active Tasks</div> <div class="stat-value" id="activeTasks">0</div> </div> <div class="stat-item"> <div class="stat-label">Cached Data</div> <div class="stat-value" id="cachedData">0</div> </div> <div class="stat-item"> <div class="stat-label">WS Connections</div> <div class="stat-value" id="wsConnections">0</div> </div> </div> </div>
<div class="card"> <h2>📈 Recent Activity</h2> <div class="log-container" id="activityLog"> <div class="log-entry"> <span class="log-time">--:--:--</span> Waiting for updates... </div> </div> </div> </div>
<div class="card"> <h2>🔌 API Sources</h2> <div class="api-list" id="apiList"> Loading... </div> </div> </div>
<!-- Schedule Modal --> <div class="modal" id="scheduleModal"> <div class="modal-content"> <div class="modal-header"> <h2>⏰ Configure Schedule</h2> <button class="modal-close" onclick="closeScheduleModal()">×</button> </div> <div class="form-group"> <label class="form-label">API Source</label> <select class="form-select" id="scheduleApiSelect"></select> </div> <div class="form-group"> <label class="form-label">Interval (seconds)</label> <input type="number" class="form-input" id="scheduleInterval" value="60" min="10"> </div> <div class="form-group"> <label class="form-label">Enabled</label> <input type="checkbox" id="scheduleEnabled" checked> </div> <button class="btn btn-primary" onclick="updateSchedule()">Save Schedule</button> </div> </div>
<!-- Toast notification --> <div class="toast" id="toast"></div>
<script> let ws = null; let reconnectAttempts = 0; const maxReconnectAttempts = 5; const reconnectDelay = 3000;
// Initialize WebSocket connection function initWebSocket() { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${protocol}//${window.location.host}/api/v2/ws`;
ws = new WebSocket(wsUrl);
ws.onopen = () => { console.log('WebSocket connected'); updateWSStatus(true); reconnectAttempts = 0;
// Subscribe to all updates ws.send(JSON.stringify({ type: 'subscribe_all' }));
// Start heartbeat startHeartbeat(); };
ws.onmessage = (event) => { const message = JSON.parse(event.data); handleWSMessage(message); };
ws.onerror = (error) => { console.error('WebSocket error:', error); };
ws.onclose = () => { console.log('WebSocket disconnected'); updateWSStatus(false); attemptReconnect(); }; }
function attemptReconnect() { if (reconnectAttempts < maxReconnectAttempts) { reconnectAttempts++; console.log(`Reconnecting... Attempt ${reconnectAttempts}`); setTimeout(initWebSocket, reconnectDelay); } }
let heartbeatInterval; function startHeartbeat() { clearInterval(heartbeatInterval); heartbeatInterval = setInterval(() => { if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ping' })); } }, 30000); }
function updateWSStatus(connected) { const indicator = document.getElementById('wsStatus'); const text = document.getElementById('wsStatusText');
if (connected) { indicator.classList.remove('disconnected'); text.textContent = 'Connected'; } else { indicator.classList.add('disconnected'); text.textContent = 'Disconnected'; } }
function handleWSMessage(message) { console.log('Received:', message);
switch (message.type) { case 'api_update': handleApiUpdate(message); break; case 'status_update': handleStatusUpdate(message); break; case 'schedule_update': handleScheduleUpdate(message); break; case 'subscribed': addLog(`Subscribed to ${message.api_id || 'all updates'}`); break; } }
function handleApiUpdate(message) { addLog(`Updated: ${message.api_id}`, 'success'); loadSystemStatus(); }
function handleStatusUpdate(message) { addLog('System status updated'); loadSystemStatus(); }
function handleScheduleUpdate(message) { addLog(`Schedule updated for ${message.schedule.api_id}`); loadAPIs(); }
function addLog(text, type = 'info') { const logContainer = document.getElementById('activityLog'); const time = new Date().toLocaleTimeString();
const entry = document.createElement('div'); entry.className = 'log-entry'; entry.innerHTML = `<span class="log-time">${time}</span>${text}`;
logContainer.insertBefore(entry, logContainer.firstChild);
// Keep only last 50 entries while (logContainer.children.length > 50) { logContainer.removeChild(logContainer.lastChild); } }
function showToast(message, duration = 3000) { const toast = document.getElementById('toast'); toast.textContent = message; toast.classList.add('show');
setTimeout(() => { toast.classList.remove('show'); }, duration); }
// Load system status async function loadSystemStatus() { try { const response = await fetch('/api/v2/status'); const data = await response.json();
document.getElementById('totalApis').textContent = data.services.config_loader.apis_loaded; document.getElementById('activeTasks').textContent = data.services.scheduler.total_tasks; document.getElementById('cachedData').textContent = data.services.persistence.cached_apis; document.getElementById('wsConnections').textContent = data.services.websocket.total_connections;
} catch (error) { console.error('Error loading status:', error); } }
// Load APIs async function loadAPIs() { try { const response = await fetch('/api/v2/config/apis'); const data = await response.json();
const scheduleResponse = await fetch('/api/v2/schedule/tasks'); const schedules = await scheduleResponse.json();
displayAPIs(data.apis, schedules);
} catch (error) { console.error('Error loading APIs:', error); } }
function displayAPIs(apis, schedules) { const listElement = document.getElementById('apiList'); listElement.innerHTML = '';
for (const [apiId, api] of Object.entries(apis)) { const schedule = schedules[apiId] || {};
const item = document.createElement('div'); item.className = 'api-item'; item.innerHTML = ` <div class="api-info"> <div class="api-name">${api.name}</div> <div class="api-meta"> <span>📂 ${api.category}</span> <span>⏱️ ${schedule.interval || 300}s</span> <span class="status-badge ${schedule.last_status === 'success' ? 'status-success' : 'status-pending'}"> ${schedule.last_status || 'pending'} </span> </div> </div> <div class="api-controls"> <button class="small-btn" onclick="forceUpdate('${apiId}')">🔄 Update</button> <button class="small-btn" onclick="showScheduleModalFor('${apiId}')">⚙️ Schedule</button> </div> `;
listElement.appendChild(item); } }
// Export functions async function exportJSON() { try { const response = await fetch('/api/v2/export/json', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ include_history: true }) });
const data = await response.json(); showToast('✅ JSON export created!'); addLog(`Exported to JSON: ${data.filepath}`);
// Trigger download window.open(data.download_url, '_blank');
} catch (error) { showToast('❌ Export failed'); console.error(error); } }
async function exportCSV() { try { const response = await fetch('/api/v2/export/csv', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ flatten: true }) });
const data = await response.json(); showToast('✅ CSV export created!'); addLog(`Exported to CSV: ${data.filepath}`);
// Trigger download window.open(data.download_url, '_blank');
} catch (error) { showToast('❌ Export failed'); console.error(error); } }
async function createBackup() { try { const response = await fetch('/api/v2/backup', { method: 'POST' });
const data = await response.json(); showToast('✅ Backup created!'); addLog(`Backup created: ${data.backup_file}`);
} catch (error) { showToast('❌ Backup failed'); console.error(error); } }
async function forceUpdate(apiId) { try { const response = await fetch(`/api/v2/schedule/tasks/${apiId}/force-update`, { method: 'POST' });
const data = await response.json(); showToast(`✅ ${apiId} updated!`); addLog(`Forced update: ${apiId}`); loadAPIs();
} catch (error) { showToast('❌ Update failed'); console.error(error); } }
async function forceUpdateAll() { showToast('🔄 Updating all APIs...'); addLog('Forcing update for all APIs');
try { const response = await fetch('/api/v2/config/apis'); const data = await response.json();
for (const apiId of Object.keys(data.apis)) { await forceUpdate(apiId); await new Promise(resolve => setTimeout(resolve, 100)); // Small delay }
showToast('✅ All APIs updated!'); } catch (error) { showToast('❌ Update failed'); console.error(error); } }
async function clearCache() { if (!confirm('Clear all cached data?')) return;
try { const response = await fetch('/api/v2/cleanup/cache', { method: 'POST' });
showToast('✅ Cache cleared!'); addLog('Cache cleared'); loadSystemStatus();
} catch (error) { showToast('❌ Failed to clear cache'); console.error(error); } }
// Schedule modal functions function showScheduleModal() { loadAPISelectOptions(); document.getElementById('scheduleModal').classList.add('active'); }
function closeScheduleModal() { document.getElementById('scheduleModal').classList.remove('active'); }
async function showScheduleModalFor(apiId) { await loadAPISelectOptions(); document.getElementById('scheduleApiSelect').value = apiId;
// Load current schedule try { const response = await fetch(`/api/v2/schedule/tasks/${apiId}`); const schedule = await response.json();
document.getElementById('scheduleInterval').value = schedule.interval; document.getElementById('scheduleEnabled').checked = schedule.enabled;
} catch (error) { console.error(error); }
showScheduleModal(); }
async function loadAPISelectOptions() { try { const response = await fetch('/api/v2/config/apis'); const data = await response.json();
const select = document.getElementById('scheduleApiSelect'); select.innerHTML = '';
for (const [apiId, api] of Object.entries(data.apis)) { const option = document.createElement('option'); option.value = apiId; option.textContent = api.name; select.appendChild(option); }
} catch (error) { console.error(error); } }
async function updateSchedule() { const apiId = document.getElementById('scheduleApiSelect').value; const interval = parseInt(document.getElementById('scheduleInterval').value); const enabled = document.getElementById('scheduleEnabled').checked;
try { const response = await fetch(`/api/v2/schedule/tasks/${apiId}?interval=${interval}&enabled=${enabled}`, { method: 'PUT' });
const data = await response.json(); showToast('✅ Schedule updated!'); addLog(`Updated schedule for ${apiId}`); closeScheduleModal(); loadAPIs();
} catch (error) { showToast('❌ Schedule update failed'); console.error(error); } }
// Initialize on load window.addEventListener('load', () => { initWebSocket(); loadSystemStatus(); loadAPIs();
// Refresh status every 30 seconds setInterval(loadSystemStatus, 30000); }); </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168from fastapi import FastAPI, HTTPException, Dependsfrom fastapi.middleware.cors import CORSMiddlewareimport ccxtimport osimport loggingfrom datetime import datetimeimport pandas as pdimport numpy as np# Setup logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Create data and logs directoriesos.makedirs("data", exist_ok=True)os.makedirs("logs", exist_ok=True)# Initialize FastAPI appapp = FastAPI(title="Cryptocurrency Data Source API",description="API for fetching cryptocurrency market data and technical indicators",version="1.0.0",)# Configure CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)@app.get("/")async def root():"""Root endpoint showing API status"""return {"status": "online","version": "1.0.0","timestamp": datetime.now().isoformat(),"ccxt_version": ccxt.__version__}@app.get("/exchanges")async def get_exchanges():"""List available exchanges"""# Get list of exchanges that support OHLCV dataexchanges = []for exchange_id in ccxt.exchanges:try:exchange = getattr(ccxt, exchange_id)()if exchange.has.get('fetchOHLCV'):exchanges.append({"id": exchange_id,"name": exchange.name if hasattr(exchange, 'name') else exchange_id,"url": exchange.urls.get('www') if hasattr(exchange, 'urls') and exchange.urls else None})except:# Skip exchanges that fail to initializecontinuereturn {"total": len(exchanges), "exchanges": exchanges}@app.get("/markets/{exchange_id}")async def get_markets(exchange_id: str):"""Get markets for a specific exchange"""try:# Check if exchange existsif exchange_id not in ccxt.exchanges:raise HTTPException(status_code=404, detail=f"Exchange {exchange_id} not found")# Initialize exchangeexchange = getattr(ccxt, exchange_id)({'enableRateLimit': True})# Fetch marketsmarkets = exchange.load_markets()# Format responseresult = []for symbol, market in markets.items():if market.get('active', False):result.append({"symbol": symbol,"base": market.get('base', ''),"quote": market.get('quote', ''),"type": market.get('type', 'spot')})return {"exchange": exchange_id, "total": len(result), "markets": result[:100]}except ccxt.BaseError as e:raise HTTPException(status_code=500, detail=str(e))except Exception as e:logger.error(f"Error fetching markets for {exchange_id}: {str(e)}")raise HTTPException(status_code=500, detail=str(e))@app.get("/ohlcv/{exchange_id}/{symbol}")async def get_ohlcv(exchange_id: str, symbol: str, timeframe: str = "1h", limit: int = 100):"""Get OHLCV data for a specific market"""try:# Check if exchange existsif exchange_id not in ccxt.exchanges:raise HTTPException(status_code=404, detail=f"Exchange {exchange_id} not found")# Initialize exchangeexchange = getattr(ccxt, exchange_id)({'enableRateLimit': True})# Check if exchange supports OHLCVif not exchange.has.get('fetchOHLCV'):raise HTTPException(status_code=400,detail=f"Exchange {exchange_id} does not support OHLCV data")# Check timeframeif timeframe not in exchange.timeframes:raise HTTPException(status_code=400,detail=f"Timeframe {timeframe} not supported by {exchange_id}")# Fetch OHLCV dataohlcv = exchange.fetch_ohlcv(symbol=symbol, timeframe=timeframe, limit=limit)# Convert to readable formatresult = []for candle in ohlcv:timestamp, open_price, high, low, close, volume = candleresult.append({"timestamp": timestamp,"datetime": datetime.fromtimestamp(timestamp / 1000).isoformat(),"open": open_price,"high": high,"low": low,"close": close,"volume": volume})return {"exchange": exchange_id,"symbol": symbol,"timeframe": timeframe,"data": result}except ccxt.BaseError as e:raise HTTPException(status_code=500, detail=str(e))except Exception as e:logger.error(f"Error fetching OHLCV data: {str(e)}")raise HTTPException(status_code=500, detail=str(e))@app.get("/health")async def health_check():"""Health check endpoint"""return {"status": "healthy","timestamp": datetime.now().isoformat(),"version": "1.0.0"}if __name__ == "__main__":import uvicornport = int(os.getenv("PORT", 7860))uvicorn.run("main:app", host="0.0.0.0", port=port, log_level="info")123from app import app as fastapi_appapp = fastapi_app
12345fastapi==0.104.1uvicorn[standard]==0.24.0websockets==12.0python-multipart==0.0.6pydantic==2.5.01234fastapi==0.104.1uvicorn[standard]==0.24.0aiohttp==3.9.1websockets==12.0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081@echo offchcp 65001 > nultitle Crypto API Monitor - Starting...echo ========================================echo 🚀 Crypto API Monitorecho Real-time Cryptocurrency Dashboardecho ========================================echo.REM Check if Python is installedpython --version > nul 2>&1if %errorlevel% neq 0 (echo ❌ Python is not installed or not in PATHecho.echo Please install Python 3.8 or higher from:echo https://www.python.org/downloads/echo.echo Make sure to check "Add Python to PATH" during installationpauseexit /b 1)echo ✅ Python is installedecho.REM Check if virtual environment existsif not exist "venv" (echo 📦 Creating virtual environment...python -m venv venvif %errorlevel% neq 0 (echo ❌ Failed to create virtual environmentpauseexit /b 1)echo ✅ Virtual environment createdecho.)REM Activate virtual environmentecho 🔧 Activating virtual environment...call venv\Scripts\activate.batif %errorlevel% neq 0 (echo ❌ Failed to activate virtual environmentpauseexit /b 1)echo ✅ Virtual environment activatedecho.REM Install/Update dependenciesecho 📥 Installing dependencies...pip install -q -r requirements.txtif %errorlevel% neq 0 (echo ❌ Failed to install dependenciespauseexit /b 1)echo ✅ Dependencies installedecho.echo ========================================echo 🎯 Starting Server...echo ========================================echo.echo 📊 Dashboard will be available at:echo http://localhost:8000/dashboardecho.echo 📡 API Documentation:echo http://localhost:8000/docsecho.echo 💡 Press Ctrl+C to stop the serverecho.echo ========================================echo.REM Start the applicationpython app.pypause1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253@echo offchcp 65001 > nultitle Crypto Monitor ULTIMATE - Real APIsecho ========================================echo 🚀 Crypto Monitor ULTIMATEecho Real-time Data from 100+ Free APIsecho ========================================echo.python --version > nul 2>&1if %errorlevel% neq 0 (echo ❌ Python not found!pauseexit /b 1)echo ✅ Python foundecho.if not exist "venv" (echo 📦 Creating virtual environment...python -m venv venv)echo 🔧 Activating environment...call venv\Scripts\activate.batecho 📥 Installing packages...pip install -q -r requirements.txtecho.echo ========================================echo 🎯 Starting Real-time Server...echo ========================================echo.echo 📊 Dashboard: http://localhost:8000/dashboardecho 📡 API Docs: http://localhost:8000/docsecho.echo 💡 Real APIs:echo ✓ CoinGecko - Market Dataecho ✓ CoinCap - Price Dataecho ✓ Binance - Exchange Dataecho ✓ Fear & Greed Indexecho ✓ DeFi Llama - TVL Dataecho.echo Press Ctrl+C to stopecho ========================================echo.python app.pypause
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crypto Monitor ULTIMATE - Unified Dashboard</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-dark: #0a0e1a;
--bg-card: #111827;
--bg-card-hover: #1f2937;
--text-primary: #f9fafb;
--text-secondary: #9ca3af;
--accent-blue: #3b82f6;
--accent-green: #10b981;
--accent-red: #ef4444;
--accent-yellow: #f59e0b;
--accent-purple: #8b5cf6;
--accent-pink: #ec4899;
--border: rgba(255, 255, 255, 0.1);
--shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-dark);
color: var(--text-primary);
line-height: 1.6;
overflow-x: hidden;
}
body::before {
content: '';
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background:
radial-gradient(circle at 20% 30%, rgba(59, 130, 246, 0.15) 0%, transparent 40%),
radial-gradient(circle at 80% 70%, rgba(139, 92, 246, 0.15) 0%, transparent 40%),
radial-gradient(circle at 50% 50%, rgba(16, 185, 129, 0.1) 0%, transparent 30%);
pointer-events: none;
z-index: 0;
}
.container {
max-width: 1920px;
margin: 0 auto;
padding: 20px;
position: relative;
z-index: 1;
}
/* Header */
.header {
background: linear-gradient(135deg, rgba(17, 24, 39, 0.8) 0%, rgba(31, 41, 55, 0.4) 100%);
backdrop-filter: blur(20px);
border: 1px solid var(--border);
border-radius: 24px;
padding: 30px;
margin-bottom: 30px;
box-shadow: var(--shadow);
}
.header-top {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 20px;
margin-bottom: 20px;
}
.logo {
display: flex;
align-items: center;
gap: 15px;
}
.logo-icon {
width: 60px;
height: 60px;
background: linear-gradient(135deg, #3b82f6, #8b5cf6, #ec4899);
border-radius: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 32px;
box-shadow: 0 10px 40px rgba(59, 130, 246, 0.4);
animation: pulse-glow 3s ease-in-out infinite;
}
@keyframes pulse-glow {
0%, 100% { box-shadow: 0 10px 40px rgba(59, 130, 246, 0.4); }
50% { box-shadow: 0 10px 60px rgba(139, 92, 246, 0.6); }
}
.logo-text h1 {
font-size: 32px;
font-weight: 900;
background: linear-gradient(135deg, #3b82f6, #8b5cf6, #ec4899);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
letter-spacing: -1px;
}
.logo-text p {
font-size: 14px;
color: var(--text-secondary);
font-weight: 500;
}
.header-actions {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
}
.status-badge {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 24px;
background: rgba(16, 185, 129, 0.15);
border: 1px solid rgba(16, 185, 129, 0.3);
border-radius: 12px;
font-size: 14px;
font-weight: 600;
}
.status-dot {
width: 10px;
height: 10px;
background: var(--accent-green);
border-radius: 50%;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(1.2); }
}
.live-indicator {
padding: 8px 16px;
background: rgba(239, 68, 68, 0.15);
border: 1px solid rgba(239, 68, 68, 0.3);
border-radius: 8px;
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
color: var(--accent-red);
animation: blink 2s infinite;
}
@keyframes blink {
0%, 50%, 100% { opacity: 1; }
25%, 75% { opacity: 0.3; }
}
/* Tabs */
.tabs {
display: flex;
gap: 10px;
margin-bottom: 30px;
flex-wrap: wrap;
border-bottom: 2px solid var(--border);
padding-bottom: 10px;
}
.tab {
padding: 12px 24px;
background: transparent;
border: none;
border-radius: 12px 12px 0 0;
color: var(--text-secondary);
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
font-size: 14px;
position: relative;
}
.tab:hover {
color: var(--text-primary);
background: rgba(255, 255, 255, 0.05);
}
.tab.active {
color: var(--accent-blue);
background: rgba(59, 130, 246, 0.1);
}
.tab.active::after {
content: '';
position: absolute;
bottom: -12px;
left: 0;
right: 0;
height: 3px;
background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple));
border-radius: 2px;
}
.tab-content {
display: none;
animation: fadeIn 0.3s;
}
.tab-content.active {
display: block;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
/* Stats Grid */
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: rgba(17, 24, 39, 0.6);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: 20px;
padding: 25px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
overflow: hidden;
}
.stat-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple), var(--accent-pink));
transform: scaleX(0);
transition: transform 0.3s ease;
}
.stat-card:hover {
transform: translateY(-8px) scale(1.02);
border-color: rgba(59, 130, 246, 0.5);
box-shadow: 0 20px 50px rgba(59, 130, 246, 0.3);
}
.stat-card:hover::before {
transform: scaleX(1);
}
.stat-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
}
.stat-icon {
width: 48px;
height: 48px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
background: linear-gradient(135deg, rgba(59, 130, 246, 0.2), rgba(139, 92, 246, 0.2));
}
.stat-value {
font-size: 36px;
font-weight: 900;
margin-bottom: 5px;
background: linear-gradient(135deg, var(--text-primary), var(--text-secondary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.stat-label {
font-size: 13px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 1px;
font-weight: 600;
}
.stat-change {
font-size: 14px;
font-weight: 700;
margin-top: 12px;
display: flex;
align-items: center;
gap: 6px;
}
.stat-change.positive { color: var(--accent-green); }
.stat-change.negative { color: var(--accent-red); }
/* Market Table */
.market-section {
background: rgba(17, 24, 39, 0.6);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: 24px;
padding: 30px;
margin-bottom: 30px;
box-shadow: var(--shadow);
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 25px;
flex-wrap: wrap;
gap: 15px;
}
.section-title {
font-size: 24px;
font-weight: 800;
background: linear-gradient(135deg, var(--accent-blue), var(--accent-purple));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.refresh-btn {
padding: 10px 20px;
background: linear-gradient(135deg, var(--accent-blue), var(--accent-purple));
border: none;
border-radius: 10px;
color: white;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
}
.refresh-btn:hover {
transform: scale(1.05);
box-shadow: 0 10px 30px rgba(59, 130, 246, 0.4);
}
table {
width: 100%;
border-collapse: collapse;
}
thead {
background: rgba(59, 130, 246, 0.1);
}
th {
padding: 16px;
text-align: left;
font-size: 12px;
font-weight: 700;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 1px;
}
td {
padding: 16px;
border-top: 1px solid var(--border);
font-size: 14px;
}
tr:hover {
background: rgba(59, 130, 246, 0.05);
}
.crypto-name {
display: flex;
align-items: center;
gap: 12px;
}
.crypto-img {
width: 36px;
height: 36px;
border-radius: 10px;
object-fit: cover;
}
.price {
font-weight: 700;
font-size: 15px;
}
.change {
padding: 6px 12px;
border-radius: 8px;
font-weight: 700;
font-size: 13px;
}
.change.positive {
background: rgba(16, 185, 129, 0.15);
color: var(--accent-green);
}
.change.negative {
background: rgba(239, 68, 68, 0.15);
color: var(--accent-red);
}
/* Charts */
.chart-container {
background: rgba(17, 24, 39, 0.6);
backdrop-filter: blur(10px);
border: 1px solid var(--border);
border-radius: 24px;
padding: 30px;
margin-bottom: 30px;
}
canvas {
max-height: 350px;
}
/* Loading */
.loading {
display: flex;
align-items: center;
justify-content: center;
padding: 60px;
}
.spinner {
width: 50px;
height: 50px;
border: 4px solid var(--border);
border-top-color: var(--accent-blue);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Forms */
.form-group {
margin-bottom: 20px;
}
.form-label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: var(--text-primary);
}
.form-input, .form-select, .form-textarea {
width: 100%;
padding: 12px;
background: rgba(17, 24, 39, 0.6);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
font-family: inherit;
font-size: 14px;
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
outline: none;
border-color: var(--accent-blue);
}
.form-textarea {
resize: vertical;
min-height: 100px;
}
/* Badges */
.badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
}
.badge-success {
background: rgba(16, 185, 129, 0.15);
color: var(--accent-green);
}
.badge-warning {
background: rgba(245, 158, 11, 0.15);
color: var(--accent-yellow);
}
.badge-danger {
background: rgba(239, 68, 68, 0.15);
color: var(--accent-red);
}
.badge-info {
background: rgba(59, 130, 246, 0.15);
color: var(--accent-blue);
}
/* Alert */
.alert {
padding: 12px 16px;
border-radius: 8px;
margin-bottom: 16px;
font-size: 14px;
}
.alert-success {
background: rgba(16, 185, 129, 0.15);
color: var(--accent-green);
border-left: 4px solid var(--accent-green);
}
.alert-error {
background: rgba(239, 68, 68, 0.15);
color: var(--accent-red);
border-left: 4px solid var(--accent-red);
}
/* Responsive */
@media (max-width: 768px) {
.stats-grid {
grid-template-columns: 1fr;
}
.header-top {
flex-direction: column;
align-items: flex-start;
}
table {
font-size: 12px;
}
th, td {
padding: 10px;
}
.tabs {
overflow-x: auto;
}
}
/* Modal Styles */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
backdrop-filter: blur(5px);
z-index: 1000;
justify-content: center;
align-items: center;
animation: fadeIn 0.3s;
}
.modal.active {
display: flex;
}
.modal-content {
background: var(--bg-card);
border-radius: 20px;
padding: 30px;
max-width: 600px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
border: 1px solid var(--border);
box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);
animation: slideUp 0.3s;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Improved Button Styles */
.btn-icon {
padding: 8px 12px;
border-radius: 8px;
border: 1px solid;
cursor: pointer;
font-size: 12px;
font-weight: 600;
transition: all 0.3s;
display: inline-flex;
align-items: center;
gap: 6px;
}
.btn-icon:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
/* Pool Card Hover Effect */
.pool-card-hover {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.pool-card-hover:hover {
transform: translateY(-5px);
box-shadow: 0 20px 40px rgba(59, 130, 246, 0.2);
}
/* Improved Empty States */
.empty-state {
text-align: center;
padding: 60px 20px;
background: rgba(17, 24, 39, 0.6);
border-radius: 20px;
border: 2px dashed var(--border);
}
.empty-state-icon {
font-size: 64px;
margin-bottom: 20px;
opacity: 0.5;
}
/* Loading States */
.skeleton {
background: linear-gradient(90deg, rgba(255, 255, 255, 0.05) 25%, rgba(255, 255, 255, 0.1) 50%, rgba(255, 255, 255, 0.05) 75%);
background-size: 200% 100%;
animation: loading 1.5s infinite;
}
@keyframes loading {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
/* Scrollbar */
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: var(--bg-dark);
}
::-webkit-scrollbar-thumb {
background: linear-gradient(135deg, var(--accent-blue), var(--accent-purple));
border-radius: 5px;
}
::-webkit-scrollbar-thumb:hover {
background: linear-gradient(135deg, var(--accent-purple), var(--accent-pink));
}
/* Toast Notifications */
.toast {
position: fixed;
bottom: 20px;
right: 20px;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px 20px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
z-index: 2000;
display: flex;
align-items: center;
gap: 12px;
min-width: 300px;
animation: slideInRight 0.3s;
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.toast-success {
border-left: 4px solid var(--accent-green);
}
.toast-error {
border-left: 4px solid var(--accent-red);
}
.toast-info {
border-left: 4px solid var(--accent-blue);
}
</style>
</head>
<body>
<div class="container">
<!-- Header -->
<div class="header">
<div class="header-top">
<div class="logo">
<div class="logo-icon">₿</div>
<div class="logo-text">
<h1>Crypto Monitor ULTIMATE</h1>
<p>Unified Dashboard • Real-time data from 100+ free APIs</p>
</div>
</div>
<div class="header-actions">
<div class="live-indicator">● LIVE</div>
<div class="status-badge">
<div class="status-dot"></div>
<span id="statusText">All Systems Operational</span>
</div>
</div>
</div>
<!-- Tabs -->
<div class="tabs">
<button class="tab active" onclick="switchTab('market')">📊 Market</button>
<button class="tab" onclick="switchTab('monitor')">📡 API Monitor</button>
<button class="tab" onclick="switchTab('advanced')">⚡ Advanced</button>
<button class="tab" onclick="switchTab('admin')">⚙️ Admin</button>
<button class="tab" onclick="switchTab('hf')">🤗 HuggingFace</button>
<button class="tab" onclick="switchTab('pools')">🔄 Pools</button>
</div>
</div>
<!-- Market Tab -->
<div id="tab-market" class="tab-content active">
<!-- Stats Grid -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">💰</div>
</div>
<div class="stat-value" id="totalMarketCap">$0.00T</div>
<div class="stat-label">Total Market Cap</div>
<div class="stat-change positive" id="mcapChange">
<span>↑</span> <span>0.0%</span>
</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">📊</div>
</div>
<div class="stat-value" id="totalVolume">$0.00B</div>
<div class="stat-label">24h Trading Volume</div>
<div class="stat-change positive">
<span>↑</span> <span>Volume spike</span>
</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">₿</div>
</div>
<div class="stat-value" id="btcDominance">0.0%</div>
<div class="stat-label">BTC Dominance</div>
<div class="stat-change">
<span id="btcDomIcon">↑</span> <span id="btcDomChange">0.0%</span>
</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">🔥</div>
</div>
<div class="stat-value" id="fearGreed">50</div>
<div class="stat-label">Fear & Greed Index</div>
<div class="stat-change" id="sentimentLabel">
<span>Neutral</span>
</div>
</div>
</div>
<!-- Market Table -->
<div class="market-section">
<div class="section-header">
<div class="section-title">💎 Live Market Data</div>
<button class="refresh-btn" onclick="loadMarketData()">↻ Refresh</button>
</div>
<div style="overflow-x: auto;">
<table id="marketTable">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Price</th>
<th>24h Change</th>
<th>Market Cap</th>
<th>Volume 24h</th>
</tr>
</thead>
<tbody id="marketTableBody">
<tr>
<td colspan="6">
<div class="loading"><div class="spinner"></div></div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Charts Row -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 30px; margin-bottom: 30px;">
<div class="chart-container">
<div class="section-title" style="margin-bottom: 20px;">📈 Market Dominance</div>
<canvas id="dominanceChart"></canvas>
</div>
<div class="chart-container">
<div class="section-title" style="margin-bottom: 20px;">😱 Fear & Greed Index</div>
<div style="text-align: center;">
<canvas id="gaugeChart"></canvas>
<div style="font-size: 48px; font-weight: 900; margin: 20px 0 10px;" id="sentimentValue">50</div>
<div style="color: var(--text-secondary); font-size: 16px; font-weight: 600;" id="sentimentText">Neutral</div>
</div>
</div>
</div>
<!-- Trending Section -->
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">🔥 Trending Now</div>
<div id="trendingGrid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
<div class="loading"><div class="spinner"></div></div>
</div>
</div>
<!-- DeFi Section -->
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">🏦 Top DeFi Protocols</div>
<div id="defiList">
<div class="loading"><div class="spinner"></div></div>
</div>
</div>
</div>
<!-- API Monitor Tab -->
<div id="tab-monitor" class="tab-content">
<div class="stats-grid">
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">📡</div>
</div>
<div class="stat-value" id="totalAPIs">0</div>
<div class="stat-label">Total APIs</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">✅</div>
</div>
<div class="stat-value" id="onlineAPIs" style="color: var(--accent-green);">0</div>
<div class="stat-label">Online</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">❌</div>
</div>
<div class="stat-value" id="offlineAPIs" style="color: var(--accent-red);">0</div>
<div class="stat-label">Offline</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">⚡</div>
</div>
<div class="stat-value" id="avgResponse" style="font-size: 28px;">0ms</div>
<div class="stat-label">Avg Response</div>
</div>
</div>
<div class="market-section">
<div class="section-header">
<div class="section-title">📊 API Providers Status</div>
<button class="refresh-btn" onclick="loadMonitorData()">↻ Refresh</button>
</div>
<div style="overflow-x: auto;">
<table>
<thead>
<tr>
<th>Provider</th>
<th>Category</th>
<th>Status</th>
<th>Response Time</th>
<th>Last Check</th>
</tr>
</thead>
<tbody id="providersTable">
<tr><td colspan="5" style="text-align: center;">Loading...</td></tr>
</tbody>
</table>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">🤗 HuggingFace Sentiment Analysis</div>
<div class="form-group">
<label class="form-label">Enter crypto-related text (one per line):</label>
<textarea class="form-textarea" id="sentimentText" rows="5" placeholder="BTC strong breakout ETH looks weak Market is bullish">BTC strong breakout
ETH looks weak
Market is bullish today</textarea>
</div>
<button class="refresh-btn" onclick="runSentiment()">🧠 Analyze Sentiment</button>
<div id="sentimentResult" style="margin-top: 20px; padding: 20px; background: rgba(17, 24, 39, 0.6); border-radius: 12px; text-align: center; font-size: 36px; font-weight: 900;">—</div>
<pre id="sentimentDetails" style="background: #1e293b; color: #e2e8f0; padding: 15px; border-radius: 8px; overflow-x: auto; font-size: 12px; margin-top: 15px; max-height: 300px; overflow-y: auto;"></pre>
</div>
</div>
<!-- Advanced Tab -->
<div id="tab-advanced" class="tab-content">
<div class="stats-grid">
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">📡</div>
</div>
<div class="stat-value" id="totalApis">0</div>
<div class="stat-label">Total APIs</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">⚙️</div>
</div>
<div class="stat-value" id="activeTasks">0</div>
<div class="stat-label">Active Tasks</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">💾</div>
</div>
<div class="stat-value" id="cachedData">0</div>
<div class="stat-label">Cached Data</div>
</div>
<div class="stat-card">
<div class="stat-header">
<div class="stat-icon">🔌</div>
</div>
<div class="stat-value" id="wsConnections">0</div>
<div class="stat-label">WS Connections</div>
</div>
</div>
<div class="market-section">
<div class="section-header">
<div class="section-title">🔧 Advanced Actions</div>
</div>
<div style="display: flex; gap: 15px; flex-wrap: wrap;">
<button class="refresh-btn" onclick="exportJSON()">💾 Export JSON</button>
<button class="refresh-btn" onclick="exportCSV()">📊 Export CSV</button>
<button class="refresh-btn" onclick="createBackup()">🔄 Create Backup</button>
<button class="refresh-btn" onclick="clearCache()">🗑️ Clear Cache</button>
<button class="refresh-btn" onclick="forceUpdateAll()">🔃 Force Update All</button>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">📈 Recent Activity</div>
<div id="activityLog" style="max-height: 400px; overflow-y: auto; font-family: monospace; font-size: 12px;">
<div style="padding: 10px; border-left: 3px solid var(--accent-blue); margin-bottom: 8px;">
<span style="opacity: 0.6;">--:--:--</span> Waiting for updates...
</div>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">🔌 API Sources</div>
<div id="apiList">
<div class="loading"><div class="spinner"></div></div>
</div>
</div>
</div>
<!-- Admin Tab -->
<div id="tab-admin" class="tab-content">
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">➕ Add New API Source</div>
<div class="form-group">
<label class="form-label">API Name</label>
<input type="text" class="form-input" id="newApiName" placeholder="e.g., CoinGecko">
</div>
<div class="form-group">
<label class="form-label">API URL</label>
<input type="text" class="form-input" id="newApiUrl" placeholder="https://api.example.com/endpoint">
</div>
<div class="form-group">
<label class="form-label">Category</label>
<select class="form-select" id="newApiCategory">
<option value="market_data">Market Data</option>
<option value="blockchain_explorers">Blockchain Explorers</option>
<option value="news">News & Social</option>
<option value="sentiment">Sentiment</option>
<option value="defi">DeFi</option>
<option value="nft">NFT</option>
</select>
</div>
<button class="refresh-btn" onclick="addNewAPI()">➕ Add API Source</button>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">📋 Current API Sources</div>
<div id="apisList">Loading...</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">⚙️ Settings</div>
<div class="form-group">
<label class="form-label">API Check Interval (seconds)</label>
<input type="number" class="form-input" id="checkInterval" value="30" min="10" max="300">
</div>
<div class="form-group">
<label class="form-label">Dashboard Auto-Refresh (seconds)</label>
<input type="number" class="form-input" id="dashboardRefresh" value="30" min="5" max="300">
</div>
<button class="refresh-btn" onclick="saveSettings()">💾 Save Settings</button>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">📊 Statistics</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value" id="statTotal">0</div>
<div class="stat-label">Total API Sources</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statOnline" style="color: var(--accent-green);">0</div>
<div class="stat-label">Currently Online</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statOffline" style="color: var(--accent-red);">0</div>
<div class="stat-label">Currently Offline</div>
</div>
</div>
</div>
</div>
<!-- HuggingFace Tab -->
<div id="tab-hf" class="tab-content">
<div class="market-section">
<div class="section-header">
<div class="section-title">📊 Health Status</div>
<button class="refresh-btn" onclick="loadHFHealth()">🔄 Refresh</button>
</div>
<pre id="healthOutput" style="background: #1e293b; color: #e2e8f0; padding: 15px; border-radius: 8px; overflow-x: auto; font-size: 12px; max-height: 200px; overflow-y: auto;">Loading...</pre>
</div>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px;">
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">🤖 Models Registry</div>
<button class="refresh-btn" onclick="loadModels()" style="margin-bottom: 15px;">Load Models</button>
<div id="modelsList" style="max-height: 300px; overflow-y: auto; background: rgba(17, 24, 39, 0.6); padding: 15px; border-radius: 8px;">
<p style="color: var(--text-secondary);">Click "Load Models" to fetch...</p>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">📚 Datasets Registry</div>
<button class="refresh-btn" onclick="loadDatasets()" style="margin-bottom: 15px;">Load Datasets</button>
<div id="datasetsList" style="max-height: 300px; overflow-y: auto; background: rgba(17, 24, 39, 0.6); padding: 15px; border-radius: 8px;">
<p style="color: var(--text-secondary);">Click "Load Datasets" to fetch...</p>
</div>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">🔍 Search Registry</div>
<div class="form-group">
<input type="text" class="form-input" id="searchQuery" placeholder="Search query (e.g., crypto, bitcoin, sentiment)" value="crypto">
</div>
<div style="display: flex; gap: 10px; margin-bottom: 15px;">
<button class="refresh-btn" onclick="doSearch()">Search Models</button>
<button class="refresh-btn" onclick="doSearchDatasets()">Search Datasets</button>
</div>
<div id="searchResults" style="max-height: 300px; overflow-y: auto; background: rgba(17, 24, 39, 0.6); padding: 15px; border-radius: 8px;">
<p style="color: var(--text-secondary);">Enter a query and click search...</p>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">💭 Sentiment Analysis</div>
<div class="form-group">
<label class="form-label">Enter text samples (one per line):</label>
<textarea class="form-textarea" id="sentimentTexts" rows="5" placeholder="BTC strong breakout ETH looks weak Market sentiment is bullish">BTC strong breakout
ETH looks weak
Crypto market is bullish today</textarea>
</div>
<button class="refresh-btn" onclick="doSentiment()">🧠 Run Sentiment Analysis</button>
<div id="voteDisplay" style="margin-top: 20px; padding: 20px; background: rgba(17, 24, 39, 0.6); border-radius: 12px; text-align: center; font-size: 36px; font-weight: 900;">—</div>
<pre id="sentimentOutput" style="background: #1e293b; color: #e2e8f0; padding: 15px; border-radius: 8px; overflow-x: auto; font-size: 12px; margin-top: 15px; max-height: 300px; overflow-y: auto;">Results will appear here...</pre>
</div>
</div>
<!-- Pools Tab -->
<div id="tab-pools" class="tab-content">
<div class="market-section">
<div class="section-header">
<div class="section-title">🔄 Source Pool Management</div>
<div style="display: flex; gap: 10px;">
<button class="refresh-btn" onclick="showCreatePoolModal()">➕ Create Pool</button>
<button class="refresh-btn" onclick="loadPools()">🔄 Refresh</button>
</div>
</div>
<div id="poolsContainer" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); gap: 20px;">
<div class="loading"><div class="spinner"></div></div>
</div>
</div>
<div class="market-section">
<div class="section-title" style="margin-bottom: 20px;">📜 Rotation History</div>
<div id="rotationHistory" style="max-height: 400px; overflow-y: auto;">
<div class="loading"><div class="spinner"></div></div>
</div>
</div>
</div>
<!-- Create Pool Modal -->
<div id="createPoolModal" class="modal">
<div class="modal-content">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2 style="font-size: 24px; font-weight: 800;">➕ Create New Pool</h2>
<button onclick="closeCreatePoolModal()" style="background: none; border: none; color: var(--text-secondary); font-size: 28px; cursor: pointer; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;">×</button>
</div>
<form id="createPoolForm">
<div class="form-group">
<label class="form-label">Pool Name</label>
<input type="text" class="form-input" id="poolName" required placeholder="e.g., Market Data Pool">
</div>
<div class="form-group">
<label class="form-label">Category</label>
<select class="form-select" id="poolCategory" required>
<option value="market_data">Market Data</option>
<option value="blockchain_explorers">Blockchain Explorers</option>
<option value="news">News & Social</option>
<option value="sentiment">Sentiment</option>
<option value="defi">DeFi</option>
<option value="nft">NFT</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Rotation Strategy</label>
<select class="form-select" id="rotationStrategy" required>
<option value="round_robin">Round Robin</option>
<option value="priority">Priority Based</option>
<option value="weighted">Weighted</option>
<option value="least_used">Least Used</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Description (optional)</label>
<textarea class="form-textarea" id="poolDescription" rows="3" placeholder="Pool description..."></textarea>
</div>
<div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
<button type="button" class="refresh-btn" onclick="closeCreatePoolModal()" style="background: rgba(239, 68, 68, 0.2); color: var(--accent-red);">Cancel</button>
<button type="submit" class="refresh-btn">Create Pool</button>
</div>
</form>
</div>
</div>
<!-- Add Member Modal -->
<div id="addMemberModal" class="modal">
<div class="modal-content">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2 style="font-size: 24px; font-weight: 800;">➕ Add Provider to Pool</h2>
<button onclick="closeAddMemberModal()" style="background: none; border: none; color: var(--text-secondary); font-size: 28px; cursor: pointer; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;">×</button>
</div>
<form id="addMemberForm">
<div class="form-group">
<label class="form-label">Provider</label>
<select class="form-select" id="memberProvider" required>
<option value="">Select a provider...</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Priority (1-10, higher = better)</label>
<input type="number" class="form-input" id="memberPriority" value="1" min="1" max="10">
</div>
<div class="form-group">
<label class="form-label">Weight (1-100, for weighted strategy)</label>
<input type="number" class="form-input" id="memberWeight" value="1" min="1" max="100">
</div>
<div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px;">
<button type="button" class="refresh-btn" onclick="closeAddMemberModal()" style="background: rgba(239, 68, 68, 0.2); color: var(--accent-red);">Cancel</button>
<button type="submit" class="refresh-btn">Add Member</button>
</div>
</form>
</div>
</div>
</div>
<script>
// Global variables
let charts = {};
let wsConnection = null;
let currentTab = 'market';
// Tab switching
function switchTab(tabName) {
currentTab = tabName;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
event.target.classList.add('active');
document.getElementById(`tab-${tabName}`).classList.add('active');
// Load data for specific tabs
if (tabName === 'market') {
loadMarketData();
} else if (tabName === 'monitor') {
loadMonitorData();
} else if (tabName === 'advanced') {
loadAdvancedData();
} else if (tabName === 'admin') {
loadAdminData();
} else if (tabName === 'hf') {
loadHFHealth();
} else if (tabName === 'pools') {
loadPools();
}
}
// Initialize
document.addEventListener('DOMContentLoaded', async () => {
await loadMarketData();
initCharts();
connectWebSocket();
setInterval(() => {
if (currentTab === 'market') loadMarketData();
else if (currentTab === 'monitor') loadMonitorData();
}, 60000);
});
// Market Data Functions
async function loadMarketData() {
try {
const [market, stats, sentiment, trending, defi] = await Promise.all([
fetch('/api/market').then(r => r.json()),
fetch('/api/stats').then(r => r.json()),
fetch('/api/sentiment').then(r => r.json()),
fetch('/api/trending').then(r => r.json()),
fetch('/api/defi').then(r => r.json())
]);
updateStats(stats, sentiment);
updateMarketTable(market.cryptocurrencies);
updateTrending(trending.trending);
updateDeFi(defi);
updateCharts(market, sentiment);
} catch (error) {
console.error('Error loading market data:', error);
}
}
function updateStats(stats, sentiment) {
const mcap = stats.market.total_market_cap;
document.getElementById('totalMarketCap').textContent = '$' + (mcap / 1e12).toFixed(2) + 'T';
const volume = stats.market.total_volume;
document.getElementById('totalVolume').textContent = '$' + (volume / 1e9).toFixed(2) + 'B';
const btcDom = stats.market.btc_dominance;
document.getElementById('btcDominance').textContent = btcDom.toFixed(1) + '%';
const fg = sentiment.fear_greed_index.value;
const classification = sentiment.fear_greed_index.classification;
document.getElementById('fearGreed').textContent = fg;
document.getElementById('sentimentLabel').innerHTML = `<span>${classification}</span>`;
const sentEl = document.getElementById('sentimentLabel');
if (fg < 25) {
sentEl.style.color = 'var(--accent-red)';
} else if (fg < 45) {
sentEl.style.color = 'var(--accent-yellow)';
} else if (fg < 55) {
sentEl.style.color = 'var(--text-secondary)';
} else if (fg < 75) {
sentEl.style.color = 'var(--accent-blue)';
} else {
sentEl.style.color = 'var(--accent-green)';
}
}
function updateMarketTable(cryptos) {
const tbody = document.getElementById('marketTableBody');
tbody.innerHTML = cryptos.map((crypto, index) => `
<tr>
<td style="font-weight: 700; color: var(--text-secondary);">${crypto.rank || index + 1}</td>
<td>
<div class="crypto-name">
${crypto.image ? `<img src="${crypto.image}" class="crypto-img" alt="${crypto.symbol}">` :
`<div class="crypto-img" style="background: linear-gradient(135deg, #3b82f6, #8b5cf6); display: flex; align-items: center; justify-content: center; font-weight: 700;">${crypto.symbol[0]}</div>`}
<div>
<div style="font-weight: 600;">${crypto.name}</div>
<div class="crypto-symbol">${crypto.symbol}</div>
</div>
</div>
</td>
<td class="price">$${crypto.price.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 6})}</td>
<td><span class="change ${crypto.change_24h >= 0 ? 'positive' : 'negative'}">${crypto.change_24h >= 0 ? '+' : ''}${crypto.change_24h.toFixed(2)}%</span></td>
<td style="font-weight: 600;">$${(crypto.market_cap / 1e9).toFixed(2)}B</td>
<td style="color: var(--text-secondary);">$${(crypto.volume_24h / 1e9).toFixed(2)}B</td>
</tr>
`).join('');
}
function updateTrending(trending) {
const grid = document.getElementById('trendingGrid');
grid.innerHTML = trending.map((coin, index) => `
<div style="background: rgba(59, 130, 246, 0.1); border: 1px solid rgba(59, 130, 246, 0.2); border-radius: 12px; padding: 15px; display: flex; align-items: center; gap: 12px;">
<div style="font-size: 20px; font-weight: 900; color: var(--accent-yellow);">#${index + 1}</div>
${coin.thumb ? `<img src="${coin.thumb}" style="width: 32px; height: 32px; border-radius: 8px;">` : ''}
<div>
<div style="font-weight: 600;">${coin.name}</div>
<div style="font-size: 12px; color: var(--text-secondary);">${coin.symbol}</div>
</div>
</div>
`).join('');
}
function updateDeFi(defi) {
const list = document.getElementById('defiList');
const protocols = defi.protocols || [];
list.innerHTML = `
<div style="margin-bottom: 20px; padding: 20px; background: rgba(59, 130, 246, 0.1); border-radius: 16px; text-align: center;">
<div style="font-size: 36px; font-weight: 900; margin-bottom: 5px;">$${(defi.total_tvl / 1e9).toFixed(2)}B</div>
<div style="color: var(--text-secondary); font-size: 14px;">Total Value Locked</div>
</div>
<div style="display: grid; gap: 12px;">
${protocols.map((p, i) => `
<div style="display: flex; justify-content: space-between; align-items: center; padding: 15px; background: rgba(255, 255, 255, 0.05); border-radius: 12px;">
<div>
<div style="font-weight: 600;">${i + 1}. ${p.name}</div>
<div style="font-size: 12px; color: var(--text-secondary);">${p.chain}</div>
</div>
<div style="text-align: right;">
<div style="font-weight: 700; font-size: 16px;">$${(p.tvl / 1e9).toFixed(2)}B</div>
<div style="font-size: 12px; color: ${p.change_24h >= 0 ? 'var(--accent-green)' : 'var(--accent-red)'};">
${p.change_24h >= 0 ? '+' : ''}${p.change_24h.toFixed(2)}%
</div>
</div>
</div>
`).join('')}
</div>
`;
}
function initCharts() {
Chart.defaults.color = '#9ca3af';
Chart.defaults.borderColor = 'rgba(255, 255, 255, 0.1)';
charts.dominance = new Chart(document.getElementById('dominanceChart'), {
type: 'doughnut',
data: {
labels: ['Bitcoin', 'Ethereum', 'Others'],
datasets: [{
data: [45, 18, 37],
backgroundColor: ['#f7931a', '#627eea', '#8b5cf6'],
borderWidth: 0
}]
},
options: {
responsive: true,
plugins: {
legend: { position: 'bottom', labels: { padding: 15, font: { size: 12, weight: 600 } } }
}
}
});
charts.gauge = new Chart(document.getElementById('gaugeChart'), {
type: 'doughnut',
data: {
datasets: [{
data: [50, 50],
backgroundColor: ['#3b82f6', 'rgba(255, 255, 255, 0.1)'],
borderWidth: 0
}]
},
options: {
rotation: -90,
circumference: 180,
cutout: '75%',
plugins: { legend: { display: false }, tooltip: { enabled: false } }
}
});
}
function updateCharts(market, sentiment) {
const btcDom = market.global.btc_dominance;
const ethDom = market.global.eth_dominance;
charts.dominance.data.datasets[0].data = [btcDom, ethDom, 100 - btcDom - ethDom];
charts.dominance.update();
const fg = sentiment.fear_greed_index.value;
charts.gauge.data.datasets[0].data = [fg, 100 - fg];
if (fg < 25) {
charts.gauge.data.datasets[0].backgroundColor[0] = '#ef4444';
} else if (fg < 45) {
charts.gauge.data.datasets[0].backgroundColor[0] = '#f59e0b';
} else if (fg < 55) {
charts.gauge.data.datasets[0].backgroundColor[0] = '#6b7280';
} else if (fg < 75) {
charts.gauge.data.datasets[0].backgroundColor[0] = '#3b82f6';
} else {
charts.gauge.data.datasets[0].backgroundColor[0] = '#10b981';
}
charts.gauge.update();
document.getElementById('sentimentValue').textContent = fg;
document.getElementById('sentimentText').textContent = sentiment.fear_greed_index.classification;
}
function connectWebSocket() {
const ws = new WebSocket(`ws://${window.location.host}/ws/live`);
ws.onopen = () => {
console.log('✅ WebSocket connected');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'market_update') {
console.log('📊 Market update received');
}
if (data.type === 'sentiment_update') {
updateCharts({global: {}}, {fear_greed_index: data.data});
}
};
ws.onerror = () => {
console.log('❌ WebSocket error');
};
ws.onclose = () => {
console.log('⚠️ WebSocket disconnected, reconnecting...');
setTimeout(connectWebSocket, 5000);
};
}
// Monitor Functions
async function loadMonitorData() {
try {
const [status, providers] = await Promise.all([
fetch('/api/status').then(r => r.json()),
fetch('/api/providers').then(r => r.json())
]);
document.getElementById('totalAPIs').textContent = status.total_providers;
document.getElementById('onlineAPIs').textContent = status.online;
document.getElementById('offlineAPIs').textContent = status.offline;
document.getElementById('avgResponse').textContent = status.avg_response_time_ms + 'ms';
const tbody = document.getElementById('providersTable');
tbody.innerHTML = providers.map(p => {
let statusClass = 'badge-success';
if (p.status === 'offline') statusClass = 'badge-danger';
else if (p.status === 'degraded') statusClass = 'badge-warning';
return `
<tr>
<td><strong>${p.name}</strong></td>
<td><span class="badge badge-info">${p.category}</span></td>
<td><span class="badge ${statusClass}">${p.status.toUpperCase()}</span></td>
<td>${p.response_time_ms}ms</td>
<td style="color: var(--text-secondary); font-size: 13px;">${new Date(p.last_fetch).toLocaleTimeString()}</td>
</tr>
`;
}).join('');
} catch (error) {
console.error('Error loading monitor data:', error);
}
}
async function runSentiment() {
const text = document.getElementById('sentimentText').value;
const texts = text.split('\n').filter(t => t.trim());
if (texts.length === 0) {
showToast('Please enter at least one line of text', 'info');
return;
}
try {
document.getElementById('sentimentResult').textContent = '⏳ Analyzing...';
document.getElementById('sentimentDetails').textContent = '';
const res = await fetch('/api/hf/run-sentiment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ texts })
});
const data = await res.json();
const vote = data.vote || 0;
let emoji = '😐';
let color = 'var(--text-secondary)';
if (vote > 0.2) {
emoji = '📈';
color = 'var(--accent-green)';
} else if (vote < -0.2) {
emoji = '📉';
color = 'var(--accent-red)';
}
document.getElementById('sentimentResult').innerHTML = `<span style="color: ${color};">${emoji} ${vote.toFixed(3)}</span>`;
document.getElementById('sentimentDetails').textContent = JSON.stringify(data, null, 2);
} catch (error) {
document.getElementById('sentimentResult').innerHTML = '<span style="color: var(--accent-red);">❌ Error</span>';
document.getElementById('sentimentDetails').textContent = 'Error: ' + error.message;
}
}
// Advanced Functions
async function loadAdvancedData() {
try {
const response = await fetch('/api/v2/status');
const data = await response.json();
document.getElementById('totalApis').textContent = data.services.config_loader.apis_loaded;
document.getElementById('activeTasks').textContent = data.services.scheduler.total_tasks;
document.getElementById('cachedData').textContent = data.services.persistence.cached_apis;
document.getElementById('wsConnections').textContent = data.services.websocket.total_connections;
const apisResponse = await fetch('/api/v2/config/apis');
const apisData = await apisResponse.json();
displayAPIs(apisData.apis);
} catch (error) {
console.error('Error loading advanced data:', error);
}
}
function displayAPIs(apis) {
const listElement = document.getElementById('apiList');
listElement.innerHTML = '';
for (const [apiId, api] of Object.entries(apis)) {
const item = document.createElement('div');
item.style.cssText = 'background: rgba(17, 24, 39, 0.6); padding: 15px; border-radius: 12px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;';
item.innerHTML = `
<div>
<div style="font-weight: 600;">${api.name}</div>
<div style="font-size: 12px; color: var(--text-secondary);">${api.category}</div>
</div>
<button class="refresh-btn" onclick="forceUpdate('${apiId}')" style="padding: 6px 12px; font-size: 12px;">🔄 Update</button>
`;
listElement.appendChild(item);
}
}
async function exportJSON() {
try {
const response = await fetch('/api/v2/export/json', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ include_history: true })
});
const data = await response.json();
showToast('✅ JSON export created!', 'success');
addLog(`Exported to JSON: ${data.filepath}`);
} catch (error) {
showToast('❌ Export failed', 'error');
console.error(error);
}
}
async function exportCSV() {
try {
const response = await fetch('/api/v2/export/csv', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ flatten: true })
});
const data = await response.json();
showToast('✅ CSV export created!', 'success');
addLog(`Exported to CSV: ${data.filepath}`);
} catch (error) {
showToast('❌ Export failed', 'error');
console.error(error);
}
}
async function createBackup() {
try {
const response = await fetch('/api/v2/backup', { method: 'POST' });
const data = await response.json();
showToast('✅ Backup created!', 'success');
addLog(`Backup created: ${data.backup_file}`);
} catch (error) {
showToast('❌ Backup failed', 'error');
console.error(error);
}
}
async function clearCache() {
if (!confirm('Clear all cached data?')) return;
try {
await fetch('/api/v2/cleanup/cache', { method: 'POST' });
showToast('✅ Cache cleared!', 'success');
addLog('Cache cleared');
} catch (error) {
showToast('❌ Failed to clear cache', 'error');
console.error(error);
}
}
async function forceUpdateAll() {
try {
const response = await fetch('/api/v2/config/apis');
const data = await response.json();
for (const apiId of Object.keys(data.apis)) {
await forceUpdate(apiId);
await new Promise(resolve => setTimeout(resolve, 100));
}
showToast('✅ All APIs updated!', 'success');
} catch (error) {
showToast('❌ Update failed', 'error');
console.error(error);
}
}
async function forceUpdate(apiId) {
try {
await fetch(`/api/v2/schedule/tasks/${apiId}/force-update`, { method: 'POST' });
addLog(`Forced update: ${apiId}`);
} catch (error) {
console.error(error);
}
}
function addLog(text) {
const logContainer = document.getElementById('activityLog');
const time = new Date().toLocaleTimeString();
const entry = document.createElement('div');
entry.style.cssText = 'padding: 10px; border-left: 3px solid var(--accent-blue); margin-bottom: 8px;';
entry.innerHTML = `<span style="opacity: 0.6;">${time}</span> ${text}`;
logContainer.insertBefore(entry, logContainer.firstChild);
while (logContainer.children.length > 50) {
logContainer.removeChild(logContainer.lastChild);
}
}
// Admin Functions
async function loadAdminData() {
try {
const [status, providers] = await Promise.all([
fetch('/api/status').then(r => r.json()),
fetch('/api/providers').then(r => r.json())
]);
document.getElementById('statTotal').textContent = status.total_providers;
document.getElementById('statOnline').textContent = status.online;
document.getElementById('statOffline').textContent = status.offline;
const list = document.getElementById('apisList');
list.innerHTML = providers.map(api => `
<div style="background: rgba(17, 24, 39, 0.6); padding: 15px; border-radius: 12px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
<div>
<div style="font-weight: 600;">${api.name}</div>
<div style="font-size: 12px; color: var(--text-secondary);">${api.category}</div>
</div>
<span class="badge ${api.status === 'online' ? 'badge-success' : 'badge-danger'}">${api.status.toUpperCase()}</span>
</div>
`).join('');
} catch (error) {
console.error('Error loading admin data:', error);
}
}
async function addNewAPI() {
const name = document.getElementById('newApiName').value;
const url = document.getElementById('newApiUrl').value;
const category = document.getElementById('newApiCategory').value;
if (!name || !url) {
showToast('Please fill in API name and URL', 'info');
return;
}
showToast('✅ API added! Note: Restart server to activate.', 'success');
document.getElementById('newApiName').value = '';
document.getElementById('newApiUrl').value = '';
loadAdminData();
}
function saveSettings() {
const interval = document.getElementById('checkInterval').value;
const refresh = document.getElementById('dashboardRefresh').value;
localStorage.setItem('monitorSettings', JSON.stringify({ interval, refresh }));
showToast('✅ Settings saved!', 'success');
}
// HuggingFace Functions
async function loadHFHealth() {
try {
const data = await fetch('/api/hf/health').then(r => r.json());
document.getElementById('healthOutput').textContent = JSON.stringify(data, null, 2);
} catch (err) {
document.getElementById('healthOutput').textContent = `Error: ${err.message}`;
}
}
async function loadModels() {
try {
document.getElementById('modelsList').innerHTML = '<p style="color: var(--text-secondary);">Loading...</p>';
// Mock data for now
document.getElementById('modelsList').innerHTML = '<p style="color: var(--text-secondary);">Models registry endpoint not implemented</p>';
} catch (err) {
document.getElementById('modelsList').innerHTML = `<p style="color: var(--accent-red);">Error: ${err.message}</p>`;
}
}
async function loadDatasets() {
try {
document.getElementById('datasetsList').innerHTML = '<p style="color: var(--text-secondary);">Loading...</p>';
// Mock data for now
document.getElementById('datasetsList').innerHTML = '<p style="color: var(--text-secondary);">Datasets registry endpoint not implemented</p>';
} catch (err) {
document.getElementById('datasetsList').innerHTML = `<p style="color: var(--accent-red);">Error: ${err.message}</p>`;
}
}
async function doSearch() {
const q = document.getElementById('searchQuery').value;
document.getElementById('searchResults').innerHTML = `<p style="color: var(--text-secondary);">Searching for "${q}"...</p>`;
// Mock search
document.getElementById('searchResults').innerHTML = '<p style="color: var(--text-secondary);">Search endpoint not implemented</p>';
}
async function doSearchDatasets() {
const q = document.getElementById('searchQuery').value;
document.getElementById('searchResults').innerHTML = `<p style="color: var(--text-secondary);">Searching datasets for "${q}"...</p>`;
// Mock search
document.getElementById('searchResults').innerHTML = '<p style="color: var(--text-secondary);">Search endpoint not implemented</p>';
}
async function doSentiment() {
const texts = document.getElementById('sentimentTexts').value.split('\n').filter(t => t.trim());
if (texts.length === 0) {
showToast('Please enter at least one text sample', 'info');
return;
}
try {
document.getElementById('voteDisplay').innerHTML = '<span>⏳ Analyzing...</span>';
document.getElementById('sentimentOutput').textContent = 'Running sentiment analysis...';
const data = await fetch('/api/hf/run-sentiment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ texts })
}).then(r => r.json());
const vote = data.vote || 0;
let voteClass = 'vote-neutral';
let voteEmoji = '😐';
if (vote > 0.2) { voteClass = 'vote-positive'; voteEmoji = '📈'; }
else if (vote < -0.2) { voteClass = 'vote-negative'; voteEmoji = '📉'; }
document.getElementById('voteDisplay').innerHTML = `<span style="color: ${voteClass === 'vote-positive' ? 'var(--accent-green)' : voteClass === 'vote-negative' ? 'var(--accent-red)' : 'var(--text-secondary)'};">${voteEmoji} ${vote.toFixed(3)}</span>`;
document.getElementById('sentimentOutput').textContent = JSON.stringify(data, null, 2);
} catch (err) {
document.getElementById('voteDisplay').innerHTML = '<span style="color: var(--accent-red);">Error</span>';
document.getElementById('sentimentOutput').textContent = `Error: ${err.message}`;
}
}
// Pools Functions
let currentPoolId = null;
let allProvidersList = [];
async function loadPools() {
try {
const [poolsRes, historyRes] = await Promise.all([
fetch('/api/pools').then(r => r.json()),
fetch('/api/pools/history?limit=20').then(r => r.json())
]);
const pools = poolsRes.pools || [];
const container = document.getElementById('poolsContainer');
if (pools.length === 0) {
container.innerHTML = `
<div style="grid-column: 1/-1; text-align: center; padding: 40px; background: rgba(17, 24, 39, 0.6); border-radius: 20px; border: 2px dashed var(--border);">
<div style="font-size: 48px; margin-bottom: 15px;">🔄</div>
<div style="font-size: 18px; font-weight: 600; margin-bottom: 10px; color: var(--text-primary);">No pools configured</div>
<div style="color: var(--text-secondary); margin-bottom: 20px;">Create your first pool to get started with API source rotation</div>
<button class="refresh-btn" onclick="showCreatePoolModal()">➕ Create Pool</button>
</div>
`;
} else {
container.innerHTML = pools.map(pool => createPoolCard(pool)).join('');
}
// Load rotation history
const history = historyRes.history || [];
const historyContainer = document.getElementById('rotationHistory');
if (history.length === 0) {
historyContainer.innerHTML = '<p style="color: var(--text-secondary); text-align: center; padding: 20px;">No rotation history yet</p>';
} else {
historyContainer.innerHTML = history.map(h => `
<div style="padding: 15px; background: rgba(17, 24, 39, 0.6); border-radius: 12px; margin-bottom: 10px; border-left: 3px solid var(--accent-blue);">
<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
<div>
<div style="font-weight: 600; margin-bottom: 5px;">${h.pool_name}</div>
<div style="font-size: 12px; color: var(--text-secondary);">Rotated to: <strong>${h.provider_name}</strong></div>
</div>
<div style="text-align: right;">
<div style="font-size: 12px; color: var(--text-secondary);">${new Date(h.timestamp).toLocaleString()}</div>
<span class="badge badge-info" style="margin-top: 5px; display: inline-block;">${h.reason}</span>
</div>
</div>
</div>
`).join('');
}
} catch (error) {
console.error('Error loading pools:', error);
document.getElementById('poolsContainer').innerHTML = `
<div style="grid-column: 1/-1; text-align: center; padding: 40px; color: var(--accent-red);">
<div>❌ Error loading pools: ${error.message}</div>
</div>
`;
}
}
function createPoolCard(pool) {
const currentProvider = pool.current_provider
? `<div style="margin-bottom: 15px; padding: 12px; background: rgba(16, 185, 129, 0.1); border-radius: 10px; border: 1px solid rgba(16, 185, 129, 0.3);">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="width: 10px; height: 10px; background: var(--accent-green); border-radius: 50%; display: inline-block;"></span>
<span style="font-weight: 600;">Current: ${pool.current_provider.name}</span>
</div>
</div>`
: '<div style="margin-bottom: 15px; padding: 12px; background: rgba(239, 68, 68, 0.1); border-radius: 10px; border: 1px solid rgba(239, 68, 68, 0.3); color: var(--text-secondary);">No active provider</div>';
const membersHTML = pool.members && pool.members.length > 0
? pool.members.map(member => {
const successRate = member.success_rate || 0;
const statusClass = successRate >= 90 ? 'badge-success' : successRate >= 70 ? 'badge-warning' : 'badge-danger';
const rateLimit = member.rate_limit || { usage: 0, limit: 100, percentage: 0 };
return `
<div style="background: rgba(255, 255, 255, 0.05); padding: 12px; border-radius: 10px; margin-bottom: 8px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
<div style="font-weight: 600;">${member.provider_name}</div>
<span class="badge ${statusClass}">${successRate.toFixed(1)}%</span>
</div>
<div style="display: flex; gap: 15px; font-size: 12px; color: var(--text-secondary); margin-bottom: 8px;">
<span>Used: ${member.use_count || 0}</span>
<span>Priority: ${member.priority || 1}</span>
<span>Weight: ${member.weight || 1}</span>
</div>
<div>
<div style="font-size: 11px; color: var(--text-secondary); margin-bottom: 4px;">
Rate Limit: ${rateLimit.usage}/${rateLimit.limit} (${rateLimit.percentage}%)
</div>
<div style="height: 6px; background: rgba(255, 255, 255, 0.1); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; background: ${rateLimit.percentage < 70 ? 'var(--accent-green)' : rateLimit.percentage < 90 ? 'var(--accent-yellow)' : 'var(--accent-red)'}; width: ${rateLimit.percentage}%; transition: width 0.3s;"></div>
</div>
</div>
</div>
`;
}).join('')
: '<div style="color: var(--text-secondary); font-size: 14px; padding: 20px; text-align: center;">No members in pool</div>';
return `
<div class="pool-card-hover" style="background: rgba(17, 24, 39, 0.6); backdrop-filter: blur(10px); border: 1px solid var(--border); border-radius: 20px; padding: 25px;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;">
<div>
<div style="font-size: 20px; font-weight: 700; margin-bottom: 8px;">${pool.pool_name}</div>
<span class="badge badge-info">${pool.category}</span>
</div>
<div style="display: flex; gap: 8px;">
<button onclick="addMemberToPool(${pool.pool_id})" style="padding: 8px 12px; background: rgba(59, 130, 246, 0.2); border: 1px solid var(--accent-blue); border-radius: 8px; color: var(--accent-blue); cursor: pointer; font-size: 12px; font-weight: 600;">➕</button>
<button onclick="rotatePool(${pool.pool_id})" style="padding: 8px 12px; background: rgba(16, 185, 129, 0.2); border: 1px solid var(--accent-green); border-radius: 8px; color: var(--accent-green); cursor: pointer; font-size: 12px; font-weight: 600;">🔄</button>
<button onclick="deletePool(${pool.pool_id}, '${pool.pool_name}')" style="padding: 8px 12px; background: rgba(239, 68, 68, 0.2); border: 1px solid var(--accent-red); border-radius: 8px; color: var(--accent-red); cursor: pointer; font-size: 12px; font-weight: 600;">🗑️</button>
</div>
</div>
${currentProvider}
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin: 20px 0;">
<div style="background: rgba(255, 255, 255, 0.05); padding: 12px; border-radius: 10px;">
<div style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Strategy</div>
<div style="font-weight: 600; font-size: 14px;">${pool.rotation_strategy.replace('_', ' ')}</div>
</div>
<div style="background: rgba(255, 255, 255, 0.05); padding: 12px; border-radius: 10px;">
<div style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Rotations</div>
<div style="font-weight: 600; font-size: 14px;">${pool.total_rotations || 0}</div>
</div>
<div style="background: rgba(255, 255, 255, 0.05); padding: 12px; border-radius: 10px;">
<div style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Members</div>
<div style="font-weight: 600; font-size: 14px;">${pool.members ? pool.members.length : 0}</div>
</div>
<div style="background: rgba(255, 255, 255, 0.05); padding: 12px; border-radius: 10px;">
<div style="font-size: 12px; color: var(--text-secondary); margin-bottom: 5px;">Status</div>
<span class="badge ${pool.enabled ? 'badge-success' : 'badge-danger'}">${pool.enabled ? 'Enabled' : 'Disabled'}</span>
</div>
</div>
<div style="margin-top: 20px;">
<div style="font-weight: 600; margin-bottom: 12px; font-size: 14px;">Pool Members</div>
<div style="max-height: 300px; overflow-y: auto;">
${membersHTML}
</div>
</div>
</div>
`;
}
async function loadProvidersForPool() {
try {
const providers = await fetch('/api/providers').then(r => r.json());
allProvidersList = providers;
const select = document.getElementById('memberProvider');
select.innerHTML = '<option value="">Select a provider...</option>' + providers.map(p => {
const providerId = p.name.toLowerCase().replace(/\s+/g, '_');
return `<option value="${providerId}">${p.name} (${p.category})</option>`;
}).join('');
} catch (error) {
console.error('Error loading providers:', error);
}
}
function showCreatePoolModal() {
document.getElementById('createPoolModal').classList.add('active');
}
function closeCreatePoolModal() {
document.getElementById('createPoolModal').classList.remove('active');
document.getElementById('createPoolForm').reset();
}
function addMemberToPool(poolId) {
currentPoolId = poolId;
loadProvidersForPool();
document.getElementById('addMemberModal').classList.add('active');
}
function closeAddMemberModal() {
document.getElementById('addMemberModal').classList.remove('active');
document.getElementById('addMemberForm').reset();
currentPoolId = null;
}
document.getElementById('createPoolForm').addEventListener('submit', async (e) => {
e.preventDefault();
const data = {
name: document.getElementById('poolName').value,
category: document.getElementById('poolCategory').value,
rotation_strategy: document.getElementById('rotationStrategy').value,
description: document.getElementById('poolDescription').value
};
try {
const response = await fetch('/api/pools', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (response.ok) {
showToast('✅ Pool created successfully!', 'success');
closeCreatePoolModal();
loadPools();
} else {
const error = await response.json();
showToast('❌ Error: ' + (error.detail || 'Failed to create pool'), 'error');
}
} catch (error) {
showToast('❌ Error: ' + error.message, 'error');
console.error(error);
}
});
document.getElementById('addMemberForm').addEventListener('submit', async (e) => {
e.preventDefault();
const data = {
provider_id: document.getElementById('memberProvider').value,
priority: parseInt(document.getElementById('memberPriority').value),
weight: parseInt(document.getElementById('memberWeight').value)
};
try {
const response = await fetch(`/api/pools/${currentPoolId}/members`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (response.ok) {
showToast('✅ Member added successfully!', 'success');
closeAddMemberModal();
loadPools();
} else {
const error = await response.json();
showToast('❌ Error: ' + (error.detail || 'Failed to add member'), 'error');
}
} catch (error) {
showToast('❌ Error: ' + error.message, 'error');
console.error(error);
}
});
async function rotatePool(poolId) {
try {
const response = await fetch(`/api/pools/${poolId}/rotate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason: 'manual' })
});
if (response.ok) {
const result = await response.json();
showToast(`✅ Rotated to ${result.provider_name}`, 'success');
loadPools();
} else {
const error = await response.json();
showToast('❌ Error: ' + (error.detail || 'Failed to rotate'), 'error');
}
} catch (error) {
showToast('❌ Error: ' + error.message, 'error');
console.error(error);
}
}
async function deletePool(poolId, poolName) {
if (!confirm(`Are you sure you want to delete pool "${poolName}"?`)) {
return;
}
try {
const response = await fetch(`/api/pools/${poolId}`, {
method: 'DELETE'
});
if (response.ok) {
showToast('✅ Pool deleted successfully!', 'success');
loadPools();
} else {
const error = await response.json();
showToast('❌ Error: ' + (error.detail || 'Failed to delete pool'), 'error');
}
} catch (error) {
alert('❌ Error: ' + error.message);
console.error(error);
}
}
// Toast notification function
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.innerHTML = `
<span style="font-size: 20px;">${type === 'success' ? '✅' : type === 'error' ? '❌' : 'ℹ️'}</span>
<span>${message}</span>
`;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'slideInRight 0.3s reverse';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// Close modals when clicking outside
document.addEventListener('click', (e) => {
if (e.target.classList.contains('modal')) {
e.target.style.display = 'none';
}
});
</script>
</body>
</html>.dockerignore+103-23
.env.example+17-41
.gitignore+30-21
Dockerfile+62-7
FRONTEND_COMPLETE.mdAdded+219
QUICK_START.md+153-75
README.md+281-276
__pycache__/app.cpython-313.pycAdded
__pycache__/config.cpython-313.pycAdded
api-resources/README.mdAdded+282
api-resources/api-config-complete__1_.txtAdded+1634
api-resources/crypto_resources_unified_2025-11-11.jsonAdded+2097
api-resources/ultimate_crypto_pipeline_2025_NZasinich.jsonAdded+503
app.py+1569-325
database.py+318-22
database/__pycache__/__init__.cpython-313.pycAdded
database/__pycache__/data_access.cpython-313.pycAdded
database/__pycache__/db_manager.cpython-313.pycAdded
database/__pycache__/models.cpython-313.pycAdded
enhanced_dashboard.htmlAdded+876
main.py+2-167
requirements.txt+1-2
start.bat+17-45
unified_dashboard.htmlAdded+2107
utils/__pycache__/__init__.cpython-313.pycAdded
utils/__pycache__/logger.cpython-313.pycAdded