加密货币交易信号服务器

一个提供实时加密货币市场数据和技术分析的MCP服务器,支持Binance交易所的AI代理CLI。

  • by Sahilgul
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 Sahilgul/Binance-custom-mcp-server

使用说明

Binance Trading Signal MCP Server

A comprehensive MCP (Model Context Protocol) server that provides real-time cryptocurrency market data and technical analysis from Binance exchange for AI Agent CLI.


Table of Contents

  1. Features
  2. Project Structure
  3. Installation
  4. Configuration
  5. Available Tools
  6. Tool Parameters Reference
  7. Data Depth Configuration
  8. Supported Markets
  9. Supported Timeframes
  10. Signal Logic
  11. Architecture
  12. Code Structure
  13. Usage Examples
  14. Example Outputs
  15. Financial Agents
  16. Testing
  17. API Key Requirements
  18. Troubleshooting
  19. Disclaimer

Features

  • 21 MCP Tools - Data fetching, technical analysis, trading signals, and AI agents
  • Real-time Data - Live cryptocurrency prices from Binance
  • Technical Indicators - RSI, MACD, EMA, SMA, Bollinger Bands, Stochastic
  • Trend Detection - Automatic UPTREND/DOWNTREND/SIDEWAYS identification
  • Support/Resistance - Key price level detection
  • Volume Analysis - Volume spike and pattern detection
  • Trading Signals - Automated BUY/SELL/HOLD recommendations with confidence scores
  • Multi-Timeframe Analysis - Confluence signals across multiple timeframes
  • Financial Agents - Specialized AI agents for market analysis, risk management, portfolio screening, strategy execution, and multi-asset comparison
  • Configurable Depth - Fetch 1-1000 candles (default: 200)
  • No API Key Required - Uses public market data endpoints

Project Structure

/home/sahil/Documents/Trade/mcp_servers/binance_data/
├── server.py              # Main MCP server entry point
├── requirements.txt       # Python dependencies
├── test_client.py         # Test data connection
├── test_analysis.py       # Test technical analysis
├── test_agents.py         # Test financial agents
├── README.md              # This documentation
│
├── utils/
│   ├── __init__.py
│   ├── binance_client.py  # Binance API wrapper (data fetching)
│   └── indicators.py      # Technical indicator calculations
│
└── tools/
    ├── __init__.py
    ├── analysis.py        # MCP tool definitions and handlers
    └── agents.py          # Financial agent tools

File Descriptions

File Purpose
server.py Main entry point, initializes MCP server
requirements.txt Python package dependencies
test_client.py Tests Binance API connection and data fetching
test_analysis.py Tests all technical indicators and signals
test_agents.py Tests all financial agent tools
utils/binance_client.py Wrapper for Binance REST API
utils/indicators.py All technical indicator calculations
tools/analysis.py MCP tool schemas and call handlers
tools/agents.py Financial agent tools (market analyst, risk manager, etc.)

Installation

Prerequisites

  • Python 3.10+
  • pip package manager
  • Internet connection (for Binance API)

Steps

# Navigate to project directory
cd /home/sahil/Documents/Trade/mcp_servers/binance_data

# Install dependencies
pip install -r requirements.txt

Dependencies (requirements.txt)

mcp>=1.0.0
python-binance>=1.0.19
websockets>=12.0
pandas>=2.0.0
numpy>=1.24.0
asyncio-throttle>=1.0.2

Configuration

Configure AI Agent

Add the MCP server to your AI Agent settings file:

File: ~/.agent/settings.json

{
  "mcpServers": {
    "binance-trading-signals": {
      "command": "python3",
      "args": ["/home/sahil/Documents/Trade/mcp_servers/binance_data/server.py"],
      "cwd": "/home/sahil/Documents/Trade/mcp_servers/binance_data"
    }
  }
}

Apply Configuration

After editing the settings file, restart AI Agent for changes to take effect:

# Exit current AI Agent session
# Then restart

Verify Configuration

After restart, the MCP server tools will be available. Test by asking:

"What's the current BTC price?"

Available Tools

Data Tools (5)

Tool Description
get_price Get current price for a trading pair
get_klines Get OHLCV candlestick data
get_orderbook Get order book depth (bids/asks)
get_24h_stats Get 24-hour statistics
get_top_movers Get top gainers and losers

Technical Analysis Tools (8)

