MCP Crypto Order Flow Server
Connects to KuCoin Spot and Futures markets to collect real-time market data such as order flow, funding, open interest, liquidation, and price information.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
MCP Crypto Order Flow Server
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_metricsOrderbook Features:
get_orderbook_features,get_depth_imbalance,get_wall_detectionTrade Features:
get_trade_features,get_cvd_analysis,get_whale_detectionFunding Features:
get_funding_features,get_funding_sentimentOI Features:
get_oi_features,get_leverage_riskLiquidation/Mark:
get_liquidation_features,get_mark_price_features
Week 2: Composite Intelligence Tools (11 tools)
Smart Money:
get_smart_accumulation_signal,get_smart_money_flowSqueeze Detection:
get_short_squeeze_probability,get_stop_hunt_detectorMomentum:
get_momentum_quality_signal,get_momentum_exhaustionRisk Assessment:
get_market_maker_activity,get_liquidation_cascade_riskMarket Intelligence:
get_institutional_phase,get_aggregated_intelligence,get_execution_quality
Week 3: Visualization Tools (5 tools)
get_feature_candles- Feature-enriched OHLCV dataget_liquidity_heatmap- Real-time orderbook depth visualizationget_signal_dashboard- Composite signal gridget_regime_visualization- Market regime timelineget_correlation_matrix- Feature correlation analysis
Week 4: Feature Query Tools (4 tools)
query_historical_features- Query stored institutional featuresexport_features_csv- Export features to CSV for backtestingget_feature_statistics- Statistical analysis of feature distributionsget_feature_correlation_analysis- Cross-stream correlation discovery
Related MCP server: BotIndex MCP Server
🎯 What This System Does
Core Capabilities
🔴 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
🤖 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
🎓 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
💹 Cross-Exchange Arbitrage Detection
Real-time price monitoring across all exchanges
Identifies profitable price discrepancies instantly
Calculates profit margins and execution costs
🗄️ Persistent Storage
DuckDB with 504 isolated tables (per symbol/exchange)
7,393 records/minute ingestion capacity
Complete data isolation - no mixing
📊 Historical Analytics
Query stored DuckDB data for backtesting
Time-series aggregation and analysis
Export capabilities to CSV/Parquet
🏛️ 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
📈 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)
🔍 Advanced Analytics
Institutional flow detection
Squeeze probability computation
Smart money signals
Leverage analytics
Market regime detection
🛠️ MCP Tools Interface
252 AI-assistant-compatible tools (35 new in Phase 4)
Organized into 11 categories
Full forecasting, analytics, streaming, and institutional features
🤖 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
🔄 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 - 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
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
# 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.benchmarksConfiguration
Configuration files in crewai_integration/config/:
system.yaml- System settings, rate limits, featuresagents.yaml- Agent definitions and toolstasks.yaml- Task descriptions and workflowscrews.yaml- Crew compositions and flows
Documentation
Full documentation in crewai_integration/docs/:
🔄 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) |
| auto_reconnect on disconnect |
DataValidator | Ensure data quality & integrity |
| auto_validation every 5 min |
DataCleaner | Fix anomalies & interpolate gaps |
| gap_detection every 15 min |
SchemaManager | Manage DB schema & optimize |
| schema_optimize daily |
Tool Wrappers (MCP → CrewAI Bridge)
Phase 2 wraps all 252+ Phase 1 MCP tools into CrewAI-compatible tool classes:
# 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, compositeQuick Start (Data Operations Crew)
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
# 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 -vExpected 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 3Metrics Collected
Metric | Description | Storage |
| All agent activities |
|
| Data quality problems |
|
| Gap filling operations |
|
| Issues requiring human review |
|
| Overall system health (0-100%) | Computed from above |
⭐ Key Features (NEW in This Release)
Production Streaming System
# 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 bybitFeatures:
✅ 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
# 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 usedIntelligentRouter considers:
Data length and characteristics
Performance requirements (latency vs accuracy)
Hardware availability (GPU/CPU)
Historical model performance
Seasonality patterns
Model Drift Detection
# 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
XBTinstead ofBTCin their symbol format (e.g.,XBTUSDTMinstead ofBTCUSDTM). 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.duckdbTotal 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_tradesDynamic 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
# 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.txtInitialize Database
# Create isolated tables
python -m src.storage.isolated_database_initExpected output:
✅ Created isolated tables
📊 Tables created for 9 symbols across 7 exchanges (9 markets)
🗄️ Database: data/isolated_exchange_data.duckdbStart Robust Data Collection
# Start robust collector (recommended) - collects from all 7 exchanges
python robust_collector.py
# Or run for specific duration (in minutes)
python robust_collector.py 10Expected 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, tradesAlternative: Start Production Streaming
# 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.jsonExpected 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 lightgbmTest the System
# Run comprehensive integration tests
python test_streaming_system.pyExpected 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)
# 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:8501Architecture
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Exchanges │──────►│ MCP Server │──────►│ HTTP API │
│ (8 total) │ │ (248 tools)│ │ (FastAPI) │
└─────────────┘ └─────────────┘ └──────┬──────┘
│
▼
┌─────────────┐
│ Sibyl │
│ Dashboard │
│ (Streamlit) │
└─────────────┘See 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 routingforecast_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 forecastinglist_darts_models- List all available models
2. Production Forecasting Tools (7 tools) (NEW)
tune_forecast_hyperparameters- Automated tuning with Optunacross_validate_timeseries- 5 CV strategiesdetect_model_drift- 4 drift detection algorithmsregister_forecast_model- Model registry with trackingbacktest_forecast_strategy- Production backtestingget_model_performance- Performance metricsroute_forecast- Intelligent model routing
3. Explainability Tools (5 tools) (NEW)
explain_forecast_features- SHAP values and feature importanceget_forecast_confidence- Confidence intervalsanalyze_forecast_errors- Error analysisget_model_reasoning- Model decision explanation
4. Streaming Control Tools (8 tools) (NEW)
start_streaming- Start production streamingstop_streaming- Graceful shutdownget_streaming_status- Check streaming stateget_streaming_health- Health metrics (records/min, errors, uptime)get_streaming_alerts- System alerts (drift, errors)configure_streaming- Runtime configurationget_realtime_analytics_status- Analytics pipeline statusget_stream_forecast- Latest forecast for stream
5. Analytics Tools (60 tools)
Alpha Signal Generation (10 tools)
compute_alpha_signals- Composite intelligenceget_institutional_pressure- Smart money flowcompute_squeeze_probability- Market compression detection
Leverage Analytics (8 tools)
analyze_leverage_positioning- Position analysiscompute_oi_flow_decomposition- OI flow breakdowncompute_funding_stress- Funding rate stress
Regime Detection (12 tools)
detect_market_regime- Market state classificationdetect_event_risk- Event-driven regime changesidentify_volatility_regime- Vol regime detection
Time Series Analysis (20 tools)
detect_anomalies- Anomaly detectiondetect_changepoints- Structural break detectionanalyze_seasonality- Seasonal pattern analysis
Order Flow (10 tools)
analyze_trade_imbalance- Buy/sell pressurecompute_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 historyquery_historical_oi- Open interest historyquery_historical_funding- Funding rate historyaggregate_by_timeframe- Time aggregationexport_to_csv- Data export
8. Arbitrage Tools (5 tools)
analyze_crypto_arbitrage_tool- Cross-exchange arbitrageget_crypto_prices- Real-time pricesget_crypto_spreads- Spread matrixget_arbitrage_opportunities- Opportunity detectioncompare_exchange_prices- Exchange comparison
📈 Forecasting Examples
Quick Forecast with Auto-Routing
# 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
# 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 performanceZero-Shot Forecasting (Foundation Model)
# Use Chronos-2 for forecasting without training
result = await forecast_zero_shot(
symbol="SOLUSDT",
horizon=24
)
# Works on any data without historical model trainingProduction Backtesting
# 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
# 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
# Identify current market conditions
regime = await detect_market_regime(
symbol="ETHUSDT",
lookback_periods=100
)
# Returns:
# - regime_type: "trending_bullish"
# - volatility_state: "normal"
# - confidence: 0.89Drift Detection
# 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
# 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: 600sMonitor Health
# 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.5Get Live Forecast
# 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:
{
"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 - Complete data flow & integration diagram (NEW)
SYSTEM_WORKFLOW_DIAGRAM.md - Complete system visualization
COMPLETE_SCHEMA_REFERENCE.md - Database schema details
STREAM_REFERENCE.md - Data stream specifications
KATS_COMPARISON_SUMMARY.md - Comparison with Meta Kats
crewai_integration/docs/README.md - CrewAI integration guide
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:
Fork the repository
Create a feature branch
Commit your changes
Push to the branch
Open a Pull Request
📄 License
MIT License - see 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
Issues: Report a bug
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 |
| string | required | Trading pair |
| string | required | First exchange ID |
| 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 imbalance, trade flow analysis |
Layer 2 |
| Funding rate analysis, OI changes, liquidation tracking |
Layer 3 |
| Cross-exchange spreads, lead-lag relationships |
Layer 4 |
| Market regime detection (trending/ranging/volatile) |
Layer 5 |
| Composite signals, institutional pressure, squeeze probability |
Alpha Signals Computed
Institutional Pressure Score: Detects large player activity
Squeeze Probability Model: Predicts potential short/long squeezes
Smart Money Absorption: Identifies smart money accumulation/distribution
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 |
| Standard container compatible with institutional calculations |
Forecast Results |
| Forecasts with confidence intervals |
Anomaly Results |
| Anomaly detection outputs |
Change Points |
| Structural break detection results |
Regime Results |
| Market regime classification |
Regime Types |
| Enum: TRENDING_UP/DOWN, RANGING, HIGH/LOW_VOLATILITY, BREAKOUT, BREAKDOWN |
Capabilities
🔮 Forecasting Models
Model | Method | Description |
ARIMA |
| AutoRegressive Integrated Moving Average |
Exponential Smoothing |
| Holt-Winters with trend/seasonality |
Theta |
| Theta method for trend extrapolation |
Auto-Selection |
| Automatically selects best model |
🚨 Anomaly Detection Methods
Method | Function | Description |
Z-Score |
| Statistical z-score based detection |
IQR |
| Interquartile range method |
Isolation Forest |
| ML-based outlier detection |
CUSUM |
| Cumulative sum control chart |
📍 Change Point Detection
Method | Function | Description |
CUSUM |
| Cumulative sum change detection |
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 |
| Fast Fourier Transform for cycles |
Decomposition |
| Trend/Seasonal/Residual decomposition |
🎯 Market Regime Detection
Regime | Description |
| Strong upward momentum |
| Strong downward momentum |
| Sideways consolidation |
| Elevated volatility environment |
| Compressed volatility (pre-breakout) |
| Volatility expansion with upward movement |
| Volatility expansion with downward movement |
Time Series Feature Calculators (7 MCP Tools)
Calculator | MCP Tool | Description |
Price Forecast |
| Multi-model price forecasting with confidence intervals |
Anomaly Detection |
| Ensemble anomaly detection across multiple methods |
Change Points |
| Detect structural breaks and regime changes |
Feature Extraction |
| Extract 40+ statistical features for ML |
Regime Detection |
| Classify market regime with transition matrix |
Seasonality |
| Detect seasonal patterns and decompose trends |
Funding Forecast |
| Forecast funding rates with arbitrage signals |
Usage Examples
# 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:
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 |
| Query stored price history with OHLC aggregation |
| Query stored trade data with flow analysis |
| Query funding rate history with patterns |
| Query liquidation history |
| Query open interest history |
| Get database stats and available tables |
| Custom OHLC/volatility/volume profile queries |
Example: Query Historical Data
# 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 |
| Live prices + historical OHLC context |
| Current price with historical stats |
| Funding rate arbitrage with historical patterns |
| Liquidation distribution by price level |
| Z-score anomaly detection vs history |
Example: Market Snapshot with History
# 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 |
| Anomaly detection, feature extraction, change points |
Liquidation Cascade |
| Isolation forest anomalies, cascade onset detection |
Funding Arbitrage |
| Rate forecasting, seasonality detection |
Volatility Regime |
| Regime detection, transition matrix, seasonality |
Time Series Calculators (7) - Full TimeSeriesEngine Integration
Calculator | MCP Tool | Description |
Price Forecast |
| Multi-model price forecasting (ARIMA, ETS, Theta) |
Anomaly Detection |
| Ensemble anomaly detection (Z-score, IQR, Isolation Forest) |
Change Point Detection |
| Structural break and regime change detection |
Feature Extraction |
| 40+ statistical features for ML pipelines |
Regime Detection |
| Market regime classification with transitions |
Seasonality Analysis |
| Seasonal patterns and trend decomposition |
Funding Forecast |
| Funding rate forecasting with arbitrage signals |
Listing Available Calculators
# Use the MCP tool to list all calculators
await list_feature_calculators()Creating Custom Calculators
To add your own feature calculator:
Create a new Python file in
src/features/calculators/:
# 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}
}Restart the MCP server - Your calculator will be auto-discovered!
Use via MCP tool:
calculate_my_custom_feature
TimeSeriesEngine Methods Available
Every calculator has access to self.timeseries_engine with these methods:
Method | Description |
| Multi-model forecasting (ARIMA, ETS, Theta) |
| Z-score anomaly detection |
| IQR-based anomaly detection |
| ML isolation forest |
| CUSUM change point detection |
| PELT algorithm change points |
| Regime detection with transitions |
| Seasonal pattern detection |
| 40+ statistical features |
| 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 - TimeSeriesEngineAvailable Utilities in src/features/utils.py
Function | Description |
| Calculate z-score |
| Rolling mean calculation |
| EMA calculation |
| Annualized volatility |
| Volume-weighted average price |
| Identify whale trades |
| Orderbook imbalance ratio |
| Create standardized signals |
| 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 exchange connections |
|
| Logging verbosity (DEBUG, INFO, WARNING, ERROR) |
|
| Seconds between database flushes |
|
| Seconds between stats logging |
Collector Settings
Located in src/storage/production_isolated_collector.py:
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'"
pip install duckdb2. Database locked error DuckDB is single-writer. Stop the collector before querying:
# Press Ctrl+C in the collector terminal
# Then run your queries3. 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
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):
{
"mcpServers": {
"crypto-arbitrage": {
"command": "python",
"args": ["run_server.py"],
"cwd": "C:\\path\\to\\mcp-options-order-flow-server"
}
}
}Running as Background Service
Windows (PowerShell):
Start-Process -NoNewWindow -FilePath "python" -ArgumentList "-m src.storage.production_isolated_collector"Linux/Mac:
nohup python -m src.storage.production_isolated_collector > collector.log 2>&1 &📊 Data Schema Reference
Prices Table Schema
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
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
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
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
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 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 file for details.
🤝 Contributing
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Commit your changes (
git commit -m 'Add amazing feature')Push to the branch (
git push origin feature/amazing-feature)Open a Pull Request
📞 Support
For issues and feature requests, please use the GitHub Issues page.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Crypto MCP with 21 tools for market data, DeFi, analytics, and sentiment. Post-paid USDC billing.
Real-time crypto market data: candles, tickers, orderbooks across 13+ exchanges via MCP.
Trade 16 crypto exchanges + MetaTrader 5 from your AI assistant via one MCP connection.
MCP server with quote and live cryptocurrency price tools, local and cloud-deployed transports.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceA remote Model Context Protocol (MCP) server for real-time cryptocurrency and stock market analysis. Provides AI-powered market intelligence tools with 9 theory-based analysis engines, multi-chain DEX discovery, and enterprise features.-
- AlicenseNot gradedqualityDmaintenanceProvides predictive crypto market intelligence synthesized from whale positions, developer activity, and behavioral demand signals. Enables convergence scoring, whale divergence detection, and risk radar through MCP tools.116 npmMIT
- AlicenseAqualityCmaintenanceProvides real-time and historical crypto market data via WebSocket and REST for MCP clients, supporting multiple exchanges, 73 technical indicators, and advanced chart analysis tools.1929 PyPI1MIT
- AlicenseNot gradedqualityBmaintenanceQuantitative research, backtesting, creator-marketplace subscriptions, editable strategy forks, continuous copy trading, and controlled brokerage execution through 125 MCP tools.1,143 npm11MIT