1. Connecting to the Service

The app needs a running FastAPI backend (locally or on Hugging Face) with all required routes and environment variables configured.

  • Start server locally: python -m uvicorn production_server:app --host 0.0.0.0 --port 7860 or python -m uvicorn hf_unified_server:app --host 0.0.0.0 --port 7860.
  • HF Spaces: configure the Space command to start hf_unified_server:app and set API keys in Settings → Variables and secrets.
  • Required model routes: /api/models/list, /api/models/status, /api/models/health, /api/models/reinit-all.

Open /docs (Swagger UI) to confirm these routes exist and respond with HTTP 200.

2. Environment Variables & API Keys

System uses 55 functional resources with 11 active API keys. Many features use external services with automatic fallback to backup providers.

Available Resources:

  • Total Functional Resources: 55 (87.3% success rate)
  • Total API Keys: 11 active keys
  • Total Endpoints: 200+ endpoints
  • Market Data: 13 providers (3 with keys, 10 free)
  • News: 10 providers (2 with keys, 8 free)
  • Sentiment: 6 providers (all free)
  • Analytics: 13 providers (all free)
  • Block Explorers: 6 providers (5 with keys)

API Keys Configuration:

  • HF Inference: HF_TOKEN or HF_API_TOKEN
  • CoinMarketCap: COINMARKETCAP_KEY_1, COINMARKETCAP_KEY_2
  • NewsAPI: NEWSAPI_KEY
  • CryptoCompare: CRYPTOCOMPARE_KEY
  • Alpha Vantage: ALPHA_VANTAGE_KEY
  • Etherscan: ETHERSCAN_KEY, ETHERSCAN_BACKUP_KEY
  • BscScan: BSCSCAN_KEY
  • TronScan: TRONSCAN_KEY

System automatically uses fallback providers if primary source fails. After changing variables on Hugging Face, restart the Space.

3. Dashboard & Prices

The Dashboard pulls real-time data from endpoints like /api/status, /api/resources, /api/trending, /api/coins/top, and /api/sentiment/global.

  • Top coins: GET /api/coins/top?limit=50 returns prices, market cap and volume.
  • Global sentiment: GET /api/sentiment/global returns overall market mood and history.
  • No sentiment / categories data: check the Network tab for these endpoints and ensure they return non-empty JSON.

4. Models, AI Analyst & Sentiment Testing

The Models and AI Analyst pages use backend AI routes for model management, sentiment analysis and trading decisions.

  • Re-initialize models: POST /api/models/reinit-all (triggered by the “Re-initialize All” button).
  • List & health: GET /api/models/list, /api/models/status, /api/models/health power the model cards and health monitor.
  • Sentiment analysis: POST /api/sentiment/analyze with a payload such as {"text": "...", "mode": "crypto", "model_key": "CryptoBERT"}.
  • AI Analyst decisions: POST /api/ai/decision returns structured buy / sell / hold style recommendations with confidence, signals, risks and price targets for the AI Analyst page.
  • WebSocket (OPTIONAL) vs HTTP (Recommended):
    • HTTP REST API (Recommended): All data is available via HTTP endpoints. This is the primary and most reliable method. Use endpoints like GET /api/market, GET /api/models/status, etc.
    • WebSocket (Optional Alternative): Provided as an optional alternative for users who prefer real-time streaming. Not required - HTTP works perfectly.
    • If WebSocket is unavailable or blocked, the app automatically uses HTTP polling (30s intervals).
    • All features work identically with HTTP - WebSocket is just a different transport method.
  • WebSocket Connection Issues (Non-Critical): If you see WebSocket errors (403, connection refused, etc.), this is expected and non-critical:
    • HuggingFace Spaces may limit WebSocket connections - this is normal
    • Network/firewall may block WebSocket - use HTTP instead
    • The application automatically falls back to HTTP polling - no action needed
    • All functionality works via HTTP endpoints - WebSocket is completely optional

5. Providers & Resources

System has 55 functional resources organized in backup providers. All resources are automatically loaded from functional_backup_resources.py.

  • List providers: GET /api/providers returns configured data sources and their status.
  • Resources stats: GET /api/resources/stats returns total resources, API keys count, and success rate.
  • Automatic Fallback: System automatically switches to backup providers if primary fails.
  • Error Handling: All endpoints have timeout (10s) and fallback mechanisms.
  • Use the UI Providers page to inspect availability, auth requirements, and categories.

Available Endpoints:

  • GET /api/ohlcv?symbol=BTC&timeframe=1h&limit=500 - OHLCV data (Binance + cache)
  • GET /api/klines?symbol=BTCUSDT&interval=1h&limit=500 - Alias to OHLCV
  • GET /api/historical?symbol=BTC&days=30 - Historical data
  • GET /api/signals - Trading signals (empty array, client-side generation)
  • GET /api/fear-greed - Fear & Greed Index (alias to sentiment)
  • GET /api/whale - Whale transactions (from cache)
  • GET /api/market?limit=100 - Market data (with fallback providers)
  • GET /api/news?limit=20 - News articles (with fallback providers)

6. Troubleshooting

  1. WebSocket Connection Errors: If you see WebSocket connection failures:
    • This is expected and non-critical on Hugging Face Spaces
    • The application automatically falls back to HTTP polling (30s intervals)
    • All features work perfectly without WebSocket - no action needed
    • See docs/WEBSOCKET_TROUBLESHOOTING.md for detailed information
  2. If you see 404 or 500, confirm the server process (production or unified) is running and that the endpoint appears in /docs.
  3. If a page shows "No data", open DevTools → Network and inspect failing calls such as /api/resources, /api/sentiment/global, or model routes.
  4. If responses are empty, verify your API keys and upstream providers, then restart the server or Space.
  5. Model Loading Failures: If models fail to load with "not a valid model identifier" errors:
    • Verify the model exists on Hugging Face Hub (check the model page URL)
    • For private/gated models, ensure HF_TOKEN or HF_API_TOKEN is set
    • Some models may require authentication even if marked as public
    • The system will use fallback lexical analysis if models fail to load
  6. Hard-refresh the browser (Ctrl+Shift+R) to bypass stale caches.
  7. Warnings about ambient-light-sensor or battery can be ignored unless features visibly break.

7. WebSocket (Optional) - Alternative Data Retrieval Method