Tool Description
calculate_rsi RSI - Oversold (<30) / Overbought (>70)
calculate_macd MACD line, signal line, histogram
calculate_ema EMAs for multiple periods (9, 21, 50, 200)
calculate_bollinger Bollinger Bands (upper, middle, lower)
calculate_stochastic Stochastic Oscillator (%K, %D)
detect_trend UPTREND / DOWNTREND / SIDEWAYS detection
find_support_resistance Key support and resistance levels
analyze_volume Volume spikes and patterns

Signal Tools (3)

Tool Description
get_trading_signal BUY/SELL/HOLD with confidence % and entry/exit points
get_full_analysis Complete technical analysis report
get_mtf_signal Multi-timeframe confluence signal (15m, 1h, 4h, 1d)

Financial Agent Tools (5)

Tool Description
agent_market_analyst Comprehensive market analysis with regime detection, momentum, risk factors, and recommendations
agent_risk_manager Position sizing, stop-loss strategies (ATR/support-based), take-profit targets, leverage recommendations
agent_portfolio_screener Scan multiple symbols and rank by trading opportunity strength
agent_strategy_executor Execute specific strategies: momentum, mean_reversion, breakout, support_bounce, ema_crossover
agent_multi_asset_analyst Compare and rank multiple assets by relative strength, returns, and signals

Tool Parameters Reference

Data Tools

get_price

{
  "symbol": "BTCUSDT"        // Required: Trading pair
}

get_klines

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Number of candles (default: 200, max: 1000)
}

get_orderbook

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "limit": 20                // Optional: Depth levels (default: 20, options: 5,10,20,50,100)
}

get_24h_stats

{
  "symbol": "BTCUSDT"        // Required: Trading pair
}

get_top_movers

{
  "limit": 10                // Optional: Number of results (default: 10)
}

Technical Analysis Tools

calculate_rsi

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "period": 14,              // Optional: RSI period (default: 14)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

calculate_macd

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "fast": 12,                // Optional: Fast EMA period (default: 12)
  "slow": 26,                // Optional: Slow EMA period (default: 26)
  "signal": 9,               // Optional: Signal line period (default: 9)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

calculate_ema

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "periods": [9, 21, 50, 200], // Optional: EMA periods (default: [9,21,50,200])
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

calculate_bollinger

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "period": 20,              // Optional: BB period (default: 20)
  "std_dev": 2.0,            // Optional: Standard deviation (default: 2.0)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

calculate_stochastic

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "k_period": 14,            // Optional: %K period (default: 14)
  "d_period": 3,             // Optional: %D period (default: 3)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

detect_trend

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

find_support_resistance

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

analyze_volume

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

Signal Tools

get_trading_signal

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

get_full_analysis

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

get_mtf_signal

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "timeframes": ["15m", "1h", "4h", "1d"],  // Optional: Timeframes to analyze
  "limit": 200               // Optional: Candles per timeframe (default: 200)
}

Financial Agent Tools

agent_market_analyst

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

agent_risk_manager

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "account_balance": 10000,  // Required: Account balance in USDT
  "risk_per_trade": 1.0,     // Optional: Risk percentage per trade (default: 1%)
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

agent_portfolio_screener

{
  "symbols": ["BTCUSDT", "ETHUSDT", "SOLUSDT"],  // Optional: Symbols to scan (default: top 20 by volume)
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "min_confidence": 60,      // Optional: Minimum confidence threshold (default: 60)
  "limit": 200               // Optional: Candles per symbol (default: 200)
}

agent_strategy_executor

{
  "symbol": "BTCUSDT",       // Required: Trading pair
  "strategy": "momentum",    // Required: Strategy name (see available strategies below)
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles to analyze (default: 200)
}

Available Strategies:

  • momentum - Trend following with momentum confirmation
  • mean_reversion - Buy oversold, sell overbought (RSI + Bollinger)
  • breakout - Trade breakouts from volatility squeeze
  • support_bounce - Buy at support levels with confirmation
  • ema_crossover - Trade EMA 9/21 crossovers

agent_multi_asset_analyst

{
  "symbols": ["BTCUSDT", "ETHUSDT", "SOLUSDT"],  // Required: Symbols to compare
  "interval": "1h",          // Optional: Timeframe (default: 1h)
  "limit": 200               // Optional: Candles per symbol (default: 200)
}

Data Depth Configuration

All analysis tools support a limit parameter to control how many candles to fetch.

Settings

