hyperliquid-monitor-plus 4.0.0
Advanced Production-Ready Whale Tracking & Intelligence System for Hyperliquid DEX
License: MIT
Requires Python: <3.14,>=3.9
Keywords: ai, crypto, dashboard, dex, hyperliquid, intelligence, ml, monitoring, tracking, trading, whale

# Hyperliquid Monitor Plus

<div align="center">

[![PyPI version](https://badge.fury.io/py/hyperliquid-monitor-plus.svg)](https://badge.fury.io/py/hyperliquid-monitor-plus)
[![Python](https://img.shields.io/pypi/pyversions/hyperliquid-monitor-plus.svg)](https://pypi.org/project/hyperliquid-monitor-plus/)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://pepy.tech/badge/hyperliquid-monitor-plus)](https://pepy.tech/project/hyperliquid-monitor-plus)

> **💝 Found this library useful? Support continued development:**  
> **🔗 Wallet:** `0xB05675CE390c895133dE8Aa1A873484f1FA1Df2C` *(Any amount appreciated!)*

**Advanced Production-Ready Whale Tracking & Intelligence System for Hyperliquid DEX**

A comprehensive, enterprise-grade Python library for real-time monitoring, tracking, and analyzing whale wallet transactions on Hyperliquid DEX. Built with production-ready features including ML-powered intelligence, cross-chain tracking, advanced analytics, PnL management, and real-time dashboards.

---

## 🚀 Key Features

### Core Monitoring
- **Real-time Trade Tracking**: Monitor whale wallet fills (executed trades) with WebSocket streaming
- **Multi-Address Support**: Track multiple wallet addresses simultaneously
- **Thread-Safe Operations**: Production-ready with concurrent access handling
- **Automatic Database Storage**: SQLite-based persistent storage with optimized queries
- **Correct Side Mapping**: Properly handles Hyperliquid's side encoding (A=SELL, B=BUY)

### Advanced Analytics & Intelligence
- **Whale Tier Classification**: Automatic categorization (Minnow, Dolphin, Whale, Mega Whale, Giant Whale)
- **Market Impact Analysis**: Predict price impact, slippage, and optimal entry timing
- **Volume Anomaly Detection**: Identify unusual trading volumes and patterns
- **Correlation Engine**: Track correlations between whale movements and market behavior
- **Sentiment Analysis**: Integrate social sentiment into trading decisions
- **Pattern Recognition**: ML-powered detection of recurring whale behaviors

### PnL & Position Management
- **Real-Time PnL Tracking**: Automatic profit/loss calculation per coin and portfolio
- **Position Tracking**: Live position monitoring with liquidation risk alerts
- **Unrealized PnL**: Dynamic calculation with current market prices
- **Portfolio Analytics**: Comprehensive statistics, win rates, best/worst performers
- **Risk Assessment**: Leverage tracking, margin monitoring, liquidation distance

### Smart Alert System
- **Flexible Conditions**: Custom alerts based on volume, price, coins, addresses
- **Alert Levels**: Info, Warning, Critical with different notification strategies
- **Filter System**: Advanced trade filtering by multiple criteria
- **Alert History**: Track and analyze past alerts
- **Callback Support**: Integrate with Discord, Telegram, or custom notifications

### ML & Advanced Features (Phase 3)
- **Machine Learning Models**: Predict whale behavior and price movements
- **Cross-Chain Analytics**: Track whale activity across multiple blockchains
- **Portfolio Optimization**: AI-powered position sizing and risk management
- **Real-Time Dashboard**: Beautiful web interface with live updates
- **Predictive Intelligence**: Forecast whale movements and market trends

### Notifications & Integrations
- **Discord Integration**: Automated alerts to Discord channels
- **Telegram Bots**: Real-time notifications via Telegram
- **Custom Webhooks**: Integrate with any external service
- **Report Generation**: Automated HTML, PDF, and JSON reports

---

## 📦 Installation

### Basic Installation

```bash
pip install hyperliquid-monitor-plus
```

### Installation with Optional Features

```bash
# For visualization support (charts, graphs)
pip install hyperliquid-monitor-plus[viz]

# For machine learning features
pip install hyperliquid-monitor-plus[ml]

# For web dashboard
pip install hyperliquid-monitor-plus[web]

# For Discord/Telegram notifications
pip install hyperliquid-monitor-plus[notifications]

# For development (testing, linting, type checking)
pip install hyperliquid-monitor-plus[dev]

# Install everything
pip install hyperliquid-monitor-plus[all]
```

### From Source

```bash
git clone https://github.com/Pezhman5252/hyperliquid_monitor_plus.git
cd hyperliquid_monitor_plus
pip install -e .
```

---

## 🎯 Quick Start

### 1. Basic Whale Monitoring

```python
from hyperliquid_monitor_plus import HyperliquidMonitor, Trade

# Define callback for trades
def on_trade(trade: Trade):
    print(f"🐋 Whale Trade Detected!")
    print(f"   Coin: {trade.coin}")
    print(f"   Side: {trade.side}")
    print(f"   Size: {trade.size} @ ${trade.price}")
    print(f"   Value: ${trade.size * trade.price:,.2f}")
    print(f"   Address: {trade.address[:10]}...")
    if trade.leverage:
        print(f"   Leverage: {trade.leverage}x")
    print()

# Initialize monitor
monitor = HyperliquidMonitor(
    addresses=[
        "0x1234567890123456789012345678901234567890",  # Replace with actual whale address
        "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"   # Add more addresses
    ],
    db_path="whale_trades.db",  # Optional: store trades in database
    callback=on_trade,
    track_pnl=True  # Enable automatic PnL tracking
)

# Start monitoring
monitor.start()
```

### 2. Monitor with Alert System

```python
from hyperliquid_monitor_plus import (
    HyperliquidMonitor,
    AlertManager,
    AlertCondition,
    AlertLevel,
    AlertType
)

# Create alert callback
def on_alert(alert):
    print(f"🚨 ALERT [{alert.level}]: {alert.message}")
    if alert.level == "CRITICAL":
        # Send urgent notification
        print(f"   URGENT: {alert.trade.coin} - ${alert.trade.size * alert.trade.price:,.0f}")

# Setup alert manager
alert_manager = AlertManager(alert_callback=on_alert)

# Add alert conditions
alert_manager.add_condition(
    AlertCondition(
        name="Large BTC Trade",
        alert_type=AlertType.LARGE_TRADE,
        level=AlertLevel.CRITICAL,
        min_volume_usd=1_000_000,  # $1M+ trades
        coins=["BTC"]
    )
)

alert_manager.add_condition(
    AlertCondition(
        name="ETH Whale Activity",
        alert_type=AlertType.WHALE_ACTIVITY,
        level=AlertLevel.WARNING,
        min_volume_usd=500_000,  # $500K+ trades
        coins=["ETH"]
    )
)

alert_manager.add_condition(
    AlertCondition(
        name="Any SELL Over $250K",
        alert_type=AlertType.VOLUME_SPIKE,
        level=AlertLevel.INFO,
        min_volume_usd=250_000,
        sides=["SELL"]
    )
)

# Start monitoring with alerts
monitor = HyperliquidMonitor(
    addresses=["0x1234..."],
    db_path="whale_trades.db",
    alert_callback=on_alert,
    track_pnl=True
)

monitor.start()
```

### 3. Advanced PnL Tracking

```python
from hyperliquid_monitor_plus import HyperliquidMonitor, PnLManager

# Create PnL callback
def on_pnl_update(pnl_record):
    if pnl_record.pnl > 0:
        print(f"✅ Profitable Close: {pnl_record.coin}")
    else:
        print(f"❌ Loss Taken: {pnl_record.coin}")
    print(f"   PnL: ${pnl_record.pnl:,.2f}")
    print(f"   Entry: ${pnl_record.entry_price:.2f} -> Exit: ${pnl_record.exit_price:.2f}")
    print(f"   Size: {pnl_record.size}")

# Initialize with PnL tracking
monitor = HyperliquidMonitor(
    addresses=["0x1234..."],
    db_path="whale_trades.db",
    pnl_callback=on_pnl_update,
    track_pnl=True
)

# Access PnL manager
pnl_manager = monitor.pnl_manager

# Start monitoring
monitor.start()

# In another thread/after some trades, you can query:
# Get portfolio statistics
stats = pnl_manager.get_statistics()
print(f"Total Realized PnL: ${stats['total_realized_pnl']:,.2f}")
print(f"Total Unrealized PnL: ${stats['total_unrealized_pnl']:,.2f}")
print(f"Net PnL (after fees): ${stats['net_pnl']:,.2f}")
print(f"Win Rate: {stats['win_rate']:.1f}%")

# Get specific coin PnL
btc_pnl = pnl_manager.get_coin_pnl("BTC")
if btc_pnl:
    print(f"BTC Trades: {btc_pnl.trades_count}")
    print(f"BTC Realized PnL: ${btc_pnl.realized_pnl:,.2f}")
    print(f"BTC Win/Loss: {btc_pnl.winning_trades}/{btc_pnl.losing_trades}")

# Generate summary report
report = pnl_manager.get_summary_report()
print(report)
```

### 4. Live Position Tracking

```python
from hyperliquid_monitor_plus import PositionTracker

# Create position change callback
def on_position_change(change):
    print(f"📍 Position {change.event_type}: {change.coin}")
    if change.old_position:
        print(f"   Old: {change.old_position.side} {change.old_position.size}")
    if change.new_position:
        print(f"   New: {change.new_position.side} {change.new_position.size}")
    print(f"   Size Change: {change.size_change:+.4f}")
    print(f"   PnL Change: ${change.pnl_change:+,.2f}")

# Initialize position tracker
tracker = PositionTracker(
    address="0x1234567890123456789012345678901234567890",
    position_callback=on_position_change
)

# Fetch current positions
snapshot = tracker.fetch_positions()
print(f"Total Unrealized PnL: ${snapshot.total_unrealized_pnl:,.2f}")
print(f"Margin Used: ${snapshot.total_margin_used:,.2f}")
print(f"Account Value: ${snapshot.account_value:,.2f}")

# Get open positions
open_positions = tracker.get_open_positions()
for coin, position in open_positions.items():
    print(f"{coin}: {position.side} {position.size} @ ${position.entry_price:.2f}")
    print(f"  Mark Price: ${position.mark_price:.2f}")
    print(f"  Unrealized PnL: ${position.unrealized_pnl:,.2f} ({position.pnl_percentage:+.2f}%)")
    print(f"  Leverage: {position.leverage}x")
    if position.liquidation_price:
        print(f"  Liquidation: ${position.liquidation_price:.2f} ({position.distance_to_liquidation:.1f}% away)")

# Check risky positions
risky = tracker.get_risky_positions(threshold=15.0)  # 15% from liquidation
if risky:
    print(f"⚠️ WARNING: {len(risky)} position(s) at risk!")
    for pos in risky:
        print(f"  {pos.coin}: {pos.distance_to_liquidation:.1f}% to liquidation")

# Get comprehensive statistics
stats = tracker.get_statistics()
print(f"Open Positions: {stats['open_positions_count']}")
print(f"Best Position: {stats['best_position']} (${stats['best_pnl']:,.2f})")
print(f"Worst Position: {stats['worst_position']} (${stats['worst_pnl']:,.2f})")
```

---

## 📚 Comprehensive Usage Guide

### Working with the Database

```python
from hyperliquid_monitor_plus import Database, init_database

# Initialize database
db_path = "whale_trades.db"
db = init_database(db_path)

# Or use Database class directly
db = Database(db_path)

# Query recent trades
recent_trades = db.get_recent_trades(limit=10)
for trade in recent_trades:
    print(f"{trade.timestamp} - {trade.coin} {trade.side} {trade.size} @ ${trade.price}")

# Query trades by coin
btc_trades = db.get_trades_by_coin("BTC", limit=50)
print(f"Found {len(btc_trades)} BTC trades")

# Query trades by address
whale_trades = db.get_trades_by_address("0x1234...", limit=100)

# Query trades by date range
from datetime import datetime, timedelta
start_date = datetime.now() - timedelta(days=7)
end_date = datetime.now()
weekly_trades = db.get_trades_by_date_range(start_date, end_date)

# Get trade statistics
stats = db.get_trade_statistics(coin="ETH")
print(f"Total ETH Volume: ${stats['total_volume']:,.2f}")
print(f"Average Trade Size: {stats['avg_size']:.4f}")
print(f"Largest Trade: {stats['max_size']:.4f} @ ${stats['max_price']:.2f}")

# Get unique coins and addresses
coins = db.get_unique_coins()
addresses = db.get_unique_addresses()

# Close database when done
db.close()
```

### Advanced Alert Configuration

```python
from hyperliquid_monitor_plus import (
    AlertManager,
    AlertCondition,
    AlertLevel,
    AlertType,
    TradeFilter
)

alert_manager = AlertManager()

# Multi-coin large trade alert
alert_manager.add_condition(
    AlertCondition(
        name="Major Altcoin Movement",
        alert_type=AlertType.LARGE_TRADE,
        level=AlertLevel.WARNING,
        min_volume_usd=100_000,
        coins=["SOL", "AVAX", "ARB", "OP"],
        message_template="🔔 Large {side} on {coin}: {size} @ ${price} (${volume_usd:,.0f})"
    )
)

# Specific address monitoring
alert_manager.add_condition(
    AlertCondition(
        name="Known Whale Activity",
        alert_type=AlertType.WHALE_ACTIVITY,
        level=AlertLevel.CRITICAL,
        addresses=["0xspecificwhale..."],
        min_volume_usd=50_000,
        message_template="🐋 Known whale {address} {side} {coin}: ${volume_usd:,.0f}"
    )
)

# Liquidation monitoring (based on side patterns)
alert_manager.add_condition(
    AlertCondition(
        name="Possible Liquidations",
        alert_type=AlertType.LIQUIDATION,
        level=AlertLevel.INFO,
        min_volume_usd=200_000,
        sides=["SELL"],
        message_template="⚡ Potential liquidation: {coin} - ${volume_usd:,.0f}"
    )
)

# Enable/disable conditions dynamically
alert_manager.disable_condition("Known Whale Activity")
alert_manager.enable_condition("Known Whale Activity")

# Update condition parameters
alert_manager.update_condition(
    "Major Altcoin Movement",
    min_volume_usd=150_000,
    level=AlertLevel.CRITICAL
)

# Get alert statistics
stats = alert_manager.get_statistics()
print(f"Total Conditions: {stats['total_conditions']}")
print(f"Enabled: {stats['enabled_conditions']}")
print(f"Total Triggered: {stats['total_triggered']}")

# Get alert history
recent_alerts = alert_manager.get_history(limit=20)
for alert in recent_alerts:
    print(f"[{alert.timestamp}] {alert.level}: {alert.message}")
```

### Strategy Analysis

```python
from hyperliquid_monitor_plus import StrategyAnalyzer

# Initialize analyzer with trade history
analyzer = StrategyAnalyzer(address="0x1234...")

# Analyze trading patterns
metrics = analyzer.analyze_trading_strategy(
    start_date=datetime.now() - timedelta(days=30),
    end_date=datetime.now()
)

print("📊 Strategy Metrics:")
print(f"  Total Trades: {metrics.total_trades}")
print(f"  Win Rate: {metrics.win_rate:.1f}%")
print(f"  Profit Factor: {metrics.profit_factor:.2f}")
print(f"  Sharpe Ratio: {metrics.sharpe_ratio:.2f}")
print(f"  Max Drawdown: {metrics.max_drawdown:.1f}%")
print(f"  Average Trade Duration: {metrics.avg_trade_duration}")

# Identify trade patterns
patterns = analyzer.identify_patterns()
for pattern in patterns:
    print(f"Pattern: {pattern.type}")
    print(f"  Frequency: {pattern.frequency}")
    print(f"  Success Rate: {pattern.success_rate:.1f}%")
    print(f"  Avg PnL: ${pattern.avg_pnl:,.2f}")

# Time-based analysis
time_analysis = analyzer.analyze_by_time_of_day()
print("\n⏰ Trading Activity by Hour:")
for hour, stats in time_analysis.items():
    print(f"  {hour}:00 - Trades: {stats['count']}, Win Rate: {stats['win_rate']:.1f}%")

# Coin performance comparison
coin_comparison = analyzer.compare_coin_performance()
print("\n💰 Best Performing Coins:")
for coin, metrics in coin_comparison[:5]:
    print(f"  {coin}: ${metrics.total_pnl:,.2f} ({metrics.win_rate:.1f}% win rate)")
```

### Whale Bot Intelligence System

```python
from hyperliquid_monitor_plus import (
    WhaleBotCore,
    WhaleBotConfig,
    EnhancedTrade,
    WhaleDetectionEvent
)

# Configure whale bot
config = WhaleBotConfig(
    min_whale_threshold=100_000,  # $100K minimum
    mega_whale_threshold=1_000_000,  # $1M for mega whale
    giant_whale_threshold=5_000_000,  # $5M for giant whale
    max_response_time_ms=100,  # 100ms max processing time
    follow_ratio=0.1,  # Follow with 10% of whale size
    max_position_risk=0.05,  # Max 5% of portfolio per position
    enable_real_time_alerts=True,
    dashboard=False
)

# Create whale bot
whale_bot = WhaleBotCore(config)

# Add detection callback
def on_whale_detected(enhanced_trade: EnhancedTrade):
    print(f"🐋 {enhanced_trade.whale_tier.value} Detected!")
    print(f"   {enhanced_trade.coin}: {enhanced_trade.whale_direction}")
    print(f"   Size: ${enhanced_trade.size_usd:,.0f}")
    print(f"   Urgency: {enhanced_trade.urgency}")
    print(f"   Market Impact: {enhanced_trade.market_impact:.3f}%")
    print(f"   Slippage: {enhanced_trade.slippage:.3f}%")
    print(f"   Follow Opportunity: {enhanced_trade.follow_opportunity}")

whale_bot.add_detection_callback(on_whale_detected)

# Add follow recommendation callback
def on_follow_recommendation(recommendation):
    if recommendation.action == "FOLLOW":
        print(f"✅ FOLLOW RECOMMENDATION")
        print(f"   Confidence: {recommendation.confidence:.1%}")
        print(f"   Reasoning: {recommendation.reasoning}")
        print(f"   Position Size: {recommendation.position_size_ratio:.1%}")
        print(f"   Entry Delay: {recommendation.optimal_entry_delay}s")
        print(f"   Stop Loss: {recommendation.stop_loss_ratio:.1%}")
        print(f"   Take Profit Levels: {recommendation.take_profit_levels}")
    elif recommendation.action == "HEDGE":
        print(f"⚠️ HEDGE RECOMMENDED: {recommendation.reasoning}")
    else:
        print(f"🚫 SKIP: {recommendation.reasoning}")

whale_bot.add_follow_callback(on_follow_recommendation)

# Start whale monitoring
addresses = ["0xwhale1...", "0xwhale2..."]
whale_bot.start_monitoring(addresses, db_path="whale_intelligence.db")

# Get bot statistics
stats = whale_bot.get_bot_statistics()
print(f"Status: {stats['status']}")
print(f"Whales Detected: {stats['performance']['whales_detected']}")
print(f"Follow Recommendations: {stats['performance']['follow_recommendations']}")
print(f"Avg Processing Time: {stats['performance']['avg_processing_time_ms']:.1f}ms")
```

### Report Generation

```python
from hyperliquid_monitor_plus import (
    ReportGenerator,
    ReportConfig,
    ReportFormat,
    ReportType,
    ReportPeriod
)

# Configure report
report_config = ReportConfig(
    report_type=ReportType.PORTFOLIO,
    period=ReportPeriod.WEEKLY,
    format=ReportFormat.HTML,
    include_charts=True,
    include_trades_table=True,
    include_pnl_breakdown=True,
    output_path="reports/"
)

# Create report generator
generator = ReportGenerator(
    db_path="whale_trades.db",
    config=report_config
)

# Generate report
report = generator.generate_report(
    start_date=datetime.now() - timedelta(days=7),
    end_date=datetime.now()
)

print(f"Report generated: {report.file_path}")
print(f"Report size: {report.file_size_kb:.1f} KB")
print(f"Trades analyzed: {report.trades_count}")
print(f"Charts generated: {report.charts_count}")

# Generate multiple formats
for fmt in [ReportFormat.HTML, ReportFormat.PDF, ReportFormat.JSON]:
    report_config.format = fmt
    report = generator.generate_report()
    print(f"Generated {fmt.value} report: {report.file_path}")
```

### Notification Integration

```python
from hyperliquid_monitor_plus import (
    NotificationManager,
    TelegramConfig,
    DiscordConfig,
    NotificationPriority
)

# Setup Telegram
telegram_config = TelegramConfig(
    bot_token="YOUR_BOT_TOKEN",
    chat_id="YOUR_CHAT_ID",
    parse_mode="Markdown"
)

# Setup Discord
discord_config = DiscordConfig(
    webhook_url="YOUR_DISCORD_WEBHOOK_URL",
    username="Whale Bot",
    avatar_url="https://example.com/whale-icon.png"
)

# Create notification manager
notif_manager = NotificationManager()
notif_manager.add_telegram(telegram_config)
notif_manager.add_discord(discord_config)

# Send notifications
def on_large_trade(trade):
    message = f"""
🐋 **Large Whale Trade Detected**

**Coin:** {trade.coin}
**Side:** {trade.side}
**Size:** {trade.size:,.4f}
**Price:** ${trade.price:,.2f}
**Value:** ${trade.size * trade.price:,.0f}
**Leverage:** {trade.leverage}x
**Address:** `{trade.address[:10]}...`
    """
    
    # Send to both Telegram and Discord
    notif_manager.send(
        message=message,
        priority=NotificationPriority.HIGH,
        channels=["telegram", "discord"]
    )

# Use with monitor
monitor = HyperliquidMonitor(
    addresses=["0x1234..."],
    callback=on_large_trade
)
```

---

## 🎓 Advanced Features

### Phase 3: ML & Advanced Analytics

```python
from hyperliquid_monitor_plus import (
    WhaleBotCore,
    Phase3Config,
    get_phase3_config
)
import asyncio

# Configure Phase 3 features
phase3_config = get_phase3_config("advanced")
phase3_config.ml_model_enabled = True
phase3_config.cross_chain_enabled = True
phase3_config.dashboard_enabled = True
phase3_config.dashboard_port = 8080
phase3_config.portfolio_optimization_enabled = True

# Create whale bot with Phase 3 capabilities
whale_bot = WhaleBotCore(
    config=whale_bot_config,
    phase3_config=phase3_config
)

# Start advanced features
async def run_advanced_features():
    # Start ML models, cross-chain tracking, and dashboard
    await whale_bot.start_advanced_features()
    
    # Monitor whale activity
    whale_bot.start_monitoring(addresses, "advanced_whale_db.db")
    
    # Run ML prediction for a trade
    prediction = await whale_bot.run_ml_prediction(enhanced_trade)
    if prediction:
        print(f"ML Prediction: {prediction['behavior_score']:.2f}")
        print(f"Price Forecast: ${prediction['predicted_price']:.2f}")
    
    # Track cross-chain activity
    cross_chain_data = await whale_bot.track_cross_chain_activity(enhanced_trade)
    if cross_chain_data:
        print(f"Cross-chain activity detected: {cross_chain_data['chains']}")
    
    # Run portfolio optimization
    optimization = await whale_bot.optimize_portfolio()
    if optimization:
        print("Recommended portfolio adjustments:")
        for coin, recommendation in optimization['adjustments'].items():
            print(f"  {coin}: {recommendation['action']} {recommendation['size']}")
    
    # Get Phase 3 status
    status = await whale_bot.get_phase3_status()
    print(f"ML Models Active: {status['components']['ml_manager']['active_models']}")
    print(f"Cross-chain Whales Tracked: {status['components']['cross_chain_tracker']['whales_tracked']}")
    print(f"Dashboard Running: Port {status['components']['dashboard']['port']}")

# Run the async application
asyncio.run(run_advanced_features())
```

### Cross-Chain Whale Tracking

```python
from hyperliquid_monitor_plus import CrossChainAnalytics, CrossChainMonitor

# Initialize cross-chain analytics
cross_chain = CrossChainAnalytics(
    chains=["ethereum", "arbitrum", "optimism", "base"],
    whale_address="0x1234..."
)

# Track whale across chains
async def track_whale_movements():
    # Get whale activity summary
    summary = await cross_chain.get_whale_summary()
    print(f"Total Value Across Chains: ${summary['total_value_usd']:,.0f}")
    print(f"Active Chains: {summary['active_chains']}")
    
    # Check for coordinated movements
    movements = await cross_chain.detect_coordinated_movements()
    if movements:
        print("⚠️ Coordinated cross-chain activity detected!")
        for movement in movements:
            print(f"  Chain: {movement['chain']}")
            print(f"  Action: {movement['action']}")
            print(f"  Value: ${movement['value_usd']:,.0f}")
            print(f"  Timing: {movement['timing_correlation']:.1%} correlated")

asyncio.run(track_whale_movements())
```

### Real-Time Dashboard

The library includes a beautiful real-time web dashboard for monitoring whale activity:

```python
from hyperliquid_monitor_plus import RealTimeDashboard, AdvancedWhaleBot

# Create whale bot
whale_bot = AdvancedWhaleBot(config)

# Create dashboard
dashboard = RealTimeDashboard(
    whale_bot=whale_bot,
    port=8080,
    host="0.0.0.0"
)

# Start dashboard
async def run_dashboard():
    await dashboard.start_dashboard()
    print("Dashboard running at http://localhost:8080")
    
    # Keep running
    while True:
        await asyncio.sleep(1)

asyncio.run(run_dashboard())
```

Visit `http://localhost:8080` to see:
- Real-time whale trade feed
- Interactive charts and graphs
- Position tracking
- PnL visualization
- Alert notifications
- Market impact analysis

---

## 🛠️ CLI Tools

### Hyperliquid Monitor CLI

```bash
# Basic monitoring
hyperliquid-monitor --address 0x1234... --db whale_trades.db

# Multiple addresses
hyperliquid-monitor --addresses 0x1234... 0x5678... --db trades.db

# With alerts
hyperliquid-monitor --address 0x1234... --alert-discord --db trades.db

# Telegram alerts (requires TELEGRAM_BOT_TOKEN env var)
hyperliquid-monitor --address 0x1234... --alert-telegram

# Silent mode (only database storage)
hyperliquid-monitor --address 0x1234... --db trades.db --silent

# Verbose logging
hyperliquid-monitor --address 0x1234... --db trades.db --verbose

# Disable PnL tracking
hyperliquid-monitor --address 0x1234... --db trades.db --no-pnl

# Dry run (test configuration)
hyperliquid-monitor --address 0x1234... --dry-run
```

### Whale Bot CLI

```bash
# Conservative mode (default)
hyperliquid-whale-bot --address 0x1234... --config config.yaml

# Aggressive mode
hyperliquid-whale-bot --addresses 0x1234... 0x5678... --aggressive-mode

# Demo mode (no real trading)
hyperliquid-whale-bot --address 0x1234... --demo

# Custom parameters
hyperliquid-whale-bot --address 0x1234... \
    --min-whale-size 500000 \
    --max-whales 10 \
    --log-level DEBUG

# Multiple addresses with aggressive strategy
hyperliquid-whale-bot --addresses 0x1234... 0x5678... 0x9abc... \
    --aggressive-mode \
    --min-whale-size 1000000
```

---

## 🛡️ Advanced Risk Management System

Comprehensive risk monitoring and management system for whale tracking.

### Core Risk Classes

```python
from hyperliquid_monitor_plus.risk import (
    AdvancedRiskManager,
    RiskMetrics,
    PositionRisk,
    MarketRisk,
    RiskAlert
)
```

### Key Features

- **Real-time Risk Monitoring**: Continuous assessment of portfolio and position risks
- **Position-specific Analysis**: Individual position risk breakdown
- **Market Regime Detection**: Automatic identification of market conditions
- **Correlation Risk Assessment**: Cross-asset correlation analysis
- **Automated Risk Alerts**: Configurable risk threshold alerts

### Risk Management Example

```python
# Initialize risk manager
risk_manager = AdvancedRiskManager(config)

# Monitor portfolio risk
risk_metrics = await risk_manager.assess_portfolio_risk(positions)
print(f"Portfolio Risk: {risk_metrics.portfolio_risk:.2%}")
print(f"Position Risk: {risk_metrics.position_risk:.2%}")
print(f"Correlation Risk: {risk_metrics.correlation_risk:.2%}")

# Analyze specific position
position_risk = await risk_manager.analyze_position_risk("BTC", position)
if position_risk.risk_level == "HIGH":
    print(f"⚠️ High risk position: {position_risk.symbol}")
    print(f"   Risk Score: {position_risk.total_risk:.2%}")
    print(f"   Var 95%: ${position_risk.var_95_usd:,.2f}")

# Check market conditions
market_risk = await risk_manager.assess_market_conditions()
print(f"Market Regime: {market_risk.market_regime}")
print(f"Volatility Level: {market_risk.volatility_level:.2%}")
print(f"Liquidity: {market_risk.liquidity_conditions}")

# Get risk alerts
alerts = await risk_manager.get_active_risk_alerts()
for alert in alerts:
    print(f"🚨 {alert.severity}: {alert.message}")
    print(f"   Recommended Action: {alert.recommended_action}")
```

---

## 💼 Portfolio Optimization System

AI-powered portfolio optimization with whale intelligence integration.

### Core Optimization Classes

```python
from hyperliquid_monitor_plus.optimization import (
    PortfolioOptimizer,
    RiskAnalyzer,
    WhaleOpportunityDetector,
    PortfolioMetrics,
    OptimizationConstraints
)
```

### Key Features

- **AI-powered Portfolio Rebalancing**: Intelligent allocation optimization
- **Whale Trading Opportunity Detection**: Identify follow/hedge opportunities
- **Risk-adjusted Optimization**: VaR and volatility constrained optimization
- **Correlation-aware Allocation**: Multi-asset correlation consideration
- **Real-time Portfolio Monitoring**: Live portfolio performance tracking

### Portfolio Optimization Example

```python
# Initialize portfolio optimizer
optimizer = PortfolioOptimizer(config)

# Optimize current portfolio
optimization_result = await optimizer.optimize_portfolio(positions)
print("📊 Portfolio Optimization Results:")
print(f"Expected Return: {optimization_result.expected_return:.2%}")
print(f"Portfolio Risk: {optimization_result.portfolio_risk:.2%}")
print(f"Sharpe Ratio: {optimization_result.sharpe_ratio:.2f}")

print("\n📈 Recommended Allocation:")
for asset, weight in optimization_result.recommended_weights.items():
    current_weight = positions.get(asset, {}).get('weight', 0)
    change = weight - current_weight
    print(f"  {asset}: {weight:.2%} (change: {change:+.2%})")

# Detect whale opportunities
opportunities = await optimizer.opportunity_detector.detect_follow_opportunities(whale_trades)
for opp in opportunities:
    print(f"\n🐋 Whale Opportunity Detected:")
    print(f"   Asset: {opp.asset}")
    print(f"   Type: {opp.opportunity_type}")
    print(f"   Expected Return: {opp.expected_return:.2%}")
    print(f"   Confidence: {opp.confidence:.1%}")
    print(f"   Suggested Allocation: {opp.suggested_allocation:.2%}")
    print(f"   Entry Timing: {opp.entry_timing}")

# Get portfolio metrics
metrics = optimizer.risk_analyzer.calculate_portfolio_risk(positions)
print(f"\n📊 Portfolio Metrics:")
print(f"   Total Value: ${metrics.total_value_usd:,.2f}")
print(f"   Daily Return: {metrics.daily_return:.2%}")
print(f"   Sharpe Ratio: {metrics.sharpe_ratio:.2f}")
print(f"   Max Drawdown: {metrics.max_drawdown:.2%}")
print(f"   VaR 95%: ${metrics.var_95:,.2f}")
```

---

## ⚙️ Advanced Configuration Management

Comprehensive configuration system for all library features.

### Configuration Classes

```python
from hyperliquid_monitor_plus.config import (
    Config,
    Phase3Config,
    WhaleBotConfig
)
```

### Configuration Methods

#### Environment Variables

```bash
# Basic API Configuration
export HYPERLIQUID_API_URL="https://api.hyperliquid.xyz"
export HYPERLIQUID_WS_URL="wss://ws.hyperliquid.xyz"
export DATABASE_PATH="whale_trades.db"

# Risk Management Settings
export MAX_POSITION_SIZE=0.25
export MAX_PORTFOLIO_RISK=0.15
export RISK_WARNING_THRESHOLD=0.10
export CRITICAL_RISK_THRESHOLD=0.20

# Portfolio Optimization
export ENABLE_PORTFOLIO_OPTIMIZATION=true
export OPTIMIZATION_INTERVAL_HOURS=1
export MAX_WHALE_CORRELATION=0.7
export REBALANCE_THRESHOLD=0.05

# ML and Intelligence
export ML_MODEL_PATH="/models/"
export ENABLE_SENTIMENT_ANALYSIS=true
export CROSS_CHAIN_ENABLED=true
export SENTIMENT_UPDATE_INTERVAL=300

# Notifications
export DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/..."
export TELEGRAM_BOT_TOKEN="your_bot_token"
export TELEGRAM_CHAT_ID="your_chat_id"
```

#### Configuration Files (YAML)

```yaml
# config.yaml - Complete Configuration

# Core Whale Bot Settings
whale_bot:
  min_whale_threshold: 100000      # $100K minimum
  mega_whale_threshold: 1000000    # $1M for mega whale
  giant_whale_threshold: 5000000   # $5M for giant whale
  max_response_time_ms: 100
  max_whales: 10
  follow_ratio: 0.1               # Follow with 10% of whale size
  max_position_risk: 0.05          # Max 5% risk per position
  enable_real_time_alerts: true
  alert_cooldown_seconds: 30

# Advanced Risk Management
risk_management:
  enabled: true
  max_position_size: 0.25          # 25% max per position
  max_portfolio_risk: 0.15         # 15% max portfolio risk
  high_risk_threshold: 0.10        # Warning at 10%
  critical_risk_threshold: 0.20    # Critical at 20%
  auto_position_management: true
  liquidation_buffer: 0.05         # 5% buffer from liquidation

# Portfolio Optimization
portfolio_optimization:
  enabled: true
  optimization_frequency: "hourly"  # hourly, daily, weekly
  risk_budget: 0.15                # Risk allocation
  correlation_limit: 0.7           # Max correlation between assets
  rebalance_threshold: 0.05        # 5% drift triggers rebalance
  min_trade_size_usd: 1000
  max_turnover: 0.20               # 20% max turnover

# Phase 3 Advanced Features
phase3:
  ml_model_enabled: true
  ml_model_config:
    model_path: "/models/whale_behavior_v3.pkl"
    confidence_threshold: 0.75
    auto_update: true
    update_frequency: "daily"
  
  cross_chain_enabled: true
  cross_chain_config:
    enabled_chains: ["ethereum", "arbitrum", "optimism", "base"]
    sync_frequency_seconds: 30
    enable_coordination_detection: true
  
  dashboard_enabled: true
  dashboard_config:
    port: 8080
    host: "0.0.0.0"
    enable_api: true
    enable_websockets: true
    auth_enabled: false
  
  portfolio_optimization_enabled: true
  optimization_config:
    risk_model: "historical"
    optimization_algorithm: "mean_variance"
    rebalance_frequency: "weekly"
  
  sentiment_analysis_enabled: true
  sentiment_config:
    data_sources: ["twitter", "reddit", "discord"]
    update_interval: 300           # 5 minutes
    sentiment_threshold: 0.1       # Alert threshold

# Notification Channels
notifications:
  discord:
    enabled: true
    webhook_url: "${DISCORD_WEBHOOK_URL}"
    username: "Whale Bot"
    avatar_url: "https://example.com/whale-icon.png"
    alert_levels: ["WARNING", "CRITICAL"]
  
  telegram:
    enabled: true
    bot_token: "${TELEGRAM_BOT_TOKEN}"
    chat_id: "${TELEGRAM_CHAT_ID}"
    parse_mode: "Markdown"
    alert_levels: ["INFO", "WARNING", "CRITICAL"]
  
  email:
    enabled: false
    smtp_server: "smtp.gmail.com"
    smtp_port: 587
    username: "your_email@gmail.com"
    password: "your_app_password"
    recipients: ["admin@yourcompany.com"]

# Database Configuration
database:
  path: "whale_trades.db"
  backup_enabled: true
  backup_interval_hours: 24
  retention_days: 365
  vacuum_interval_days: 7

# Logging Configuration
logging:
  level: "INFO"
  format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
  file_path: "logs/whale_monitor.log"
  max_file_size_mb: 100
  backup_count: 5
  enable_console: true
```

### Configuration Loading Example

```python
# Load configuration from multiple sources
config = Config()

# Load from environment variables
config.load_from_env()

# Load from YAML file
config.load_from_file("config.yaml")

# Load from JSON file
config.load_from_file("config.json")

# Create specific configurations
whale_config = WhaleBotConfig(
    min_whale_threshold=100_000,
    mega_whale_threshold=1_000_000,
    giant_whale_threshold=5_000_000,
    follow_ratio=0.1
)

phase3_config = Phase3Config(
    ml_model_enabled=True,
    cross_chain_enabled=True,
    dashboard_enabled=True,
    dashboard_port=8080
)

# Validate configuration
validation_result = config.validate()
if not validation_result.is_valid:
    print("Configuration errors:")
    for error in validation_result.errors:
        print(f"  - {error}")
```

---

## 📊 Advanced Type System Reference

Comprehensive type definitions for all library features.

### Enhanced Trade Types

```python
from hyperliquid_monitor_plus.core_types.types import (
    EnhancedTrade,
    WhaleTier,
    WhaleDetectionEvent,
    MarketImpactAnalysis,
    TradeUrgency
)

# Trade Urgency Levels
class TradeUrgency(str, Enum):
    LOW = "LOW"        # Normal trading activity
    MEDIUM = "MEDIUM"  # Elevated activity
    HIGH = "HIGH"      # Unusual activity
    CRITICAL = "CRITICAL"  # Emergency/liquidation

# Whale Tier Classification
whale_tier = EnhancedTrade(
    coin="BTC",
    size=100.5,
    price=45000,
    whale_tier=WhaleTier.MEGA_WHALE,
    urgency=TradeUrgency.HIGH,
    market_impact=0.0025,  # 0.25% price impact
    follow_opportunity=True
)
```

### Strategy & Risk Types

```python
from hyperliquid_monitor_plus.core_types.strategy_types import (
    StrategyMetrics,
    RiskAssessment,
    PositionRisk,
    MarketRisk,
    PatternType,
    RecommendationType
)

# Strategy Performance Metrics
metrics = StrategyMetrics(
    total_trades=150,
    win_rate=0.68,
    profit_factor=1.45,
    sharpe_ratio=1.23,
    max_drawdown=0.08,
    avg_trade_duration=timedelta(hours=4.5),
    best_trade_pnl=5000.0,
    worst_trade_pnl=-1200.0
)

# Risk Assessment Types
risk_assessment = RiskAssessment(
    overall_risk_score=0.65,      # 0-1 scale
    position_risk_score=0.45,
    correlation_risk_score=0.78,
    liquidity_risk_score=0.23,
    volatility_risk_score=0.56,
    recommended_actions=[
        "Reduce BTC exposure by 5%",
        "Increase stable coin allocation",
        "Set tighter stop losses"
    ]
)
```

### Portfolio & Optimization Types

```python
from hyperliquid_monitor_plus.optimization.portfolio_optimizer import (
    PortfolioMetrics,
    OptimizationConstraints,
    WhaleOpportunity,
    PortfolioPosition
)

# Portfolio Position
position = PortfolioPosition(
    asset="BTC",
    current_weight=0.25,
    target_weight=0.20,
    market_value_usd=25000,
    entry_price=44000,
    current_price=45000,
    unrealized_pnl=1000,
    whale_exposure=True,
    risk_contribution=0.15
)

# Whale Trading Opportunity
opportunity = WhaleOpportunity(
    opportunity_id="btc_follow_001",
    asset="BTC",
    opportunity_type="FOLLOW",
    expected_return=0.035,        # 3.5% expected return
    confidence=0.78,              # 78% confidence
    risk_level="MEDIUM",
    whale_address="0x1234...",
    suggested_allocation=0.05,    # 5% of portfolio
    entry_timing="immediate"      # immediate, 5min, 15min, 1hour
)
```

### Alert & Notification Types

```python
from hyperliquid_monitor_plus.risk.risk_manager import RiskAlert
from hyperliquid_monitor_plus.alerts.types import AlertType, AlertLevel

# Risk Alert
risk_alert = RiskAlert(
    alert_type="HIGH_RISK_POSITION",
    severity="WARNING",
    message="BTC position approaching liquidation threshold",
    recommended_action="Reduce position size or add margin",
    position_details={
        "symbol": "BTC",
        "size": 2.5,
        "leverage": 10,
        "distance_to_liquidation": 0.08  # 8% away
    }
)

# Alert Condition Types
class AlertType(str, Enum):
    LARGE_TRADE = "LARGE_TRADE"
    WHALE_ACTIVITY = "WHALE_ACTIVITY"
    VOLUME_SPIKE = "VOLUME_SPIKE"
    LIQUIDATION = "LIQUIDATION"
    RISK_ALERT = "RISK_ALERT"
    PORTFOLIO_ALERT = "PORTFOLIO_ALERT"

class AlertLevel(str, Enum):
    INFO = "INFO"
    WARNING = "WARNING"
    CRITICAL = "CRITICAL"
    EMERGENCY = "EMERGENCY"
```

### Dashboard & Visualization Types

```python
from hyperliquid_monitor_plus.visualization.dashboard_components import (
    TradingMetrics,
    AlertData,
    ChartConfig
)

# Real-time Trading Metrics
metrics = TradingMetrics(
    timestamp=datetime.now(),
    total_volume_24h=1_250_000_000,
    whale_volume_24h=250_000_000,
    active_whales=15,
    avg_trade_size=125_000,
    largest_trade_size=5_000_000,
    volume_change_24h=0.15,  # 15% increase
    whale_activity_score=0.78
)

# Chart Configuration
chart_config = ChartConfig(
    chart_type="line",
    timeframe="1h",
    indicators=["SMA", "RSI", "Volume"],
    colors=["#1f77b4", "#ff7f0e", "#2ca02c"],
    width=1200,
    height=600,
    show_grid=True,
    show_legend=True
)
```

---

## 🎨 Advanced Visualization System

Comprehensive visualization and dashboard system with real-time updates.

### Chart Classes

```python
from hyperliquid_monitor_plus.visualization import (
    WhaleVolumeChart,
    MarketImpactPlot,
    TradeDistributionChart,
    PortfolioPerformanceChart,
    SentimentAnalysisPlot,
    CorrelationHeatmap,
    RealTimeWhaleTracker,
    
    # Dashboard Components
    TradingMetricsWidget,
    AlertDistributionWidget,
    PerformanceDashboard,
    RealTimeChart,
    
    # Exporters
    ChartExporter,
    HTMLReportGenerator,
    PDFReportGenerator
)
```

### Key Features

- **Interactive Charts**: Plotly-based interactive visualizations
- **Real-time Updates**: Live data streaming and chart updates
- **Multiple Export Formats**: PNG, PDF, SVG, HTML export
- **