⚠️ IMPORTANT: WebSocket is completely optional. All data can be retrieved via HTTP REST API endpoints. WebSocket is just an alternative method for users who prefer real-time streaming. If WebSocket is unavailable or you prefer HTTP, the application automatically uses HTTP polling (30-second intervals) and all features work perfectly.

The system supports WebSocket connections as an optional alternative for real-time data streaming. WebSocket is not required - the application automatically falls back to HTTP polling if WebSocket is unavailable. This is just another option users can choose if they prefer real-time updates over polling.

Available WebSocket Endpoints (Optional - Use HTTP if Preferred):

For HuggingFace Space: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/...
Note: WebSocket may be limited on HuggingFace Spaces. HTTP endpoints are recommended and work perfectly.

  • Master Endpoint: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/master
    • Access to all services (market data, news, sentiment, monitoring, HuggingFace)
    • Supports subscription/unsubscription to specific services
    • Send JSON messages: {"action": "subscribe", "service": "market_data"}
    • Alternative HTTP: Use GET /api/market, GET /api/news, etc.
  • Live Data: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/live
    • Real-time price updates, market snapshots, and OHLCV data
    • Automatic heartbeat/ping-pong for connection health
    • Alternative HTTP: Use GET /api/ohlcv with polling (30s intervals)
  • AI Data: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/ai/data
    • Real-time AI model status, sentiment analysis results
    • HuggingFace model loading/unloading notifications
    • Alternative HTTP: Use GET /api/models/status with polling
  • Data Collection: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/data
    • Market data, news, sentiment, whale tracking streams
    • Alternative HTTP: Use GET /api/market, GET /api/news, etc.
  • Monitoring: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/monitoring
    • Health checks, pool manager status, scheduler status
    • Alternative HTTP: Use GET /api/status, GET /api/resources/stats
  • Integration: wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/integration
    • HuggingFace integration status, persistence updates
    • Alternative HTTP: Use GET /api/resources/stats/combined

WebSocket Usage Example (Optional):

// OPTIONAL: WebSocket connection for real-time updates
// If WebSocket fails, use HTTP endpoints instead (recommended)

const ws = new WebSocket('wss://Really-amin-Datasourceforcryptocurrency-2.hf.space/ws/master');

ws.onopen = () => {
  console.log('WebSocket connected (optional)');
  // Subscribe to market data
  ws.send(JSON.stringify({
    action: 'subscribe',
    service: 'market_data'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Real-time update:', data);
};

ws.onerror = (error) => {
  console.warn('WebSocket error (non-critical):', error);
  // Fallback to HTTP polling
  setInterval(() => {
    fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/market')
      .then(r => r.json())
      .then(data => console.log('HTTP poll result:', data));
  }, 30000);
};

// ALTERNATIVE: Use HTTP polling (recommended, works everywhere)
setInterval(async () => {
  const response = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/market?limit=100');
  const data = await response.json();
  console.log('Market data:', data);
}, 30000); // Poll every 30 seconds

WebSocket Error Handling:

  • Automatic Reconnection: Client automatically reconnects with exponential backoff (1s → 16s max)
  • Connection State Management: Tracks connection status (connecting, connected, disconnected)
  • Error Logging: All WebSocket errors are logged with client ID and timestamp
  • Graceful Degradation: If WebSocket fails, app falls back to HTTP polling (30s intervals)
  • Timeout Handling: 30-second timeout for WebSocket operations
  • Message Validation: Invalid JSON messages are caught and logged without crashing
  • Connection Cleanup: Proper cleanup on disconnect prevents memory leaks

WebSocket Configuration:

  • Protocol Detection: Automatically uses wss:// for HTTPS and ws:// for HTTP
  • Heartbeat: Ping messages every 30 seconds to keep connection alive
  • Max Connections: No hard limit, but rate limiting applies per client
  • CORS: WebSocket connections respect CORS settings from main server
  • Authentication: Optional - can require HF_TOKEN for protected endpoints

Troubleshooting WebSocket Issues:

  1. Connection Refused (403/404):
    • Check if WebSocket endpoint exists in /docs
    • Verify server is running and WebSocket routes are registered
    • On Hugging Face Spaces, WebSocket may be limited - this is normal and non-critical
  2. Connection Timeout:
    • Check network connectivity
    • Verify firewall/proxy allows WebSocket connections
    • Application will automatically fall back to HTTP polling
  3. Message Parsing Errors:
    • Ensure messages are valid JSON
    • Check message format matches expected schema
    • Errors are logged but don't crash the connection
  4. High Memory Usage:
    • Connection manager automatically cleans up disconnected clients
    • Event logs are limited to last 100 events per client
    • Old connections are removed after timeout

📌 Summary: WebSocket is completely optional and just an alternative method. All features work perfectly via HTTP REST API endpoints. WebSocket is only useful if you prefer real-time streaming over HTTP polling. For HuggingFace Spaces, HTTP endpoints are recommended as they are more reliable and work in all environments.

Recommended Approach:

  • Primary Method (Recommended): Use HTTP REST API endpoints with polling (30s intervals)
  • Optional Alternative: Use WebSocket for real-time streaming (if available and preferred)
  • Automatic Fallback: Application automatically uses HTTP if WebSocket fails
  • No Configuration Needed: Both methods work out of the box - choose what you prefer

8. Retrieving Data from HuggingFace

This application runs on Hugging Face Spaces and provides multiple ways to retrieve data from the backend API. All endpoints are accessible via HTTP REST API.

Base URL Configuration:

  • Local Development: http://localhost:7860
  • Hugging Face Space (Production): https://huggingface.co/spaces/Really-amin/Datasourceforcryptocurrency-2
    API Base: https://Really-amin-Datasourceforcryptocurrency-2.hf.space
  • Custom Domain: Your configured domain URL

Note: The application automatically detects the environment and uses the correct base URL. When running on HuggingFace Spaces, it uses relative URLs for seamless operation.

How to Retrieve Data:

1. Market Data & Prices:

// JavaScript/TypeScript
// Using HuggingFace Space URL
const response = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/market?limit=100');
const data = await response.json();
// Returns: { success: true, items: [{symbol, name, price, change_24h, ...}] }

// Or use relative URL when on the same domain
const response = await fetch('/api/market?limit=100');
const data = await response.json();

// Python
import requests
response = requests.get('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/market?limit=100')
data = response.json()

2. OHLCV/Candlestick Data:

// Get OHLCV data for charting
const response = await fetch(
  'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/ohlcv?symbol=BTC&timeframe=1h&limit=500'
);
const data = await response.json();
// Returns: { success: true, data: [{t, o, h, l, c, v}, ...] }

// Historical data
const historical = await fetch(
  'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/historical?symbol=BTC&days=30'
);

3. News Articles:

const response = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/news?limit=20');
const data = await response.json();
// Returns: { success: true, articles: [{title, content, source, ...}] }

4. Sentiment Analysis:

// Global sentiment
const global = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/sentiment/global');
const globalData = await global.json();

// Analyze text
const analysis = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/sentiment/analyze', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    text: 'Bitcoin is going to the moon!',
    mode: 'crypto'
  })
});
const sentimentData = await analysis.json();
// Returns: { ok: true, label: 'bullish', score: 0.85, ... }

