Skip to main content
Glama
MCP Crypto Order Flow Server

MCP Crypto Order Flow Server

README.md
# MCP Crypto Order Flow Server

[![Python](https://img.shields.io/badge/Python-3.11%2B-blue?logo=python&logoColor=white)](https://python.org)
[![MCP](https://img.shields.io/badge/MCP-Compatible-green)](https://modelcontextprotocol.io)
[![DuckDB](https://img.shields.io/badge/DuckDB-Storage-yellow)](https://duckdb.org)
[![Darts](https://img.shields.io/badge/Darts-Forecasting-orange)](https://unit8co.github.io/darts/)
[![WebSocket](https://img.shields.io/badge/WebSocket-Real--Time-purple)](https://websockets.readthedocs.io)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A **production-grade** Model Context Protocol (MCP) server for **real-time cryptocurrency market data collection, AI-powered forecasting, and advanced analytics**. Features **252 MCP tools** (including 35 new institutional-grade tools), **38+ forecasting models** via Darts integration, **production streaming system** with health monitoring, **intelligent model routing** for optimal predictions, **139 institutional features** with **15 composite signals** for smart money detection, **Sibyl Dashboard** for real-time visualization, and **CrewAI Data Operations Crew** with 4 specialized agents. Connects to **7 exchanges (9 markets)** simultaneously including KuCoin Spot/Futures, stores data in DuckDB with 200+ isolated tables, and provides enterprise-grade time series analytics.

---

## šŸ†• Phase 4 Complete: Institutional Features & MCP Tool Integration

**35 New MCP Tools** for institutional-grade market analysis:

### Week 1: Per-Stream Feature Tools (15 tools)
- **Price Features**: `get_price_features`, `get_spread_dynamics`, `get_price_efficiency_metrics`
- **Orderbook Features**: `get_orderbook_features`, `get_depth_imbalance`, `get_wall_detection`
- **Trade Features**: `get_trade_features`, `get_cvd_analysis`, `get_whale_detection`
- **Funding Features**: `get_funding_features`, `get_funding_sentiment`
- **OI Features**: `get_oi_features`, `get_leverage_risk`
- **Liquidation/Mark**: `get_liquidation_features`, `get_mark_price_features`

### Week 2: Composite Intelligence Tools (11 tools)
- **Smart Money**: `get_smart_accumulation_signal`, `get_smart_money_flow`
- **Squeeze Detection**: `get_short_squeeze_probability`, `get_stop_hunt_detector`
- **Momentum**: `get_momentum_quality_signal`, `get_momentum_exhaustion`
- **Risk Assessment**: `get_market_maker_activity`, `get_liquidation_cascade_risk`
- **Market Intelligence**: `get_institutional_phase`, `get_aggregated_intelligence`, `get_execution_quality`

### Week 3: Visualization Tools (5 tools)
- `get_feature_candles` - Feature-enriched OHLCV data
- `get_liquidity_heatmap` - Real-time orderbook depth visualization
- `get_signal_dashboard` - Composite signal grid
- `get_regime_visualization` - Market regime timeline
- `get_correlation_matrix` - Feature correlation analysis

### Week 4: Feature Query Tools (4 tools)
- `query_historical_features` - Query stored institutional features
- `export_features_csv` - Export features to CSV for backtesting
- `get_feature_statistics` - Statistical analysis of feature distributions
- `get_feature_correlation_analysis` - Cross-stream correlation discovery

---

## šŸŽÆ What This System Does

### Core Capabilities

1. **šŸ”“ Real-Time Streaming System** *(NEW)*
   - Production-grade streaming controller with health monitoring
   - Automatic data collection from 7 exchanges (9 markets) via WebSocket
   - Real-time analytics pipeline with live forecasting
   - Model drift detection and auto-retraining
   - Alert system with multiple dispatch channels

2. **šŸ¤– AI-Powered Forecasting** *(NEW)*
   - **38+ forecasting models** via Darts integration
   - Intelligent model routing based on data characteristics
   - Statistical: ARIMA, ETS, Prophet, Theta, TBATS
   - Machine Learning: LightGBM, XGBoost, CatBoost, Random Forest
   - Deep Learning: N-BEATS, N-HiTS, TFT, Transformer, TCN, RNN, LSTM, GRU
   - Foundation Models: Chronos-2 (zero-shot forecasting)
   - Ensemble methods with meta-learning

3. **šŸŽ“ Production ML Operations** *(NEW)*
   - Automated hyperparameter tuning (Optuna)
   - Time series cross-validation (5 strategies)
   - Model drift detection (4 algorithms)
   - GPU task scheduling and optimization
   - Model registry with performance tracking
   - Backtesting with performance grading

4. **šŸ’¹ Cross-Exchange Arbitrage Detection**
   - Real-time price monitoring across all exchanges
   - Identifies profitable price discrepancies instantly
   - Calculates profit margins and execution costs

5. **šŸ—„ļø Persistent Storage**
   - DuckDB with 504 isolated tables (per symbol/exchange)
   - 7,393 records/minute ingestion capacity
   - Complete data isolation - no mixing

6. **šŸ“Š Historical Analytics**
   - Query stored DuckDB data for backtesting
   - Time-series aggregation and analysis
   - Export capabilities to CSV/Parquet

7. **šŸ›ļø Institutional Feature Engine** *(NEW - Phase 4)*
   - **139 institutional-grade features** computed in real-time
   - **15 composite signals** (smart money, squeeze probability, stop hunt)
   - **8 feature calculators**: prices, orderbook, trades, funding, OI, liquidations, mark prices, ticker
   - **Signal Aggregator**: AI-powered signal ranking and conflict resolution
   - **Trade Recommendations**: Automated direction, strength, and risk assessment

8. **šŸ“ˆ 35 New MCP Tools** *(Phase 4)*
   - Per-stream feature analysis (15 tools)
   - Composite intelligence signals (11 tools)
   - Real-time visualization (5 tools)
   - Historical feature queries (4 tools)

7. **šŸ” Advanced Analytics**
   - Institutional flow detection
   - Squeeze probability computation
   - Smart money signals
   - Leverage analytics
   - Market regime detection

9. **šŸ› ļø MCP Tools Interface**
   - **252 AI-assistant-compatible tools** (35 new in Phase 4)
   - Organized into 11 categories
   - Full forecasting, analytics, streaming, and institutional features

10. **šŸ¤– CrewAI Integration** *(Phase 1 Foundation + Phase 2 Data Ops)*
    - Multi-agent orchestration framework for autonomous analysis
    - 8 specialized AI agents with role-based permissions
    - 5 crews: Data, Analytics, Intelligence, Operations, Research
    - Shadow mode for safe testing alongside live system
    - Event-driven communication and state management

11. **šŸ”„ Phase 2: Data Operations Crew** *(NEW)*
    - 4 specialized agents: DataCollector, DataValidator, DataCleaner, SchemaManager
    - **StreamingControllerBridge**: Real-time connection to Phase 1 streaming
    - **DuckDBHistoricalAccess**: Query historical data from 504 tables
    - **DataOpsMetricsCollector**: Track agent actions, quality issues, escalations
    - **Autonomous Behaviors**: auto_reconnect, auto_validation, gap_detection, schema_optimize
    - **EventBus Integration**: DATA_RECEIVED, STREAM_STATUS, QUALITY_ALERT, AGENT_ACTION
    - **100% Test Coverage**: 27/27 integration tests passing

---

## šŸ“Š System Data Flow Diagram

For a comprehensive visual representation of the entire system architecture, data flows, and integration points, see:

**šŸ“„ [DATA_FLOW_DIAGRAM.md](DATA_FLOW_DIAGRAM.md)** - Complete data flow visualization including:
- External data sources (7 exchanges, 9 markets)
- Phase 1 MCP Server & Streaming Layer (252+ tools)
- Phase 2 CrewAI Data Operations Crew (4 agents)
- Storage Layer (504 DuckDB tables)
- Visualization Layer (Sibyl Dashboard)
- Debug points and common issues

---

## šŸ¤– CrewAI Integration (Phase 1 - Foundation)

The system now includes a comprehensive CrewAI integration layer for multi-agent autonomous market analysis.

### Architecture Overview

```
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                     CrewAI Controller                        │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”         │
│  │ Data Crew   │  │Analytics Crew│  │ Intel Crew  │         │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜         │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                      Event Bus                               │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”         │
│  │Tool Wrappers│  │State Manager│  │ Config Loader│         │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜         │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                   MCP Server (248+ Tools)                    │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
```

### AI Agents (8 Specialized Agents)

| Agent | Crew | Role |
|-------|------|------|
| **data_acquisition_agent** | Data | Collects market data from 7 exchanges (9 markets) |
| **data_quality_agent** | Data | Validates data quality and detects anomalies |
| **forecasting_agent** | Analytics | Generates ML-powered price forecasts |
| **regime_detection_agent** | Analytics | Identifies market regimes |
| **institutional_flow_agent** | Intelligence | Detects smart money activity |
| **risk_assessment_agent** | Intelligence | Evaluates market risks |
| **system_health_agent** | Operations | Monitors system health |
| **market_researcher_agent** | Research | Compiles market briefings |

### Quick Start with CrewAI

```python
from crewai_integration import CrewAIController

# Initialize controller
controller = CrewAIController()
await controller.initialize()

# Start in shadow mode (safe testing)
await controller.start(shadow_mode=True)

# Check health
health = await controller.get_health()
print(f"Status: {health['status']}")
print(f"Agents: {health['agents_registered']}")
print(f"Tools: {health['tools_registered']}")

# Stop gracefully
await controller.stop()
```

### Run Tests

```bash
# Unit tests
python -m crewai_integration.tests.unit_tests

# Integration tests
python -m crewai_integration.tests.integration_tests

# Performance benchmarks
python -m crewai_integration.tests.benchmarks
```

### Configuration

Configuration files in `crewai_integration/config/`:
- `system.yaml` - System settings, rate limits, features
- `agents.yaml` - Agent definitions and tools
- `tasks.yaml` - Task descriptions and workflows
- `crews.yaml` - Crew compositions and flows

### Documentation

Full documentation in `crewai_integration/docs/`:
- [Main Documentation](crewai_integration/docs/README.md)
- [Tool Wrapper Reference](crewai_integration/docs/TOOL_WRAPPER_REFERENCE.md)
- [State Management Guide](crewai_integration/docs/STATE_MANAGEMENT_GUIDE.md)

---

## šŸ”„ Phase 2: Data Operations Crew

Phase 2 extends the CrewAI integration with a fully operational **Data Operations Crew** that connects directly to Phase 1 MCP tools and streaming infrastructure.

### Architecture

```
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                         DATA OPERATIONS CREW                                 │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │
│  │ DataCollector  │  │ DataValidator  │  │  DataCleaner   │  │ Schema    │ │
│  │    Agent       │──▶│    Agent       │──▶│    Agent       │──▶│ Manager   │ │
│  │                │  │                │  │                │  │           │ │
│  │ • collect_data │  │ • validate_data│  │ • clean_anomaly│  │ • optimize│ │
│  │ • stream_status│  │ • check_gaps   │  │ • fill_gaps    │  │ • vacuum  │ │
│  │ • reconnect    │  │ • verify       │  │ • normalize    │  │ • stats   │ │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                         INTEGRATION COMPONENTS                               │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  │
│  │StreamingController  │  │ DuckDBHistorical    │  │DataOpsMetrics      │  │
│  │    Bridge           │  │    Access           │  │    Collector       │  │
│  │                     │  │                     │  │                    │  │
│  │ • connect()         │  │ • list_tables()     │  │ • record_action()  │  │
│  │ • get_status()      │  │ • get_historical()  │  │ • record_quality() │  │
│  │ • trigger_reconnect │  │ • get_statistics()  │  │ • get_dashboard()  │  │
│  │ • get_table_stats() │  │ • detect_gaps()     │  │ • export_metrics() │  │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                              EVENT BUS                                       │
│   DATA_RECEIVED │ STREAM_STATUS │ QUALITY_ALERT │ AGENT_ACTION │ ESCALATION │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
```

### 4 Specialized Agents

| Agent | Role | Tools | Autonomous Behaviors |
|-------|------|-------|---------------------|
| **DataCollector** | Collect data from 7 exchanges (9 markets) | `collect_exchange_data`, `get_stream_status`, `trigger_reconnect` | auto_reconnect on disconnect |
| **DataValidator** | Ensure data quality & integrity | `validate_recent_data`, `check_data_gaps`, `verify_cross_exchange` | auto_validation every 5 min |
| **DataCleaner** | Fix anomalies & interpolate gaps | `clean_data_anomalies`, `fill_data_gaps`, `normalize_data` | gap_detection every 15 min |
| **SchemaManager** | Manage DB schema & optimize | `optimize_schema`, `vacuum_tables`, `get_table_stats` | schema_optimize daily |

### Tool Wrappers (MCP → CrewAI Bridge)

Phase 2 wraps all 252+ Phase 1 MCP tools into CrewAI-compatible tool classes:

```python
# Tool wrapper categories
ExchangeDataTools   # 60+ tools: binance_get_ticker, bybit_get_orderbook, etc.
StreamingTools      # 20+ tools: start_stream, stop_stream, health_check
AnalyticsTools      # 40+ tools: order_flow, regime_detect, alpha_signals
ForecastingTools    # 38+ models: ARIMA, Prophet, N-BEATS, TFT, etc.
FeatureTools        # 35+ tools: price_features, orderbook_features, composite
```

### Quick Start (Data Operations Crew)

```python
from crewai_integration.crews.data_ops import DataOperationsCrew

# Initialize crew
crew = DataOperationsCrew()
await crew.initialize()

# Run single task
result = await crew.kickoff({
    "task": "validate_all_streams",
    "exchanges": ["binance", "bybit"]
})

# Run continuous monitoring
await crew.run_continuous(interval=300)  # Every 5 minutes

# Get metrics dashboard
dashboard = crew.metrics.get_dashboard_metrics()
print(f"Actions: {dashboard['agent_actions']}")
print(f"Quality Issues: {dashboard['quality_issues']}")
print(f"Health Score: {dashboard['health_score']}%")
```

### Run Phase 2 Tests

```bash
# Quick integration test
python test_phase_integration_10min.py --quick

# Full 10-minute test with monitoring
python test_phase_integration_10min.py

# Phase 2 unit tests
python -m pytest tests/test_phase2_integration.py -v
```

Expected output:
```
======================================================================
šŸ”¬ PHASE 1-2 INTEGRATION TEST SUITE
======================================================================
Running 27 tests...

āœ… test_mcp_tools_available - PASSED
āœ… test_exchange_data_tools - PASSED
āœ… test_streaming_tools - PASSED
āœ… test_analytics_tools - PASSED
āœ… test_forecasting_tools - PASSED
āœ… test_data_ops_crew_init - PASSED
āœ… test_streaming_controller_bridge - PASSED
āœ… test_duckdb_historical_access - PASSED
āœ… test_metrics_collector - PASSED
āœ… test_event_bus - PASSED
... (17 more tests)

šŸ“Š RESULTS: 27/27 PASSED (100%)
āœ… SYSTEM READY FOR PHASE 3
```

### Metrics Collected

| Metric | Description | Storage |
|--------|-------------|---------|
| `agent_actions` | All agent activities | `crewai_data_ops.duckdb:agent_actions` |
| `quality_issues` | Data quality problems | `crewai_data_ops.duckdb:quality_issues` |
| `interpolations` | Gap filling operations | `crewai_data_ops.duckdb:interpolations` |
| `escalations` | Issues requiring human review | `crewai_data_ops.duckdb:escalations` |
| `health_score` | Overall system health (0-100%) | Computed from above |

---

## ⭐ Key Features (NEW in This Release)

### Production Streaming System
```python
# Start streaming with MCP tool
await start_streaming(
    symbols=["BTCUSDT", "ETHUSDT"],
    exchanges=["binance", "bybit"]
)

# Or via CLI
python start_streaming.py --symbols BTCUSDT ETHUSDT --exchanges binance bybit
```

**Features:**
- āœ… Multi-exchange data collection (7 exchanges, 9 markets)
- āœ… Real-time analytics callbacks
- āœ… Automatic forecast generation
- āœ… Health monitoring (records/min, errors, uptime)
- āœ… Alert system (drift detection, errors, warnings)
- āœ… Graceful error handling and recovery
- āœ… Python 3.11+ compatible (modern async/await)

### Intelligent Forecasting
```python
# Automatic model selection based on requirements
result = await forecast_with_darts_quick(
    symbol="BTCUSDT",
    horizon=24,
    priority="accurate"  # or "fast", "realtime"
)
# āœ… Router automatically selects optimal model
# āœ… GPU acceleration if available
# āœ… Returns forecast + confidence intervals + model used
```

**IntelligentRouter** considers:
- Data length and characteristics
- Performance requirements (latency vs accuracy)
- Hardware availability (GPU/CPU)
- Historical model performance
- Seasonality patterns

### Model Drift Detection
```python
# Automatic drift monitoring
drift = await detect_model_drift(
    model_id="btc_forecast_v1",
    actual_data=[...],
    predictions=[...]
)
# āœ… Detects accuracy degradation
# āœ… Triggers automatic retraining
# āœ… Alerts on severe drift
```

---

## šŸ›ļø Supported Exchanges (7 Exchanges, 9 Markets)

| Exchange | Market Type | Data Streams |
|----------|-------------|--------------|
| **Binance Futures** | Perpetuals | Prices, Orderbook, Trades, Mark Price, Funding, OI, Liquidations, Candles |
| **Binance Spot** | Spot | Prices, Orderbook, Trades, 24h Ticker, Candles |
| **Bybit Futures** | Perpetuals | Prices, Orderbook, Trades, Mark Price, Funding, OI, Liquidations, Candles |
| **Bybit Spot** | Spot | Prices, Orderbook, Trades |
| **OKX** | Perpetuals | Prices, Orderbook, Trades, Mark Price, Funding, OI, Liquidations, Index Prices |
| **Gate.io** | Perpetuals | Prices, Orderbook, Trades, Mark Price, Funding, OI, Liquidations, Candles |
| **Hyperliquid** | Perpetuals | Prices, Orderbook, Trades, Mark Price, Funding, OI, Liquidations, Candles |
| **KuCoin Spot** | Spot | Prices, Orderbook, Trades |
| **KuCoin Futures** | Perpetuals | Prices, Trades, Candles |

> **Note:** KuCoin Futures uses `XBT` instead of `BTC` in their symbol format (e.g., `XBTUSDTM` instead of `BTCUSDTM`). The collector handles this mapping automatically.

---

## šŸ’¹ Supported Symbols (9 Trading Pairs)

| Symbol | Description | Category |
|--------|-------------|----------|
| **BTCUSDT** | Bitcoin/USDT | Major |
| **ETHUSDT** | Ethereum/USDT | Major |
| **SOLUSDT** | Solana/USDT | Major |
| **XRPUSDT** | Ripple/USDT | Major |
| **ARUSDT** | Arweave/USDT | Major |
| **BRETTUSDT** | Brett/USDT | Meme |
| **POPCATUSDT** | Popcat/USDT | Meme |
| **WIFUSDT** | dogwifhat/USDT | Meme |
| **PNUTUSDT** | Peanut/USDT | Meme |

---

## šŸ“Š Data Streams Collected

| Stream | Description | Fields |
|--------|-------------|--------|
| **prices** | Real-time bid/ask prices | mid_price, bid, ask, spread, spread_bps |
| **orderbooks** | 10-level order book snapshots | bid/ask prices and quantities (20 levels) |
| **trades** | Individual trade executions | price, quantity, side, trade_id |
| **mark_prices** | Mark prices for perpetuals | mark_price, index_price |
| **funding_rates** | Perpetual funding rates | funding_rate, next_funding_time |
| **open_interest** | Open interest data | open_interest, oi_change |
| **ticker_24h** | 24-hour statistics | volume_24h, price_change, high, low |
| **candles** | OHLCV candlestick data | open, high, low, close, volume |
| **liquidations** | Liquidation events | side, price, quantity, value |

---

## šŸ—„ļø Database Architecture

### Storage Engine: DuckDB
- **File Location**: `data/isolated_exchange_data.duckdb`
- **Total Tables**: 504 isolated tables
- **Ingestion Rate**: 7,393 records/minute average
- **Table Naming**: `{symbol}_{exchange}_{market_type}_{stream}`
- **Flush Interval**: Every 5 seconds (batch optimization)

### Table Examples
```
btcusdt_binance_futures_prices
btcusdt_binance_futures_orderbooks
btcusdt_binance_futures_trades
btcusdt_binance_spot_prices
ethusdt_bybit_futures_funding_rates
solusdt_okx_futures_liquidations
btcusdt_kucoin_spot_prices
btcusdt_kucoin_futures_trades
```

### Dynamic Table Count
- Tables are created dynamically based on available data streams
- **9 symbols** Ɨ **7 exchanges** Ɨ **9 markets** Ɨ **~7 stream types**
- Complete data isolation - no mixing of data from different sources
- Enables precise per-exchange, per-coin analysis
- Fast queries on specific data subsets
- Optimal for time-series analytics and backtesting

---

## šŸ—ļø System Architecture

```
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                   MCP CRYPTO ORDER FLOW SERVER (217 TOOLS)                  │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                                                                             │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”   │
│  │ Forecasting  │  │  Analytics   │  │  Streaming   │  │  Formatters  │   │
│  │  (22 tools)  │  │  (60 tools)  │  │  (8 tools)   │  │              │   │
│  │              │  │              │  │              │  │              │   │
│  │ • 38+ Models │  │ • Alpha      │  │ • Start/Stop │  │ • XML Output │   │
│  │ • Ensemble   │  │ • Leverage   │  │ • Health     │  │ • LLM-Ready  │   │
│  │ • Explain    │  │ • Regime     │  │ • Alerts     │  │              │   │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜   │
│         │                 │                  │                             │
│         ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜                             │
│                           │                                                │
│                           ā–¼                                                │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”           │
│  │              PRODUCTION STREAMING CONTROLLER                 │           │
│  │                                                              │           │
│  │  • Multi-exchange collection  • Real-time analytics          │           │
│  │  • Health monitoring         • Drift detection              │           │
│  │  • Alert dispatch            • Auto-retraining              │           │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜           │
│                           │                                                │
│                           ā–¼                                                │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”           │
│  │              INTELLIGENT ROUTER + DARTS BRIDGE               │           │
│  │                                                              │           │
│  │  • Automatic model selection  • GPU optimization             │           │
│  │  • 38+ forecasting models     • Meta-learning                │           │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜           │
│                           │                                                │
│                           ā–¼                                                │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”           │
│  │              ISOLATED DATA COLLECTOR (Enhanced)              │           │
│  │                                                              │           │
│  │  • Callback system           • Real-time analytics           │           │
│  │  • Batch optimization        • Health metrics                │           │
│  │  • 7,393 records/min         • Error recovery                │           │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜           │
│                           │                                                │
│                           ā–¼                                                │
│  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”           │
│  │              DUCKDB STORAGE (200+ TABLES)                    │           │
│  │                                                              │           │
│  │  data/isolated_exchange_data.duckdb                          │           │
│  │  Complete Isolation • File-Based • Time-Partitioned          │           │
│  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜           │
│                                                                             │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                                    │
                                    ā–¼
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                        EXCHANGES (7 Exchanges, 9 Markets)                    │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│  Binance  │  Bybit  │  OKX  │  Gate.io  │  Hyperliquid  │  KuCoin           │
│  (Futures + Spot)   │ (Futures + Spot) │ (Futures)  │  (Futures + Spot)    │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
```

**Key Components:**
- **IntelligentRouter**: Automatic model selection based on data characteristics
- **DartsBridge**: Integration with 38+ forecasting models
- **RealTimeAnalytics**: Live forecast generation on streaming data
- **DriftDetector**: Model performance monitoring with auto-retraining
- **ProductionController**: Orchestrates all streaming operations

---

## ⚔ Quick Start

### Prerequisites
- Python 3.11+ (3.10 supported with warnings)
- pip (Python package manager)
- Git
- Optional: CUDA-compatible GPU for deep learning models

### Installation

```bash
# 1. Clone the repository
git clone https://github.com/gitrepohub-cpu/mcp-crpto-order-flow-server.git
cd mcp-crpto-order-flow-server

# 2. Create virtual environment
python -m venv .venv

# 3. Activate virtual environment
# Windows:
.venv\Scripts\activate
# Linux/Mac:
source .venv/bin/activate

# 4. Install dependencies
pip install -r requirements.txt
```

### Initialize Database

```bash
# Create isolated tables
python -m src.storage.isolated_database_init
```

Expected output:
```
āœ… Created isolated tables
šŸ“Š Tables created for 9 symbols across 7 exchanges (9 markets)
šŸ—„ļø Database: data/isolated_exchange_data.duckdb
```

### Start Robust Data Collection

```bash
# Start robust collector (recommended) - collects from all 7 exchanges
python robust_collector.py

# Or run for specific duration (in minutes)
python robust_collector.py 10
```

Expected output:
```
======================================================================
 ROBUST MULTI-EXCHANGE DATA COLLECTOR
======================================================================
āœ… BINANCE_FUTURES: 9 symbols - prices, orderbooks, trades, funding, oi
āœ… BINANCE_SPOT: 7 symbols - prices, orderbooks, trades
āœ… BYBIT_LINEAR: 9 symbols - prices, orderbooks, trades, funding, oi
āœ… BYBIT_SPOT: 9 symbols - prices, orderbooks, trades
āœ… OKX: 5 symbols - prices, orderbooks, trades, funding, oi
āœ… GATEIO: 9 symbols - prices, orderbooks, trades, funding, oi
āœ… HYPERLIQUID: 7 symbols - prices, orderbooks, trades
āœ… KUCOIN_SPOT: 4 symbols - prices, orderbooks, trades
āœ… KUCOIN_FUTURES: 4 symbols - prices, trades
```

### Alternative: Start Production Streaming

```bash
# Start streaming with default config
python start_streaming.py

# Or with specific symbols/exchanges
python start_streaming.py --symbols BTCUSDT ETHUSDT --exchanges binance bybit

# Or with custom config
python start_streaming.py --config config/streaming_config.json
```

Expected output:
```
======================================================================
šŸš€ PRODUCTION STREAMING SYSTEM
======================================================================
šŸ“Š Symbols: ['BTCUSDT', 'ETHUSDT']
šŸ¦ Exchanges: ['binance', 'bybit']
šŸ“ˆ Market Type: futures
ā±ļø  Forecast Interval: 300s
šŸ” Drift Check Interval: 600s
======================================================================

āœ… Connected analytics callbacks to data collector
āœ… Streaming started: 2 symbols Ɨ 2 exchanges = 4 streams
šŸ’¾ Flushed 1,234 records to 8 tables
āœ… Forecast generated for BTCUSDT/binance using theta
āœ… Forecast generated for ETHUSDT/binance using lightgbm
```

### Test the System

```bash
# Run comprehensive integration tests
python test_streaming_system.py
```

Expected output:
```
======================================================================
šŸŽ‰ ALL TESTS PASSED! Streaming system is ready.
======================================================================
   IsolatedDataCollector Callbacks: āœ… PASS
   RealTimeAnalytics: āœ… PASS
   Streaming Control Tools: āœ… PASS
   Tool Count: āœ… PASS (217 tools)

   Total: 4/4 tests passed
```

---

## ļæ½ļø Sibyl Dashboard (NEW)

The **Sibyl Dashboard** is a comprehensive visualization frontend for real-time market analytics.

### Features
- **šŸ“Š MCP Dashboard** - Real-time exchange data overview with live prices
- **šŸ›ļø Institutional Features** - 139 feature visualization with heatmaps
- **šŸ“” Signal Aggregator** - 15 composite signals (smart money, squeeze, stop hunt)
- **šŸŽ­ Regime Analyzer** - Market regime detection and timeline
- **šŸ”® Forecasting Studio** - 38+ AI model predictions with confidence bands
- **šŸ”¬ Feature Explorer** - Deep feature analysis tools
- **šŸ”€ Cross-Exchange** - Arbitrage opportunity scanner
- **🌊 Streaming Monitor** - System health and data collection status

### Quick Start (Sibyl Dashboard)

```bash
# 1. Start the MCP HTTP API (required)
python -m uvicorn src.http_api:app --host 127.0.0.1 --port 8000

# 2. Start the Sibyl Dashboard (separate terminal)
streamlit run sibyl_integration/frontend/index_router.py --server.port 8501

# 3. Open browser
# API: http://localhost:8000
# Dashboard: http://localhost:8501
```

### Architecture

```
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”       ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”       ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  Exchanges  │──────►│  MCP Server │──────►│  HTTP API   │
│  (8 total)  │       │  (248 tools)│       │  (FastAPI)  │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜       ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜       ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                                                    │
                                                    ā–¼
                                            ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
                                            │   Sibyl     │
                                            │  Dashboard  │
                                            │ (Streamlit) │
                                            ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
```

See [SYSTEM_ARCHITECTURE.md](SYSTEM_ARCHITECTURE.md) for complete workflow diagram.

---

## šŸ› ļø MCP Tools (248 Total)

### Tool Categories

#### 1. **Forecasting Tools (22 tools)** *(NEW)*
- `forecast_with_darts_quick` - Fast forecasting with intelligent routing
- `forecast_with_darts_statistical` - Statistical models (ARIMA, ETS, Prophet, etc.)
- `forecast_with_darts_ml` - ML models (LightGBM, XGBoost, CatBoost, RF)
- `forecast_with_darts_dl` - Deep learning (N-BEATS, TFT, Transformer, etc.)
- `forecast_zero_shot` - Foundation model (Chronos-2)
- `forecast_ensemble` - Ensemble forecasting
- `list_darts_models` - List all available models

#### 2. **Production Forecasting Tools (7 tools)** *(NEW)*
- `tune_forecast_hyperparameters` - Automated tuning with Optuna
- `cross_validate_timeseries` - 5 CV strategies
- `detect_model_drift` - 4 drift detection algorithms
- `register_forecast_model` - Model registry with tracking
- `backtest_forecast_strategy` - Production backtesting
- `get_model_performance` - Performance metrics
- `route_forecast` - Intelligent model routing

#### 3. **Explainability Tools (5 tools)** *(NEW)*
- `explain_forecast_features` - SHAP values and feature importance
- `get_forecast_confidence` - Confidence intervals
- `analyze_forecast_errors` - Error analysis
- `get_model_reasoning` - Model decision explanation

#### 4. **Streaming Control Tools (8 tools)** *(NEW)*
- `start_streaming` - Start production streaming
- `stop_streaming` - Graceful shutdown
- `get_streaming_status` - Check streaming state
- `get_streaming_health` - Health metrics (records/min, errors, uptime)
- `get_streaming_alerts` - System alerts (drift, errors)
- `configure_streaming` - Runtime configuration
- `get_realtime_analytics_status` - Analytics pipeline status
- `get_stream_forecast` - Latest forecast for stream

#### 5. **Analytics Tools (60 tools)**
- Alpha Signal Generation (10 tools)
  - `compute_alpha_signals` - Composite intelligence
  - `get_institutional_pressure` - Smart money flow
  - `compute_squeeze_probability` - Market compression detection
  
- Leverage Analytics (8 tools)
  - `analyze_leverage_positioning` - Position analysis
  - `compute_oi_flow_decomposition` - OI flow breakdown
  - `compute_funding_stress` - Funding rate stress
  
- Regime Detection (12 tools)
  - `detect_market_regime` - Market state classification
  - `detect_event_risk` - Event-driven regime changes
  - `identify_volatility_regime` - Vol regime detection

- Time Series Analysis (20 tools)
  - `detect_anomalies` - Anomaly detection
  - `detect_changepoints` - Structural break detection
  - `analyze_seasonality` - Seasonal pattern analysis
  
- Order Flow (10 tools)
  - `analyze_trade_imbalance` - Buy/sell pressure
  - `compute_volume_profile` - Volume distribution

#### 6. **Exchange Data Tools (80 tools)**
- Binance Futures (12 tools)
- Binance Spot (10 tools)
- Bybit (12 tools)
- OKX (10 tools)
- Kraken (10 tools)
- Gate.io (10 tools)
- Deribit (10 tools)
- Hyperliquid (6 tools)

#### 7. **Historical Query Tools (40 tools)**
- `query_historical_prices` - Price history
- `query_historical_oi` - Open interest history
- `query_historical_funding` - Funding rate history
- `aggregate_by_timeframe` - Time aggregation
- `export_to_csv` - Data export

#### 8. **Arbitrage Tools (5 tools)**
- `analyze_crypto_arbitrage_tool` - Cross-exchange arbitrage
- `get_crypto_prices` - Real-time prices
- `get_crypto_spreads` - Spread matrix
- `get_arbitrage_opportunities` - Opportunity detection
- `compare_exchange_prices` - Exchange comparison

---

## šŸ“ˆ Forecasting Examples

### Quick Forecast with Auto-Routing

```python
# Let the intelligent router choose the best model
result = await forecast_with_darts_quick(
    symbol="BTCUSDT",
    exchange="binance",
    horizon=24,
    priority="accurate"  # or "fast", "realtime"
)

# Result includes:
# - predictions: [65000, 65100, 65200, ...]
# - confidence_intervals: [(64900, 65100), ...]
# - model_used: "lightgbm"
# - metrics: {"mape": 1.8, "rmse": 120.5}
```

### Ensemble Forecasting

```python
# Combine multiple models for better accuracy
result = await forecast_ensemble(
    symbol="ETHUSDT",
    horizon=48,
    models=["arima", "lightgbm", "nbeats"],
    aggregation="weighted"  # or "mean", "median"
)

# Automatically weights models by historical performance
```

### Zero-Shot Forecasting (Foundation Model)

```python
# Use Chronos-2 for forecasting without training
result = await forecast_zero_shot(
    symbol="SOLUSDT",
    horizon=24
)

# Works on any data without historical model training
```

### Production Backtesting

```python
# Test strategy with realistic conditions
result = await backtest_forecast_strategy(
    symbol="BTCUSDT",
    model="lightgbm",
    start_date="2024-01-01",
    end_date="2024-12-31",
    forecast_horizon=24,
    retrain_frequency="weekly"
)

# Returns grade (S/A/B/C/D/F) based on performance
```

---

## šŸ” Analytics Examples

### Alpha Signal Generation

```python
# Detect institutional activity and smart money flow
signals = await compute_alpha_signals(
    symbol="BTCUSDT",
    exchange="binance"
)

# Returns:
# - institutional_pressure: 0.75 (bullish)
# - squeeze_probability: 0.82 (high compression)
# - smart_money_flow: "accumulation"
# - signal_strength: "strong_buy"
```

### Market Regime Detection

```python
# Identify current market conditions
regime = await detect_market_regime(
    symbol="ETHUSDT",
    lookback_periods=100
)

# Returns:
# - regime_type: "trending_bullish"
# - volatility_state: "normal"
# - confidence: 0.89
```

### Drift Detection

```python
# Monitor model accuracy degradation
drift = await detect_model_drift(
    model_id="btc_forecast_v1",
    metric="mape",
    window_size=50
)

# Returns:
# - drift_detected: true
# - severity: "HIGH"
# - recommendation: "retrain_immediately"
```

---

## šŸ“Š Real-Time Streaming Examples

### Start Streaming

```python
# Via MCP tool
result = await start_streaming(
    symbols=["BTCUSDT", "ETHUSDT", "SOLUSDT"],
    exchanges=["binance", "bybit", "okx"]
)

# Returns:
# - status: "RUNNING"
# - active_streams: 9 (3 symbols Ɨ 3 exchanges)
# - forecast_interval: 300s
# - drift_check_interval: 600s
```

### Monitor Health

```python
# Get real-time health metrics
health = await get_streaming_health()

# Returns:
# - records_per_minute: 7393
# - forecasts_generated: 156
# - drift_alerts: 2
# - active_connections: 9
# - errors: 0
# - uptime_hours: 24.5
```

### Get Live Forecast

```python
# Get latest forecast for a stream
forecast = await get_stream_forecast(
    symbol="BTCUSDT",
    exchange="binance"
)

# Returns:
# - predictions: [65000, 65100, ...]
# - model_used: "theta"
# - generated_at: "2026-01-22T17:30:00Z"
# - confidence: 0.92
```

---

## šŸ”§ Configuration

### Streaming Configuration

Edit `config/streaming_config.json`:

```json
{
  "symbols": ["BTCUSDT", "ETHUSDT", "SOLUSDT"],
  "exchanges": ["binance", "bybit", "okx"],
  "market_type": "futures",
  "forecast_interval_seconds": 300,
  "drift_check_interval_seconds": 600,
  "batch_size": 100,
  "flush_interval_seconds": 5,
  "health_check_interval_seconds": 60,
  "alert_channels": ["log", "file"],
  "auto_retrain": true,
  "retraining_config": {
    "min_drift_severity": "HIGH",
    "max_trials": 50,
    "timeout_seconds": 300
  },
  "forecasting_config": {
    "default_priority": "fast",
    "default_horizon": 24,
    "use_gpu": true,
    "cache_models": true
  }
}
```

---

## šŸ“š Documentation

- **[DATA_FLOW_DIAGRAM.md](DATA_FLOW_DIAGRAM.md)** - Complete data flow & integration diagram *(NEW)*
- **[SYSTEM_WORKFLOW_DIAGRAM.md](SYSTEM_WORKFLOW_DIAGRAM.md)** - Complete system visualization
- **[COMPLETE_SCHEMA_REFERENCE.md](COMPLETE_SCHEMA_REFERENCE.md)** - Database schema details
- **[STREAM_REFERENCE.md](STREAM_REFERENCE.md)** - Data stream specifications
- **[KATS_COMPARISON_SUMMARY.md](KATS_COMPARISON_SUMMARY.md)** - Comparison with Meta Kats
- **[crewai_integration/docs/README.md](crewai_integration/docs/README.md)** - CrewAI integration guide
- **[crewai_integration/docs/TOOL_WRAPPER_REFERENCE.md](crewai_integration/docs/TOOL_WRAPPER_REFERENCE.md)** - Tool wrapper docs

---

## šŸŽ“ Model Capabilities

| Model | Latency | Accuracy | GPU | Multivariate | Use Case |
|-------|---------|----------|-----|--------------|----------|
| **Naive** | 5ms | ⭐⭐ | No | No | Baseline |
| **Theta** | 100ms | ⭐⭐⭐ | No | No | Fast, reliable |
| **ETS** | 50ms | ⭐⭐⭐ | No | No | Exponential smoothing |
| **ARIMA** | 200ms | ⭐⭐⭐⭐ | No | No | Univariate TS |
| **Auto-ARIMA** | 500ms | ⭐⭐⭐⭐ | No | No | Auto-tuned ARIMA |
| **Prophet** | 1000ms | ⭐⭐⭐⭐ | No | No | Trend + seasonality |
| **LightGBM** | 300ms | ⭐⭐⭐⭐⭐ | No | Yes | Fast, accurate |
| **XGBoost** | 350ms | ⭐⭐⭐⭐⭐ | No | Yes | Robust ML |
| **CatBoost** | 400ms | ⭐⭐⭐⭐⭐ | No | Yes | Categorical data |
| **N-BEATS** | 1500ms | ⭐⭐⭐⭐⭐ | Yes | No | DL benchmark |
| **N-HiTS** | 1200ms | ⭐⭐⭐⭐⭐ | Yes | No | Improved N-BEATS |
| **TFT** | 2000ms | ⭐⭐⭐⭐⭐+ | Yes | Yes | State-of-the-art |
| **Transformer** | 1800ms | ⭐⭐⭐⭐⭐ | Yes | Yes | Attention-based |
| **Chronos-2** | 3000ms | ⭐⭐⭐⭐⭐ | Yes | No | Zero-shot |

**Tier Legend:**
- S-Tier (⭐⭐⭐⭐⭐+): State-of-the-art, best accuracy
- A-Tier (⭐⭐⭐⭐⭐): Production-ready, excellent
- B-Tier (⭐⭐⭐⭐): Good, reliable
- C-Tier (⭐⭐⭐): Acceptable
- D-Tier (⭐⭐): Baseline

---

## šŸš€ Performance Benchmarks

| Metric | Value |
|--------|-------|
| **Total MCP Tools** | 252+ |
| **Forecasting Models** | 38+ |
| **Exchanges Supported** | 7 (9 markets) |
| **DuckDB Tables** | 200+ (dynamic) |
| **Data Ingestion Rate** | 7,393 records/min |
| **Forecast Latency** | 300-3000ms (model-dependent) |
| **Model Selection Time** | <50ms (IntelligentRouter) |
| **Best MAPE Achieved** | 1.8% (TFT on BTCUSDT) |
| **Drift Detection Latency** | <100ms |
| **Health Check Interval** | 60s |
| **CrewAI Agents** | 8 (4 in Data Ops Crew) |
| **Integration Test Coverage** | 100% (27/27 tests) |

---

## šŸ¤ Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Commit your changes
4. Push to the branch
5. Open a Pull Request

---

## šŸ“„ License

MIT License - see [LICENSE](LICENSE) file for details

---

## šŸ™ Acknowledgments

- **Darts** - Forecasting library by Unit8
- **DuckDB** - Embedded analytical database
- **Model Context Protocol** - By Anthropic
- **PyTorch Lightning** - For GPU acceleration

---

## šŸ“§ Contact

- **GitHub**: [gitrepohub-cpu/mcp-crpto-order-flow-server](https://github.com/gitrepohub-cpu/mcp-crpto-order-flow-server)
- **Issues**: [Report a bug](https://github.com/gitrepohub-cpu/mcp-crpto-order-flow-server/issues)

---

**Built with ā¤ļø for the crypto trading community**
| `min_profit` | float | 0.0 | Minimum profit % to include |
| `limit` | int | 20 | Maximum opportunities to return |

### 5. `compare_exchange_prices`
Compare prices between two specific exchanges.

**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `symbol` | string | required | Trading pair |
| `exchange1` | string | required | First exchange ID |
| `exchange2` | string | required | Second exchange ID |

**Exchange IDs:** `binance_futures`, `binance_spot`, `bybit_futures`, `bybit_spot`, `okx_futures`, `gate_futures`, `hyperliquid_futures`, `kucoin_spot`, `kucoin_futures`

### 6. `crypto_scanner_health`
Check health and connectivity of the arbitrage scanner.

---

## šŸ“ˆ Analytics Engine

### Layer Architecture

| Layer | Module | Purpose |
|-------|--------|---------|
| **Layer 1** | `order_flow_analytics.py` | Order flow imbalance, trade flow analysis |
| **Layer 2** | `leverage_analytics.py` | Funding rate analysis, OI changes, liquidation tracking |
| **Layer 3** | `cross_exchange_analytics.py` | Cross-exchange spreads, lead-lag relationships |
| **Layer 4** | `regime_analytics.py` | Market regime detection (trending/ranging/volatile) |
| **Layer 5** | `alpha_signals.py` | Composite signals, institutional pressure, squeeze probability || **Layer 6** | `timeseries_engine.py` | **Time Series Analytics** - Forecasting, anomaly detection, seasonality || **Engine** | `streaming_analyzer.py` | Real-time streaming analysis with configurable windows |

### Alpha Signals Computed

1. **Institutional Pressure Score**: Detects large player activity
2. **Squeeze Probability Model**: Predicts potential short/long squeezes
3. **Smart Money Absorption**: Identifies smart money accumulation/distribution
4. **Composite Signal**: Combined actionable trading signal

---

## 🧠 Time Series Analytics Engine (Kats-Equivalent)

A comprehensive time series analysis engine providing Facebook Kats-equivalent functionality using `statsmodels`, `scipy`, and `scikit-learn`. Designed to work with institutional calculations that have timestamps.

### Core Components

| Component | Class | Description |
|-----------|-------|-------------|
| **Data Container** | `TimeSeriesData` | Standard container compatible with institutional calculations |
| **Forecast Results** | `ForecastResult` | Forecasts with confidence intervals |
| **Anomaly Results** | `AnomalyResult` | Anomaly detection outputs |
| **Change Points** | `ChangePointResult` | Structural break detection results |
| **Regime Results** | `RegimeResult` | Market regime classification |
| **Regime Types** | `MarketRegime` | Enum: TRENDING_UP/DOWN, RANGING, HIGH/LOW_VOLATILITY, BREAKOUT, BREAKDOWN |

### Capabilities

#### šŸ”® Forecasting Models
| Model | Method | Description |
|-------|--------|-------------|
| **ARIMA** | `forecast_arima()` | AutoRegressive Integrated Moving Average |
| **Exponential Smoothing** | `forecast_exponential_smoothing()` | Holt-Winters with trend/seasonality |
| **Theta** | `forecast_theta()` | Theta method for trend extrapolation |
| **Auto-Selection** | `auto_forecast()` | Automatically selects best model |

#### 🚨 Anomaly Detection Methods
| Method | Function | Description |
|--------|----------|-------------|
| **Z-Score** | `detect_anomalies_zscore()` | Statistical z-score based detection |
| **IQR** | `detect_anomalies_iqr()` | Interquartile range method |
| **Isolation Forest** | `detect_anomalies_isolation_forest()` | ML-based outlier detection |
| **CUSUM** | `detect_anomalies_cusum()` | Cumulative sum control chart |

#### šŸ“ Change Point Detection
| Method | Function | Description |
|--------|----------|-------------|
| **CUSUM** | `detect_change_points_cusum()` | Cumulative sum change detection |
| **Binary Segmentation** | `detect_change_points_binary_segmentation()` | Segment-based detection |

#### šŸ“Š Feature Extraction (40+ Features)
| Category | Features |
|----------|----------|
| **Statistical** | mean, std, var, skew, kurtosis, median, q25, q75, iqr, min, max, range |
| **Trend** | trend_slope, trend_r2, direction_changes, total_return, cagr |
| **Volatility** | volatility, mean_abs_change, max_abs_change, range_to_mean_ratio |
| **Autocorrelation** | autocorr_lag1, autocorr_lag5, autocorr_lag10 |
| **Complexity** | sample_entropy, hurst_exponent |
| **Distribution** | coeff_variation, above_mean_pct, below_mean_pct |

#### 🌊 Seasonality Analysis
| Method | Function | Description |
|--------|----------|-------------|
| **FFT Detection** | `detect_seasonality()` | Fast Fourier Transform for cycles |
| **Decomposition** | `decompose_seasonality()` | Trend/Seasonal/Residual decomposition |

#### šŸŽÆ Market Regime Detection
| Regime | Description |
|--------|-------------|
| `TRENDING_UP` | Strong upward momentum |
| `TRENDING_DOWN` | Strong downward momentum |
| `RANGING` | Sideways consolidation |
| `HIGH_VOLATILITY` | Elevated volatility environment |
| `LOW_VOLATILITY` | Compressed volatility (pre-breakout) |
| `BREAKOUT` | Volatility expansion with upward movement |
| `BREAKDOWN` | Volatility expansion with downward movement |

### Time Series Feature Calculators (7 MCP Tools)

| Calculator | MCP Tool | Description |
|------------|----------|-------------|
| **Price Forecast** | `calculate_price_forecast` | Multi-model price forecasting with confidence intervals |
| **Anomaly Detection** | `calculate_anomaly_detection` | Ensemble anomaly detection across multiple methods |
| **Change Points** | `calculate_change_point_detection` | Detect structural breaks and regime changes |
| **Feature Extraction** | `calculate_feature_extraction` | Extract 40+ statistical features for ML |
| **Regime Detection** | `calculate_regime_detection` | Classify market regime with transition matrix |
| **Seasonality** | `calculate_seasonality_analysis` | Detect seasonal patterns and decompose trends |
| **Funding Forecast** | `calculate_funding_forecast` | Forecast funding rates with arbitrage signals |

### Usage Examples

```python
# Forecast BTC prices using auto-selected model
await calculate_price_forecast(
    symbol="BTCUSDT",
    exchange="binance",
    hours=168,  # 7 days history
    forecast_steps=24,  # 24 hours ahead
    model="auto",  # arima, exponential_smoothing, theta, auto
    confidence=0.95
)

# Detect anomalies using ensemble methods
await calculate_anomaly_detection(
    symbol="ETHUSDT",
    exchange="binance",
    data_type="prices",  # prices, trades, funding_rates, liquidations
    hours=24,
    method="ensemble"  # zscore, iqr, isolation_forest, cusum, ensemble
)

# Detect market regime
await calculate_regime_detection(
    symbol="SOLUSDT",
    exchange="binance",
    hours=168,
    lookback=20,
    volatility_threshold=0.02
)

# Extract ML features
await calculate_feature_extraction(
    symbol="BTCUSDT",
    exchange="binance",
    data_type="prices",
    hours=24,
    include_advanced=True  # Include Hurst exponent, sample entropy
)

# Forecast funding rates for arbitrage
await calculate_funding_forecast(
    symbol="BTCUSDT",
    exchange="binance",
    hours=168,
    forecast_periods=8,  # 8 funding periods (64 hours)
    include_seasonality=True
)
```

### Institutional Calculations Support

The `TimeSeriesData` class is designed to work with future institutional calculations:

```python
from src.analytics import TimeSeriesData, get_timeseries_engine

# Create from DataFrame with timestamps (future institutional data)
ts = TimeSeriesData.from_dataframe(
    df,
    time_col="timestamp",
    value_col="institutional_metric"
)

# Or from DuckDB results
ts = TimeSeriesData.from_duckdb_result(results, name="metric")

# Apply forecasting
engine = get_timeseries_engine()
forecast = engine.auto_forecast(ts, forecast_steps=24)
```

---

## šŸ“Š DuckDB Historical Data Tools

Query the stored historical data in DuckDB using these MCP tools:

| Tool | Description |
|------|-------------|
| `get_historical_price_data` | Query stored price history with OHLC aggregation |
| `get_historical_trade_data` | Query stored trade data with flow analysis |
| `get_historical_funding_data` | Query funding rate history with patterns |
| `get_historical_liquidation_data` | Query liquidation history |
| `get_historical_oi_data` | Query open interest history |
| `get_database_statistics` | Get database stats and available tables |
| `query_historical_analytics` | Custom OHLC/volatility/volume profile queries |

### Example: Query Historical Data
```python
# Get BTC price history for last 24 hours
await get_historical_price_data(
    symbol="BTCUSDT",
    exchange="binance",
    hours=24,
    aggregation="1h"  # 1m, 5m, 15m, 1h, 4h, 1d
)
```

---

## šŸ”€ Live + Historical Combined Tools

Combine real-time data with historical context:

| Tool | Description |
|------|-------------|
| `get_full_market_snapshot` | Live prices + historical OHLC context |
| `get_price_with_historical_context` | Current price with historical stats |
| `analyze_funding_arbitrage` | Funding rate arbitrage with historical patterns |
| `get_liquidation_heatmap_analysis` | Liquidation distribution by price level |
| `detect_price_anomalies` | Z-score anomaly detection vs history |

### Example: Market Snapshot with History
```python
# Get BTC market snapshot with 24h historical context
await get_full_market_snapshot(
    symbol="BTCUSDT",
    historical_hours=24
)
```

---

## šŸ”Œ Plugin-Based Feature Calculator Framework

### Overview

The Feature Calculator Framework allows you to create custom analytics scripts that automatically become MCP tools. This enables extensible, modular analytics without modifying core code.

**ALL CALCULATORS USE THE TIME SERIES ENGINE** - Every calculator (existing and future) has access to `self.timeseries_engine` for advanced time series analysis including forecasting, anomaly detection, change points, and regime detection.

### Built-in Calculators (11 Total)

#### Core Market Calculators (4) - v2.0.0 with TimeSeriesEngine

| Calculator | MCP Tool | TimeSeriesEngine Features Used |
|------------|----------|-------------------------------|
| **Order Flow Imbalance** | `calculate_order_flow_imbalance` | Anomaly detection, feature extraction, change points |
| **Liquidation Cascade** | `calculate_liquidation_cascade` | Isolation forest anomalies, cascade onset detection |
| **Funding Arbitrage** | `calculate_funding_arbitrage` | Rate forecasting, seasonality detection |
| **Volatility Regime** | `calculate_volatility_regime` | Regime detection, transition matrix, seasonality |

#### Time Series Calculators (7) - Full TimeSeriesEngine Integration

| Calculator | MCP Tool | Description |
|------------|----------|-------------|
| **Price Forecast** | `calculate_price_forecast` | Multi-model price forecasting (ARIMA, ETS, Theta) |
| **Anomaly Detection** | `calculate_anomaly_detection` | Ensemble anomaly detection (Z-score, IQR, Isolation Forest) |
| **Change Point Detection** | `calculate_change_point_detection` | Structural break and regime change detection |
| **Feature Extraction** | `calculate_feature_extraction` | 40+ statistical features for ML pipelines |
| **Regime Detection** | `calculate_regime_detection` | Market regime classification with transitions |
| **Seasonality Analysis** | `calculate_seasonality_analysis` | Seasonal patterns and trend decomposition |
| **Funding Forecast** | `calculate_funding_forecast` | Funding rate forecasting with arbitrage signals |

### Listing Available Calculators

```python
# Use the MCP tool to list all calculators
await list_feature_calculators()
```

### Creating Custom Calculators

To add your own feature calculator:

1. **Create a new Python file** in `src/features/calculators/`:

```python
# src/features/calculators/my_custom_feature.py

from src.features.base import FeatureCalculator, FeatureResult
from src.features.utils import generate_signal

class MyCustomCalculator(FeatureCalculator):
    name = "my_custom_feature"
    description = "Calculate my custom market feature with time series analysis"
    category = "custom"
    version = "1.0.0"
    
    async def calculate(
        self,
        symbol: str,
        exchange: str = None,
        hours: int = 24,
        **params
    ) -> FeatureResult:
        # 1. Query data from DuckDB
        query = f"""
            SELECT timestamp, price, volume 
            FROM exchange_data 
            WHERE symbol = '{symbol}'
            ORDER BY timestamp
        """
        results = self.db.execute(query).fetchall()
        
        # 2. Convert to TimeSeriesData for analysis
        ts_data = self.create_timeseries_data(results, name="price")
        
        # 3. USE TIME SERIES ENGINE FOR ANALYSIS
        # Detect anomalies
        anomalies = self.timeseries_engine.detect_anomalies_zscore(ts_data)
        
        # Forecast future values
        forecast = self.timeseries_engine.auto_forecast(ts_data, horizon=3)
        
        # Detect regime changes
        regime = self.timeseries_engine.detect_regime(ts_data)
        
        # Extract features
        features = self.timeseries_engine.extract_features(ts_data)
        
        data = {
            'anomaly_count': len([a for a in anomalies if a['is_anomaly']]),
            'forecast_next': forecast.get('forecast', []),
            'current_regime': regime.get('current_regime'),
            'hurst_exponent': features.get('hurst_exponent')
        }
        
        signals = []
        if data['anomaly_count'] > 0:
            signals.append(generate_signal(
                'WARNING', 0.8,
                f"Detected {data['anomaly_count']} anomalies",
                data
            ))
        
        return self.create_result(
            symbol=symbol,
            exchanges=[exchange or 'all'],
            data=data,
            signals=signals
        )
    
    def get_parameters(self):
        return {
            'symbol': {'type': 'str', 'required': True},
            'exchange': {'type': 'str', 'default': None},
            'hours': {'type': 'int', 'default': 24}
        }
```

2. **Restart the MCP server** - Your calculator will be auto-discovered!

3. **Use via MCP tool**: `calculate_my_custom_feature`

### TimeSeriesEngine Methods Available

Every calculator has access to `self.timeseries_engine` with these methods:

| Method | Description |
|--------|-------------|
| `auto_forecast(ts_data, horizon)` | Multi-model forecasting (ARIMA, ETS, Theta) |
| `detect_anomalies_zscore(ts_data)` | Z-score anomaly detection |
| `detect_anomalies_iqr(ts_data)` | IQR-based anomaly detection |
| `detect_anomalies_isolation_forest(ts_data)` | ML isolation forest |
| `detect_change_points_cusum(ts_data)` | CUSUM change point detection |
| `detect_change_points_pelt(ts_data)` | PELT algorithm change points |
| `detect_regime(ts_data)` | Regime detection with transitions |
| `detect_seasonality(ts_data)` | Seasonal pattern detection |
| `extract_features(ts_data)` | 40+ statistical features |
| `decompose(ts_data)` | Trend/seasonal decomposition |

### Framework Architecture

```
src/features/
ā”œā”€ā”€ __init__.py           # Package exports
ā”œā”€ā”€ base.py               # FeatureCalculator base class & FeatureResult
ā”œā”€ā”€ registry.py           # Auto-discovery & MCP registration
ā”œā”€ā”€ utils.py              # Shared utilities (stats, signals, etc.)
└── calculators/          # Your calculator plugins go here
    ā”œā”€ā”€ __init__.py
    ā”œā”€ā”€ order_flow_imbalance.py   # v2.0.0 - TimeSeriesEngine
    ā”œā”€ā”€ liquidation_cascade.py    # v2.0.0 - TimeSeriesEngine
    ā”œā”€ā”€ funding_arbitrage.py      # v2.0.0 - TimeSeriesEngine
    └── volatility_regime.py      # v2.0.0 - TimeSeriesEngine
```

### Available Utilities in `src/features/utils.py`

| Function | Description |
|----------|-------------|
| `calculate_zscore()` | Calculate z-score |
| `rolling_mean()` | Rolling mean calculation |
| `exponential_moving_average()` | EMA calculation |
| `calculate_volatility()` | Annualized volatility |
| `calculate_vwap()` | Volume-weighted average price |
| `detect_large_trades()` | Identify whale trades |
| `calculate_orderbook_imbalance()` | Orderbook imbalance ratio |
| `generate_signal()` | Create standardized signals |
| `classify_market_regime()` | Classify market conditions |

---

## šŸ“ Project Structure

```
mcp-options-order-flow-server/
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ mcp_server.py                    # Main MCP server (199 tools)
│   │
│   ā”œā”€ā”€ storage/                          # Data Layer
│   │   ā”œā”€ā”€ direct_exchange_client.py    # WebSocket connections to 9 exchanges
│   │   ā”œā”€ā”€ production_isolated_collector.py  # Production data collector
│   │   ā”œā”€ā”€ isolated_database_init.py    # Creates 504 tables
│   │   ā”œā”€ā”€ isolated_data_collector.py   # Buffering and flushing logic
│   │   ā”œā”€ā”€ duckdb_manager.py            # DuckDB operations
│   │   ā”œā”€ā”€ binance_rest_client.py       # Binance REST API
│   │   ā”œā”€ā”€ bybit_rest_client.py         # Bybit REST API
│   │   ā”œā”€ā”€ okx_rest_client.py           # OKX REST API
│   │   ā”œā”€ā”€ kraken_rest_client.py        # Kraken REST API
│   │   ā”œā”€ā”€ gateio_rest_client.py        # Gate.io REST API
│   │   ā”œā”€ā”€ hyperliquid_rest_client.py   # Hyperliquid REST API
│   │   └── deribit_rest_client.py       # Deribit REST API
│   │
│   ā”œā”€ā”€ analytics/                        # Analytics Layer
│   │   ā”œā”€ā”€ alpha_signals.py             # Composite intelligence signals
│   │   ā”œā”€ā”€ order_flow_analytics.py      # Order flow analysis
│   │   ā”œā”€ā”€ leverage_analytics.py        # Leverage & funding analysis
│   │   ā”œā”€ā”€ cross_exchange_analytics.py  # Cross-exchange analysis
│   │   ā”œā”€ā”€ regime_analytics.py          # Market regime detection
│   │   ā”œā”€ā”€ streaming_analyzer.py        # Real-time streaming analysis
│   │   ā”œā”€ā”€ feature_engine.py            # Feature computation
│   │   └── timeseries_engine.py         # Time Series Analytics Engine (NEW)
│   │
│   ā”œā”€ā”€ features/                         # Plugin Feature Framework
│   │   ā”œā”€ā”€ __init__.py                  # Package exports
│   │   ā”œā”€ā”€ base.py                      # FeatureCalculator base class
│   │   ā”œā”€ā”€ registry.py                  # Auto-discovery & MCP registration
│   │   ā”œā”€ā”€ utils.py                     # Shared utilities
│   │   └── calculators/                 # Calculator plugins (11 total)
│   │       ā”œā”€ā”€ __init__.py
│   │       ā”œā”€ā”€ order_flow_imbalance.py  # Order flow analysis
│   │       ā”œā”€ā”€ liquidation_cascade.py   # Cascade detection
│   │       ā”œā”€ā”€ funding_arbitrage.py     # Funding arb finder
│   │       ā”œā”€ā”€ volatility_regime.py     # Volatility regimes
│   │       ā”œā”€ā”€ price_forecast.py        # Price forecasting (NEW)
│   │       ā”œā”€ā”€ anomaly_detection.py     # Anomaly detection (NEW)
│   │       ā”œā”€ā”€ change_point_detection.py # Change points (NEW)
│   │       ā”œā”€ā”€ feature_extraction.py    # ML features (NEW)
│   │       ā”œā”€ā”€ regime_detection.py      # Regime detection (NEW)
│   │       ā”œā”€ā”€ seasonality_analysis.py  # Seasonality (NEW)
│   │       └── funding_forecast.py      # Funding forecast (NEW)
│   │
│   ā”œā”€ā”€ tools/                            # MCP Tools
│   │   ā”œā”€ā”€ crypto_arbitrage_tool.py     # Arbitrage detection tools
│   │   ā”œā”€ā”€ duckdb_historical_tools.py   # DuckDB historical queries (NEW)
│   │   ā”œā”€ā”€ live_historical_tools.py     # Live + historical combined (NEW)
│   │   ā”œā”€ā”€ binance_futures_tools.py     # Binance-specific tools
│   │   ā”œā”€ā”€ binance_spot_tools.py        # Binance Spot tools
│   │   ā”œā”€ā”€ bybit_tools.py               # Bybit tools
│   │   ā”œā”€ā”€ okx_tools.py                 # OKX tools
│   │   ā”œā”€ā”€ kraken_tools.py              # Kraken tools
│   │   ā”œā”€ā”€ gateio_tools.py              # Gate.io tools
│   │   ā”œā”€ā”€ hyperliquid_tools.py         # Hyperliquid tools
│   │   ā”œā”€ā”€ deribit_tools.py             # Deribit tools
│   │   ā”œā”€ā”€ options_flow_tool.py         # Options flow tools
│   │   └── options_monitoring_tool.py   # Options monitoring
│   │
│   ā”œā”€ā”€ formatters/                       # Output Formatting
│   │   ā”œā”€ā”€ xml_formatter.py             # XML output for LLMs
│   │   └── context_builder.py           # Context building
│   │
│   └── proto/                            # Protocol Buffers
│       ā”œā”€ā”€ options_order_flow_pb2.py
│       └── options_order_flow_pb2_grpc.py
│
ā”œā”€ā”€ data/                                 # Data Storage
│   └── isolated_exchange_data.duckdb    # Main database (504 tables)
│
ā”œā”€ā”€ run_server.py                         # MCP Server entry point
ā”œā”€ā”€ test_tools.py                         # Tool tests
ā”œā”€ā”€ test_data_collection.py              # Data collection tests
ā”œā”€ā”€ validate_data_streams.py             # Stream validation
ā”œā”€ā”€ requirements.txt                      # Python dependencies
ā”œā”€ā”€ pyproject.toml                        # Package configuration
ā”œā”€ā”€ CHANGELOG.md                          # Version history
└── README.md                             # This file
```

---

## šŸ”§ Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `USE_DIRECT_EXCHANGES` | `true` | Use direct exchange connections |
| `LOG_LEVEL` | `INFO` | Logging verbosity (DEBUG, INFO, WARNING, ERROR) |
| `FLUSH_INTERVAL` | `5` | Seconds between database flushes |
| `STATS_INTERVAL` | `30` | Seconds between stats logging |

### Collector Settings

Located in `src/storage/production_isolated_collector.py`:

```python
self._flush_interval = 5      # Flush to DB every 5 seconds
self._stats_interval = 30     # Log stats every 30 seconds
```

---

## šŸ› Troubleshooting

### Common Issues

**1. "ModuleNotFoundError: No module named 'duckdb'"**
```bash
pip install duckdb
```

**2. Database locked error**
DuckDB is single-writer. Stop the collector before querying:
```bash
# Press Ctrl+C in the collector terminal
# Then run your queries
```

**3. Exchange connection failed**
- Check internet connectivity
- Some corporate networks block WebSocket connections
- Exchange may be rate-limiting - wait a few minutes

**4. No data appearing**
- Wait 5 seconds for first flush
- Check logs for connection errors
- Ensure exchanges are reachable from your network

### Verifying Data Collection

```python
import duckdb

# Connect read-only while collector is stopped
conn = duckdb.connect('data/isolated_exchange_data.duckdb', read_only=True)

# Count records
result = conn.execute("SELECT COUNT(*) FROM btcusdt_binance_futures_prices").fetchone()
print(f"BTC prices: {result[0]} records")

# View recent data
result = conn.execute("""
    SELECT timestamp, mid_price, spread_bps 
    FROM btcusdt_binance_futures_prices 
    ORDER BY timestamp DESC 
    LIMIT 5
""").fetchall()
for row in result:
    print(row)

conn.close()
```

---

## šŸš€ Production Deployment

### Claude Desktop Integration

Add to your Claude Desktop config (`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "crypto-arbitrage": {
      "command": "python",
      "args": ["run_server.py"],
      "cwd": "C:\\path\\to\\mcp-options-order-flow-server"
    }
  }
}
```

### Running as Background Service

**Windows (PowerShell):**
```powershell
Start-Process -NoNewWindow -FilePath "python" -ArgumentList "-m src.storage.production_isolated_collector"
```

**Linux/Mac:**
```bash
nohup python -m src.storage.production_isolated_collector > collector.log 2>&1 &
```

---

## šŸ“Š Data Schema Reference

### Prices Table Schema
```sql
CREATE TABLE {symbol}_{exchange}_{type}_prices (
    id              BIGINT PRIMARY KEY,
    timestamp       TIMESTAMP NOT NULL,
    mid_price       DOUBLE NOT NULL,
    bid_price       DOUBLE,
    ask_price       DOUBLE,
    spread          DOUBLE,
    spread_bps      DOUBLE
)
```

### Trades Table Schema
```sql
CREATE TABLE {symbol}_{exchange}_{type}_trades (
    id              BIGINT PRIMARY KEY,
    timestamp       TIMESTAMP NOT NULL,
    trade_id        VARCHAR,
    price           DOUBLE NOT NULL,
    quantity        DOUBLE NOT NULL,
    side            VARCHAR,  -- 'buy' or 'sell'
    value           DOUBLE
)
```

### Orderbooks Table Schema
```sql
CREATE TABLE {symbol}_{exchange}_{type}_orderbooks (
    id              BIGINT PRIMARY KEY,
    timestamp       TIMESTAMP NOT NULL,
    bid_1_price     DOUBLE, bid_1_qty DOUBLE,
    bid_2_price     DOUBLE, bid_2_qty DOUBLE,
    -- ... up to 10 levels
    ask_1_price     DOUBLE, ask_1_qty DOUBLE,
    ask_2_price     DOUBLE, ask_2_qty DOUBLE,
    -- ... up to 10 levels
    total_bid_qty   DOUBLE,
    total_ask_qty   DOUBLE,
    imbalance       DOUBLE
)
```

### Funding Rates Table Schema
```sql
CREATE TABLE {symbol}_{exchange}_futures_funding_rates (
    id                  BIGINT PRIMARY KEY,
    timestamp           TIMESTAMP NOT NULL,
    funding_rate        DOUBLE NOT NULL,
    predicted_rate      DOUBLE,
    next_funding_time   TIMESTAMP
)
```

### Liquidations Table Schema
```sql
CREATE TABLE {symbol}_{exchange}_futures_liquidations (
    id              BIGINT PRIMARY KEY,
    timestamp       TIMESTAMP NOT NULL,
    side            VARCHAR NOT NULL,  -- 'long' or 'short'
    price           DOUBLE NOT NULL,
    quantity        DOUBLE NOT NULL,
    value           DOUBLE
)
```

---

## šŸ”„ Version History

See [CHANGELOG.md](CHANGELOG.md) for detailed version history.

### Current Version: 2.2.0

**New in 2.2.0:**
- āœ… Time Series Analytics Engine (Kats-equivalent)
- āœ… 7 New Time Series Calculators
- āœ… Forecasting: ARIMA, Exponential Smoothing, Theta
- āœ… Anomaly Detection: Z-score, IQR, Isolation Forest, CUSUM
- āœ… Change Point Detection: CUSUM, Binary Segmentation
- āœ… Feature Extraction: 40+ statistical features
- āœ… Seasonality Analysis: FFT, decomposition
- āœ… Market Regime Detection with transitions
- āœ… Total: **206 MCP Tools** (11 Feature Calculators)

**Version 2.1.0:**
- āœ… DuckDB Historical Query Tools (7 new tools)
- āœ… Live + Historical Combined Tools (5 new tools)
- āœ… Plugin-Based Feature Calculator Framework
- āœ… 4 Built-in Feature Calculators
- āœ… Auto-discovery and MCP registration
- āœ… 7 exchange support (Binance, Bybit, OKX, Gate.io, Hyperliquid, KuCoin)
- āœ… 9 markets (Binance Futures/Spot, Bybit Futures/Spot, OKX, Gate.io, Hyperliquid, KuCoin Spot/Futures)
- āœ… 200+ isolated DuckDB tables
- āœ… Real-time arbitrage detection
- āœ… Advanced analytics engine (5-layer architecture)
- āœ… Production-grade error handling
- āœ… MCP tools interface

---

## šŸ“„ License

MIT License - see [LICENSE](LICENSE) file for details.

---

## šŸ¤ Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

## šŸ“ž Support

For issues and feature requests, please use the [GitHub Issues](https://github.com/fintools-ai/mcp-options-order-flow-server/issues) page.