Metadata-Version: 2.4
Name: tradingview-mcp
Version: 0.9.1
Summary: Advanced AI Trading Intelligence Framework — MCP server with live market intelligence, trade analytics, strategy optimization, pattern recognition, walk-forward backtesting, and 73 technical analysis tools
Author: Debarpan Bose Chowdhury
License-Expression: MIT
Project-URL: Repository, https://github.com/DEBARPAN2000/tradingview-mcp
Project-URL: Bug Tracker, https://github.com/DEBARPAN2000/tradingview-mcp/issues
Project-URL: Changelog, https://github.com/DEBARPAN2000/tradingview-mcp/blob/main/CHANGELOG.md
Keywords: mcp,tradingview,crypto,technical analysis,screener,backtesting,walk-forward,sentiment,yahoo-finance,trading,agents,algorithmic-trading,equity-curve,live-market,pattern-recognition,strategy-optimization,egx,nse,bse
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Development Status :: 4 - Beta
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: feedparser>=6.0.12
Requires-Dist: mcp[cli]>=1.12.0
Requires-Dist: tradingview-screener>=0.6.4
Requires-Dist: tradingview-ta>=3.3.0
Dynamic: license-file

# tradingview-assistant — AI Trading Intelligence MCP Server

**Author:** DEBARPAN BOSE CHOWDHURY  
**Repository:** https://github.com/DEBARPAN2000/tradingview-mcp  
**PyPI:** [tradingview-assistant](https://pypi.org/project/tradingview-assistant/)

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![MCP Ready](https://img.shields.io/badge/MCP-Ready-brightgreen)](https://modelcontextprotocol.com/)
[![Version](https://img.shields.io/badge/version-v0.8.2-blue)](https://github.com/DEBARPAN2000/tradingview-mcp/releases)
[![PyPI](https://img.shields.io/badge/PyPI-tradingview--assistant-orange)](https://pypi.org/project/tradingview-assistant/)
[![OpenClaw Ready](https://img.shields.io/badge/OpenClaw-Ready-blueviolet)](https://openclaw.ai)

> The most complete open-source AI trading toolkit for Claude and MCP-compatible clients.  
> 40+ tools · Backtesting · Walk-Forward Validation · Live Sentiment · Yahoo Finance · Paper Trading — no API keys required.

---

## Table of Contents

- [Why tradingview-assistant?](#why-tradingview-assistant)
- [Architecture](#architecture)
- [Quick Start](#quick-start)
- [MCP Setup](#mcp-setup)
- [All Tools](#all-tools)
- [Example Prompts](#example-prompts)
- [Docker](#docker)
- [OpenClaw (Telegram / WhatsApp)](#openclaw-telegram--whatsapp)
- [Troubleshooting](#troubleshooting)
- [Project Structure](#project-structure)
- [Contributing](#contributing)
- [License](#license)

---

## Why tradingview-assistant?

| Feature | This Server | Typical DIY Setup | Bloomberg Terminal |
|---------|-------------|--------------------|--------------------|
| **Setup Time** | 2 minutes | Hours | Weeks |
| **Cost** | Free & Open Source | Variable | ~$30k/year |
| **API Keys Required** | **None** | Multiple | N/A |
| **Backtesting** | 6 strategies + walk-forward | Manual scripting | Proprietary |
| **Live Sentiment** | Reddit + RSS news | Separate service | Terminal only |
| **Market Coverage** | Crypto + 12 stock markets | Limited | Broad |
| **Multi-Agent Analysis** | 3-agent AI debate | Not available | Not available |
| **Paper Trading** | Built-in SQLite persistence | Not available | Not available |

---

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│               Claude Desktop / MCP-Compatible Client            │
└──────────────────────────┬──────────────────────────────────────┘
                           │  MCP Protocol (stdio or HTTP)
┌──────────────────────────▼──────────────────────────────────────┐
│               tradingview-assistant MCP Server                  │
│                       (server.py)                               │
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │   Screener   │  │   Backtest   │  │  Sentiment & News    │  │
│  │   Service    │  │   Service    │  │      Service         │  │
│  └──────┬───────┘  └──────┬───────┘  └──────────┬───────────┘  │
│         │                 │                      │              │
│  ┌──────▼───────┐  ┌──────▼───────┐  ┌──────────▼───────────┐  │
│  │  TradingView │  │ Yahoo Finance│  │  Reddit API + RSS    │  │
│  │  Screener    │  │     API      │  │       Feeds          │  │
│  └──────────────┘  └──────────────┘  └──────────────────────┘  │
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │  Portfolio   │  │  Risk &      │  │   Market Adapters    │  │
│  │  Service     │  │  Correlation │  │  (EGX, NSE, BIST…)  │  │
│  │  (SQLite)    │  │  Tools       │  │                      │  │
│  └──────────────┘  └──────────────┘  └──────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
```

### Layer overview

| Layer | Location | Responsibility |
|-------|----------|----------------|
| **Transport** | `server.py` | MCP tool registry, input validation, response shaping |
| **Services** | `core/services/*.py` | Business logic — screener, backtest, sentiment, EGX, NSE, risk |
| **Adapters** | `core/services/market_adapters/` | Market-specific logic (EGX, NSE) |
| **Static Data** | `core/data/` | EGX and NSE sector / index datasets |
| **Utils** | `core/utils/` | Input validators, error contracts |
| **Portfolio** | `core/portfolio.py` | SQLite-backed paper trading persistence |

---

## Quick Start

### Option 1 — PyPI install (recommended)

```bash
pip install tradingview-assistant
```

### Option 2 — uvx (zero-install, always latest)

```bash
uvx --from tradingview-assistant tradingview-mcp
```

### Option 3 — Source

```bash
git clone https://github.com/DEBARPAN2000/tradingview-mcp.git
cd tradingview-mcp
uv sync
uv run tradingview-mcp
```

For detailed instructions (Docker, virtual envs, Claude Desktop, troubleshooting) see **[INSTALLATION.md](INSTALLATION.md)**.

---

## MCP Setup

### Claude Desktop (`claude_desktop_config.json`)

**macOS / Linux:**
```json
{
  "mcpServers": {
    "tradingview": {
      "command": "/Users/YOUR_USERNAME/.local/bin/uvx",
      "args": ["--from", "tradingview-assistant", "tradingview-mcp"]
    }
  }
}
```

**Windows:**
```json
{
  "mcpServers": {
    "tradingview": {
      "command": "uvx",
      "args": ["--python", "3.13", "--from", "tradingview-assistant", "tradingview-mcp"]
    }
  }
}
```

> **macOS note:** GUI apps may not have `~/.local/bin` in PATH. Use the full absolute path to `uvx`.  
> **Windows note:** Pin `--python 3.13` to use prebuilt wheels and avoid the 60-second initialization timeout.

### HTTP / Streamable-HTTP transport

```bash
tradingview-mcp streamable-http --host 0.0.0.0 --port 8000
```

Metrics endpoints:

| Endpoint | Format | Description |
|----------|--------|-------------|
| `GET /metrics/rate_limit` | JSON | Rate limiting stats |
| `GET /metrics/observability` | JSON | Tool usage and latency |
| `GET /metrics/prometheus` | Text | Prometheus scrape target |

---

## All Tools

The server currently exposes **69 MCP tools** across 13 categories. For the full parameter reference with types, defaults, and example prompts for every tool, see [TOOLS.md](TOOLS.md).

### Screener Tools

| Tool | Description |
|------|-------------|
| `top_gainers` | Top gaining assets on any exchange, ranked by % change |
| `top_losers` | Top losing assets on any exchange, ranked by % change |
| `bollinger_scan` | Bollinger Band squeeze scanner — finds low-volatility setups before breakouts |
| `rating_filter` | Filter assets by TradingView BB rating (-3 Strong Sell to +3 Strong Buy) |

### Asset Analysis

| Tool | Description |
|------|-------------|
| `coin_analysis` | Full TradingView indicator suite for a single asset (oscillators, MAs, sentiment) |
| `multi_agent_analysis` | Three-agent AI debate (Technical + Sentiment + Risk) with a final confidence-scored decision |
| `multi_timeframe_analysis` | Trend alignment across five timeframes simultaneously (Weekly through 15m) |
| `combined_analysis` | Flagship tool — technical + Reddit sentiment + news in one confluence-scored response |

### Candle Pattern Tools

| Tool | Description |
|------|-------------|
| `consecutive_candles_scan` | Scans for assets with N consecutive growing (bullish) or shrinking (bearish) candles |
| `advanced_candle_pattern` | Multi-timeframe candle acceleration analysis — detects momentum building |

### Volume Scanner Tools

| Tool | Description |
|------|-------------|
| `volume_breakout_scanner` | Detects simultaneous price breakouts and volume spikes |
| `volume_confirmation_analysis` | Checks whether current volume confirms or contradicts price movement for a symbol |
| `smart_volume_scanner` | Volume anomaly scanner with RSI market-condition filter |

### EGX (Egyptian Exchange) Tools

| Tool | Description |
|------|-------------|
| `egx_market_overview` | Full EGX snapshot — top gainers/losers, volume leaders, sector summary |
| `egx_sector_scan` | Scan stocks in a specific EGX sector (leave blank to list all sectors) |
| `egx_sector_scanner` | Sector rotation scanner — ranks hottest/coldest EGX sectors with top stock picks |
| `egx_index_analysis` | Constituent analysis for EGX30, EGX70, EGX100, SHARIAH33, EGX35LV, TAMAYUZ |
| `egx_stock_screener` | Composite-scored stock ranking engine for the full EGX universe |
| `egx_trade_plan` | Complete trade plan for an EGX stock — entry, stop-loss, target, R:R |
| `egx_fibonacci_retracement` | Fibonacci retracement levels using swing high/low for EGX stocks |

### NSE (India) Tools

| Tool | Description |
|------|-------------|
| `nse_sector_list` | Lists all NSE sectors |
| `nse_market_overview` | High-level NSE overview — sectors, Nifty indices, trading hours |
| `nse_sector_scanner` | Sector rotation scanner for NSE with top stock picks per hot sector |
| `nse_stock_screener` | Composite-scored stock ranking engine for NSE — supports NIFTY50/BANK/IT index filters |
| `nse_trade_plan` | Complete trade plan for an NSE stock — entry, stop-loss, target, R:R |
| `nse_index_analysis` | Constituent analysis for Nifty 50, Nifty Bank, Nifty IT, Nifty 100 |
| `nse_fibonacci_retracement` | Fibonacci retracement levels for NSE stocks |

### BSE (India) Tools

| Tool | Description |
|------|-------------|
| `bse_market_overview` | Full BSE snapshot — top stocks per category and sector summary |
| `bse_sector_scanner` | Sector rotation scanner for BSE with top stock picks per hot sector |
| `bse_stock_screener` | Composite-scored stock ranking engine for BSE — supports SENSEX/BSE100 filters |
| `bse_trade_plan` | Complete trade plan for a BSE stock — entry, stop-loss, target, R:R |
| `bse_index_analysis` | Constituent analysis for SENSEX, BSE100, and other BSE indices |
| `bse_fibonacci_retracement` | Fibonacci retracement levels for BSE stocks |

### Sentiment & News Tools

| Tool | Description |
|------|-------------|
| `market_sentiment` | Real-time Reddit sentiment score for any asset (crypto, stocks) |
| `financial_news` | Aggregated financial news from Reuters, CoinDesk, FT, and other RSS feeds |

### Backtest Tools

| Tool | Description |
|------|-------------|
| `backtest_strategy` | Single-strategy backtest on Yahoo Finance data — Sharpe, Max DD, Win Rate, equity curve |
| `compare_strategies` | Runs all 6 strategies simultaneously and returns a ranked leaderboard |
| `walk_forward_backtest_strategy` | Walk-forward validation with N folds to detect overfitting |

Supported strategies: `rsi`, `bollinger`, `macd`, `ema_cross`, `supertrend`, `donchian`

### Yahoo Finance Tools

| Tool | Description |
|------|-------------|
| `yahoo_price` | Real-time price for any Yahoo Finance symbol (stocks, crypto, FX, indices, ETFs) |
| `market_snapshot` | Global macro snapshot — major indices, top crypto, FX rates, commodity ETFs |

### Portfolio & Paper Trading

| Tool | Description |
|------|-------------|
| `get_user_portfolio` | Current portfolio state — open positions, total value, unrealised P&L |
| `execute_portfolio_trade` | Execute a paper trade with risk controls (no real money) |
| `get_portfolio_trade_history` | Recent paper trade executions for a user |

### Signals, Alerts & Execution

| Tool | Description |
|------|-------------|
| `save_trade_signal` | Persist a BUY/SELL/HOLD signal with confidence and optional metadata |
| `list_trade_signals` | List stored trade signals |
| `set_user_alert_preferences` | Configure alert delivery channel (webhook, email) and confidence threshold |
| `dispatch_trade_alert` | Dispatch an alert using the user's stored preferences |
| `execute_order` | Unified order entry — paper mode now, live brokerage integration in future |

### Risk & Position Sizing

| Tool | Description |
|------|-------------|
| `get_kelly_position_size` | Half-Kelly position size fraction from win rate and R:R ratio |
| `get_trade_levels` | Compute stop-loss and take-profit price levels from entry and percentages |
| `assess_portfolio_trade_risk` | Pre-trade risk assessment checking sector concentration and leverage limits |
| `assess_trade_risk_full` | Comprehensive risk assessment across EGX/NSE/BSE — symbol validity, position sizing, R:R, account impact |
| `assess_liquidity_for_trade` | Liquidity assessment for a proposed position size |
| `kelly_position_size` | Full Kelly Criterion sizing with configurable Kelly fraction and account balance |
| `risk_based_position_size` | Position size from fixed % risk per trade rule |
| `portfolio_position_size` | Position size respecting max open positions and concentration limits |
| `compute_portfolio_correlation` | Pairwise Pearson correlation matrix from historical return series |

### Live Market & Trade Analytics

| Tool | Description |
|------|-------------|
| `get_live_price` | Real-time price snapshot for any symbol — price, 24h change, volume, bid/ask |
| `get_multi_price` | Live prices for multiple symbols in one call |
| `get_global_market_overview` | Global market overview with major indices, crypto, and ETFs |
| `create_price_alert` | Create an "above" or "below" price alert for any symbol |
| `get_active_price_alerts` | List all active price alerts, optionally filtered by symbol |
| `record_trade` | Record a trade entry (open or completed) for analytics tracking |
| `close_trade` | Close an open trade at exit price and compute realised P&L |
| `get_user_trade_history` | Trade history with optional symbol and status filters |
| `calculate_trade_metrics` | Performance metrics — win rate, profit factor, Sharpe, max drawdown, recovery factor |

### Strategy Optimization

| Tool | Description |
|------|-------------|
| `recognize_market_pattern` | AI-powered pattern recognition from OHLCV candles and indicators — detects reversal, breakout, consolidation, and more |
| `optimize_strategy` | AI-driven parameter optimization suggestions from current metrics and market regime |
| `detect_market_anomalies` | Statistical anomaly detection (z-score) in performance metrics history |

---

## Example Prompts

```
# Screening
"Show top gainers on KuCoin 15m"
"Run a Bollinger squeeze scan on Binance 4h"
"Find NASDAQ strong buy signals"

# Analysis
"Full technical analysis of BTCUSDT on Binance 4h"
"Multi-timeframe analysis of ETHUSDT on KuCoin"
"Run a 3-agent debate on AAPL NASDAQ daily"
"Combined technical + sentiment + news for TSLA"

# EGX
"EGX market overview today"
"Scan EGX banks sector"
"Generate a trade plan for COMI"
"EGX30 index analysis"

# Backtesting
"Backtest RSI strategy on AAPL for 1 year"
"Compare all 6 strategies on BTC-USD 2 years"
"Walk-forward validate MACD on SPY — is it overfitted?"

# Real-time data
"What is Apple's current price?"
"Global market snapshot"
"Latest crypto news"

# Portfolio
"Paper buy 0.1 BTC at 45000 for user alice"
"Show my portfolio for user alice"

# Risk
"Kelly position size: 55% win rate, 2:1 reward/risk"
"Trade levels for long at 45000, 3% stop, 9% target"
```

---

## Docker

```bash
# Pull and run
docker pull debarpan2000/tradingview-mcp:latest
docker run -p 8000:8000 debarpan2000/tradingview-mcp:latest

# Or with docker compose
docker compose up -d
```

Claude Desktop config for Docker:
```json
{
  "mcpServers": {
    "tradingview": {
      "command": "curl",
      "args": ["-s", "http://localhost:8000/mcp"]
    }
  }
}
```

---

## OpenClaw (Telegram / WhatsApp)

Route Claude through Telegram, WhatsApp, Discord, and 20+ messaging platforms with [OpenClaw](https://openclaw.ai):

```
Telegram message -> OpenClaw agent -> trading.py -> tradingview-assistant -> result
```

```bash
# Install the tool
uv tool install tradingview-assistant

# Install the skill and wrapper
mkdir -p ~/.agents/skills/tradingview-mcp ~/.openclaw/tools
curl -fsSL https://raw.githubusercontent.com/DEBARPAN2000/tradingview-mcp/main/openclaw/SKILL.md \
  -o ~/.agents/skills/tradingview-mcp/SKILL.md
curl -fsSL https://raw.githubusercontent.com/DEBARPAN2000/tradingview-mcp/main/openclaw/trading.py \
  -o ~/.openclaw/tools/trading.py && chmod +x ~/.openclaw/tools/trading.py

openclaw gateway install && systemctl --user start openclaw-gateway.service
```

See **[OPENCLAW.md](OPENCLAW.md)** for the full setup guide, multi-provider AI model options, and common mistakes.

---

## Troubleshooting

### Windows: MCP timeout on first launch

**Symptom:** `MCP error -32001: Request timed out` in Claude Desktop logs.

**Cause:** `uvx` compiles pandas from source on Python 3.14 (no prebuilt wheel), exceeding the 60-second timeout.

**Fix — pin to Python 3.13:**
```json
{
  "mcpServers": {
    "tradingview": {
      "command": "uvx",
      "args": ["--python", "3.13", "--from", "tradingview-assistant", "tradingview-mcp"]
    }
  }
}
```

**Or pre-warm the cache once:**
```bash
uv tool install --python 3.13 tradingview-assistant
```

### macOS: `uvx: command not found`

Use the absolute path in your config: `/Users/YOUR_USERNAME/.local/bin/uvx`

### No symbols returned for an exchange

Check the exchange code is uppercase and supported: `KUCOIN`, `BINANCE`, `BYBIT`, `MEXC`, `OKX`, `EGX`, `NASDAQ`, `NYSE`, `BIST`, etc.

### TradingView rate limiting

Space out scans by a few seconds. The server has a built-in request guard with configurable rate limits.

---

## Project Structure

```
tradingview-mcp/
├── src/tradingview_mcp/
│   ├── server.py                        # MCP tool registry (40+ tools)
│   ├── coinlist/                        # Per-exchange symbol lists
│   └── core/
│       ├── services/
│       │   ├── backtest_service.py      # 6-strategy backtesting engine
│       │   ├── egx_service.py           # Egyptian Exchange tools
│       │   ├── correlation_service.py   # Portfolio correlation
│       │   ├── risk_service.py          # Kelly, trade levels, risk checks
│       │   ├── portfolio_service.py     # Paper trading execution
│       │   ├── alert_service.py         # Alert delivery
│       │   ├── data_source.py           # TradingView screener integration
│       │   ├── http_client.py           # Shared HTTP client
│       │   └── market_adapters/         # EGX and NSE adapters
│       ├── data/                        # Static datasets (sectors, indices)
│       ├── utils/                       # Validators and error contracts
│       └── portfolio.py                 # SQLite persistence layer
├── tests/
│   ├── unit/                            # Unit tests
│   └── integration/                     # Live integration tests
├── scripts/
│   └── repo_hygiene_check.py            # Security hygiene checker
├── openclaw/
│   ├── SKILL.md                         # OpenClaw skill definition
│   └── trading.py                       # OpenClaw tool wrapper
├── Dockerfile
├── docker-compose.yml
├── TOOLS.md                             # Complete tool reference
├── INSTALLATION.md                      # Detailed installation guide
├── OPENCLAW.md                          # OpenClaw integration guide
├── CONTRIBUTING.md                      # Contribution guide
└── SECURITY.md                          # Security policy
```

---

## Contributing

See **[CONTRIBUTING.md](CONTRIBUTING.md)** for the full guide.

Quick steps:
1. Fork and clone the repo
2. `uv sync` to install all dependencies
3. `uv run pytest tests/unit/` to verify your setup
4. Create a feature branch, make changes, run tests
5. Open a PR against `main` with a clear description

---

## License

MIT © 2025 DEBARPAN BOSE CHOWDHURY — see [LICENSE](LICENSE).