Setting Value
Default 200 candles
Maximum 1000 candles
Minimum 1 candle

Code Location

# File: tools/analysis.py (lines 12-14)
DEFAULT_LIMIT = 200
MAX_LIMIT = 1000

What 200 Candles Represents

Timeframe 200 Candles =
1m 3.3 hours
5m 16.6 hours
15m 50 hours (~2 days)
1h 8.3 days
4h 33 days
1d 200 days
1w 200 weeks (~4 years)

Why 200 is the Default

  • Properly calculates EMA 200 (requires 200+ data points)
  • Better trend detection accuracy
  • More reliable support/resistance levels
  • Still fast response (~100-200ms)

Custom Limit Usage

# Use more candles for longer-term analysis
"Get trading signal for BTCUSDT with 500 candles"

# Use fewer candles for faster response
"Calculate RSI for ETH with 50 candles"

Supported Markets

This MCP server connects to Binance exchange and supports cryptocurrency trading pairs only.

Type Examples
Crypto/USDT BTCUSDT, ETHUSDT, SOLUSDT, BNBUSDT, XRPUSDT, DOGEUSDT
Crypto/BTC ETHBTC, SOLBTC, BNBBTC, XRPBTC
Crypto/ETH SOLETH, BNBETH
Total Pairs 500+ trading pairs

NOT Supported

Market Alternative
Stocks Use Yahoo Finance API or Alpaca
Forex Use MetaTrader 5 or OANDA API
Gold/Commodities Use TradingView or MetaTrader

Supported Timeframes

Interval Description Use Case
1m 1 minute Scalping
3m 3 minutes Scalping
5m 5 minutes Day trading
15m 15 minutes Day trading
30m 30 minutes Swing trading
1h 1 hour (default) Swing trading
2h 2 hours Swing trading
4h 4 hours Position trading
6h 6 hours Position trading
8h 8 hours Position trading
12h 12 hours Position trading
1d 1 day Long-term
3d 3 days Long-term
1w 1 week Long-term
1M 1 month Long-term

Signal Logic

The get_trading_signal tool uses a scoring system to generate BUY/SELL/HOLD recommendations.

Code Location

# File: utils/indicators.py
# Function: get_trading_signal() (lines 267-370)

BUY Signal Scoring

Condition Points
RSI < 30 (oversold) +2
MACD bullish crossover (histogram crosses above 0) +2
MACD histogram positive +1
Uptrend (EMA 9 > EMA 21 > EMA 50) - Strong +2
Uptrend - Moderate +1
Price near support level (<2% distance) +1
Volume spike in uptrend (>1.5x average) +1
Stochastic %K < 20 (oversold) +1

SELL Signal Scoring

Condition Points
RSI > 70 (overbought) +2
MACD bearish crossover (histogram crosses below 0) +2
MACD histogram negative +1
Downtrend (EMA 9 < EMA 21 < EMA 50) - Strong +2
Downtrend - Moderate +1
Price near resistance level (<2% distance) +1
Volume spike in downtrend (>1.5x average) +1
Stochastic %K > 80 (overbought) +1

Final Decision

if buy_score > sell_score:
    action = "BUY"
    confidence = 50 + (buy_score - sell_score) * 10
elif sell_score > buy_score:
    action = "SELL"
    confidence = 50 + (sell_score - buy_score) * 10
else:
    action = "HOLD"
    confidence = 50
  • Maximum confidence: 95%
  • Minimum confidence: 50%

Entry/Exit Calculation

Uses ATR (Average True Range) for dynamic stop loss and take profit:

# For BUY signals:
entry = current_price
stop_loss = current_price - (ATR * 1.5)
take_profit = current_price + (ATR * 3.0)
risk_reward = 1:2

# For SELL signals:
entry = current_price
stop_loss = current_price + (ATR * 1.5)
take_profit = current_price - (ATR * 3.0)
risk_reward = 1:2

Architecture

