Crypto-Market-Data-MCP-Server-

shubhamkumar62092/Crypto-Market-Data-MCP-Server-

3.1

If you are the rightful owner of Crypto-Market-Data-MCP-Server- and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

A production-ready Model Context Protocol (MCP) server for retrieving real-time and historical cryptocurrency market data from major exchanges.

🚀 Crypto Market Data MCP Server

A production-ready Model Context Protocol (MCP) server for retrieving real-time and historical cryptocurrency market data from major exchanges.

✨ Features

  • 🔄 Real-time Price Data - Current prices, bid/ask spreads, and volume
  • 📊 Historical Data - OHLCV candlestick data with customizable timeframes
  • 📖 Order Book - Real-time market depth analysis
  • 📈 24h Statistics - Comprehensive trading metrics
  • 🏦 Multi-Exchange - Binance, Coinbase, Kraken, Bitfinex support
  • Smart Caching - Intelligent caching with TTL to minimize API calls
  • 🛡️ Error Handling - Comprehensive error handling and logging
  • 🚦 Rate Limiting - Built-in rate limit protection
  • ⚙️ Async Architecture - Full async/await for high performance

🎯 Approach & Design Philosophy

Architecture Overview

The server is built with a layered architecture focusing on:

  1. Separation of Concerns: Each component has a single responsibility
  2. Caching Strategy: Multi-level caching to reduce API calls and costs
  3. Error Resilience: Graceful degradation with detailed error messages
  4. Type Safety: Pydantic models for validation and documentation
  5. Extensibility: Easy to add new exchanges and endpoints

Key Components

Design Decisions

1. CCXT Library Choice

  • ✅ Unified API across 100+ exchanges
  • ✅ Built-in rate limiting and error handling
  • ✅ Active maintenance and community
  • ✅ Standardized data formats

2. Caching Strategy

  • Ticker data: 10s TTL (fast-changing)
  • OHLCV data: 60s TTL (slower-changing)
  • Order book: 5s TTL (very fast-changing)
  • Markets: 1h TTL (rarely changes)

3. Async Architecture

  • Non-blocking I/O for concurrent requests
  • Better resource utilization
  • Improved response times

📋 Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)
  • Internet connection (for API access)

🔧 Installation

Option 1: Quick Start (pip)

# Clone the repository
git clone https://github.com/yourusername/crypto-mcp-server.git
cd crypto-mcp-server

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

Option 2: Development Setup

# Install with dev dependencies
pip install -r requirements-dev.txt

# Install in editable mode
pip install -e .

Option 3: Using setup.py

python setup.py install

🚀 Quick Start

Starting the Server

python -m crypto_mcp_server.server

Basic Usage Example

import asyncio
from crypto_mcp_server import CryptoMCPServer

async def main():
    server = CryptoMCPServer()
    
    # Get current BTC price
    price_data = await server._get_price({
        "symbol": "BTC/USDT",
        "exchange": "binance"
    })
    print(f"BTC Price: ${price_data['price']}")

asyncio.run(main())

📖 API Documentation

Available Tools

1. Get Current Price
{
  "name": "get_price",
  "arguments": {
    "symbol": "BTC/USDT",
    "exchange": "binance"
  }
}

Response:

{
  "symbol": "BTC/USDT",
  "exchange": "binance",
  "price": 50000.0,
  "bid": 49999.5,
  "ask": 50000.5,
  "volume": 1234.56,
  "timestamp": 1640000000000
}
2. Get Historical Data
{
  "name": "get_historical",
  "arguments": {
    "symbol": "ETH/USDT",
    "timeframe": "1h",
    "limit": 100,
    "exchange": "binance"
  }
}
3. Get Order Book
{
  "name": "get_orderbook",
  "arguments": {
    "symbol": "BTC/USDT",
    "limit": 20,
    "exchange": "binance"
  }
}
4. Get 24h Statistics
{
  "name": "get_24h_stats",
  "arguments": {
    "symbol": "BTC/USDT",
    "exchange": "binance"
  }
}

Supported Exchanges

  • Binance - binance
  • Coinbase - coinbase
  • Kraken - kraken
  • Bitfinex - bitfinex

Timeframes

  • 1m - 1 minute
  • 5m - 5 minutes
  • 15m - 15 minutes
  • 1h - 1 hour
  • 4h - 4 hours
  • 1d - 1 day
  • 1w - 1 week

🧪 Testing

Run All Tests

pytest tests/ -v

Run Specific Test Suite

# Cache tests
pytest tests/test_cache.py -v

# Exchange manager tests
pytest tests/test_exchange_manager.py -v

# Integration tests
pytest tests/test_integration.py -v

Run with Coverage

pytest --cov=crypto_mcp_server --cov-report=html

Test Markers

# Integration tests only
pytest -m integration

# Performance tests only
pytest -m performance

🔍 Assumptions & Limitations

Assumptions

  1. Network Connectivity: Assumes stable internet connection
  2. Exchange APIs: Assumes exchange APIs are available and responding
  3. Rate Limits: Assumes default rate limits for public endpoints
  4. Data Format: Assumes standardized CCXT data formats
  5. Memory: Assumes sufficient memory for caching (typically <100MB)

Limitations

  1. Public Data Only: Currently supports only public endpoints (no authentication)
  2. In-Memory Cache: Cache is not persistent across restarts
  3. Single Instance: Not designed for distributed deployment (yet)
  4. Exchange Coverage: Limited to 4 major exchanges (easily extensible)
  5. Historical Data: Limited by exchange API constraints (typically 500-1000 candles)

Future Enhancements

  • Add authentication support for private endpoints
  • Implement persistent caching (Redis)
  • Add WebSocket support for real-time streaming
  • Support more exchanges
  • Add portfolio tracking features
  • Implement distributed caching
  • Add GraphQL interface
  • Create REST API wrapper

⚙️ Configuration

Environment Variables

# Optional: Custom cache TTL (seconds)
export TICKER_CACHE_TTL=10
export OHLCV_CACHE_TTL=60
export ORDERBOOK_CACHE_TTL=5
export MARKETS_CACHE_TTL=3600

# Optional: Log level
export LOG_LEVEL=INFO  # DEBUG, INFO, WARNING, ERROR

# Optional: Exchange API keys (for private endpoints)
export BINANCE_API_KEY=your_key
export BINANCE_SECRET=your_secret

Custom Configuration

from crypto_mcp_server import ExchangeManager

# Custom cache TTL
manager = ExchangeManager()
manager.cache.set("key", data, ttl=120)  # 2 minutes

# Add API credentials
manager.exchanges['binance'].apiKey = 'your_key'
manager.exchanges['binance'].secret = 'your_secret'

🐛 Troubleshooting

Common Issues

Issue: "Unsupported exchange" error

Solution: Verify exchange name is lowercase and supported
Supported: binance, coinbase, kraken, bitfinex

Issue: Rate limit exceeded

Solution: Increase cache TTL or reduce request frequency
export TICKER_CACHE_TTL=30

Issue: Invalid symbol format

Solution: Use "BASE/QUOTE" format
Correct: "BTC/USDT"
Incorrect: "BTCUSDT" or "BTC-USDT"

Issue: Network timeout

Solution: Check internet connection or try different exchange

Made with ❤️ by shubham kumar