Skip to main content
Glama

QuantConnect MCP Server

🚀 QuantConnect MCP Server

Professional-grade Model Context Protocol server for QuantConnect's algorithmic trading platform

Seamlessly integrate QuantConnect's research environment, statistical analysis, and portfolio optimization into your AI workflows

🎯 Quick Start📖 Documentation🏗️ Architecture🤝 Contributing


✨ Why QuantConnect MCP Server?

Transform your algorithmic trading research with a production-ready MCP server that provides:

  • 🧪 Research Environment: Full QuantBook integration for interactive financial analysis
  • 📊 Advanced Analytics: PCA, cointegration testing, mean reversion analysis, and correlation studies
  • 🎯 Portfolio Optimization: Sophisticated sparse optimization with Huber Downward Risk minimization
  • 🌐 Universe Selection: ETF constituent analysis and multi-criteria asset screening
  • 🔐 Enterprise Security: SHA-256 authenticated API integration with QuantConnect
  • High Performance: Async-first design with concurrent data processing

📋 Table of Contents

🎯 Quick Start

Get up and running in under 3 minutes:

1. Install Dependencies

# Clone the repository git clone https://github.com/your-org/quantconnect-mcp cd quantconnect-mcp # Install with uv (recommended) uv sync # Or with pip pip install -e .

2. Set Up QuantConnect Credentials

export QUANTCONNECT_USER_ID="your_user_id" export QUANTCONNECT_API_TOKEN="your_api_token" export QUANTCONNECT_ORGANIZATION_ID="your_org_id" # Optional

3. Launch the Server

# STDIO transport (default) python main.py # HTTP transport MCP_TRANSPORT=streamable-http MCP_PORT=8000 python main.py

4. Start Analyzing

# Initialize research environment await initialize_quantbook(instance_name="research") # Add securities for analysis await add_multiple_equities(["AAPL", "MSFT", "GOOGL", "AMZN"], resolution="Daily") # Perform sophisticated analysis await perform_pca_analysis( symbols=["AAPL", "MSFT", "GOOGL", "AMZN"], start_date="2023-01-01", end_date="2024-01-01" )

🛠️ Installation

Prerequisites

  • Python 3.12+ (Type-annotated for maximum reliability)
  • QuantConnect LEAN (Installation Guide)
  • Active QuantConnect Account with API access

Standard Installation

# Using uv (fastest) uv sync # Using pip pip install -e . # Development installation with testing tools uv sync --dev

Verify Installation

# Check server health python -c "from src.server import mcp; print('✅ Installation successful')" # Run test suite pytest tests/ -v

🔑 Authentication

Getting Your Credentials

CredentialWhere to FindRequired
User IDEmail received when signing up✅ Yes
API TokenQuantConnect Settings✅ Yes
Organization IDOrganization URL: /organization/{ID}⚪ Optional

Configuration Methods

# Add to your .bashrc, .zshrc, or .env file export QUANTCONNECT_USER_ID="123456" export QUANTCONNECT_API_TOKEN="your_secure_token_here" export QUANTCONNECT_ORGANIZATION_ID="your_org_id" # Optional
Method 2: Runtime Configuration
# Configure programmatically await configure_quantconnect_auth( user_id="123456", api_token="your_secure_token_here", organization_id="your_org_id" # Optional ) # Validate configuration result = await validate_quantconnect_auth() print(f"Auth Status: {result['authenticated']}")
Method 3: Interactive Setup
# Check current status status = await get_auth_status() # Test API connectivity test_result = await test_quantconnect_api()

🚀 Usage Examples

Financial Research Pipeline

# 1. Initialize research environment await initialize_quantbook(instance_name="research_2024") # 2. Build universe from ETF constituents await add_etf_universe_securities( etf_ticker="QQQ", date="2024-01-01", resolution="Daily" ) # 3. Perform correlation analysis correlation_matrix = await calculate_correlation_matrix( symbols=["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"], start_date="2023-01-01", end_date="2024-01-01" ) # 4. Find uncorrelated assets for diversification uncorrelated = await select_uncorrelated_assets( symbols=correlation_matrix["symbols"], num_assets=5, method="lowest_correlation", start_date="2023-01-01", end_date="2024-01-01" ) # 5. Optimize portfolio with advanced algorithm optimized_portfolio = await sparse_optimization( portfolio_symbols=uncorrelated["selected_assets"]["symbols"], benchmark_symbol="SPY", start_date="2023-01-01", end_date="2024-01-01", max_weight=0.15, lambda_param=0.01 )

Statistical Analysis Workflow

# Cointegration analysis for pairs trading cointegration_result = await test_cointegration( symbol1="KO", symbol2="PEP", start_date="2023-01-01", end_date="2024-01-01", trend="c" ) if cointegration_result["is_cointegrated"]: print(f"✅ Cointegration detected (p-value: {cointegration_result['cointegration_pvalue']:.4f})") # Analyze mean reversion opportunities mean_reversion = await analyze_mean_reversion( symbols=["KO", "PEP"], start_date="2023-01-01", end_date="2024-01-01", lookback_period=20 )

