Skip to main content

Overview

CryptoView Pro is a sophisticated cryptocurrency forecasting system built with a modular architecture that combines real-time data collection, technical analysis, machine learning predictions, and user notifications. The system is designed to provide accurate short-term and long-term price predictions using hybrid ML models.

System Components

The application is organized into several key modules:

Data Layer

Handles data collection from cryptocurrency exchanges using CCXT

ML Layer

Three specialized models: XGBoost, Prophet, and Hybrid

Analysis Layer

Technical indicators (RSI, MACD, Bollinger Bands, EMAs)

Presentation Layer

Streamlit-based interactive dashboard

Architecture Diagram

Core Components

1. Data Collection Layer

Location: data/collectors.py The CryptoDataCollector class manages all data retrieval operations:
class CryptoDataCollector:
    def fetch_ohlcv(symbol, timeframe, limit):
        """Fetches OHLCV data with caching"""
        # Returns: timestamp, open, high, low, close, volume
        # Adds: returns, log_returns
        
    def get_current_price(symbol):
        """Real-time price retrieval"""
        
    def get_24h_stats(symbol):
        """24-hour statistics and metrics"""
Features:
  • Supports multiple exchanges via CCXT (default: Kraken)
  • Built-in caching with configurable TTL (60 seconds)
  • Automatic rate limiting
  • Error handling and retry logic
  • Calculates returns and log returns automatically
Data Flow:
  1. User selects cryptocurrency and timeframe in sidebar
  2. CryptoDataCollector.fetch_ohlcv() queries exchange API
  3. Raw OHLCV data is cached in Streamlit session
  4. Data is enriched with calculated returns
  5. DataFrame is passed to technical indicators layer

2. Technical Analysis Layer

Location: utils/indicators.py The TechnicalIndicators class provides comprehensive technical analysis:
class TechnicalIndicators:
    @staticmethod
    def calculate_rsi(data, periods=14):
        """Relative Strength Index"""
        # Measures momentum (0-100 scale)
        
    @staticmethod
    def calculate_macd(data, fast=12, slow=26, signal=9):
        """Moving Average Convergence Divergence"""
        # Returns: macd, signal_line, histogram
        
    @staticmethod
    def calculate_bollinger_bands(data, period=20, std_dev=2):
        """Volatility bands"""
        # Returns: upper, middle, lower
        
    @staticmethod
    def calculate_ema(data, period):
        """Exponential Moving Average"""
        # Computed for periods: 9, 21, 50, 200
Signal Generation: The system generates trading signals from technical indicators:
  • RSI Signals: Overbought (>70), Oversold (<30)
  • MACD Signals: Bullish (MACD > Signal), Bearish (MACD < Signal)
  • Overall Signal: Aggregates multiple indicators for buy/sell/neutral

3. Machine Learning Layer

Location: models/ Three specialized predictive models work together:
Best for: 1-72 hours (short-term trading)
  • Gradient boosted decision trees
  • 60+ engineered features
  • Fast training and inference
  • High accuracy for intraday predictions
See Models for details.

4. Visualization Layer

Location: app.py (chart functions) Three main chart types are generated:
1

Main Price Chart

Candlestick chart with volume subplot
  • OHLCV candlesticks
  • EMA overlays (50, 200)
  • Bollinger Bands
  • Volume bars with direction coloring
  • Time range selectors (24H, 2D, 7D, All)
2

Prediction Chart

Historical data with future forecasts
  • Last 336 hours of historical context
  • Predicted price line with confidence intervals
  • “Now” marker showing current time/price
  • Model comparison mode (optional)
3

Technical Indicators Chart

Dedicated charts for RSI and MACD
  • RSI with overbought/oversold lines
  • MACD with signal line and histogram
  • Unified hover mode

5. Alert System

Location: utils/alerts.py, utils/telegram_notifier.py Multi-channel alerting system:
# Alert types supported
alert_types = [
    "Precio",      # Price threshold
    "RSI",         # RSI overbought/oversold
    "Cambio %"     # Percentage change
]

# Conditions
conditions = ["Mayor que", "Menor que"]

