MCP Crypto Order Flow Server
README.md
# MCP Crypto Order Flow Server
[](https://python.org)
[](https://modelcontextprotocol.io)
[](https://duckdb.org)
[](https://unit8co.github.io/darts/)
[](https://websockets.readthedocs.io)
[](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.
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo recent community issues