5. HuggingFace Models Status:

// Get all models
const models = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/models/list');
const modelsData = await models.json();

// Get model status
const status = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/models/status');
const statusData = await status.json();
// Returns: { models_loaded: 8, hf_mode: 'public', models: {...} }

// Get resources stats (includes HF models)
const resources = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/resources/stats/combined');
const resourcesData = await resources.json();

6. Resources & Providers:

// Get resources statistics
const stats = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/resources/stats');
const statsData = await stats.json();
// Returns: { success: true, data: { total_functional: 55, total_api_keys: 11, ... } }

// Get all functional APIs
const apis = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/resources/apis');
const apisData = await apis.json();

7. AI Analysis & Trading Signals:

// Get AI trading decision
const decision = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/ai/decision', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    timeframe: '1h'
  })
});
const decisionData = await decision.json();

// Get trading signals
const signals = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/signals');
const signalsData = await signals.json();

Authentication (Optional):

Most endpoints work without authentication. For protected endpoints or HuggingFace model access, include the token in headers:

const response = await fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/protected-endpoint', {
  headers: {
    'Authorization': `Bearer ${HF_TOKEN}`,
    'Content-Type': 'application/json'
  }
});

Error Handling:

  • 404 Not Found: Endpoint doesn't exist - check URL and server routes
  • 503 Service Unavailable: Backend service is down or rate limited
  • 500 Internal Server Error: Server error - check logs
  • Timeout: Request took too long - increase timeout or check network
  • CORS Errors: Cross-origin requests blocked - ensure CORS is enabled

Best Practices:

  • Always check response.ok or status code before parsing JSON
  • Use try-catch blocks for error handling
  • Implement retry logic with exponential backoff for failed requests
  • Cache responses when appropriate (OHLCV data, model status)
  • Use WebSocket for real-time updates, HTTP for one-time queries
  • Respect rate limits (1200 requests/minute for Binance, etc.)

Example: Complete Data Retrieval Flow

// Complete example: Fetch market data with error handling
// Using HuggingFace Space: https://Really-amin-Datasourceforcryptocurrency-2.hf.space
const API_BASE = 'https://Really-amin-Datasourceforcryptocurrency-2.hf.space';

async function fetchMarketData(symbol = 'BTC') {
  try {
    // 1. Get current price
    const priceRes = await fetch(
      `${API_BASE}/api/market?limit=1&symbol=${symbol}`
    );
    if (!priceRes.ok) throw new Error(`Price API failed: ${priceRes.status}`);
    const priceData = await priceRes.json();

    // 2. Get OHLCV for chart
    const ohlcvRes = await fetch(
      `${API_BASE}/api/ohlcv?symbol=${symbol}&timeframe=1h&limit=100`
    );
    if (!ohlcvRes.ok) throw new Error(`OHLCV API failed: ${ohlcvRes.status}`);
    const ohlcvData = await ohlcvRes.json();

    // 3. Get sentiment
    const sentimentRes = await fetch(`${API_BASE}/api/sentiment/global`);
    const sentimentData = await sentimentRes.json();

    // 4. Get AI analysis
    const aiRes = await fetch(`${API_BASE}/api/ai/decision`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ symbol, timeframe: '1h' })
    });
    const aiData = await aiRes.json();

    return {
      price: priceData.items[0],
      ohlcv: ohlcvData.data,
      sentiment: sentimentData,
      aiDecision: aiData
    };
  } catch (error) {
    console.error('Error fetching data:', error);
    // Fallback to cached data or show error message
    return null;
  }
}

Tip: Use the /docs endpoint (Swagger UI) to explore all available endpoints, test requests, and see response schemas interactively.

9. Unified Service API - Complete Endpoint Guide

The Unified Service API provides a single entry point for all cryptocurrency data needs. These endpoints are the primary way to access market data, prices, sentiment, whales, and blockchain information.

Base URL:

HuggingFace Space: https://Really-amin-Datasourceforcryptocurrency-2.hf.space
Local: http://localhost:7860

Available Endpoints:

1. Exchange Rates (جفت ارزها)

// Get single exchange rate
GET /api/service/rate?pair=BTC/USDT

// Response:
{
  "data": {
    "pair": "BTC/USDT",
    "price": 50234.12,
    "quote": "USDT",
    "ts": "2025-01-15T12:00:00Z"
  },
  "meta": {
    "source": "hf",
    "generated_at": "2025-01-15T12:00:00Z",
    "cache_ttl_seconds": 10
  }
}

// Get multiple rates (batch)
GET /api/service/rate/batch?pairs=BTC/USDT,ETH/USDT,BNB/USDT

// Get pair metadata
GET /api/service/pair/BTC-USDT
// or
GET /api/service/pair/BTC/USDT

2. Market Data

// Market status
GET /api/service/market-status

// Top coins
GET /api/service/top?n=10  // or n=50

// Price history
GET /api/service/history?symbol=BTC&interval=60

3. Sentiment Analysis

// Get sentiment for a symbol
GET /api/service/sentiment?symbol=BTC

// Analyze text
POST /api/sentiment/analyze
Content-Type: application/json
{
  "text": "Bitcoin is going to the moon! 🚀"
}

// Response:
{
  "label": "positive",
  "score": 0.85,
  "confidence": 0.92
}

4. Whale Tracking (نهنگ‌ها)

// Get whale transactions
GET /api/service/whales?chain=ethereum&min_amount_usd=1000000&limit=50