┌─────────────────────────────────────────────────────────────┐
│                      USER / AI Agent                        │
│                  "Should I buy BTC now?"                    │
└─────────────────────────────┬───────────────────────────────┘
                              │ MCP Protocol (stdio)
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                     MCP SERVER (server.py)                  │
│                                                             │
│  ┌───────────┐  ┌───────────┐  ┌───────────┐  ┌──────────┐│
│  │DATA TOOLS │  │ ANALYSIS  │  │  SIGNAL   │  │  AGENT   ││
│  │           │  │   TOOLS   │  │   TOOLS   │  │  TOOLS   ││
│  │get_price  │  │calc_rsi   │  │get_trading│  │market_   ││
│  │get_klines │  │calc_macd  │  │  _signal  │  │ analyst  ││
│  │get_order  │  │calc_ema   │  │get_full_  │  │risk_     ││
│  │  book     │  │calc_boll  │  │ analysis  │  │ manager  ││
│  │get_24h_   │  │calc_stoch │  │get_mtf_   │  │portfolio_││
│  │  stats    │  │detect_    │  │  signal   │  │ screener ││
│  │get_top_   │  │  trend    │  │           │  │strategy_ ││
│  │  movers   │  │find_sr    │  │           │  │ executor ││
│  │           │  │analyze_vol│  │           │  │multi_    ││
│  │           │  │           │  │           │  │ asset    ││
│  └─────┬─────┘  └─────┬─────┘  └─────┬─────┘  └────┬─────┘│
│        │              │              │              │      │
│        └──────────────┴──────────────┴──────────────┘      │
│                            │                                │
│                            ▼                                │
│  ┌─────────────────────────────────────────────────────┐   │
│  │              BINANCE CLIENT (binance_client.py)      │   │
│  │                                                      │   │
│  │  get_price() | get_klines() | get_orderbook()       │   │
│  │  get_24h_stats() | get_recent_trades()              │   │
│  └──────────────────────────┬──────────────────────────┘   │
│                             │                               │
│  ┌──────────────────────────┼──────────────────────────┐   │
│  │           INDICATORS (indicators.py)                 │   │
│  │                                                      │   │
│  │  calculate_rsi() | calculate_macd() | calculate_ema()│   │
│  │  calculate_bollinger() | calculate_stochastic()     │   │
│  │  calculate_atr() | calculate_obv()                  │   │
│  │  detect_trend() | find_support_resistance()         │   │
│  │  analyze_volume() | get_trading_signal()            │   │
│  │  get_mtf_confluence()                               │   │
│  └──────────────────────────────────────────────────────┘   │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │        FINANCIAL AGENTS (tools/agents.py)            │   │
│  │                                                      │   │
│  │  market_analyst() | risk_manager()                  │   │
│  │  portfolio_screener() | strategy_executor()         │   │
│  │  multi_asset_analyst()                              │   │
│  └──────────────────────────────────────────────────────┘   │
└─────────────────────────────┬───────────────────────────────┘
                              │ HTTPS REST API
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      BINANCE API                            │
│                 https://api.binance.com                     │
│                                                             │
│  /api/v3/ticker/price    - Current price                   │
│  /api/v3/klines          - Candlestick data                │
│  /api/v3/depth           - Order book                      │
│  /api/v3/ticker/24hr     - 24h statistics                  │
│  /api/v3/trades          - Recent trades                   │
└─────────────────────────────────────────────────────────────┘

Code Structure

Key Functions Location

Data Fetching (utils/binance_client.py)

Function Line Description
get_price() 25 Fetch current price
get_klines() 38 Fetch OHLCV data
get_orderbook() 75 Fetch order book
get_24h_stats() 95 Fetch 24h statistics
get_recent_trades() 125 Fetch recent trades
get_top_gainers_losers() 155 Fetch top movers

Technical Indicators (utils/indicators.py)

Function Line Description
calculate_sma() 18 Simple Moving Average
calculate_ema() 23 Exponential Moving Average
calculate_rsi() 28 Relative Strength Index
calculate_macd() 45 MACD indicator
calculate_bollinger_bands() 68 Bollinger Bands
calculate_stochastic() 90 Stochastic Oscillator
calculate_atr() 115 Average True Range
calculate_obv() 135 On-Balance Volume
detect_trend() 150 Trend detection
find_support_resistance() 185 S/R levels
analyze_volume() 230 Volume analysis
get_trading_signal() 267 Combined signal

MCP Tools (tools/analysis.py)

Constant Line Value
DEFAULT_LIMIT 13 200
MAX_LIMIT 14 1000
Function Line Description
list_tools() 27 Tool schema definitions
call_tool() 388 Tool call handlers
get_limit() 395 Limit bounds checking
get_df() 400 DataFrame helper

Financial Agents (tools/agents.py)