Project and Backtest Management

# Create new algorithmic trading project project = await create_project( name="Mean_Reversion_Strategy_v2", language="Py" ) # Upload algorithm code await create_file( project_id=project["project"]["projectId"], name="main.py", content=algorithm_code ) # Run backtest backtest = await create_backtest( project_id=project["project"]["projectId"], compile_id="latest", backtest_name="Mean_Reversion_Test_Run", parameters={"lookback_period": 20, "threshold": 2.0} ) # Analyze results results = await read_backtest( project_id=project["project"]["projectId"], backtest_id=backtest["backtest"]["backtestId"] )

📖 Comprehensive API Reference

🔐 Authentication Tools

ToolDescriptionKey Parameters
configure_quantconnect_authSet up API credentialsuser_id, api_token, organization_id
validate_quantconnect_authTest credential validity-
get_auth_statusCheck authentication status-
test_quantconnect_apiTest API connectivityendpoint, method
clear_quantconnect_authClear stored credentials-

📊 Project Management Tools

ToolDescriptionKey Parameters
create_projectCreate new QuantConnect projectname, language, organization_id
read_projectGet project details or list allproject_id (optional)
update_projectUpdate project name/descriptionproject_id, name, description

📁 File Management Tools

ToolDescriptionKey Parameters
create_fileCreate file in projectproject_id, name, content
read_fileRead file(s) from projectproject_id, name (optional)
update_file_contentUpdate file contentproject_id, name, content
update_file_nameRename file in projectproject_id, old_file_name, new_name

🧪 QuantBook Research Tools

ToolDescriptionKey Parameters
initialize_quantbookCreate new research instanceinstance_name, organization_id, token
list_quantbook_instancesView all active instances-
get_quantbook_infoGet instance detailsinstance_name
remove_quantbook_instanceClean up instanceinstance_name

📈 Data Retrieval Tools

ToolDescriptionKey Parameters
add_equityAdd single equity securityticker, resolution, instance_name
add_multiple_equitiesAdd multiple securitiestickers, resolution, instance_name
get_historyGet historical price datasymbols, start_date, end_date, resolution
add_alternative_dataSubscribe to alt datadata_type, symbol, instance_name
get_alternative_data_historyGet alt data historydata_type, symbols, start_date, end_date

🔬 Statistical Analysis Tools

ToolDescriptionKey Parameters
perform_pca_analysisPrincipal Component Analysissymbols, start_date, end_date, n_components
test_cointegrationEngle-Granger cointegration testsymbol1, symbol2, start_date, end_date
analyze_mean_reversionMean reversion analysissymbols, start_date, end_date, lookback_period
calculate_correlation_matrixAsset correlation analysissymbols, start_date, end_date

💰 Portfolio Optimization Tools

ToolDescriptionKey Parameters
sparse_optimizationAdvanced sparse optimizationportfolio_symbols, benchmark_symbol, optimization params
calculate_portfolio_performancePerformance metricssymbols, weights, start_date, end_date
optimize_equal_weight_portfolioEqual-weight optimizationsymbols, start_date, end_date, rebalance_frequency

🌐 Universe Selection Tools

ToolDescriptionKey Parameters
get_etf_constituentsGet ETF holdingsetf_ticker, date, instance_name
add_etf_universe_securitiesAdd all ETF constituentsetf_ticker, date, resolution
select_uncorrelated_assetsFind uncorrelated assetssymbols, num_assets, method
screen_assets_by_criteriaMulti-criteria screeningsymbols, min_return, max_volatility, etc.

🔥 Backtest Management Tools

ToolDescriptionKey Parameters
create_backtestCreate new backtestproject_id, compile_id, backtest_name
read_backtestGet backtest resultsproject_id, backtest_id, chart
read_backtest_chartGet chart dataproject_id, backtest_id, name
read_backtest_ordersGet order historyproject_id, backtest_id, start, end
read_backtest_insightsGet insights dataproject_id, backtest_id, start, end

🏗️ Architecture

quantconnect-mcp/ ├── 🎛️ main.py # Server entry point & configuration ├── 📊 src/ │ ├── 🖥️ server.py # FastMCP server core │ ├── 🔧 tools/ # Tool implementations │ │ ├── 🔐 auth_tools.py # Authentication management │ │ ├── 📁 project_tools.py # Project CRUD operations │ │ ├── 📄 file_tools.py # File management │ │ ├── 🧪 quantbook_tools.py # Research environment │ │ ├── 📈 data_tools.py # Data retrieval │ │ ├── 🔬 analysis_tools.py # Statistical analysis │ │ ├── 💰 portfolio_tools.py # Portfolio optimization │ │ ├── 🌐 universe_tools.py # Universe selection │ │ └── 📊 backtest_tools.py # Backtest management │ ├── 🔐 auth/ # Authentication system │ │ ├── __init__.py │ │ └── quantconnect_auth.py # Secure API authentication │ └── 📊 resources/ # System resources │ ├── __init__.py │ └── system_resources.py # Server monitoring ├── 🧪 tests/ # Comprehensive test suite │ ├── test_auth.py │ ├── test_server.py │ └── __init__.py ├── 📋 pyproject.toml # Project configuration └── 📖 README.md # This file