# Delivery channels
- In-app notifications
- Telegram messages (if configured)
Alert Flow:
  1. User creates alert with condition/threshold
  2. Alert stored in st.session_state.alerts
  3. Background check evaluates conditions
  4. If triggered, notification sent via Telegram
  5. Alert displayed in dashboard

Data Flow

Complete Request Cycle

Session State Management

The application maintains state across interactions:
st.session_state.collector         # CryptoDataCollector instance
st.session_state.data             # Current OHLCV DataFrame
st.session_state.predictor_xgb    # XGBoost model instance
st.session_state.predictor_prophet # Prophet model instance
st.session_state.predictor_hybrid  # Hybrid model instance
st.session_state.model_trained    # Boolean training flag
st.session_state.predictions      # Latest predictions
st.session_state.backtest_results # Validation metrics
st.session_state.selected_model   # Current model choice
st.session_state.alerts           # Active alerts list
st.session_state.telegram_notifier # Telegram client

Configuration System

Location: config/settings.py Centralized configuration using environment variables:
BINANCE_API_KEY = os.getenv('BINANCE_API_KEY', '')
BINANCE_API_SECRET = os.getenv('BINANCE_API_SECRET', '')
AVAILABLE_CRYPTOS = [
    'BTC/USDT', 'ETH/USDT', 'BNB/USDT', 'SOL/USDT',
    'ADA/USDT', 'XRP/USDT', 'DOGE/USDT', 'DOT/USDT',
    'MATIC/USDT', 'AVAX/USDT', 'LINK/USDT', 'UNI/USDT'
]

TIMEFRAMES = {
    '1m': '1 minuto', '5m': '5 minutos', '15m': '15 minutos',
    '1h': '1 hora', '4h': '4 horas', '1d': '1 día'
}
MODELS_CONFIG = {
    'xgboost': {
        'n_estimators': 200,
        'learning_rate': 0.07,
        'max_depth': 6,
        'subsample': 0.8,
        'colsample_bytree': 0.8
    },
    'prophet': {
        'changepoint_prior_scale': 0.5,
        'seasonality_prior_scale': 10,
        'daily_seasonality': True,
        'weekly_seasonality': True
    }
}
INDICATORS_CONFIG = {
    'rsi_period': 14,
    'macd_fast': 12,
    'macd_slow': 26,
    'macd_signal': 9,
    'bb_period': 20,
    'bb_std': 2,
    'ema_periods': [9, 21, 50, 200]
}

Performance Optimizations

Caching

Streamlit’s @st.cache_data decorator caches:
  • Exchange API calls (60s TTL)
  • Technical indicator calculations
  • Model predictions

Lazy Loading

Models are loaded only when needed:
  • XGBoost imported conditionally
  • Prophet imported conditionally
  • Fallback to available models

Vectorization

NumPy/Pandas operations:
  • Vectorized indicator calculations
  • Batch predictions
  • Efficient data transformations

Session Persistence

Models persist in session:
  • Train once, predict many times
  • Reuse scalers and feature sets
  • Avoid redundant computations

Error Handling

Robust error handling at every layer:
1

API Errors

Exchange connection failures handled gracefully with user-friendly messages
2

Data Validation

Minimum data points enforced (500+), empty DataFrames detected
3

Model Errors

Training failures caught with informative error messages
4

Feature Engineering

NaN values from indicators are dropped automatically

Security Considerations

API keys and secrets are loaded from environment variables (.env file) and never committed to version control.
The system uses read-only API access for data collection. No trading operations are performed.

Scalability

The architecture supports scaling in several dimensions:
  • Horizontal: Multiple instances can run independently
  • Data Sources: Easy to add new exchanges via CCXT
  • Models: New ML models can be integrated with minimal changes
  • Cryptos: Simply add symbols to AVAILABLE_CRYPTOS list
  • Indicators: Extend TechnicalIndicators class with new calculations

Next Steps

ML Models

Dive deep into XGBoost, Prophet, and Hybrid model architectures

Technical Indicators

Learn about RSI, MACD, Bollinger Bands, and signal generation

Build docs developers (and LLMs) love