Class/Function Line Description
FinancialAgents 25 Main agent class
market_analyst() 40 Comprehensive market analysis
risk_manager() 178 Position sizing and risk calculations
portfolio_screener() 313 Multi-symbol opportunity scanner
strategy_executor() 430 Strategy-specific signals
multi_asset_analyst() 794 Multi-asset comparison
register_agent_tools() 913 Register agents with MCP server

Usage Examples

Quick Signal Queries

"Should I buy BTC now?"
"Give me a trading signal for ETHUSDT"
"What's the signal for SOL on 4h timeframe?"
"Is it time to sell BNB?"

Technical Analysis Queries

"What's the RSI for BTC?"
"Calculate MACD for SOLUSDT on 4h timeframe"
"Find support and resistance for ETH"
"Is BTC in an uptrend or downtrend?"
"Show me Bollinger Bands for XRPUSDT"
"Analyze volume for DOGEUSDT"

Full Analysis Queries

"Give me full analysis of BTCUSDT"
"Complete technical breakdown for ETH on daily"
"Analyze BTC on 1h and 4h timeframes"

Custom Depth Queries

"Get trading signal for BTCUSDT with 500 candles"
"Calculate EMA for ETH using 1000 candles"
"Analyze trend with 100 candles only"

Market Overview Queries

"What's the current BTC price?"
"Show me top gainers today"
"What are the biggest losers in 24h?"
"Get 24h stats for ETHUSDT"

Multi-Timeframe Queries

"Get multi-timeframe signal for BTC"
"Analyze ETHUSDT across 15m, 1h, 4h, and daily"
"Is there confluence for SOL across timeframes?"

Financial Agent Queries

# Market Analyst
"Analyze the market for BTCUSDT"
"What's the market regime for ETH?"
"Give me a comprehensive market analysis for SOL"

# Risk Manager
"Calculate position size for BTC with $10,000 account risking 1%"
"What's my stop loss and take profit for ETHUSDT?"
"How much SOL should I buy with $5000 account?"

# Portfolio Screener
"Scan top 20 coins for trading opportunities"
"Find the best buy signals across major altcoins"
"Screen BTCUSDT, ETHUSDT, SOLUSDT, BNBUSDT for signals"

# Strategy Executor
"Run momentum strategy on BTCUSDT"
"Check mean reversion setup for ETHUSDT"
"Is there a breakout on SOL?"
"Check support bounce opportunity for BNB"
"Run EMA crossover strategy on XRPUSDT"

# Multi-Asset Analyst
"Compare BTC, ETH, and SOL"
"Rank these coins by strength: BTCUSDT, ETHUSDT, SOLUSDT, BNBUSDT"
"Which is stronger - BTC or ETH right now?"

Example Outputs

Trading Signal Output

{
  "symbol": "BTCUSDT",
  "interval": "1h",
  "candles_analyzed": 200,
  "action": "SELL",
  "confidence": 60,
  "current_price": 89247.87,
  "entry": 89247.87,
  "stop_loss": 89483.76,
  "take_profit": 88776.08,
  "risk_reward_ratio": "1:2",
  "signals": [
    "RSI 31.9 (Neutral)",
    "MACD Bearish",
    "Trend: DOWNTREND (STRONG)",
    "Near Support $88578.36",
    "Stochastic Oversold (16.7)"
  ],
  "scores": {
    "buy_score": 2,
    "sell_score": 3
  }
}

RSI Output

{
  "symbol": "BTCUSDT",
  "interval": "1h",
  "candles_analyzed": 200,
  "rsi": 32.67,
  "signal": "NEUTRAL",
  "rsi_history": [35.2, 34.1, 33.5, 32.8, 32.1, 31.9, 32.0, 32.3, 32.5, 32.67]
}

Trend Detection Output

{
  "symbol": "BTCUSDT",
  "interval": "1h",
  "candles_analyzed": 200,
  "trend": "DOWNTREND",
  "strength": "STRONG",
  "ema_short": 89346.81,
  "ema_medium": 89435.85,
  "ema_long": 89559.39,
  "price_vs_ema": {
    "above_short": false,
    "above_medium": false,
    "above_long": false
  }
}

Support/Resistance Output

{
  "symbol": "BTCUSDT",
  "interval": "1h",
  "candles_analyzed": 200,
  "current_price": 89247.87,
  "nearest_support": 88578.36,
  "nearest_resistance": 95521.71,
  "support_distance_pct": 0.75,
  "resistance_distance_pct": 7.03,
  "all_support_levels": [88578.36, 87234.12, 85100.00],
  "all_resistance_levels": [95521.71, 97800.00, 100000.00],
  "near_support": true,
  "near_resistance": false
}