// Response:
{
  "data": [
    {
      "from": "0x...",
      "to": "0x...",
      "amount": 100.5,
      "amount_usd": 1500000,
      "chain": "ethereum",
      "ts": "2025-01-15T12:00:00Z"
    }
  ],
  "meta": {
    "source": "whale_alert",
    "generated_at": "2025-01-15T12:00:00Z"
  }
}

// Alternative endpoint
GET /api/whales/transactions?limit=50&chain=ethereum
GET /api/whales/stats?hours=24

5. On-Chain Data (بلاکچین)

// Get on-chain data for an address
GET /api/service/onchain?address=0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb&chain=ethereum&limit=50

// Get gas prices
GET /api/blockchain/gas?chain=ethereum

// Response:
{
  "slow": 20,
  "standard": 25,
  "fast": 30,
  "unit": "gwei"
}

6. Generic Query Endpoint

// Universal query endpoint
POST /api/service/query
Content-Type: application/json
{
  "type": "rate",  // or: history, sentiment, econ, whales, onchain, pair
  "payload": {
    "pair": "BTC/USDT"
  },
  "options": {
    "prefer_hf": true,
    "persist": true
  }
}

Complete Usage Examples:

JavaScript Example:

// Complete client example
const API_BASE = 'https://Really-amin-Datasourceforcryptocurrency-2.hf.space';

class CryptoAPIClient {
  constructor(baseUrl = API_BASE) {
    this.baseUrl = baseUrl;
  }

  // Get exchange rate
  async getRate(pair) {
    const response = await fetch(`${this.baseUrl}/api/service/rate?pair=${pair}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  }

  // Get multiple rates
  async getBatchRates(pairs) {
    const pairsStr = Array.isArray(pairs) ? pairs.join(',') : pairs;
    const response = await fetch(`${this.baseUrl}/api/service/rate/batch?pairs=${pairsStr}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  }

  // Get whale transactions
  async getWhales(chain = 'ethereum', minAmount = 1000000) {
    const response = await fetch(
      `${this.baseUrl}/api/service/whales?chain=${chain}&min_amount_usd=${minAmount}&limit=50`
    );
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  }

  // Analyze sentiment
  async analyzeSentiment(text) {
    const response = await fetch(`${this.baseUrl}/api/sentiment/analyze`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text })
    });
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  }

  // Get on-chain data
  async getOnChainData(address, chain = 'ethereum') {
    const response = await fetch(
      `${this.baseUrl}/api/service/onchain?address=${address}&chain=${chain}&limit=50`
    );
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  }
}

// Usage
const client = new CryptoAPIClient();

// Get BTC price
const btcRate = await client.getRate('BTC/USDT');
console.log(`BTC Price: $${btcRate.data.price}`);

// Get multiple prices
const rates = await client.getBatchRates(['BTC/USDT', 'ETH/USDT', 'BNB/USDT']);
rates.data.forEach(rate => {
  console.log(`${rate.pair}: $${rate.price}`);
});

// Get whale transactions
const whales = await client.getWhales('ethereum', 1000000);
console.log(`Found ${whales.data.length} whale transactions`);

// Analyze sentiment
const sentiment = await client.analyzeSentiment('Bitcoin is bullish!');
console.log(`Sentiment: ${sentiment.label} (${sentiment.score})`);

Python Example:

import requests
from typing import Optional, Dict, Any

