MCP server for crypto trading via Binance.US
Project description
Crypto MCP Trading Server
A Model Context Protocol (MCP)-compliant server for crypto trading via Binance.US, enabling LLM-driven trading with built-in risk management and paper trading support.
Features
- โ
MCP Protocol Compliance: Standard
/mcp/contextsand/mcp/actionsendpoints - ๐ Secure Authentication: Auto-generated 64-character token on startup
- ๐ Complete Market Visibility: AI can see ALL tradable coins on Binance
- ๐น Comprehensive Market Data: Real-time prices, order books, candlesticks, 24h tickers
- ๐ Technical Analysis: RSI, MACD, SMA, EMA, Bollinger Bands on all timeframes
- ๐ฐ Fee Structure Access: See maker/taker fees for every trading pair
- ๐ค Trade Execution: Support for MARKET, LIMIT, STOP orders via Binance.US API
- ๐ก๏ธ Optional Risk Management: Set limits or let AI trade freely
- ๐ Paper Trading: Full mock trading mode for testing strategies without risk
- ๐พ Database Logging: SQLite database for trade logs and context snapshots
- ๐ Portfolio Tracking: Real-time balance and position monitoring
Architecture
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
โ โ MCP โ โ REST โ โ
โ LLM Client โโโโโโโโโโบโ MCP Server โโโโโโโโโโบโ Binance.US โ
โ โProtocol โ (FastAPI) โ API โ Exchange โ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
โ
โ Logs
โผ
โโโโโโโโโโโโโโโ
โ SQLite โ
โ Database โ
โโโโโโโโโโโโโโโ
Installation
Prerequisites
- Python 3.8+
- Binance.US account with API keys (for live trading)
- pip package manager
Option 1: Install from Source (Development)
- Clone or download the project
git clone <repository-url>
cd "Crypto MCP"
- Install package in editable mode
pip install -e .
Or install with development dependencies for testing:
pip install -e ".[dev]"
- Configure environment variables
Copy the example environment file and edit it:
cp .env.example .env
Edit the .env file and replace placeholder values:
# REQUIRED: Add your Binance.US API keys
BINANCE_API_KEY=your_real_api_key_here
BINANCE_API_SECRET=your_real_api_secret_here
# Set trading mode (paper or live)
TRADING_MODE=paper
# OPTIONAL: Risk limits (omit for unlimited AI trading)
# MAX_TRADE_SIZE_USD=1000
# MAX_DAILY_LOSS_USD=500
# MAX_POSITION_SIZE_USD=5000
๐ No auth token needed! A secure 64-character token is auto-generated on startup.
Option 2: Install for Claude Desktop
- Install the package
pip install binance-mcp
- Configure Claude Desktop
Add to your Claude Desktop configuration file:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
Minimal Configuration (AI Asks Trading Mode):
{
"mcpServers": {
"crypto-trading": {
"command": "binance-mcp",
"env": {
"BINANCE_API_KEY": "your_binance_api_key_here",
"BINANCE_API_SECRET": "your_binance_api_secret_here"
}
}
}
}
With Daily Loss Limit (Safety Net for Live Trading):
{
"mcpServers": {
"crypto-trading": {
"command": "binance-mcp",
"env": {
"BINANCE_API_KEY": "your_binance_api_key_here",
"BINANCE_API_SECRET": "your_binance_api_secret_here",
"MAX_DAILY_LOSS_USD": "500.0"
}
}
}
}
๐ค AI asks trading mode: The AI will ask you "Do you want paper or live trading?" before each session ๐ Auth token auto-generated: Secure 64-character token created on startup โ Auto-detect balance: Always enabled, no configuration needed
๐ก See claude_desktop_config_examples.md for more configuration examples
- Restart Claude Desktop
The MCP server will automatically start when Claude Desktop launches.
See INSTALL.md for detailed installation instructions.
Usage
Starting the Server
If installed as package:
binance-mcp
If running from source:
python -m crypto_mcp_server.server
The server will start on http://localhost:8000
Running the Example Client
# Run trading workflow example
python llm_client_example.py
# Run monitoring loop
python llm_client_example.py 2
API Endpoints
Health Check
GET /health
Get Contexts (Market Data, Account State, Trade History)
POST /mcp/contexts
Authorization: Bearer <your_token>
# Get market data for specific symbols
{
"context_types": ["market_data"],
"symbols": ["BTCUSD", "ETHUSD"]
}
# Discover ALL tradable coins
{
"context_types": ["all_markets"]
}
# Get trading fees
{
"context_types": ["fee_structure"],
"symbols": ["BTCUSD", "ETHUSD"] # Optional: all symbols if omitted
}
# Get candlestick data for technical analysis
{
"context_types": ["candlestick_data"],
"symbols": ["BTCUSD"],
"timeframe": "1h", # Optional: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w
"limit": 100 # Optional: number of candles (default 100)
}
# Get order book depth
{
"context_types": ["order_book"],
"symbols": ["BTCUSD"],
"limit": 100 # Optional: depth levels (default 100)
}
# Get 24h ticker statistics
{
"context_types": ["ticker_24h"],
"symbols": ["BTCUSD", "ETHUSD"] # Optional: all tickers if omitted
}
# Get technical indicators
{
"context_types": ["technical_indicators"],
"symbols": ["BTCUSD"],
"timeframe": "1h" # Optional: default 1h
}
# Get multiple context types at once
{
"context_types": ["market_data", "account_state", "technical_indicators"],
"symbols": ["BTCUSD"],
"timeframe": "1h"
}
Execute Actions (Trade Orders, Cancellations)
POST /mcp/actions
Authorization: Bearer <your_token>
{
"actions": [
{
"action_id": "action_123",
"action": {
"action_type": "trade_order",
"symbol": "BTCUSD",
"side": "BUY",
"order_type": "MARKET",
"quantity": 0.01
}
}
],
"auth_token": "<your_token>"
}
MCP Protocol Schema
Context Types
The AI has access to the following context types for complete market visibility:
-
market_data: Current market information for specific symbols
- Real-time price, bid/ask spread
- 24h volume, high, low
- Price change and percentage
-
all_markets: Discover ALL tradable coins on Binance
- List of every trading pair available
- Base/quote assets for each pair
- Trading status (TRADING, HALT, etc.)
- Current price and 24h volume for all pairs
- Margin/spot trading capabilities
-
fee_structure: Trading fees for all symbols
- Maker fee percentage
- Taker fee percentage
- Per-symbol fee information
-
candlestick_data: OHLCV data for technical analysis
- Open, High, Low, Close, Volume
- Multiple timeframes: 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w
- Historical data up to 1000 candles
- Quote volume and trade counts
-
order_book: Real-time order book depth
- Bid orders (buy side)
- Ask orders (sell side)
- Price levels and quantities
- Up to 5000 levels of depth
-
ticker_24h: 24-hour statistics for symbols
- Price change and percentage
- Weighted average price
- Previous close, open, high, low
- Current bid/ask prices
- 24h volume and quote volume
- Number of trades
-
technical_indicators: Calculated indicators for any symbol/timeframe
- RSI (Relative Strength Index): Oversold/overbought signals
- MACD (Moving Average Convergence Divergence): Trend momentum
- SMA (Simple Moving Average): 20 and 50 period
- EMA (Exponential Moving Average): 12 and 26 period
- Bollinger Bands: Upper, middle, lower bands
- Buy/Sell/Neutral signals for each indicator
-
account_state: Account balances and positions
- Asset balances (free, locked, total)
- Portfolio value in USD
- Open positions with P&L
-
trade_history: Historical trades
- Past orders, fills, commissions
- Trade timestamps and prices
Action Types
-
trade_order: Execute a trade
- Required: symbol, side, quantity
- Optional: price, stop_price, order_type
-
cancel_order: Cancel an existing order
- Required: symbol, order_id
Risk Management
The server includes optional risk controls - you decide what limits to set:
Optional Limits (Can be omitted for AI full control)
- Max Trade Size: Limit per individual trade (omit for unlimited)
- Max Position Size: Maximum position value (omit for unlimited)
- Daily Loss Limit: Maximum loss allowed per day (omit for unlimited)
- Circuit Breaker: Only triggers if daily loss limit is set
AI Trading Modes
๐ค AI Full Control (No Limits):
- Omit all
MAX_*environment variables - AI uses entire available balance
- No restrictions on trade size or frequency
- Use with: Paper trading or if you trust the AI completely
โ๏ธ AI with Daily Loss Limit Only:
- Set only
MAX_DAILY_LOSS_USD - AI trades freely until daily loss limit hit
- Circuit breaker stops trading for the day
- Use with: Live trading when you want safety net
๐ก๏ธ Conservative Mode (All Limits):
- Set all
MAX_TRADE_SIZE_USD,MAX_DAILY_LOSS_USD,MAX_POSITION_SIZE_USD - Maximum protection with strict controls
- Use with: Live trading for beginners
See claude_desktop_config_examples.md for detailed configuration examples
Paper Trading vs Live Trading
Paper Trading (Default)
- No real money involved
- Mock execution engine
- Starting balance: $10,000 USD
- Perfect for testing strategies
Live Trading
- Real orders on Binance.US
- Requires valid API keys
- Real money at risk
- Set
TRADING_MODE=livein.env
โ ๏ธ WARNING: Always test thoroughly in paper mode before switching to live!
Database
The server maintains a SQLite database (trading.db) with:
- trade_logs: All executed trades
- context_snapshots: Historical context data
- daily_pnl: Daily profit/loss tracking
Security
- API keys stored in environment variables (never committed)
- Token-based authentication for MCP endpoints
- Request validation and authorization
- No direct key access for LLM clients
Development
Project Structure
Crypto MCP/
โโโ crypto_mcp_server/ # Main package
โ โโโ __init__.py # Package init
โ โโโ server.py # Entry point
โ โโโ mcp_server.py # FastAPI server
โ โโโ schemas.py # Pydantic models
โ โโโ binance_client.py # Binance.US integration
โ โโโ paper_trading.py # Mock trading engine
โ โโโ risk_manager.py # Risk controls
โ โโโ database.py # SQLAlchemy models
โ โโโ config.py # Configuration
โโโ tests/ # Test suite
โ โโโ conftest.py # Test fixtures
โ โโโ test_mcp_server.py # API tests
โ โโโ test_paper_trading.py # Trading engine tests
โ โโโ test_risk_manager.py # Risk tests
โ โโโ test_database.py # Database tests
โ โโโ test_integration.py # E2E tests
โ โโโ README.md # Test documentation
โโโ setup.py # Package setup (legacy)
โโโ pyproject.toml # Package configuration
โโโ pytest.ini # Pytest configuration
โโโ MANIFEST.in # Package manifest
โโโ requirements.txt # Dependencies
โโโ .env.example # Example environment
โโโ INSTALL.md # Installation guide
โโโ claude_desktop_config.json # Claude Desktop config example
โโโ README.md # This file
Adding New Features
- New Context Types: Add to
schemas.pyand implement inmcp_server.py - New Actions: Define in
schemas.py, implement handler inmcp_server.py - Risk Rules: Extend
risk_manager.pyvalidation logic - Trading Strategies: Implement in LLM client logic
Testing
Running Tests
The project includes a comprehensive test suite with 64+ tests covering:
- API endpoints and authentication
- Paper trading engine
- Risk management
- Database operations
- End-to-end workflows
Run all tests:
pytest
Run with verbose output:
pytest -v
Run with coverage report:
pytest --cov=crypto_mcp_server --cov-report=html
Run specific test file:
pytest tests/test_mcp_server.py
See tests/README.md for detailed testing documentation.
Manual Testing
# Test health endpoint
curl http://localhost:8000/health
# Test context retrieval
curl -X POST http://localhost:8000/mcp/contexts \
-H "Authorization: Bearer mcp_secure_token_12345" \
-H "Content-Type: application/json" \
-d '{"context_types": ["market_data"], "symbols": ["BTCUSD"]}'
Troubleshooting
"Failed to initialize Binance client"
- Expected when using placeholder API keys
- Switch to live mode and add real keys, or continue with paper trading
"Invalid authorization token"
- Ensure
MCP_AUTH_TOKENmatches in.envand client - Check Authorization header format:
Bearer <token>
"Circuit breaker triggered"
- Daily loss limit exceeded
- Reset by clearing
daily_pnltable or waiting for next day - Adjust
MAX_DAILY_LOSS_USDin.env
Connection errors
- Ensure server is running on correct port
- Check firewall settings
- Verify network connectivity to Binance.US (for live mode)
License
MIT License - see LICENSE file for details
Disclaimer
This software is for educational purposes. Trading cryptocurrencies involves significant risk. Always test thoroughly in paper trading mode before risking real capital. The authors are not responsible for any financial losses.
Support
For issues or questions:
- Check this README
- Review logs in console output
- Examine
trading.dbfor trade history - Open an issue on GitHub (if applicable)
What the AI Can See and Do
Complete Market Visibility โ
The AI has full access to all Binance market data:
- โ
Every tradable coin/pair on Binance (use
all_marketscontext) - โ Real-time prices for all symbols
- โ Trading fees (maker/taker) for every pair
- โ Order book depth up to 5000 levels
- โ Historical candlesticks (OHLCV) on all timeframes
- โ 24h ticker statistics (volume, price change, etc.)
- โ Technical indicators (RSI, MACD, SMA, EMA, Bollinger Bands)
Timeframes Supported โฐ
The AI can analyze any symbol on these timeframes:
1m- 1 minute5m- 5 minutes15m- 15 minutes30m- 30 minutes1h- 1 hour (default)4h- 4 hours1d- 1 day1w- 1 week
Technical Indicators ๐
The AI can request calculated indicators for any symbol/timeframe:
-
RSI (Relative Strength Index)
- 14-period RSI
- Buy signal when < 30 (oversold)
- Sell signal when > 70 (overbought)
-
MACD (Moving Average Convergence Divergence)
- 12/26/9 period MACD
- Buy signal when MACD > signal line
- Sell signal when MACD < signal line
-
SMA (Simple Moving Average)
- 20-period and 50-period SMA
- Buy signal when SMA20 > SMA50 (golden cross)
- Sell signal when SMA20 < SMA50 (death cross)
-
EMA (Exponential Moving Average)
- 12-period and 26-period EMA
- Used for MACD calculation
-
Bollinger Bands
- 20-period, 2 standard deviations
- Upper, middle (SMA20), and lower bands
- Buy signal when price < lower band
- Sell signal when price > upper band
Trading Capabilities ๐ฐ
The AI can execute:
- MARKET orders - Instant execution at current price
- LIMIT orders - Execute at specific price or better
- STOP orders - Trigger at stop price
- Order cancellations - Cancel pending orders
Discovery Workflow Example ๐
1. AI: "What coins can I trade?"
โ Request context_type: "all_markets"
โ See all 300+ trading pairs
2. AI: "What are the fees for BTCUSD?"
โ Request context_type: "fee_structure" with symbol "BTCUSD"
โ See maker/taker fees (typically 0.1%)
3. AI: "Show me BTC price history"
โ Request context_type: "candlestick_data" with symbol "BTCUSD", timeframe "1h"
โ Get 100 hourly candles
4. AI: "What do the indicators say about BTC?"
โ Request context_type: "technical_indicators" with symbol "BTCUSD"
โ Get RSI, MACD, SMA, EMA, Bollinger Bands with buy/sell signals
5. AI: "Buy 0.01 BTC"
โ Execute action: trade_order with symbol "BTCUSD", side "BUY", quantity 0.01
โ Order executed
AI Trading Modes ๐ค
Paper Trading (Safe)
- All context data uses mock/realistic values
- No real API calls to Binance
- Perfect for testing and strategy development
Live Trading (Real Money)
- All context data from real Binance API
- Real-time prices, order books, fees
- Real money at risk - use with caution!
๐ก The AI will ask you: "Do you want paper or live trading?" before each session
Roadmap
- Margin/futures trading support for shorts
- WebSocket streaming for real-time market data
- Advanced order types (trailing stop, OCO)
- Multi-exchange support
- Backtesting framework
- Performance analytics dashboard
- Telegram/Discord notifications
- Strategy templates library
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file binance_mcp-1.0.0.tar.gz.
File metadata
- Download URL: binance_mcp-1.0.0.tar.gz
- Upload date:
- Size: 28.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
81fab3d25e5d11543740a100acd054a89eb64e2e666ac1ae10b95efbb8649a75
|
|
| MD5 |
d69546177e6e3b9a328073d39ca4d8a8
|
|
| BLAKE2b-256 |
7d3d56ee7cc0103c81f471097d8f7d1792f59085614d81b7585ee9a1713f2381
|
File details
Details for the file binance_mcp-1.0.0-py3-none-any.whl.
File metadata
- Download URL: binance_mcp-1.0.0-py3-none-any.whl
- Upload date:
- Size: 27.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
00bc4e5411896af969b064d9519dd774b2052f620a8ce050599b0b53e897e426
|
|
| MD5 |
96df639a985a4d885f0ccd34049f068f
|
|
| BLAKE2b-256 |
f2029acbc8f2ba39f648d3b2c24deaa047179fbbf67c86092ec73cc9ef562220
|