Full Analysis Output

{
  "symbol": "BTCUSDT",
  "interval": "1h",
  "candles_analyzed": 200,
  "current_price": 89259.97,
  "24h_change": -0.379,
  "24h_high": 89957.39,
  "24h_low": 89162.08,
  "24h_volume": 4213.02,
  "indicators": {
    "rsi": 32.67,
    "macd": -85.95,
    "macd_signal": -69.69,
    "macd_histogram": -16.26,
    "stochastic_k": 16.68,
    "stochastic_d": 27.03,
    "bollinger_upper": 89780.70,
    "bollinger_lower": 89144.55
  },
  "trend": {
    "trend": "DOWNTREND",
    "strength": "STRONG",
    "ema_short": 89349.23,
    "ema_medium": 89436.95,
    "ema_long": 89559.86
  },
  "support_resistance": {
    "nearest_support": 88578.36,
    "nearest_resistance": 95521.71,
    "near_support": true,
    "near_resistance": false
  },
  "volume_analysis": {
    "volume_ratio": 0.26,
    "volume_signal": "LOW",
    "interpretation": "Low interest / consolidation"
  },
  "trading_signal": {
    "action": "SELL",
    "confidence": 60,
    "entry": 89259.97,
    "stop_loss": 89495.86,
    "take_profit": 88788.19,
    "signals": ["RSI 32.7 (Neutral)", "MACD Bearish", "Trend: DOWNTREND (STRONG)"]
  }
}

Multi-Timeframe Signal Output

{
  "symbol": "BTCUSDT",
  "timeframes_analyzed": ["15m", "1h", "4h", "1d"],
  "action": "SELL",
  "strength": "MODERATE",
  "confidence": 65,
  "confluence_score": -3,
  "timeframe_signals": {
    "15m": {"action": "SELL", "confidence": 60},
    "1h": {"action": "SELL", "confidence": 60},
    "4h": {"action": "HOLD", "confidence": 50},
    "1d": {"action": "SELL", "confidence": 55}
  },
  "alignment": "3/4 timeframes aligned bearish"
}

Market Analyst Agent Output

{
  "agent": "market_analyst",
  "symbol": "BTCUSDT",
  "interval": "1h",
  "current_price": 89250.00,
  "analysis": {
    "market_regime": "TRENDING",
    "trend": "DOWNTREND",
    "trend_strength": "STRONG",
    "momentum": "BEARISH",
    "volatility": 2.15,
    "volume_profile": "NORMAL"
  },
  "indicators": {
    "rsi": 35.50,
    "macd_histogram": -85.23,
    "stochastic_k": 22.50,
    "atr": 450.25,
    "atr_percent": 0.50
  },
  "key_levels": {
    "immediate_support": 88500.00,
    "immediate_resistance": 90500.00,
    "ema_9": 89300.00,
    "ema_21": 89450.00,
    "ema_50": 89600.00,
    "bollinger_upper": 90200.00,
    "bollinger_lower": 88800.00
  },
  "risk_factors": [
    "Near support - bounce or breakdown"
  ],
  "recommendations": [
    "TREND FOLLOWING: Consider selling rallies to EMA 21",
    "Trail stop above EMA 50 (89600.00)"
  ]
}

Risk Manager Agent Output

{
  "agent": "risk_manager",
  "symbol": "BTCUSDT",
  "current_price": 89250.00,
  "account_balance": 10000,
  "risk_per_trade_pct": 1.0,
  "risk_amount_usdt": 100.00,
  "volatility_metrics": {
    "atr": 450.25,
    "atr_percent": 0.50,
    "volatility_assessment": "LOW",
    "recommended_max_leverage": 5
  },
  "position_sizing": {
    "atr_tight": {
      "stop_loss_price": 88574.63,
      "stop_distance_pct": 0.76,
      "position_size": 0.000148,
      "position_value_usdt": 13.21,
      "max_loss_usdt": 100.00,
      "description": "1.5x ATR - Tight stop for scalping"
    },
    "atr_normal": {
      "stop_loss_price": 88349.50,
      "stop_distance_pct": 1.01,
      "position_size": 0.000111,
      "position_value_usdt": 9.91,
      "max_loss_usdt": 100.00,
      "description": "2x ATR - Standard swing trading stop"
    }
  },
  "take_profit_targets": [
    {"risk_reward": "1:1.5", "take_profit_price": 90150.75, "profit_pct": 1.01, "potential_profit_usdt": 150.00},
    {"risk_reward": "1:2", "take_profit_price": 90601.00, "profit_pct": 1.51, "potential_profit_usdt": 200.00},
    {"risk_reward": "1:3", "take_profit_price": 91501.50, "profit_pct": 2.52, "potential_profit_usdt": 300.00}
  ]
}