Core Design Principles

  • 🏛️ Modular Architecture: Each tool category is cleanly separated for maintainability
  • 🔒 Security First: SHA-256 authenticated API with secure credential management
  • ⚡ Async Performance: Non-blocking operations for maximum throughput
  • 🧪 Type Safety: Full type annotations with mypy verification
  • 🔧 Extensible: Plugin-based architecture for easy feature additions

🔧 Advanced Configuration

Transport Options

# STDIO (default) - Best for MCP clients python main.py # HTTP Server - Best for web integrations MCP_TRANSPORT=streamable-http MCP_HOST=0.0.0.0 MCP_PORT=8000 python main.py # Custom path for HTTP MCP_PATH=/api/v1/mcp python main.py

Environment Variables

VariableDescriptionDefaultExample
MCP_TRANSPORTTransport methodstdiostreamable-http
MCP_HOSTServer host127.0.0.10.0.0.0
MCP_PORTServer port80003000
MCP_PATHHTTP endpoint path/mcp/api/v1/mcp
LOG_LEVELLogging verbosityINFODEBUG

System Resources

Monitor server performance and status:

# System information system_info = await get_resource("resource://system/info") # Server status and active instances server_status = await get_resource("resource://quantconnect/server/status") # Available tools summary tools_summary = await get_resource("resource://quantconnect/tools/summary") # Performance metrics performance = await get_resource("resource://quantconnect/performance/metrics") # Top processes by CPU usage top_processes = await get_resource("resource://system/processes/10")

🧪 Testing

Run the Test Suite

# Run all tests pytest tests/ -v # Run with coverage pytest tests/ --cov=src --cov-report=html # Run specific test category pytest tests/test_auth.py -v # Run tests in parallel pytest tests/ -n auto

Manual Testing

# Test authentication python -c " import asyncio from src.auth import validate_authentication print(asyncio.run(validate_authentication())) " # Test server startup python main.py --help

🤝 Contributing

We welcome contributions! This project follows the highest Python development standards:

Development Setup

# Fork and clone the repository git clone https://github.com/your-username/quantconnect-mcp cd quantconnect-mcp # Install development dependencies uv sync --dev # Install pre-commit hooks pre-commit install

Code Quality Standards

  • Type Hints: All functions must have complete type annotations
  • Documentation: Comprehensive docstrings for all public functions
  • Testing: Minimum 90% test coverage required
  • Formatting: Black code formatting enforced
  • Linting: Ruff linting with zero warnings
  • Type Checking: mypy verification required

Development Workflow

# Create feature branch git checkout -b feature/amazing-new-feature # Make changes and run quality checks ruff check src/ black src/ tests/ mypy src/ # Run tests pytest tests/ --cov=src # Commit with conventional commits git commit -m "feat: add amazing new feature" # Push and create pull request git push origin feature/amazing-new-feature

Pull Request Guidelines

  1. 📝 Clear Description: Explain what and why, not just how
  2. 🧪 Test Coverage: Include tests for all new functionality
  3. 📖 Documentation: Update README and docstrings as needed
  4. 🔍 Code Review: Address all review feedback
  5. ✅ CI Passing: All automated checks must pass

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❤️ for the algorithmic trading community

⭐ Star this repo🐛 Report issues💡 Request features

Related MCP Servers

  • -
    security
    A
    license
    -
    quality
    Enables seamless integration with any LLM client supporting MCP for creating and optimizing technical content and product positioning using Open Strategy Partners' methodologies.
    Last updated -
    149
    Python
    CC BY-SA 4.0
    • Apple
  • -
    security
    A
    license
    -
    quality
    Provides a semantic memory layer that integrates LLMs with OpenSearch, enabling storage and retrieval of memories within the OpenSearch engine.
    Last updated -
    Python
    Apache 2.0
  • -
    security
    F
    license
    -
    quality
    Enables interaction with lightning addresses and common lightning tools via your LLM, providing Lightning Network functionality through natural language.
    Last updated -
    10
    1
    TypeScript
  • -
    security
    F
    license
    -
    quality
    Enables communication and coordination between different LLM agents across multiple systems, allowing specialized agents to collaborate on tasks, share context, and coordinate work through a unified platform.
    Last updated -
    4
    TypeScript
    • Linux
    • Apple

View all related MCP servers

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/taylorwilsdon/quantconnect-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server