class CryptoAPIClient:
    def __init__(self, base_url: str = "https://Really-amin-Datasourceforcryptocurrency-2.hf.space"):
        self.base_url = base_url
    
    def get_rate(self, pair: str) -> Dict[str, Any]:
        """Get exchange rate for a pair"""
        url = f"{self.base_url}/api/service/rate"
        params = {"pair": pair}
        response = requests.get(url, params=params, timeout=30)
        response.raise_for_status()
        return response.json()
    
    def get_batch_rates(self, pairs: list) -> Dict[str, Any]:
        """Get rates for multiple pairs"""
        url = f"{self.base_url}/api/service/rate/batch"
        params = {"pairs": ",".join(pairs)}
        response = requests.get(url, params=params, timeout=30)
        response.raise_for_status()
        return response.json()
    
    def get_whales(self, chain: str = "ethereum", min_amount: int = 1000000) -> Dict[str, Any]:
        """Get whale transactions"""
        url = f"{self.base_url}/api/service/whales"
        params = {
            "chain": chain,
            "min_amount_usd": min_amount,
            "limit": 50
        }
        response = requests.get(url, params=params, timeout=30)
        response.raise_for_status()
        return response.json()
    
    def analyze_sentiment(self, text: str) -> Dict[str, Any]:
        """Analyze sentiment"""
        url = f"{self.base_url}/api/sentiment/analyze"
        payload = {"text": text}
        response = requests.post(url, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()
    
    def get_onchain_data(self, address: str, chain: str = "ethereum") -> Dict[str, Any]:
        """Get on-chain data"""
        url = f"{self.baseUrl}/api/service/onchain"
        params = {
            "address": address,
            "chain": chain,
            "limit": 50
        }
        response = requests.get(url, params=params, timeout=30)
        response.raise_for_status()
        return response.json()

# Usage
client = CryptoAPIClient()

# Get BTC price
btc_rate = client.get_rate("BTC/USDT")
print(f"BTC Price: ${btc_rate['data']['price']}")

# Get multiple prices
rates = client.get_batch_rates(["BTC/USDT", "ETH/USDT", "BNB/USDT"])
for rate in rates['data']:
    print(f"{rate['pair']}: ${rate['price']}")

# Get whales
whales = client.get_whales("ethereum", 1000000)
print(f"Found {len(whales['data'])} whale transactions")

# Analyze sentiment
sentiment = client.analyze_sentiment("Bitcoin is bullish!")
print(f"Sentiment: {sentiment['label']} ({sentiment['score']})")

cURL Examples:

# Get BTC/USDT rate
curl "https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/service/rate?pair=BTC/USDT"

# Get multiple rates
curl "https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/service/rate/batch?pairs=BTC/USDT,ETH/USDT"

# Get whale transactions
curl "https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/service/whales?chain=ethereum&min_amount_usd=1000000"

# Analyze sentiment
curl -X POST "https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/sentiment/analyze" \
  -H "Content-Type: application/json" \
  -d '{"text": "Bitcoin is rising!"}'

# Get gas prices
curl "https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/blockchain/gas?chain=ethereum"

10. Common Errors & Solutions

This section covers the most common errors users encounter and how to fix them.

Error 1: 404 Not Found - /api/service/* endpoints

Problem: Getting 404 errors when calling /api/service/rate, /api/service/whales, etc.
Cause: Unified Service API router not loaded in server
Solution: Ensure app_unified.py or hf_unified_server.py includes the router
// Check if router is loaded
GET /api/routers

// Should return:
{
  "routers": {
    "unified_service_api": "loaded"  // ✅ Should be "loaded"
  }
}

// If "not_available", the router needs to be added to server file

Fix: Make sure your server file includes:

from backend.routers.unified_service_api import router as unified_service_router
app.include_router(unified_service_router)

Error 2: 503 Service Unavailable - OHLC Data

Problem: GET /api/market/ohlc returns 503: "All OHLC sources failed"
Cause: All OHLC providers (Binance, CoinGecko) are failing or rate limited
Solution: Check API keys, wait for rate limit reset, or use alternative endpoints
// Alternative: Use market tickers instead
GET /api/market/tickers?limit=100

// Or use direct API
GET /api/v1/binance/klines?symbol=BTC&timeframe=1h&limit=100

Error 3: 500 Internal Server Error - HuggingFace Models

Problem: POST /api/sentiment/analyze or POST /api/news/summarize returns 500
Error Message: "404 Not Found for url 'https://router.huggingface.co/models/...'"
Cause: Model not found on HuggingFace Hub or requires authentication
Solution: System uses fallback analysis, but you can configure alternative models
// Check model status
GET /api/models/status

// If models fail, system uses fallback lexical analysis
// You can also use direct sentiment endpoint
POST /api/v1/hf/sentiment
{
  "text": "Your text here",
  "model": "ProsusAI/finbert"  // Alternative model
}

Error 4: Timeout Errors

Problem: Requests timeout after 10-30 seconds
Cause: HuggingFace Space may be slow or sleeping
Solution: Increase timeout, add retry logic, or wake up the Space
// JavaScript - Increase timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 60000); // 60 seconds

try {
  const response = await fetch(url, {
    signal: controller.signal,
    // ... other options
  });
  clearTimeout(timeoutId);
  // ... handle response
} catch (error) {
  clearTimeout(timeoutId);
  if (error.name === 'AbortError') {
    console.error('Request timeout');
  }
}

// Python - Increase timeout
import requests
response = requests.get(url, timeout=60)  # 60 seconds

Error 5: CORS Errors

Problem: "CORS policy blocked" errors in browser console
Cause: CORS not configured properly
Solution: Server should have CORS enabled (already configured), but check if you're using correct URL
// Make sure you're using the correct base URL
// ✅ Correct:
const API_BASE = 'https://Really-amin-Datasourceforcryptocurrency-2.hf.space';

// ❌ Wrong (will cause CORS):
const API_BASE = 'http://localhost:7860';  // If running from different origin

Error 6: Empty Responses

Problem: Endpoint returns 200 but data is empty
Cause: No data available, provider failed, or cache issue
Solution: Check response structure, try different endpoint, or wait for data refresh
// Check response structure
const response = await fetch('/api/news/latest?symbol=BTC&limit=10');
const data = await response.json();

// Response might be:
{
  "success": true,
  "news": [],  // Empty array - no news available
  "meta": {
    "source": "newsapi",
    "total": 0
  }
}

// Try alternative endpoint
const altResponse = await fetch('/api/news?limit=10');

Error 7: Rate Limit Exceeded (429)

Problem: Getting 429 "Rate limit exceeded" errors
Cause: Too many requests in short time
Solution: Implement rate limiting, add delays, or use caching
// Check rate limit headers
const response = await fetch('/api/service/rate?pair=BTC/USDT');
console.log('Limit:', response.headers.get('X-RateLimit-Limit'));
console.log('Remaining:', response.headers.get('X-RateLimit-Remaining'));
console.log('Reset:', response.headers.get('X-RateLimit-Reset'));

// Implement client-side rate limiting
let lastRequest = 0;
const MIN_DELAY = 100; // 100ms between requests

async function rateLimitedFetch(url, options) {
  const now = Date.now();
  const timeSinceLastRequest = now - lastRequest;
  
  if (timeSinceLastRequest < MIN_DELAY) {
    await new Promise(resolve => setTimeout(resolve, MIN_DELAY - timeSinceLastRequest));
  }
  
  lastRequest = Date.now();
  return fetch(url, options);
}

Quick Diagnostic Checklist:

  1. Check Health: GET /api/health - Should return 200 with "healthy" status
  2. Check Routers: GET /api/routers - Verify unified_service_api is "loaded"
  3. Check Status: GET /api/status - See overall system status
  4. Check Docs: Visit /docs - See all available endpoints
  5. Test Simple Endpoint: GET /api/market/tickers?limit=10 - Should work if system is running
  6. Check Network Tab: Open browser DevTools → Network tab to see actual requests and responses
  7. Check Server Logs: If on HuggingFace Space, check Space logs for errors

11. Technical Analysis - Advanced Trading Tools

صفحه Technical Analysis ابزارهای پیشرفته تحلیل تکنیکال را با 5 حالت مختلف تحلیل ارائه می‌دهد. این صفحه شامل تشخیص الگوهای هارمونیک، تحلیل Elliott Wave، اندیکاتورهای پیشرفته و توصیه‌های معاملاتی است.

5 حالت تحلیل (Analysis Modes):

1. Quick Technical Analysis (TA_QUICK)

تحلیل سریع روند کوتاه‌مدت و مومنتوم:

// JavaScript
const response = await fetch('/api/technical/ta-quick', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    timeframe: '4h',
    ohlcv: [...] // Array of OHLCV candles
  })
});
const data = await response.json();
// Returns: { success: true, trend: 'Bullish', rsi: 65.5, macd: {...}, support_resistance: {...}, entry_range: {...}, exit_range: {...} }

// Python
import requests
response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/ta-quick',
    json={
        'symbol': 'BTC',
        'timeframe': '4h',
        'ohlcv': [...]  # List of OHLCV dictionaries
    }
)
data = response.json()

2. Fundamental Evaluation (FA_EVAL)

ارزیابی بنیادی پروژه و پتانسیل بلندمدت:

// JavaScript
const response = await fetch('/api/technical/fa-eval', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    whitepaper_summary: 'Bitcoin is a decentralized digital currency...',
    team_credibility_score: 9,
    token_utility_description: 'Store of value and digital gold...',
    total_supply_mechanism: 'Fixed supply of 21 million coins'
  })
});
const data = await response.json();
// Returns: { success: true, fundamental_score: 8.5, justification: '...', risks: [...], growth_potential: 'High' }

// Python
import requests
response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/fa-eval',
    json={
        'symbol': 'BTC',
        'whitepaper_summary': 'Bitcoin is a decentralized digital currency...',
        'team_credibility_score': 9,
        'token_utility_description': 'Store of value and digital gold...',
        'total_supply_mechanism': 'Fixed supply of 21 million coins'
    }
)
data = response.json()

3. On-Chain Network Health (ON_CHAIN_HEALTH)

تحلیل سلامت شبکه و رفتار نهنگ‌ها:

// JavaScript
const response = await fetch('/api/technical/onchain-health', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    active_addresses_7day_avg: 850000,
    exchange_net_flow_24h: -150000000,  // Negative = outflow (bullish)
    mrvv_z_score: -0.5
  })
});
const data = await response.json();
// Returns: { success: true, network_phase: 'Accumulation', cycle_position: 'Bottom Zone', health_status: 'Healthy' }

// Python
import requests
response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/onchain-health',
    json={
        'symbol': 'BTC',
        'active_addresses_7day_avg': 850000,
        'exchange_net_flow_24h': -150000000,
        'mrvv_z_score': -0.5
    }
)
data = response.json()

4. Risk & Volatility Assessment (RISK_ASSESSMENT)

ارزیابی ریسک و نوسانات:

// JavaScript
const response = await fetch('/api/technical/risk-assessment', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    historical_daily_prices: [...],  // Last 90 days
    max_drawdown_percentage: 25.5
  })
});
const data = await response.json();
// Returns: { success: true, risk_level: 'Medium', volatility: 0.045, max_drawdown: 25.5, justification: '...' }

// Python
import requests
response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/risk-assessment',
    json={
        'symbol': 'BTC',
        'historical_daily_prices': [...],  # List of prices for last 90 days
        'max_drawdown_percentage': 25.5
    }
)
data = response.json()

5. Comprehensive Analysis (COMPREHENSIVE)

تحلیل جامع ترکیبی از همه حالت‌ها:

// JavaScript
const response = await fetch('/api/technical/comprehensive', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    timeframe: '4h',
    ohlcv: [...],
    fundamental_data: {...},
    onchain_data: {...}
  })
});
const data = await response.json();
// Returns: { success: true, recommendation: 'BUY', confidence: 0.85, executive_summary: '...', ta_score: 8, fa_score: 7.5, onchain_score: 9 }

// Python
import requests
response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/comprehensive',
    json={
        'symbol': 'BTC',
        'timeframe': '4h',
        'ohlcv': [...],
        'fundamental_data': {...},
        'onchain_data': {...}
    }
)
data = response.json()

API Endpoint اصلی - تحلیل تکنیکال جامع:

// JavaScript - تحلیل تکنیکال کامل با همه اندیکاتورها و الگوها
const response = await fetch('/api/technical/analyze', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    timeframe: '4h',
    ohlcv: [
      { t: 1234567890000, o: 50000, h: 51000, l: 49500, c: 50500, v: 1000000 },
      // ... more candles
    ],
    indicators: {
      rsi: true,
      macd: true,
      volume: true,
      ichimoku: false,
      elliott: true
    },
    patterns: {
      gartley: true,
      butterfly: true,
      bat: true,
      crab: true,
      candlestick: true
    }
  })
});
const analysis = await response.json();
// Returns: {
//   success: true,
//   support_resistance: { support: 49500, resistance: 51000, levels: [...] },
//   harmonic_patterns: [{ type: 'Gartley', pattern: 'Bullish', confidence: 0.75 }],
//   elliott_wave: { wave_count: 5, current_wave: 3, direction: 'up' },
//   candlestick_patterns: [{ type: 'Hammer', signal: 'Bullish' }],
//   indicators: { rsi: 65.5, macd: {...}, sma20: 50200, sma50: 49800 },
//   signals: [{ type: 'BUY', source: 'RSI Oversold', strength: 'Strong' }],
//   trade_recommendations: { entry: 50000, tp: 52000, sl: 49000 }
// }

// Python
import requests
response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/analyze',
    json={
        'symbol': 'BTC',
        'timeframe': '4h',
        'ohlcv': [
            {'t': 1234567890000, 'o': 50000, 'h': 51000, 'l': 49500, 'c': 50500, 'v': 1000000},
            # ... more candles
        ],
        'indicators': {
            'rsi': True,
            'macd': True,
            'volume': True,
            'ichimoku': False,
            'elliott': True
        },
        'patterns': {
            'gartley': True,
            'butterfly': True,
            'bat': True,
            'crab': True,
            'candlestick': True
        }
    }
)
analysis = response.json()

دریافت داده‌های OHLCV برای تحلیل:

// JavaScript - دریافت داده‌های OHLCV
const ohlcvResponse = await fetch('/api/ohlcv?symbol=BTC&timeframe=4h&limit=200');
const ohlcvData = await ohlcvResponse.json();
// Returns: { success: true, data: [{ t, o, h, l, c, v }, ...] }

// استفاده از داده‌ها در تحلیل
const analysisResponse = await fetch('/api/technical/ta-quick', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    symbol: 'BTC',
    timeframe: '4h',
    ohlcv: ohlcvData.data  // استفاده از داده‌های دریافت شده
  })
});

// Python
import requests

# دریافت داده‌های OHLCV
ohlcv_response = requests.get(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/ohlcv',
    params={'symbol': 'BTC', 'timeframe': '4h', 'limit': 200}
)
ohlcv_data = ohlcv_response.json()

# استفاده در تحلیل
analysis_response = requests.post(
    'https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/technical/ta-quick',
    json={
        'symbol': 'BTC',
        'timeframe': '4h',
        'ohlcv': ohlcv_data['data']
    }
)
analysis = analysis_response.json()

مثال کامل: تحلیل جامع یک ارز:

// JavaScript - مثال کامل
async function analyzeCrypto(symbol = 'BTC') {
  const API_BASE = window.location.origin; // یا URL کامل HuggingFace Space
  
  try {
    // 1. دریافت داده‌های OHLCV
    const ohlcvRes = await fetch(`${API_BASE}/api/ohlcv?symbol=${symbol}&timeframe=4h&limit=200`);
    if (!ohlcvRes.ok) throw new Error('Failed to fetch OHLCV');
    const ohlcvData = await ohlcvRes.json();
    
    // 2. تحلیل تکنیکال سریع
    const taQuickRes = await fetch(`${API_BASE}/api/technical/ta-quick`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        symbol: symbol,
        timeframe: '4h',
        ohlcv: ohlcvData.data
      })
    });
    const taQuick = await taQuickRes.json();
    
    // 3. تحلیل بنیادی (اگر داده‌ها موجود باشد)
    const faRes = await fetch(`${API_BASE}/api/technical/fa-eval`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        symbol: symbol,
        whitepaper_summary: '...',  // داده‌های پروژه
        team_credibility_score: 8,
        token_utility_description: '...',
        total_supply_mechanism: '...'
      })
    });
    const faData = await faRes.json();
    
    // 4. تحلیل جامع
    const comprehensiveRes = await fetch(`${API_BASE}/api/technical/comprehensive`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        symbol: symbol,
        timeframe: '4h',
        ohlcv: ohlcvData.data,
        fundamental_data: faData,
        onchain_data: {}  // اگر داده‌های on-chain موجود باشد
      })
    });
    const comprehensive = await comprehensiveRes.json();
    
    return {
      taQuick: taQuick,
      fundamental: faData,
      comprehensive: comprehensive
    };
  } catch (error) {
    console.error('Analysis error:', error);
    return null;
  }
}

// استفاده
analyzeCrypto('BTC').then(results => {
  console.log('TA Quick:', results.taQuick);
  console.log('Fundamental:', results.fundamental);
  console.log('Comprehensive:', results.comprehensive);
  console.log('Recommendation:', results.comprehensive.recommendation);
});

// Python
import requests

def analyze_crypto(symbol='BTC'):
    API_BASE = 'https://Really-amin-Datasourceforcryptocurrency-2.hf.space'
    
    try:
        # 1. دریافت داده‌های OHLCV
        ohlcv_res = requests.get(
            f'{API_BASE}/api/ohlcv',
            params={'symbol': symbol, 'timeframe': '4h', 'limit': 200}
        )
        ohlcv_data = ohlcv_res.json()
        
        # 2. تحلیل تکنیکال سریع
        ta_quick_res = requests.post(
            f'{API_BASE}/api/technical/ta-quick',
            json={
                'symbol': symbol,
                'timeframe': '4h',
                'ohlcv': ohlcv_data['data']
            }
        )
        ta_quick = ta_quick_res.json()
        
        # 3. تحلیل جامع
        comprehensive_res = requests.post(
            f'{API_BASE}/api/technical/comprehensive',
            json={
                'symbol': symbol,
                'timeframe': '4h',
                'ohlcv': ohlcv_data['data']
            }
        )
        comprehensive = comprehensive_res.json()
        
        return {
            'ta_quick': ta_quick,
            'comprehensive': comprehensive
        }
    except Exception as e:
        print(f'Analysis error: {e}')
        return None

# استفاده
results = analyze_crypto('BTC')
print(f"Recommendation: {results['comprehensive']['recommendation']}")

اندیکاتورها و الگوهای پشتیبانی شده:

  • اندیکاتورها: RSI (14), MACD, Volume, Ichimoku Cloud, Elliott Wave, SMA 20/50
  • الگوهای هارمونیک: Gartley, Butterfly, Bat, Crab
  • الگوهای کندل استیک: Doji, Hammer, Engulfing (Bullish/Bearish)
  • سطوح Support/Resistance: محاسبه خودکار بر اساس Pivot Points
  • توصیه‌های معاملاتی: Entry, Take Profit (TP), Stop Loss (SL)

نکات مهم:

  • برای تحلیل دقیق‌تر، حداقل 100-200 کندل داده نیاز است
  • Timeframe پیشنهادی برای TA_QUICK: 4h
  • سیستم به صورت خودکار از محاسبات محلی استفاده می‌کند اگر API در دسترس نباشد
  • همه endpointها از retry logic با exponential backoff استفاده می‌کنند
  • برای تحلیل جامع، داده‌های TA، FA و On-Chain را ترکیب کنید

Error Handling:

// JavaScript - مدیریت خطا با retry
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);
      if (response.ok) return await response.json();
      
      if (i < maxRetries - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        continue;
      }
      
      throw new Error(`HTTP ${response.status}`);
    } catch (error) {
      if (i < maxRetries - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        continue;
      }
      throw error;
    }
  }
}

// استفاده
try {
  const analysis = await fetchWithRetry('/api/technical/ta-quick', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ symbol: 'BTC', timeframe: '4h', ohlcv: [...] })
  });
  console.log('Analysis:', analysis);
} catch (error) {
  console.error('Analysis failed after retries:', error);
  // استفاده از fallback calculations
}

💡 نکته: برای مشاهده تمام endpointها و تست آنها، به /docs (Swagger UI) مراجعه کنید. همچنین می‌توانید از صفحه Technical Analysis در UI استفاده کنید که همه این تحلیل‌ها را به صورت بصری نمایش می‌دهد.

12. Quick Start Guide for Average Users

This section provides simple, step-by-step examples for average users who want to quickly start using the API.

Step 1: Get a Single Price

// Simplest example - Get BTC price
fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/service/rate?pair=BTC/USDT')
  .then(r => r.json())
  .then(data => {
    console.log(`BTC Price: $${data.data.price}`);
  })
  .catch(err => console.error('Error:', err));

Step 2: Get Multiple Prices

// Get prices for multiple coins
fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/service/rate/batch?pairs=BTC/USDT,ETH/USDT,BNB/USDT')
  .then(r => r.json())
  .then(data => {
    data.data.forEach(rate => {
      console.log(`${rate.pair}: $${rate.price}`);
    });
  });

Step 3: Get Latest News

// Get latest crypto news
fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/news/latest?symbol=BTC&limit=5')
  .then(r => r.json())
  .then(data => {
    data.news.forEach(article => {
      console.log(`- ${article.title}`);
      console.log(`  Source: ${article.source}`);
      console.log(`  URL: ${article.url}\n`);
    });
  });

Step 4: Get Whale Transactions

// Get large transactions (whales)
fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/service/whales?chain=ethereum&min_amount_usd=1000000&limit=20')
  .then(r => r.json())
  .then(data => {
    console.log(`Found ${data.data.length} whale transactions:`);
    data.data.forEach(tx => {
      console.log(`From: ${tx.from}`);
      console.log(`To: ${tx.to}`);
      console.log(`Amount: $${tx.amount_usd.toLocaleString()}\n`);
    });
  });

Step 5: Analyze Sentiment

// Analyze text sentiment
fetch('https://Really-amin-Datasourceforcryptocurrency-2.hf.space/api/sentiment/analyze', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    text: 'Bitcoin is going to the moon! 🚀'
  })
})
  .then(r => r.json())
  .then(data => {
    console.log(`Sentiment: ${data.label}`);
    console.log(`Score: ${data.score}`);
    console.log(`Confidence: ${data.confidence || 'N/A'}`);
  });

Complete Working Example:

<!DOCTYPE html>
<html>
<head>
  <title>Crypto API Example</title>
</head>
<body>
  <h1>Crypto Data</h1>
  <div id="prices">Loading...</div>
  <div id="news">Loading...</div>

  <script>
    const API_BASE = 'https://Really-amin-Datasourceforcryptocurrency-2.hf.space';

    // Get prices
    async function loadPrices() {
      try {
        const response = await fetch(`${API_BASE}/api/service/rate/batch?pairs=BTC/USDT,ETH/USDT,BNB/USDT`);
        const data = await response.json();
        
        const pricesHtml = data.data.map(rate => 
          `<p><strong>${rate.pair}:</strong> $${rate.price.toFixed(2)}</p>`
        ).join('');
        
        document.getElementById('prices').innerHTML = pricesHtml;
      } catch (error) {
        document.getElementById('prices').innerHTML = `Error: ${error.message}`;
      }
    }

    // Get news
    async function loadNews() {
      try {
        const response = await fetch(`${API_BASE}/api/news/latest?symbol=BTC&limit=5`);
        const data = await response.json();
        
        const newsHtml = data.news.map(article => 
          `<div>
            <h3>${article.title}</h3>
            <p>${article.summary}</p>
            <a href="${article.url}" target="_blank">Read more</a>
          </div>`
        ).join('');
        
        document.getElementById('news').innerHTML = newsHtml;
      } catch (error) {
        document.getElementById('news').innerHTML = `Error: ${error.message}`;
      }
    }

    // Load data on page load
    loadPrices();
    loadNews();

    // Refresh every 30 seconds
    setInterval(() => {
      loadPrices();
      loadNews();
    }, 30000);
  </script>
</body>
</html>

Python Quick Start:

import requests

API_BASE = "https://Really-amin-Datasourceforcryptocurrency-2.hf.space"

# Get BTC price
response = requests.get(f"{API_BASE}/api/service/rate?pair=BTC/USDT")
data = response.json()
print(f"BTC Price: ${data['data']['price']}")

# Get multiple prices
response = requests.get(f"{API_BASE}/api/service/rate/batch?pairs=BTC/USDT,ETH/USDT")
data = response.json()
for rate in data['data']:
    print(f"{rate['pair']}: ${rate['price']}")

# Get news
response = requests.get(f"{API_BASE}/api/news/latest?symbol=BTC&limit=5")
data = response.json()
for article in data['news']:
    print(f"- {article['title']}")

# Analyze sentiment
response = requests.post(
    f"{API_BASE}/api/sentiment/analyze",
    json={"text": "Bitcoin is bullish!"}
)
data = response.json()
print(f"Sentiment: {data['label']} ({data['score']})")

13. Summary

This system provides real-time market data, global sentiment, model management and analysis tools. Ensure the correct backend server is running with valid environment variables, then use the Dashboard, Models and Providers pages to explore data and run analyses from the UI.

Available API Endpoints:

  • Unified Service API: /api/service/* - Primary endpoints for all data needs
    • /api/service/rate - Exchange rates
    • /api/service/whales - Whale transactions
    • /api/service/sentiment - Sentiment analysis
    • /api/service/onchain - Blockchain data
    • /api/service/market-status - Market overview
  • Market Data: /api/market/* - Prices, tickers, OHLCV
  • News: /api/news/* - Crypto news articles
  • Sentiment: /api/sentiment/* - Sentiment analysis
  • Blockchain: /api/blockchain/* - Gas prices, transactions
  • AI Models: /api/models/* - Model management
  • Technical Analysis: /api/technical/* - Advanced trading analysis

Key Points:

  • All data is accessible via HTTP REST API endpoints
  • Unified Service API (/api/service/*) is the primary way to access data
  • WebSocket is optional for real-time updates (automatic fallback to HTTP polling)
  • 55 functional resources with automatic fallback system
  • 11 active API keys for enhanced features
  • Comprehensive error handling and retry mechanisms
  • Full documentation available at /docs endpoint
  • Check /api/routers to see which endpoints are available
  • Use /api/health to verify system status

Common Use Cases:

  • Get Prices: Use /api/service/rate or /api/market/tickers
  • Get News: Use /api/news/latest or /api/news
  • Track Whales: Use /api/service/whales
  • Analyze Sentiment: Use /api/sentiment/analyze or /api/service/sentiment
  • Get Blockchain Data: Use /api/service/onchain or /api/blockchain/gas
  • Technical Analysis: Use /api/technical/analyze or other TA endpoints

If You Encounter Errors:

  1. Check /api/health - System should be "healthy"
  2. Check /api/routers - Verify endpoints are loaded
  3. Check /docs - See all available endpoints
  4. See Section 10: Common Errors & Solutions for specific fixes
  5. Check browser DevTools → Network tab for actual error messages
  6. Verify Space is running and not sleeping

Getting Help:

  • API Documentation: Visit /docs for interactive Swagger UI
  • OpenAPI Spec: /openapi.json for complete API specification
  • Router Status: /api/routers to see loaded endpoints
  • System Status: /api/status for detailed system information
  • This Help Page: Complete guide with examples and troubleshooting