Strategy Executor Agent Output (Momentum Strategy)

{
  "agent": "strategy_executor",
  "symbol": "BTCUSDT",
  "interval": "1h",
  "strategy": "momentum",
  "current_price": 89250.00,
  "strategy_analysis": {
    "conditions_met": [
      "Uptrend confirmed (STRONG)",
      "RSI in bullish zone (58.5)",
      "MACD momentum increasing"
    ],
    "conditions_failed": [],
    "signal": "BUY",
    "confidence": 80,
    "entry": 89250.00,
    "stop_loss": 88800.00,
    "take_profit": 90600.00,
    "strategy_rules": [
      "Buy when: Uptrend + RSI 50-70 + MACD increasing",
      "Stop loss: Below EMA 21",
      "Take profit: 3x ATR from entry"
    ]
  }
}

Portfolio Screener Agent Output

{
  "agent": "portfolio_screener",
  "interval": "1h",
  "min_confidence": 60,
  "summary": {
    "symbols_analyzed": 20,
    "buy_opportunities": 3,
    "sell_opportunities": 5,
    "market_sentiment": "BEARISH"
  },
  "top_buy_signals": [
    {
      "symbol": "SOLUSDT",
      "price": 127.50,
      "change_24h": 2.5,
      "action": "BUY",
      "confidence": 75,
      "trend": "UPTREND",
      "signals": ["RSI Oversold", "MACD Bullish Crossover", "Near Support"]
    }
  ],
  "top_sell_signals": [
    {
      "symbol": "XRPUSDT",
      "price": 0.62,
      "change_24h": -3.2,
      "action": "SELL",
      "confidence": 70,
      "trend": "DOWNTREND",
      "signals": ["RSI Overbought", "MACD Bearish", "Near Resistance"]
    }
  ]
}

Financial Agents

The Financial Agents are specialized AI tools that combine multiple technical indicators to provide higher-level trading insights.

Agent Overview

Agent Purpose Best For
Market Analyst Comprehensive market analysis with regime detection Getting a complete market overview before trading
Risk Manager Position sizing and risk calculations Determining how much to trade and where to place stops
Portfolio Screener Scan multiple symbols for opportunities Finding best trades across many assets
Strategy Executor Run specific trading strategies Getting strategy-specific entry/exit signals
Multi-Asset Analyst Compare and rank multiple assets Deciding which asset to trade from a watchlist

Available Strategies (Strategy Executor)

Strategy Description Entry Conditions
momentum Trend following with momentum confirmation Uptrend + RSI 50-70 + MACD increasing
mean_reversion Buy oversold, sell overbought RSI < 30 + Price at lower BB (buy)
breakout Trade breakouts from volatility squeeze Price breaks BB after squeeze
support_bounce Buy at support levels with confirmation Price bounces from support with bullish candle
ema_crossover Trade EMA 9/21 crossovers Golden cross (buy) / Death cross (sell)

Recommended Workflow

  1. Start with Portfolio Screener - Find opportunities across multiple assets
  2. Use Market Analyst - Get detailed analysis on selected asset
  3. Run Strategy Executor - Check specific strategy signals
  4. Apply Risk Manager - Calculate position size and stops
  5. Use Multi-Asset Analyst - Compare alternatives before final decision

Testing

Test Data Connection

cd /home/sahil/Documents/Trade/mcp_servers/binance_data
python3 test_client.py

Expected output:

==================================================
Testing Binance Data Client
==================================================
1. Testing get_price (BTCUSDT)...
   BTC Price: $89,280.37
2. Testing multiple prices...
   ETHUSDT: $2,953.81
   BNBUSDT: $887.55
   SOLUSDT: $127.22
...
==================================================
All tests completed!
==================================================

Test Technical Analysis

cd /home/sahil/Documents/Trade/mcp_servers/binance_data
python3 test_analysis.py

Expected output:

============================================================
Testing Technical Analysis Tools
============================================================
Fetching BTCUSDT data...
Loaded 200 candles

Current Price: $89,259.97
...
============================================================
9. TRADING SIGNAL (Combined Analysis)
============================================================
   🔴 SELL
   Confidence: 60%
   ...
============================================================
All tests completed!
============================================================

Test Financial Agents

cd /home/sahil/Documents/Trade/mcp_servers/binance_data
python3 test_agents.py

Expected output:

============================================================
Testing Financial Agents
============================================================
1. Testing Market Analyst Agent...
   Market Regime: TRENDING
   Momentum: BEARISH
   Recommendations: 2 items

2. Testing Risk Manager Agent...
   Position Sizes: 4 strategies calculated
   Take Profit Targets: 4 R:R ratios

3. Testing Portfolio Screener Agent...
   Symbols Analyzed: 20
   Buy Opportunities: 3
   Sell Opportunities: 5
...
============================================================
All agent tests completed!
============================================================

Test MCP Server with Inspector

npx @modelcontextprotocol/inspector python3 /home/sahil/Documents/Trade/mcp_servers/binance_data/server.py

This opens a web UI to interactively test all MCP tools.


API Key Requirements

Public Data (NO API KEY NEEDED)

All tools in this MCP server use public endpoints:

Endpoint Data
/api/v3/ticker/price Current price
/api/v3/klines Candlestick data
/api/v3/depth Order book
/api/v3/ticker/24hr 24h statistics
/api/v3/trades Recent trades

Private Data (API KEY REQUIRED)

If you want to add features for:

  • Account balance
  • Open orders
  • Trade history
  • Placing orders

You would need to:

  1. Create API keys at https://www.binance.com/en/my/settings/api-management
  2. Pass them to the server:
{
  "mcpServers": {
    "binance-trading-signals": {
      "command": "python3",
      "args": [
        "/home/sahil/Documents/Trade/mcp_servers/binance_data/server.py",
        "--api-key", "YOUR_API_KEY",
        "--api-secret", "YOUR_API_SECRET"
      ],
      "cwd": "/home/sahil/Documents/Trade/mcp_servers/binance_data"
    }
  }
}

Note: The current implementation does not include private endpoint tools.


Troubleshooting

Common Issues

1. MCP Server Not Loading

Symptom: Tools not available after restart

Solution:

# Check settings file syntax
cat ~/.agent/settings.json | python3 -m json.tool

# Verify file paths exist
ls -la /home/sahil/Documents/Trade/mcp_servers/binance_data/server.py

2. Import Errors

Symptom: ModuleNotFoundError

Solution:

cd /home/sahil/Documents/Trade/mcp_servers/binance_data
pip install -r requirements.txt

3. Connection Timeout

Symptom: BinanceAPIException: Connection timeout

Solution:

  • Check internet connection
  • Binance may be blocked in your region (use VPN)
  • API rate limits may be hit (wait and retry)

4. Invalid Symbol Error

Symptom: Invalid symbol

Solution:

  • Use correct format: BTCUSDT not BTC/USDT or BTC-USDT
  • Symbol must exist on Binance
  • Symbol is case-insensitive but uppercase is standard

5. Insufficient Data

Symptom: NaN values in indicators

Solution:

  • Increase limit parameter
  • EMA 200 needs at least 200 candles
  • Use appropriate timeframe for your analysis period

Debug Mode

Add print statements to server.py:

import logging
logging.basicConfig(level=logging.DEBUG)

Disclaimer

IMPORTANT: This tool is for educational and informational purposes only.

  • This is NOT financial advice
  • Trading cryptocurrencies involves significant risk
  • Past performance does not guarantee future results
  • Always do your own research (DYOR)
  • Never invest more than you can afford to lose
  • The signals generated are based on technical analysis only
  • Fundamental analysis, news, and market sentiment are not considered
  • The authors are not responsible for any financial losses

Use at your own risk.


License

This project is provided as-is for educational purposes.


Version History

Version Date Changes
1.1.0 2025-01-25 Added 5 Financial Agent tools and Multi-timeframe signal (21 tools total)
1.0.0 2024-01-25 Initial release with 15 tools

Author

Created for use with AI Agent CLI by Anthropic.


Support

For issues or questions:

  • Check the Troubleshooting section
  • Review the test scripts for usage examples
  • Examine the code comments for implementation details