# https://github.com/atilaahmettaner/tradingview-mcp 项目说明书

生成时间：2026-05-15 15:23:45 UTC

## 目录

- [Project Overview](#overview)
- [Installation Guide](#installation)
- [Quick Start Guide](#quick-start)
- [System Architecture](#system-architecture)
- [MCP Protocol Integration](#mcp-protocol)
- [Service Architecture](#service-architecture)
- [MCP Tools Reference](#mcp-tools-reference)
- [Backtesting Engine](#backtesting-engine)
- [Sentiment Analysis](#sentiment-analysis)
- [Multi-Exchange Integration](#exchange-integrations)

<a id='overview'></a>

## Project Overview

### 相关页面

相关主题：[System Architecture](#system-architecture), [MCP Tools Reference](#mcp-tools-reference), [Installation Guide](#installation)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)
- [CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)
- [INSTALLATION.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/INSTALLATION.md)
- [OPENCLAW.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/OPENCLAW.md)
- [src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)
- [pyproject.toml](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/pyproject.toml)
</details>

# Project Overview

## Introduction

**TradingView-MCP** is an open-source Model Context Protocol (MCP) server that bridges AI assistants (such as Claude Desktop, Codex, and OpenClaw) with TradingView's extensive market data, technical analysis tools, and financial data services.

The project enables AI agents to perform real-time market analysis, technical indicator calculations, stock screening, backtesting, and sentiment analysis through natural language interactions. 资料来源：[README.md:1]()

## Purpose and Scope

The primary objectives of TradingView-MCP are:

| Objective | Description |
|-----------|-------------|
| **Market Data Access** | Provide real-time and historical market data from multiple exchanges |
| **Technical Analysis** | Calculate 30+ technical indicators with BUY/SELL/HOLD signals |
| **Multi-Exchange Support** | Cover crypto (Binance, KuCoin, Bybit), US stocks (NASDAQ, NYSE, AMEX), and regional markets |
| **Backtesting Engine** | Test 6 trading strategies with institutional-grade metrics |
| **Sentiment Analysis** | Aggregate Reddit and news sentiment for informed decision-making |

资料来源：[README.md:1-20]()

## Architecture Overview

TradingView-MCP follows a modular architecture with clear separation of concerns:

```mermaid
graph TD
    subgraph "Client Layer"
        A[Claude Desktop] --> B[MCP Protocol]
        C[Codex] --> B
        D[OpenClaw] --> B
        E[Telegram/WhatsApp] --> F[OpenClaw Agent]
        F --> B
    end
    
    subgraph "Server Layer"
        B --> G[server.py]
        G --> H[Core Services]
        G --> I[Technical Indicators]
        G --> J[Utilities]
    end
    
    subgraph "Data Sources"
        H --> K[TradingView Screener API]
        H --> L[Yahoo Finance API]
        H --> M[Reddit API]
        H --> N[News RSS Feeds]
    end
    
    subgraph "Exchanges"
        K --> O[Binance]
        K --> P[KuCoin]
        K --> Q[NASDAQ/NYSE]
        K --> R[EGX/BIST]
    end
```

### Directory Structure

```
tradingview-mcp/
├── src/tradingview_mcp/
│   ├── server.py              # Main MCP server entry point
│   ├── core/
│   │   ├── services/         # Market data services
│   │   ├── utils/           # Utility functions (validators.py)
│   │   └── indicators/       # Technical indicators
│   └── coinlist/             # Exchange symbol lists
├── tests/
│   ├── unit/                 # Unit tests
│   └── integration/          # Integration tests
├── openclaw/                 # OpenClaw integration files
└── pyproject.toml            # Project configuration
```

资料来源：[CONTRIBUTING.md:40-55]()

## Core Features

### 1. Technical Analysis Engine

The server provides comprehensive technical analysis with 30+ indicators:

| Category | Indicators |
|----------|------------|
| **Momentum** | RSI, Stochastic, CCI, Williams %R |
| **Trend** | MACD, EMA Cross, Supertrend, ADX |
| **Volatility** | Bollinger Bands, ATR, Standard Deviation |
| **Volume** | OBV, Volume Profile, A/D Line |
| **Patterns** | 15 Candlestick Pattern Detection |

资料来源：[README.md:45-60]()

### 2. Backtesting System

The backtesting engine supports 6 trading strategies:

```mermaid
graph LR
    A[Strategy Selection] --> B[rsi]
    A --> C[bollinger]
    A --> D[macd]
    A --> E[ema_cross]
    A --> F[supertrend]
    A --> G[donchian]
    
    B --> H[Performance Metrics]
    C --> H
    D --> H
    E --> H
    F --> H
    G --> H
    
    H --> I[Win Rate]
    H --> J[Sharpe Ratio]
    H --> K[Calmar Ratio]
    H --> L[Max Drawdown]
    H --> M[Profit Factor]
```

**Available Strategies:**

| Strategy | Type | Description |
|----------|------|-------------|
| `rsi` | Mean Reversion | RSI oversold/overbought signals |
| `bollinger` | Mean Reversion | Bollinger Band price band breakout |
| `macd` | Trend Following | MACD golden/death cross |
| `ema_cross` | Trend Following | EMA 20/50 Golden/Death Cross |
| `supertrend` | Trend Following | ATR-based Supertrend |
| `donchian` | Breakout | Donchian Channel breakout (Turtle style) |

资料来源：[README.md:65-85]()

### 3. Yahoo Finance Integration (v0.6.0)

Real-time price data integration provides:

| Tool | Function |
|------|----------|
| `yahoo_price` | Real-time quote with price, change %, 52w high/low, market state |
| `market_snapshot` | Global overview: S&P500, NASDAQ, BTC, EUR/USD, etc. |
| `get_prices_bulk` | Multi-symbol price lookup |

资料来源：[README.md:95-105]()

## Supported Exchanges

TradingView-MCP supports multiple exchange types through the `EXCHANGE_SCREENER` mapping:

```mermaid
graph TD
    subgraph "Crypto Exchanges"
        A[BINANCE]
        B[KUCOIN]
        C[BYBIT+]
        D[MEXC]
    end
    
    subgraph "US Markets"
        E[NASDAQ]
        F[NYSE]
        G[AMEX]
        H[NYSEARCA]
        I[PCX]
    end
    
    subgraph "Regional Markets"
        J[EGX - Egypt]
        K[BIST - Turkey]
        L[TWSE - Taiwan]
        M[TPEX - Taiwan]
    end
```

### Exchange Configuration

| Exchange | Screener Type | Symbol Format |
|----------|---------------|---------------|
| `BINANCE` | `crypto` | `BINANCE:BTCUSDT` |
| `KUCOIN` | `crypto` | `KUCOIN:BTCUSDT` |
| `NASDAQ` | `america` | `NASDAQ:AAPL` |
| `NYSE` | `america` | `NYSE:TSLA` |
| `AMEX` | `america` | `AMEX:SPY` |
| `NYSEARCA` | `america` | `AMEX:GLD` |
| `EGX` | `egypt` | `EGX:COMI` |
| `TWSE` | `Taiwan` | `TWSE:2330` |

资料来源：[src/tradingview_mcp/core/utils/validators.py:80-100]()

### Stock Exchange Classification

The system classifies exchanges using `STOCK_EXCHANGES`:

```python
STOCK_EXCHANGES = frozenset({
    "nyse", "nasdaq", "amex", "nysearca", "pcx",
    "twse", "tpex", "egx"
})
```

资料来源：[src/tradingview_mcp/core/utils/validators.py:60-65]()

## Available Tools

### Market Data Tools

| Tool | Description |
|------|-------------|
| `top_gainers` | Find top gaining assets |
| `top_losers` | Find top losing assets |
| `screen_stocks` | Multi-exchange screener with 20+ filter criteria |
| `scan_by_signal` | Scan by signal type (oversold, trending, breakout) |
| `coin_analysis` | Comprehensive coin/symbol analysis |

### Technical Analysis Tools

| Tool | Description |
|------|-------------|
| `get_technical_analysis` | Full TA: RSI, MACD, Bollinger, 23 indicators |
| `get_multiple_analysis` | Bulk TA for multiple symbols |
| `get_bollinger_band_analysis` | Proprietary ±3 BB rating system |
| `get_stock_decision` | 3-layer decision engine |
| `get_candlestick_patterns` | 15 candlestick pattern detector |
| `get_multi_timeframe_analysis` | Weekly→Daily→4H→1H→15m alignment |

### Backtesting Tools

| Tool | Description |
|------|-------------|
| `backtest_strategy` | Backtest 1 of 6 strategies with Sharpe, Calmar, Expectancy |
| `compare_strategies` | Run all 6 strategies and rank by performance |

### Sentiment & News Tools

| Tool | Description |
|------|-------------|
| `get_reddit_sentiment` | Reddit sentiment analysis |
| `get_live_news` | Live financial news via RSS |

资料来源：[README.md:30-70]()

## Installation Methods

### Method 1: UV Package Manager (Recommended)

```bash
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install from PyPI
uv tool install tradingview-mcp-server
```

### Method 2: Claude Desktop Configuration

```json
{
  "mcpServers": {
    "tradingview": {
      "command": "uvx",
      "args": ["--from", "tradingview-mcp-server", "tradingview-mcp"]
    }
  }
}
```

资料来源：[INSTALLATION.md:25-40]()

### Method 3: Git Clone (Local Development)

```bash
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
uv sync
uv run python src/tradingview_mcp/server.py
```

资料来源：[CONTRIBUTING.md:15-25]()

## Configuration Reference

### Claude Desktop Config (Windows)

```json
{
  "mcpServers": {
    "tradingview-mcp-local": {
      "command": "C:\\Users\\YOUR_USERNAME\\tradingview-mcp\\.venv\\Scripts\\python.exe",
      "args": ["C:\\Users\\YOUR_USERNAME\\tradingview-mcp\\src\\tradingview_mcp\\server.py"],
      "cwd": "C:\\Users\\YOUR_USERNAME\\tradingview-mcp"
    }
  }
}
```

### Python Version Compatibility

| Python Version | Status | Notes |
|----------------|--------|-------|
| 3.13 | ✅ Recommended | Prebuilt pandas wheels available |
| 3.14 | ⚠️ Warning | May timeout on first launch due to source build |

For Python 3.14 on Windows, pin to Python 3.13:

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

资料来源：[INSTALLATION.md:45-55]()

## OpenClaw Integration

TradingView-MCP can be accessed via Telegram, WhatsApp, and Discord using OpenClaw:

```mermaid
graph LR
    A[Telegram User] --> B[OpenClaw Gateway]
    B --> C[AI Agent]
    C --> D[trading.py Wrapper]
    D --> E[tradingview-mcp]
    E --> F[Yahoo Finance API]
```

资料来源：[OPENCLAW.md:1-20]()

## Development Guidelines

### Code Style

| Aspect | Standard |
|--------|----------|
| Style | PEP 8 with customizations |
| Linting | Ruff |
| Type Hints | Required for all functions |
| Docstrings | Required for public functions/classes |

### Testing Standards

| Test Type | Coverage Target | Framework |
|-----------|-----------------|------------|
| Unit Tests | Core functions | pytest |
| Integration Tests | Real API calls | pytest |
| Linting | All code | ruff |
| Type Checking | All code | mypy |

资料来源：[CONTRIBUTING.md:70-95]()

## Project Roadmap

```mermaid
gantt
    title TradingView-MCP Roadmap
    dateFormat  YYYY-MM
    section Completed
    Technical Analysis (30+ indicators)    :done, 2024-01, 2024-06
    Multi-exchange support                  :done, 2024-02, 2024-08
    Yahoo Finance integration              :done, 2024-06, 2024-09
    Backtesting engine                      :done, 2024-07, 2024-12
    section In Progress
    Walk-forward backtesting               :active, 2025-01, 2025-06
    section Planned
    Twitter/X sentiment                    :todo, 2025-03, 2025-06
    Paper trading simulation               :todo, 2025-04, 2025-09
    Managed cloud hosting                  :todo, 2025-06, 2025-12
```

资料来源：[README.md:150-165]()

## License

TradingView-MCP is released under the **MIT License**. See [LICENSE](LICENSE) for details.

资料来源：[README.md:170-172]()

---

<a id='installation'></a>

## Installation Guide

### 相关页面

相关主题：[Quick Start Guide](#quick-start)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [INSTALLATION.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/INSTALLATION.md)
- [OPENCLAW.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/openclaw/OPENCLAW.md)
- [CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)
- [README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)
- [src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)
</details>

# Installation Guide

This guide covers all supported methods for installing and configuring the TradingView MCP server. The server acts as a bridge between AI agents (Claude Desktop, Codex, OpenClaw) and TradingView market data, enabling real-time technical analysis, screening, and sentiment analysis through natural language commands.

## Prerequisites

| Requirement | Version | Notes |
|-------------|---------|-------|
| Python | 3.8+ (3.10+ recommended) | Required for all installation methods |
| UV Package Manager | Latest | Fast Python package manager for dependency management |
| MCP Client | Claude Desktop, Codex, or OpenClaw | The AI agent interface |
| Internet Connection | Required | For TradingView data access |

资料来源：[INSTALLATION.md:1-5]()

## Installation Methods

### Method 1: UV Package Manager (Recommended)

UV is a fast Python package manager that handles all dependencies automatically. This is the recommended installation method for most users.

#### Step 1: Install UV

**macOS/Linux:**
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc
```

**Windows:**
```powershell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```

Verify installation:
```bash
uv --version
```

资料来源：[INSTALLATION.md:15-30]()

#### Step 2: Clone the Repository

```bash
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
```

#### Step 3: Install Dependencies

```bash
uv sync
```

资料来源：[INSTALLATION.md:35-40]()

### Method 2: Python Virtual Environment

For users who prefer traditional Python environments without UV:

**Windows:**
```powershell
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
python -m venv .venv
.\.venv\Scripts\activate
pip install -e .
```

**macOS/Linux:**
```bash
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
python -m venv .venv
source .venv/bin/activate
pip install -e .
```

资料来源：[INSTALLATION.md:120-140]()

### Method 3: PyPI Installation (uvx)

For quick testing without cloning:

```bash
uv tool install --python 3.13 tradingview-mcp-server
```

资料来源：[README.md:45-50]()

## MCP Client Configuration

### Claude Desktop

#### Locate Configuration File

| OS | Path |
|----|------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

资料来源：[INSTALLATION.md:55-65]()

#### Add Server Configuration

Open the config file and add the following:

```json
{
  "mcpServers": {
    "tradingview-mcp": {
      "command": "uv",
      "args": [
        "tool",
        "run",
        "--from",
        "git+https://github.com/atilaahmettaner/tradingview-mcp.git",
        "tradingview-mcp"
      ]
    }
  }
}
```

资料来源：[INSTALLATION.md:70-85]()

**Windows (Direct Python Path):**
```json
{
  "mcpServers": {
    "tradingview-mcp-local": {
      "command": "C:\\Users\\YOUR_USERNAME\\tradingview-mcp\\.venv\\Scripts\\python.exe",
      "args": ["C:\\Users\\YOUR_USERNAME\\tradingview-mcp\\src\\tradingview_mcp\\server.py"],
      "cwd": "C:\\Users\\YOUR_USERNAME\\tradingview-mcp"
    }
  }
}
```

资料来源：[INSTALLATION.md:18-25]()

**macOS/Linux (Using UV):**
```json
{
  "mcpServers": {
    "tradingview-mcp-local": {
      "command": "uv",
      "args": ["run", "python", "src/tradingview_mcp/server.py"],
      "cwd": "/path/to/your/tradingview-mcp"
    }
  }
}
```

资料来源：[INSTALLATION.md:105-112]()

### Codex Plugin

The repository includes MCP-only Codex plugin metadata:

- `.codex-plugin/plugin.json`
- `.codex-mcp.json`

```json
{
  "mcpServers": {
    "tradingview": {
      "command": "uvx",
      "args": [
        "--from",
        "tradingview-mcp-server",
        "tradingview-mcp"
      ]
    }
  }
}
```

资料来源：[README.md:65-78]()

After enabling the plugin in Codex, restart Codex so the MCP server is loaded in the next session.

### OpenClaw Integration

OpenClaw routes messages from Telegram, WhatsApp, Discord, and 20+ messaging platforms to an AI agent that calls tradingview-mcp functions.

```mermaid
graph LR
    A[Telegram/WhatsApp/Discord] --> B[OpenClaw Gateway]
    B --> C[AI Agent]
    C --> D[trading.py Wrapper]
    D --> E[tradingview-mcp]
    E --> F[Yahoo Finance]
```

资料来源：[OPENCLAW.md:1-15]()

#### Step 1: Install Dependencies

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc
uv tool install tradingview-mcp-server
```

资料来源：[OPENCLAW.md:8-12]()

#### Step 2: Configure Channel

Create or edit `~/.openclaw/openclaw.json`:

```json5
{
  channels: {
    telegram: {
      botToken: "YOUR_BOT_TOKEN_HERE",
    },
  },
}
```

资料来源：[OPENCLAW.md:15-22]()

#### Step 3: Install Skill and Tool

```bash
mkdir -p ~/.agents/skills/tradingview-mcp ~/.openclaw/tools

curl -fsSL https://raw.githubusercontent.com/atilaahmettaner/tradingview-mcp/main/openclaw/SKILL.md \
  -o ~/.agents/skills/tradingview-mcp/SKILL.md

curl -fsSL https://raw.githubusercontent.com/atilaahmettaner/tradingview-mcp/main/openclaw/trading.py \
  -o ~/.openclaw/tools/trading.py
chmod +x ~/.openclaw/tools/trading.py
```

资料来源：[OPENCLAW.md:25-33]()

#### Step 4: Restart OpenClaw

```bash
openclaw gateway install
systemctl --user start openclaw-gateway.service
openclaw doctor
```

资料来源：[OPENCLAW.md:55-58]()

## Development Setup

For contributors who want to modify the code or run locally:

### 1. Clone and Setup

```bash
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
```

### 2. Install Development Dependencies

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync
uv sync --dev
```

资料来源：[CONTRIBUTING.md:5-12]()

### 3. Run Tests

| Command | Purpose |
|---------|---------|
| `uv run pytest` | Run the test suite |
| `uv run ruff check` | Run linting |
| `uv run mypy src/` | Run type checking |

资料来源：[CONTRIBUTING.md:15-20]()

### 4. Test Locally

```bash
# Test the server locally
uv run python src/tradingview_mcp/server.py

# Test with MCP Inspector
uv run mcp dev src/tradingview_mcp/server.py
```

资料来源：[CONTRIBUTING.md:23-28]()

## Directory Structure

The project follows a modular architecture:

```
tradingview-mcp/
├── src/tradingview_mcp/
│   ├── server.py              # Main MCP server
│   ├── core/                  # Core business logic
│   │   ├── services/         # Market data services
│   │   ├── utils/           # Utility functions
│   │   └── indicators/      # Technical indicators
│   └── coinlist/            # Exchange symbol lists
├── tests/
│   └── unit/                # Unit tests
├── .codex-plugin/           # Codex plugin metadata
└── pyproject.toml           # Project configuration
```

资料来源：[CONTRIBUTING.md:35-48]()

## Verification

After installation, verify the setup by asking your AI agent:

```
"Can you show me the available TradingView tools?"
```

Expected tools include:

| Category | Tools |
|----------|-------|
| Market Data | `top_gainers`, `top_losers`, `yahoo_price`, `market_snapshot` |
| Technical Analysis | `bollinger_scan`, `consecutive_candles_scan`, `technical_analysis` |
| Sentiment | `coin_analysis`, `reddit_sentiment` |
| Backtesting | `backtest`, `compare_strategies` |

资料来源：[README.md:80-90]()

## Troubleshooting

### Windows: MCP Timeout on First Launch

Symptom: `MCP error -32001: Request timed out` in Claude Desktop logs shortly after adding config.

Solution: Pre-install the package before launching Claude Desktop:

```bash
uv tool install --python 3.13 tradingview-mcp-server
```

This warms the cache so the server starts instantly.

资料来源：[README.md:45-55]()

### Common Issues

| Issue | Solution |
|-------|----------|
| UV not found | Add UV to PATH or restart terminal |
| Config file not found | Create the directory and file if missing |
| Server won't start | Check Python version (3.8+ required) |
| Timeout errors | Pre-install with `uv tool install` |

## Next Steps

After successful installation:

1. Explore available tools by asking your AI agent
2. Try basic queries like "Show me top gainers on Binance"
3. Run development tests with `uv run pytest`
4. Review [CONTRIBUTING.md](CONTRIBUTING.md) for code standards

---

<a id='quick-start'></a>

## Quick Start Guide

### 相关页面

相关主题：[Installation Guide](#installation), [MCP Tools Reference](#mcp-tools-reference)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)
- [INSTALLATION.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/INSTALLATION.md)
- [OPENCLAW.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/OPENCLAW.md)
- [CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)
- [EXAMPLES.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/EXAMPLES.md)
</details>

# Quick Start Guide

This guide provides step-by-step instructions for setting up and running the `tradingview-mcp` server, enabling AI assistants like Claude Desktop, Codex, and OpenClaw to perform real-time market analysis, technical indicators, and stock screening.

## Overview

The **tradingview-mcp** project is a Model Context Protocol (MCP) server that bridges AI assistants with TradingView's market data, Yahoo Finance real-time prices, and multi-exchange screening capabilities. 资料来源：[README.md:1]()

The Quick Start process involves three main stages:

```mermaid
graph TD
    A[Install Dependencies] --> B[Configure AI Client]
    B --> C[Verify Installation]
    A --> D[Clone Repository]
    D --> B
    C --> E[Available Tools Ready]
```

## Prerequisites

Before beginning, ensure your system meets these requirements:

| Requirement | Minimum | Recommended |
|-------------|---------|-------------|
| Python | 3.12+ | 3.13 |
| UV Package Manager | Latest | Latest |
| Operating System | Windows/macOS/Linux | Ubuntu 24.04 |
| Network | Internet for market data | Stable internet connection |

资料来源：[CONTRIBUTING.md:1-5]()

## Installation Methods

The project supports multiple installation approaches depending on your use case.

### Method 1: Quick Start with uvx

The fastest way to get started is using `uvx` which runs the package directly without manual installation:

```bash
uvx --from tradingview-mcp-server tradingview-mcp
```

This method requires no local setup and pulls the latest version from PyPI automatically. 资料来源：[README.md:45-48]()

### Method 2: Claude Desktop Configuration

For Claude Desktop integration, configure the MCP server in your client configuration file.

#### Locating Configuration File

| Platform | Path |
|----------|------|
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

资料来源：[INSTALLATION.md:15-20]()

#### Windows Configuration

Add the following to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "tradingview-mcp-local": {
      "command": "C:\\Users\\YOUR_USERNAME\\tradingview-mcp\\.venv\\Scripts\\python.exe",
      "args": ["C:\\Users\\YOUR_USERNAME\\tradingview-mcp\\src\\tradingview_mcp\\server.py"],
      "cwd": "C:\\Users\\YOUR_USERNAME\\tradingview-mcp"
    }
  }
}
```

资料来源：[INSTALLATION.md:24-32]()

#### macOS/Linux Configuration

For Unix-based systems, use `uv` with the run command:

```json
{
  "mcpServers": {
    "tradingview-mcp-local": {
      "command": "uv",
      "args": ["run", "python", "src/tradingview_mcp/server.py"],
      "cwd": "/path/to/your/tradingview-mcp"
    }
  }
}
```

资料来源：[INSTALLATION.md:55-63]()

#### Linux Full Path

On Linux systems, use the full path to uvx:

```json
{
  "mcpServers": {
    "tradingview": {
      "command": "/home/YOUR_USERNAME/.local/bin/uvx",
      "args": ["--from", "tradingview-mcp-server", "tradingview-mcp"]
    }
  }
}
```

资料来源：[README.md:60-66]()

### Method 3: Local Development Setup

For development or customization, clone and run from source.

#### Step 1: Clone Repository

```bash
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
```

#### Step 2: Install Dependencies

```bash
# Install UV if not present
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc

# Sync project dependencies
uv sync

# Install development dependencies
uv sync --dev
```

#### Step 3: Verify Installation

```bash
# Test the server locally
uv run python src/tradingview_mcp/server.py

# Run the test suite
uv run pytest

# Run linting checks
uv run ruff check

# Run type checking
uv run mypy src/
```

资料来源：[CONTRIBUTING.md:5-20]()

### Method 4: Pre-installed Tool

For faster subsequent launches, pre-install the package:

```bash
# Run once before launching Claude Desktop
uv tool install --python 3.13 tradingview-mcp-server
```

This warms the cache so Claude Desktop starts instantly without downloading dependencies. 资料来源：[README.md:79-83]()

## Python Version Considerations

When using `uvx`, the default Python version may cause issues on Windows with Python 3.14 due to missing prebuilt `pandas` wheels.

### Windows Timeout Fix

If you encounter `MCP error -32001: Request timed out` on first launch, pin Python 3.13:

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

资料来源：[README.md:96-107]()

## OpenClaw Integration

For connecting to Telegram, WhatsApp, or Discord, use the OpenClaw gateway.

### Step 1: Install OpenClaw Dependencies

```bash
# Install uv if needed
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc

# Install tradingview-mcp-server as tool
uv tool install tradingview-mcp-server
```

### Step 2: Configure Messaging Channel

Create or edit `~/.openclaw/openclaw.json`:

```json5
{
  channels: {
    telegram: {
      botToken: "YOUR_BOT_TOKEN_HERE",
    },
  },
}
```

### Step 3: Install TradingView Skill

```bash
mkdir -p ~/.agents/skills/tradingview-mcp ~/.openclaw/tools

# Download skill instructions
curl -fsSL https://raw.githubusercontent.com/atilaahmettaner/tradingview-mcp/main/openclaw/SKILL.md \
  -o ~/.agents/skills/tradingview-mcp/SKILL.md

# Download trading wrapper
curl -fsSL https://raw.githubusercontent.com/atilaahmettaner/tradingview-mcp/main/openclaw/trading.py \
  -o ~/.openclaw/tools/trading.py
chmod +x ~/.openclaw/tools/trading.py
```

### Step 4: Configure AI Model

Set up OpenRouter with Gemini 3 Flash for optimal performance:

```bash
openclaw config set acp.defaultAgent main
openclaw config set gateway.mode local
```

资料来源：[OPENCLAW.md:1-50]()

## Verification and Testing

### Test Claude Desktop

After adding configuration and restarting Claude Desktop:

```
"Can you show me the available TradingView tools?"
```

Expected response includes tools like `top_gainers`, `top_losers`, `bollinger_scan`, `coin_analysis`, and `consecutive_candles_scan`. 资料来源：[INSTALLATION.md:68-74]()

### Test OpenClaw Bot

Send these commands to your Telegram bot:

```
market snapshot
backtest RSI strategy for AAPL, 1 year
compare all strategies for BTC-USD
```

### Available Tool Categories

| Category | Tools |
|----------|-------|
| Market Data | `yahoo_price`, `market_snapshot`, `get_prices_bulk` |
| Technical Analysis | `get_technical_analysis`, `get_bollinger_band_analysis`, `get_stock_decision` |
| Screening | `screen_stocks`, `scan_by_signal`, `top_gainers`, `top_losers` |
| Backtesting | `backtest_strategy`, `compare_strategies` |

资料来源：[OPENCLAW.md:55-68]()

## Example Usage

### Market Snapshot

```
You: "Give me a full market snapshot right now"
AI: [market_snapshot] →
BUY (Technical STRONG BUY + Bullish Reddit + Positive news)
```

### Strategy Backtest

```
You: "Compare all strategies on BTC-USD for 2 years"
AI: 
→ #1 Supertrend: +31.5% | Sharpe: 2.1 | WR: 62%
→ #2 Bollinger:  +18.3% | Sharpe: 3.4 | WR: 75%
→ Buy & Hold:    -5.0%
```

### Stock Screening

```
You: "Show me NASDAQ tech stocks that are oversold"
AI: [scan_by_signal(exchange="NASDAQ", signal="oversold")]
```

资料来源：[EXAMPLES.md:1-25]()

## Troubleshooting

| Issue | Cause | Solution |
|-------|-------|----------|
| `MCP error -32001` on Windows | Python 3.14 has no prebuilt pandas | Pin to Python 3.13 in config |
| Server won't start | Missing dependencies | Run `uv sync` in project directory |
| Tools not showing | Claude Desktop not restarted | Fully quit and relaunch |
| OpenClaw gateway won't start | `gateway.mode` missing | Set `openclaw config set gateway.mode local` |

资料来源：[README.md:108-125]()

## Next Steps

After successful installation:

1. Explore the [technical analysis tools](README.md#-technical-analysis-core) for indicator-based analysis
2. Try the [backtesting engine](README.md#-backtesting-engine-new-in-v060) to test trading strategies
3. Configure [multi-exchange screening](README.md#-multi-exchange-support) for global market coverage
4. Review the [contribution guidelines](CONTRIBUTING.md) if you want to extend functionality

---

<a id='system-architecture'></a>

## System Architecture

### 相关页面

相关主题：[MCP Protocol Integration](#mcp-protocol), [Service Architecture](#service-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [assets/architecture.png](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/assets/architecture.png)
- [src/tradingview_mcp/server.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/server.py)
- [src/tradingview_mcp/__init__.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/__init__.py)
- [src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)
- [src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)
</details>

# System Architecture

## Overview

The `tradingview-mcp` project is a Model Context Protocol (MCP) server that provides AI assistants (such as Claude Desktop) with real-time access to financial market data, technical analysis, and backtesting capabilities. It acts as a bridge between AI agents and TradingView's data infrastructure.

**资料来源：** [README.md](README.md)

The server follows a layered architecture pattern with clear separation between the MCP protocol layer, business logic services, and data providers.

---

## High-Level Architecture

```mermaid
graph TB
    subgraph "Client Layer"
        CLAUDE["Claude Desktop / AI Agent"]
        TELEGRAM["Telegram Bot (OpenClaw)"]
        CODEX["Codex Plugin"]
    end
    
    subgraph "MCP Protocol Layer"
        SERVER["server.py<br/>(MCP Server Entry)"]
    end
    
    subgraph "Service Layer"
        TA["Technical Analysis<br/>Indicators"]
        SCREENER["Screener Service"]
        BACKTEST["Backtesting Engine"]
        YAHOO["Yahoo Finance API"]
        SENTIMENT["Reddit Sentiment"]
    end
    
    subgraph "Data Provider Layer"
        TV["TradingView Screener"]
        YF["Yahoo Finance"]
        RSS["Live News RSS"]
    end
    
    CLAUDE --> SERVER
    TELEGRAM --> SERVER
    CODEX --> SERVER
    
    SERVER --> TA
    SERVER --> SCREENER
    SERVER --> BACKTEST
    
    SCREENER --> TV
    TA --> TV
    TA --> YF
    BACKTEST --> YAHOO
```

---

## Directory Structure

The codebase is organized following Python best practices with a modular structure:

```
tradingview-mcp/
├── src/tradingview_mcp/
│   ├── server.py              # Main MCP server entry point
│   ├── __init__.py            # Package initialization
│   ├── core/
│   │   ├── services/         # Market data services
│   │   │   ├── screener_service.py   # Stock/coin screening
│   │   │   └── ...
│   │   ├── utils/             # Utility functions
│   │   │   ├── validators.py         # Input validation & exchange mapping
│   │   │   └── ...
│   │   └── indicators/        # Technical indicators
│   │       └── ...            # RSI, MACD, Bollinger, etc.
│   └── coinlist/              # Exchange symbol lists
│       ├── binance.txt
│       ├── kucoin.txt
│       └── ...
├── tests/
│   └── unit/
├── assets/
│   └── architecture.png
└── pyproject.toml
```

**资料来源：** [CONTRIBUTING.md - Code Organization](CONTRIBUTING.md)

---

## Core Components

### MCP Server (`server.py`)

The main entry point that registers all tools as MCP resources and handlers. It exposes 30+ tools including:

| Category | Tools |
|----------|-------|
| Backtesting | `backtest_strategy`, `compare_strategies` |
| Technical Analysis | `get_technical_analysis`, `get_bollinger_band_analysis` |
| Market Data | `top_gainers`, `top_losers`, `yahoo_price` |
| Screening | `screen_stocks`, `scan_by_signal` |
| Multi-Exchange | `egx_*`, `multi_timeframe_analysis` |

**资料来源：** [src/tradingview_mcp/server.py](src/tradingview_mcp/server.py)

### Validators Module

The `validators.py` module handles exchange routing and symbol validation:

```python
EXCHANGE_SCREENER = {
    "BINANCE": "crypto",
    "KUCOIN": "crypto", 
    "BYBIT": "crypto",
    "NASDAQ": "america",
    "NYSE": "america",
    "AMEX": "america",
    "TWSE": "Taiwan",
    "TPEX": "Taiwan",
    "BIST": "turkey"
}
```

Key functions include:
- `sanitize_exchange()` - Normalizes exchange names
- `get_tv_exchange_prefix()` - Maps exchanges to TradingView prefixes (e.g., `AMEX:GLD`)
- Exchange alias support for `AMEX`, `NYSEARCA`, `PCX` → `AMEX`

**资料来源：** [src/tradingview_mcp/core/utils/validators.py](src/tradingview_mcp/core/utils/validators.py)

### Screener Service

Handles multi-exchange stock and crypto screening with configurable filters:

**资料来源：** [src/tradingview_mcp/core/services/screener_service.py](src/tradingview_mcp/core/services/screener_service.py)

---

## Backtesting Engine Architecture

The backtesting engine supports 6 trading strategies:

```mermaid
graph LR
    A[Symbol Input] --> B[Strategy Selector]
    
    B --> C[rsi<br/>RSI Mean Reversion]
    B --> D[bollinger<br/>BB Mean Reversion]
    B --> E[macd<br/>MACD Cross]
    B --> F[ema_cross<br/>EMA 20/50]
    B --> G[supertrend<br/>ATR Supertrend]
    B --> H[donchian<br/>Donchian Breakout]
    
    C --> I[Metrics Calculator]
    D --> I
    E --> I
    F --> I
    G --> I
    H --> I
    
    I --> J[Win Rate, Sharpe,<br/>Calmar, Drawdown]
```

**Performance Metrics:**
- Win Rate, Total Return
- Sharpe Ratio, Calmar Ratio
- Max Drawdown, Profit Factor
- Expectancy, Best/Worst Trade
- Commission + slippage simulation

**资料来源：** [README.md - Backtesting Engine](README.md)

---

## Integration Architecture

### Claude Desktop Integration

```json
{
  "mcpServers": {
    "tradingview-mcp": {
      "command": "uvx",
      "args": ["--from", "tradingview-mcp-server", "tradingview-mcp"]
    }
  }
}
```

**资料来源：** [README.md - Quick Start](README.md)

### OpenClaw Integration

For Telegram/WhatsApp access:

```
Telegram → OpenClaw Agent → trading.py wrapper → tradingview-mcp → Yahoo Finance
```

**资料来源：** [OPENCLAW.md](OPENCLAW.md)

---

## Data Flow

```mermaid
sequenceDiagram
    participant User
    participant MCP as MCP Server
    participant Service as Service Layer
    participant Provider as Data Provider
    
    User->>MCP: Request tool call
    MCP->>Service: Route to appropriate service
    Service->>Provider: Fetch market data
    Provider-->>Service: Raw data response
    Service-->>MCP: Processed/Formatted data
    MCP-->>User: Tool result response
```

---

## Supported Exchanges

| Exchange | Region | Type | Tools |
|----------|--------|------|-------|
| Binance | Global | Crypto | All crypto tools |
| KuCoin | Global | Crypto | All crypto tools |
| Bybit+ | Global | Crypto | All crypto tools |
| NASDAQ | US | Stocks | Stock analysis, screening |
| NYSE | US | Stocks | Stock analysis, screening |
| AMEX | US | ETFs/Stocks | Stock analysis, screening |
| TWSE | Taiwan | Stocks | Stock analysis, screening |
| TPEX | Taiwan | Stocks | Stock analysis, screening |
| BIST | Turkey | Stocks | Turkish market tools |
| EGX | Egypt | Stocks | `egx_market_overview`, `egx_stock_screener` |

**资料来源：** [src/tradingview_mcp/core/utils/validators.py](src/tradingview_mcp/core/utils/validators.py), [README.md](README.md)

---

## Development Architecture

### Local Development Setup

```bash
# Clone and install
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
uv sync

# Test server
uv run python src/tradingview_mcp/server.py

# Run with MCP Inspector
uv run mcp dev src/tradingview_mcp/server.py
```

### Testing Pipeline

| Test Type | Command | Purpose |
|-----------|---------|---------|
| Unit Tests | `uv run pytest` | Core functionality |
| Linting | `uv run ruff check` | Code style |
| Type Checking | `uv run mypy src/` | Type safety |
| Integration | `uv run python test_api.py` | End-to-end |

**资料来源：** [CONTRIBUTING.md - Testing](CONTRIBUTING.md)

---

## Adding New Components

### Adding a New Exchange

1. **Update validators.py:**
   ```python
   EXCHANGE_SCREENER = {
       "NEW_EXCHANGE": "screener_code",
       # ... existing
   }
   STOCK_EXCHANGES.add("NEW_EXCHANGE")
   ```

2. **Add symbol list:**
   ```bash
   echo "SYMBOL1\nSYMBOL2" > coinlist/new_exchange.txt
   ```

3. **Test integration:**
   ```python
   result = top_gainers(exchange="NEW_EXCHANGE")
   ```

**资料来源：** [CONTRIBUTING.md - Adding New Exchange](CONTRIBUTING.md)

### Adding Technical Indicators

1. **Create indicator function in `core/indicators/`:**
   ```python
   def calculate_custom_indicator(prices: List[float]) -> float:
       """Calculate custom technical indicator"""
       return result
   ```

2. **Integrate in server.py:**
   ```python
   custom_value = calculate_custom_indicator(price_data)
   result["technical_indicators"]["custom"] = custom_value
   ```

**资料来源：** [CONTRIBUTING.md - Adding Technical Indicators](CONTRIBUTING.md)

---

## Deployment Options

| Method | Use Case | Command/Config |
|--------|----------|----------------|
| **uvx (Recommended)** | Quick start, no local install | `uvx --from tradingview-mcp-server tradingview-mcp` |
| **Local Clone** | Development/modification | `git clone && uv sync && uv run python src/tradingview_mcp/server.py` |
| **Pre-installed Tool** | Reusable cache | `uv tool install --python 3.13 tradingview-mcp-server` |
| **Virtual Environment** | Traditional Python | `python -m venv .venv && pip install -e .` |
| **OpenClaw** | Telegram/WhatsApp | See [OPENCLAW.md](OPENCLAW.md) |

**资料来源：** [INSTALLATION.md](INSTALLATION.md), [README.md](README.md)

---

## Configuration Reference

### Claude Desktop Configuration

**Windows (Direct Python Path):**
```json
{
  "mcpServers": {
    "tradingview-mcp": {
      "command": "C:\\Users\\Username\\tradingview-mcp\\.venv\\Scripts\\python.exe",
      "args": ["C:\\Users\\Username\\tradingview-mcp\\src\\tradingview_mcp\\server.py"],
      "cwd": "C:\\Users\\Username\\tradingview-mcp"
    }
  }
}
```

**macOS/Linux (Using UV):**
```json
{
  "mcpServers": {
    "tradingview-mcp": {
      "command": "uv",
      "args": ["run", "python", "src/tradingview_mcp/server.py"],
      "cwd": "/path/to/tradingview-mcp"
    }
  }
}
```

**资料来源：** [INSTALLATION.md - Local Development Setup](INSTALLATION.md)

---

<a id='mcp-protocol'></a>

## MCP Protocol Integration

### 相关页面

相关主题：[System Architecture](#system-architecture), [MCP Tools Reference](#mcp-tools-reference)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/tradingview_mcp/server.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/server.py)
- [.codex-mcp.json](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/.codex-mcp.json)
- [.codex-plugin/plugin.json](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/.codex-plugin/plugin.json)
- [CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)
- [INSTALLATION.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/INSTALLATION.md)
</details>

# MCP Protocol Integration

## Overview

The TradingView MCP Server implements the **Model Context Protocol (MCP)** to provide AI assistants with structured access to real-time market data, technical analysis, and screening tools. MCP serves as the communication bridge between AI clients (Claude Desktop, Codex) and the TradingView data infrastructure.

## Architecture

```mermaid
graph TD
    A[AI Client<br/>Claude Desktop / Codex] --> B[MCP Protocol Layer]
    B --> C[tradingview-mcp Server]
    C --> D[Core Services]
    C --> E[Technical Indicators]
    C --> F[Screener Services]
    D --> G[Yahoo Finance API]
    D --> H[TradingView API]
    F --> I[Exchange Symbol Lists<br/>coinlist/]
    
    style B fill:#e1f5fe
    style C fill:#fff3e0
```

### Component Layers

| Layer | Responsibility | Key Components |
|-------|---------------|----------------|
| **AI Client** | User interaction, natural language processing | Claude Desktop, Codex |
| **MCP Protocol** | Standardized communication, tool discovery | JSON-RPC 2.0 messages |
| **Server** | Request routing, tool registration | `server.py` |
| **Services** | Business logic, data processing | Screener, Technical Analysis |
| **Data Sources** | External API integration | Yahoo Finance, TradingView |

## Server Implementation

The main server is implemented in `src/tradingview_mcp/server.py` and exposes TradingView tools as MCP resources.

### Available Tools

The server registers the following tools for market analysis:

| Tool Category | Tools |
|--------------|-------|
| **Market Screening** | `top_gainers`, `top_losers`, `screen_stocks`, `scan_by_signal` |
| **Technical Analysis** | `get_technical_analysis`, `get_multiple_analysis`, `get_bollinger_band_analysis` |
| **Pattern Detection** | `get_candlestick_patterns`, `consecutive_candles_scan`, `bollinger_scan` |
| **Multi-Timeframe** | `get_multi_timeframe_analysis`, `coin_analysis` |
| **Stock Decision** | `get_stock_decision` |

### Server Initialization

```python
# Minimal MCP server setup pattern
from mcp.server import Server
from mcp.server.stdio import stdio_server

app = Server("tradingview-mcp")
# Register tools and resources
```

## Client Configuration

### Claude Desktop

The server integrates with Claude Desktop via the MCP configuration file:

| Platform | Config Location |
|----------|-----------------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

**Configuration Schema:**

```json
{
  "mcpServers": {
    "tradingview-mcp": {
      "command": "uv",
      "args": [
        "tool",
        "run",
        "--from",
        "git+https://github.com/atilaahmettaner/tradingview-mcp.git",
        "tradingview-mcp"
      ]
    }
  }
}
```

资料来源：[INSTALLATION.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/INSTALLATION.md)

### Codex Plugin

The repository includes dedicated Codex plugin metadata for seamless integration:

**Plugin Configuration Files:**

| File | Purpose |
|------|---------|
| `.codex-plugin/plugin.json` | Plugin manifest |
| `.codex-mcp.json` | MCP server configuration |

**Codex Configuration:**

```json
{
  "mcpServers": {
    "tradingview": {
      "command": "uvx",
      "args": [
        "--from",
        "tradingview-mcp-server",
        "tradingview-mcp"
      ]
    }
  }
}
```

资料来源：[README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)

## Installation Methods

### Method 1: Direct Installation via UV

```bash
# Install from PyPI
uv tool install tradingview-mcp-server
```

资料来源：[INSTALLATION.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/INSTALLATION.md)

### Method 2: Source Installation

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

### Method 3: Pre-warm Cache (Windows)

For Windows users with Python 3.14, pre-install to avoid initialization timeout:

```bash
uv tool install --python 3.13 tradingview-mcp-server
```

资料来源：[README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)

## Development Workflow

```mermaid
graph LR
    A[Clone Repository] --> B[Install Dependencies<br/>uv sync]
    B --> C[Run Server<br/>uv run python src/tradingview_mcp/server.py]
    C --> D[Test with MCP Inspector<br/>uv run mcp dev src/tradingview_mcp/server.py]
    D --> E[Submit PR]
    
    style A fill:#c8e6c9
    style E fill:#c8e6c9
```

### Development Commands

| Command | Purpose |
|---------|---------|
| `uv sync` | Install all dependencies |
| `uv sync --dev` | Install development dependencies |
| `uv run pytest` | Execute test suite |
| `uv run ruff check` | Run linting |
| `uv run mypy src/` | Run type checking |

资料来源：[CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)

## OpenClaw Integration

For messaging platforms (Telegram, WhatsApp, Discord), OpenClaw provides an alternative integration path:

```mermaid
graph LR
    A[Telegram / WhatsApp] --> B[OpenClaw Agent]
    B --> C[trading.py Wrapper]
    C --> D[tradingview-mcp]
    D --> E[Yahoo Finance]
    
    style B fill:#e1f5fe
    style D fill:#fff3e0
```

### OpenClaw Quick Setup

```bash
# Install dependencies
curl -LsSf https://astral.sh/uv/install.sh | sh
uv tool install tradingview-mcp-server

# Configure channel
cat > ~/.openclaw/openclaw.json << 'EOF'
{
  channels: {
    telegram: {
      botToken: "YOUR_BOT_TOKEN_HERE",
    },
  },
}
EOF

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

资料来源：[OPENCLAW.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/OPENCLAW.md)

## Troubleshooting

### Windows Initialization Timeout

**Issue:** `MCP error -32001: Request timed out` on first launch with Python 3.14

**Root Cause:** pandas has no prebuilt wheel for Python 3.14, causing pip to fall back to source build which exceeds 60-second timeout.

**Solution:** Pin to Python 3.13:

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

资料来源：[README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)

### Verification Steps

After installation, verify the MCP server is operational:

1. Restart the AI client completely
2. Ask: "Can you show me the available TradingView tools?"
3. Confirm tools like `top_gainers`, `bollinger_scan`, `coin_analysis` are available

## Code Organization

```
src/tradingview_mcp/
├── server.py              # Main MCP server implementation
├── core/                  # Core business logic
│   ├── services/         # Market data services
│   ├── utils/           # Utility functions (validators, etc.)
│   └── indicators/      # Technical indicators
└── coinlist/            # Exchange symbol lists
```

资料来源：[CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)

## Next Steps

- Review the [Technical Analysis documentation](technical-analysis) for available indicators
- Explore the [Screening Tools](screening-tools) for market filtering
- Configure your preferred AI client following the installation guide

---

<a id='service-architecture'></a>

## Service Architecture

### 相关页面

相关主题：[System Architecture](#system-architecture), [MCP Tools Reference](#mcp-tools-reference), [Multi-Exchange Integration](#exchange-integrations)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/tradingview_mcp/core/services/backtest_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/backtest_service.py)
- [src/tradingview_mcp/core/services/sentiment_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/sentiment_service.py)
- [src/tradingview_mcp/core/services/indicators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/indicators.py)
- [src/tradingview_mcp/core/services/scanner_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/scanner_service.py)
- [src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)
- [src/tradingview_mcp/core/services/news_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/news_service.py)
- [src/tradingview_mcp/core/services/yahoo_finance_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/yahoo_finance_service.py)
- [src/tradingview_mcp/core/services/indicators_calc.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/indicators_calc.py)
</details>

# Service Architecture

The TradingView MCP (Model Context Protocol) server implements a **modular service-oriented architecture** that separates concerns across distinct functional domains. This design enables the system to provide comprehensive market analysis capabilities—including technical indicators, sentiment analysis, backtesting, and real-time price data—through a unified MCP interface.

## Overview

The service architecture follows a **layered pattern** where the MCP server acts as the presentation layer, delegating business logic to specialized services. Each service is responsible for a specific domain of functionality, communicating through well-defined interfaces.

### High-Level Architecture

```mermaid
graph TD
    subgraph "MCP Server Layer"
        SERVER[server.py - MCP Entry Point]
    end
    
    subgraph "Service Layer"
        BACKTEST[backtest_service.py]
        SENTIMENT[sentiment_service.py]
        NEWS[news_service.py]
        YAHOO[yahoo_finance_service.py]
        SCREENER[screener_service.py]
        SCANNER[scanner_service.py]
        INDICATORS[indicators.py]
        CALC[indicators_calc.py]
    end
    
    subgraph "Data Sources"
        TV[TradingView API]
        REDDIT[Reddit API]
        RSS[RSS Feeds]
        YAHOO_FIN[Yahoo Finance API]
    end
    
    SERVER --> BACKTEST
    SERVER --> SENTIMENT
    SERVER --> NEWS
    SERVER --> YAHOO
    SERVER --> SCREENER
    SERVER --> SCANNER
    SERVER --> INDICATORS
    
    INDICATORS --> CALC
    BACKTEST --> CALC
    SCREENER --> TV
    SENTIMENT --> REDDIT
    NEWS --> RSS
    YAHOO --> YAHOO_FIN
```

### Service Directory Structure

```
src/tradingview_mcp/core/services/
├── backtest_service.py      # Strategy backtesting engine
├── indicators.py            # Technical indicator orchestration
├── indicators_calc.py       # Low-level indicator calculations
├── news_service.py          # RSS news aggregation
├── scanner_service.py       # Pattern scanning and detection
├── screener_service.py      # Multi-exchange market screening
├── sentiment_service.py     # Reddit sentiment analysis
└── yahoo_finance_service.py # Real-time price data
```

资料来源：[CONTRIBUTING.md:62-70]()

## Service Components

### 1. Backtest Service

The backtest service provides a comprehensive strategy testing framework with institutional-grade metrics.

| Feature | Description |
|---------|-------------|
| Strategy Types | RSI, Bollinger Bands, MACD, EMA Cross, Supertrend, Donchian |
| Metrics | Win Rate, Sharpe Ratio, Calmar Ratio, Max Drawdown, Profit Factor |
| Commission Simulation | Realistic slippage and commission modeling |

资料来源：[src/tradingview_mcp/core/services/backtest_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/backtest_service.py)

### 2. Screener Service

The screener service aggregates market data from TradingView's screener across multiple exchanges.

| Exchange | Screener Type |
|----------|---------------|
| Binance, KuCoin, Bybit+ | Crypto screener |
| NASDAQ, NYSE | US stocks |
| TWSE, TPEX | Taiwan stocks |
| AMEX, NYSEARCA, PCX | ETFs and specialty securities |
| EGX | Egyptian exchange |

资料来源：[src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)

### 3. Indicators Service

The indicators service orchestrates calculation of 30+ technical indicators.

| Category | Indicators |
|----------|------------|
| Momentum | RSI, MACD, Stochastic, CCI, Williams %R |
| Trend | EMA, SMA, Supertrend, ADX |
| Volatility | Bollinger Bands, ATR, Standard Deviation |
| Volume | OBV, Volume Profile |

资料来源：[src/tradingview_mcp/core/services/indicators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/indicators.py)

### 4. Indicators Calculation Module

The `indicators_calc.py` module provides the underlying mathematical calculations for all technical indicators.

```python
# Example: RSI calculation pattern
def calculate_rsi(prices: List[float], period: int = 14) -> float:
    """Calculate Relative Strength Index"""
    # Implementation uses Wilder's smoothing method
    return rsi_value
```

资料来源：[src/tradingview_mcp/core/services/indicators_calc.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/indicators_calc.py)

### 5. Sentiment Service

The sentiment service analyzes social media sentiment from Reddit communities.

| Function | Purpose |
|----------|---------|
| Community Detection | Identifies relevant subreddits for symbols |
| Sentiment Scoring | Quantifies bullish/bearish community sentiment |
| Integration | Combines with technical analysis for confluence |

资料来源：[src/tradingview_mcp/core/services/sentiment_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/sentiment_service.py)

### 6. News Service

The news service aggregates financial news from RSS feeds for market sentiment and event analysis.

| Feed Type | Content |
|-----------|---------|
| Financial News | Market news, earnings reports |
| Sector News | Industry-specific developments |
| Macro News | Economic indicators and Fed communications |

资料来源：[src/tradingview_mcp/core/services/news_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/news_service.py)

### 7. Yahoo Finance Service

The Yahoo Finance service provides real-time price quotes and market data.

| Data Point | Description |
|------------|-------------|
| Price | Current and historical prices |
| Changes | Daily, weekly, yearly change percentages |
| 52-Week Range | High/low boundaries |
| Market State | Pre-market, regular, after-hours |

资料来源：[src/tradingview_mcp/core/services/yahoo_finance_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/yahoo_finance_service.py)

### 8. Scanner Service

The scanner service detects technical patterns and trading signals across markets.

| Pattern Type | Detection |
|--------------|-----------|
| Candlestick | 15 candlestick patterns (Doji, Hammer, Engulfing, etc.) |
| Technical | Bollinger Band breakouts, volume spikes |
| Signal-based | Oversold/overbought conditions, trend detection |

资料来源：[src/tradingview_mcp/core/services/scanner_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/scanner_service.py)

## Data Flow Architecture

### Request Processing Flow

```mermaid
sequenceDiagram
    participant Client as MCP Client
    participant Server as server.py
    participant Service as Service Layer
    participant External as External APIs
    
    Client->>Server: Tool Request
    Server->>Service: Delegate to Domain Service
    Service->>External: Fetch Data
    External-->>Service: Raw Data
    Service-->>Server: Processed Result
    Server-->>Client: MCP Response
```

### Multi-Timeframe Analysis Flow

The `multi_timeframe_analysis` function demonstrates cross-service integration:

```mermaid
graph LR
    A[Symbol Selection] --> B[Weekly Analysis]
    B --> C[Daily Analysis]
    C --> D[4H Analysis]
    D --> E[1H Analysis]
    E --> F[15m Analysis]
    F --> G[Confluence Decision]
    
    B --> H[indicators.py]
    C --> H
    D --> H
    E --> H
    F --> H
```

资料来源：[src/tradingview_mcp/server.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/server.py)

## Service Configuration

### Exchange Mappings

The system maintains exchange-to-screener mappings for routing:

```python
EXCHANGE_SCREENER = {
    "NASDAQ": "america",
    "NYSE": "america",
    "KUCOIN": "crypto",
    "BINANCE": "crypto",
    "EGX": "egypt",
    "TWSE": "crypto",  # Taiwan Stock Exchange
    "TPEX": "crypto",  # Taiwan OTC
    "AMEX": "america",
    "NYSEARCA": "america",
    "PCX": "america",
}
```

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

### Symbol List Management

Each exchange maintains a symbol list file for supported trading pairs:

```
coinlist/
├── binance.txt
├── kucoin.txt
├── mexc.txt
├── egx.txt
└── bybit.txt
```

## Integration Patterns

### Strategy Backtesting Integration

```mermaid
graph TD
    A[backtest_strategy] --> B[Load Historical Data]
    B --> C[Initialize Strategy]
    C --> D[Generate Signals]
    D --> E[Calculate Metrics]
    E --> F[Generate Trade Log]
    F --> G[Return Results]
    
    D --> H[indicators_calc.py]
    E --> I[Sharpe Ratio]
    E --> J[Max Drawdown]
    E --> K[Profit Factor]
```

### Confluence Analysis Pattern

The system combines multiple data sources for decision-making:

1. **Technical Analysis** → `indicators.py` + `indicators_calc.py`
2. **Sentiment Analysis** → `sentiment_service.py`
3. **News Analysis** → `news_service.py`
4. **Price Data** → `yahoo_finance_service.py`

资料来源：[openclaw/SKILL.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/openclaw/SKILL.md)

## Testing Architecture

### Unit Tests

Services are validated through dedicated unit test files:

| Test File | Coverage |
|-----------|----------|
| `tests/unit/test_exchange_fixes.py` | Exchange validation, symbol construction |
| `tests/unit/test_exchange_aliases.py` | Alias mappings, TWSE/TPEX handling |

### Integration Testing

The project includes integration tests for real market data:

```bash
uv run pytest
uv run ruff check
uv run mypy src/
```

资料来源：[CONTRIBUTING.md:30-38]()

## Summary

The service architecture of tradingview-mcp is designed around:

| Principle | Implementation |
|-----------|----------------|
| **Separation of Concerns** | Each service handles a single domain |
| **Reusability** | Shared `indicators_calc.py` for all indicator calculations |
| **Testability** | Independent services with clear interfaces |
| **Extensibility** | Easy to add new exchanges or indicators |
| **Composability** | Services combine for complex analyses like confluence |

This architecture enables the MCP server to expose 30+ tools while maintaining clean, maintainable code organized by functional responsibility.

---

<a id='mcp-tools-reference'></a>

## MCP Tools Reference

### 相关页面

相关主题：[Backtesting Engine](#backtesting-engine), [Sentiment Analysis](#sentiment-analysis), [Multi-Exchange Integration](#exchange-integrations)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [src/tradingview_mcp/server.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/server.py)
- [src/tradingview_mcp/core/types.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/types.py)
- [src/tradingview_mcp/core/services/indicators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/indicators.py)
- [src/tradingview_mcp/core/services/indicators_calc.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/indicators_calc.py)
- [src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)
- [src/tradingview_mcp/core/services/yahoo_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/yahoo_service.py)
</details>

# MCP Tools Reference

## Overview

The MCP Tools Reference documents all available Model Context Protocol (MCP) tools exposed by the TradingView MCP Server. These tools enable AI assistants like Claude Desktop, Codex, and OpenClaw to perform real-time market data retrieval, technical analysis, and trading signal generation through a standardized tool-calling interface.

The tradingview-mcp server acts as a bridge between AI agents and TradingView's market data infrastructure, providing programmatic access to cryptocurrency, stock, and forex market information across multiple exchanges worldwide.

**资料来源：** [README.md](README.md)

---

## Architecture Overview

### System Components

```mermaid
graph TD
    subgraph "AI Agent Layer"
        A[Claude Desktop / Codex / OpenClaw]
    end
    
    subgraph "MCP Protocol Layer"
        B[MCP Server<br/>tradingview-mcp]
        C[Tool Registry]
    end
    
    subgraph "Data Source Layer"
        D[TradingView Screener API]
        E[Yahoo Finance API]
        F[Exchange APIs<br/>Binance, KuCoin, NASDAQ...]
    end
    
    A -->|MCP Protocol| B
    B --> C
    C -->|Market Data| D
    C -->|Real-time Prices| E
    C -->|Bulk Queries| F
    
    style B fill:#4a90d9
    style C fill:#5ba85b
```

### Tool Categories

| Category | Description | Number of Tools |
|----------|-------------|-----------------|
| **Market Data** | Real-time prices and snapshots | 5+ |
| **Technical Analysis** | Indicators, patterns, decisions | 8+ |
| **Screening** | Top gainers/losers, custom filters | 10+ |
| **Backtesting** | Strategy comparison and metrics | 2 |
| **Multi-Exchange** | Cross-exchange analysis | 6+ |

**资料来源：** [README.md](README.md)

---

## Core Tool Types

### Tool Definition Schema

All MCP tools follow a standardized type definition structure defined in `core/types.py`:

```python
@dataclass
class ToolDefinition:
    name: str
    description: str
    input_schema: dict
    handler: Callable
```

**资料来源：** [src/tradingview_mcp/core/types.py](src/tradingview_mcp/core/types.py)

---

## Market Data Tools

### yahoo_price

Retrieves real-time quote data for a single symbol including price, change percentage, 52-week range, and market state.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `symbol` | string | Yes | - | Ticker symbol (e.g., BTC-USD, AAPL) |
| `exchange` | string | No | auto-detect | Exchange prefix (optional override) |

**Returns:**
```json
{
  "symbol": "BTC-USD",
  "price": 67432.50,
  "change_percent": 2.34,
  "52w_high": 73000.00,
  "52w_low": 52000.00,
  "market_state": "REGULAR"
}
```

**资料来源：** [src/tradingview_mcp/core/services/yahoo_service.py](src/tradingview_mcp/core/services/yahoo_service.py)

---

### market_snapshot

Provides a global market overview combining multiple asset classes in a single response.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `include_crypto` | boolean | No | true |
| `include_indices` | boolean | No | true |
| `include_forex` | boolean | No | true |

**Coverage:**
- **Crypto:** BTC-USD, ETH-USD, SOL-USD, etc.
- **Indices:** S&P 500, NASDAQ, DOW
- **Forex:** EUR/USD, GBP/USD, USD/JPY

**资料来源：** [src/tradingview_mcp/core/services/yahoo_service.py](src/tradingview_mcp/core/services/yahoo_service.py)

---

### get_prices_bulk

Retrieves price data for multiple symbols in a single call.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `symbols` | string[] | Yes | - | Array of ticker symbols |
| `exchange` | string | No | auto-detect | Exchange prefix |

**资料来源：** [server.py:server.py](src/tradingview_mcp/server.py)

---

## Technical Analysis Tools

### get_technical_analysis

Executes comprehensive technical analysis with 23+ indicators, returning BUY/SELL/HOLD signals with confluence scoring.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `symbol` | string | Yes | - | Ticker symbol |
| `exchange` | string | No | KUCOIN | Exchange identifier |
| `timeframe` | string | No | 1D | Time interval (1m, 5m, 15m, 1h, 4h, 1D, 1W) |
| `indicators` | string[] | No | all | Specific indicators to calculate |

**Included Indicators:**

| Indicator | Type | Signal Logic |
|-----------|------|--------------|
| RSI (14) | Momentum | Oversold <30, Overbought >70 |
| MACD | Trend | Signal line crossover |
| Bollinger Bands | Volatility | Price near bands |
| EMA Cross | Trend | 20/50 period crossover |
| Supertrend | Trend | ATR-based reversal |
| ATR | Volatility | Raw volatility measure |
| ADX | Trend Strength | >25 indicates strong trend |

**资料来源：** [src/tradingview_mcp/core/services/indicators.py](src/tradingview_mcp/core/services/indicators.py)

---

### get_bollinger_band_analysis

Proprietary Bollinger Band analysis with ±3 rating system for volatility and position assessment.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `symbol` | string | Yes | - |
| `exchange` | string | No | KUCOIN |
| `timeframe` | string | No | 1D |

**Response Structure:**
```python
{
    "bandwidth": 0.0342,
    "position": "upper_50_percent",
    "signal": "BUY",
    "rating": 2  # -3 to +3 scale
}
```

**Bandwidth Calculation:**
```
BBW = (Upper Band - Lower Band) / Middle Band
```

**资料来源：** [src/tradingview_mcp/core/services/indicators.py](src/tradingview_mcp/core/services/indicators.py), [CONTRIBUTING.md](CONTRIBUTING.md)

---

### get_multiple_analysis

Runs technical analysis on multiple symbols simultaneously.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `symbols` | string[] | Yes | - |
| `exchange` | string | No | KUCOIN |
| `timeframe` | string | No | 1D |

**资料来源：** [server.py](src/tradingview_mcp/server.py)

---

### get_stock_decision

Three-layer decision engine combining ranking, trade setup, and quality scoring.

**Layers:**
1. **Ranking Score** - Relative strength vs market
2. **Trade Setup** - Entry/exit signal alignment
3. **Quality Score** - Overall confidence rating

**资料来源：** [README.md](README.md)

---

### get_candlestick_patterns

Detects 15+ candlestick patterns in historical price data.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `symbol` | string | Yes | - |
| `exchange` | string | No | KUCOIN |
| `timeframe` | string | No | 1D |
| `pattern_type` | string | No | all |

**Supported Patterns:**
- Doji, Hammer, Engulfing, Morning Star
- Harami, Shooting Star, Three White Soldiers
- Dark Cloud Cover, Piercing Line

**资料来源：** [server.py](src/tradingview_mcp/server.py)

---

### get_multi_timeframe_analysis

Analyzes the same symbol across multiple timeframes to identify aligned trends.

**Timeframe Alignment:**

```mermaid
graph LR
    W[Weekly] --> D[Daily]
    D --> H4[4H]
    H4 --> H1[1H]
    H1 --> M15[15m]
    
    style W fill:#4a90d9
    style M15 fill:#d94a4a
```

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `symbol` | string | Yes | - |
| `exchange` | string | No | KUCOIN |
| `timeframes` | string[] | No | [1D, 4H, 1H, 15m] |

**资料来源：** [PR_BODY.md](PR_BODY.md), [README.md](README.md)

---

## Screening Tools

### top_gainers

Screens for top-performing assets by percentage gain on a specific exchange.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `exchange` | string | No | KUCOIN | Exchange identifier |
| `timeframe` | string | No | 1D | Time interval |
| `limit` | integer | No | 10 | Number of results (max 50) |

**Supported Exchanges:**
- **Crypto:** KUCOIN, BINANCE, BYBIT
- **US Markets:** NASDAQ, NYSE
- **Regional:** BIST, EGX, TWSE, TPEX

**资料来源：** [src/tradingview_mcp/core/services/screener_service.py](src/tradingview_mcp/core/services/screener_service.py)

---

### top_losers

Screens for worst-performing assets by percentage decline.

**Parameters:** Identical to `top_gainers`

**资料来源：** [server.py](src/tradingview_mcp/server.py)

---

### scan_by_signal

Scans markets filtered by predefined signal types.

**Signal Types:**

| Signal | Description |
|--------|-------------|
| `oversold` | RSI below 30 |
| `overbought` | RSI above 70 |
| `trending_up` | Strong upward momentum |
| `trending_down` | Strong downward momentum |
| `breakout` | Price breaking resistance |
| `breakdown` | Price breaking support |

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `signal_type` | string | Yes | - |
| `exchange` | string | No | KUCOIN |
| `timeframe` | string | No | 1D |
| `limit` | integer | No | 20 |

**资料来源：** [server.py](src/tradingview_mcp/server.py)

---

### bollinger_scan

Scans for Bollinger Band squeeze patterns indicating potential volatility expansion.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `exchange` | string | No | KUCOIN |
| `timeframe` | string | No | 1D |
| `bbw_threshold` | float | No | 0.05 | Bandwidth threshold for squeeze detection |
| `limit` | integer | No | 20 |

**Squeeze Detection Logic:**
```python
# Squeeze detected when bandwidth < threshold
if bandwidth < bbw_threshold:
    return "SQZ"  # Potential breakout setup
```

**资料来源：** [EXAMPLES.md](EXAMPLES.md)

---

### consecutive_candles_scan

Detects coins with consecutive bullish or bearish candles indicating sustained momentum.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `pattern_type` | string | No | bullish | bullish or bearish |
| `timeframe` | string | No | 1h | Time interval |
| `min_count` | integer | No | 3 | Minimum consecutive candles |
| `exchange` | string | No | KUCOIN |

**Example Response:**
```
SOLUSDT - 4 consecutive green candles (1h)
Total gain: +8.4%
Volume increasing
```

**资料来源：** [EXAMPLES.md](EXAMPLES.md)

---

### screen_stocks

Multi-criteria stock screener with 20+ filter parameters.

**Filter Categories:**

| Category | Filters |
|----------|---------|
| **Price** | price_min, price_max |
| **Volume** | volume_min, volume_max |
| **Technical** | rsi_above, rsi_below, sma_50_above, sma_200_below |
| **Fundamentals** | market_cap_min, market_cap_max |
| **Performance** | change_above, change_below |

**资料来源：** [README.md](README.md)

---

## Backtesting Tools

### backtest_strategy

Runs historical backtest for a single trading strategy with institutional-grade metrics.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `symbol` | string | Yes | - |
| `strategy` | string | Yes | - | Strategy name |
| `period` | string | No | 1Y | Backtest period |
| `initial_capital` | float | No | 10000 | Starting capital |
| `commission` | float | No | 0.1 | Commission percentage |

**Available Strategies:**

| Strategy | Logic | Best For |
|----------|-------|----------|
| `rsi` | RSI oversold/overbought mean reversion | Range-bound markets |
| `bollinger` | Bollinger Band bounce | Volatile markets |
| `macd` | MACD golden/death cross | Trend changes |
| `ema_cross` | EMA 20/50 crossover | Medium-term trends |
| `supertrend` | ATR-based trend following | Strong trends |
| `donchian` | Donchian Channel breakout | Momentum plays |

**Metrics Returned:**

| Metric | Description |
|--------|-------------|
| Win Rate | Percentage of profitable trades |
| Total Return | Overall percentage gain/loss |
| Sharpe Ratio | Risk-adjusted return |
| Calmar Ratio | Return / Max drawdown |
| Max Drawdown | Largest peak-to-trough decline |
| Profit Factor | Gross profit / Gross loss |
| Expectancy | Average expected return per trade |

**资料来源：** [README.md](README.md)

---

### compare_strategies

Runs all 6 strategies on the same symbol and ranks by performance.

**Parameters:**

| Parameter | Type | Required | Default |
|-----------|------|----------|---------|
| `symbol` | string | Yes | - |
| `period` | string | No | 1Y | Backtest period |
| `limit` | integer | No | 10 | Number of top strategies to return |

**Output Format:**
```
#1 Supertrend: +31.5% | Sharpe: 2.1 | WR: 62%
#2 Bollinger:  +18.3% | Sharpe: 3.4 | WR: 75%
#3 Buy & Hold: -5.0%
```

**资料来源：** [README.md](README.md)

---

## Exchange-Specific Tools

### Exchange Support Matrix

| Exchange | Region | Screener | Price Data | Specific Tools |
|----------|--------|----------|------------|----------------|
| KUCOIN | Global Crypto | ✅ | ✅ | All tools |
| BINANCE | Global Crypto | ✅ | ✅ | All tools |
| BYBIT | Global Crypto | ✅ | ✅ | All tools |
| NASDAQ | US Stocks | ✅ | ✅ | All tools |
| NYSE | US Stocks | ✅ | ✅ | All tools |
| BIST | Turkey | ✅ | ✅ | All tools |
| EGX | Egypt | ✅ | ✅ | egx_* tools |
| TWSE | Taiwan | ✅ | ✅ | - |
| TPEX | Taiwan | ✅ | ✅ | - |

### Symbol Construction

TradingView requires properly formatted exchange-prefixed symbols:

```
{EXCHANGE}:{SYMBOL}
Examples:
- KUCOIN:SOLUSDT
- BINANCE:BTCUSDT
- NASDAQ:AAPL
```

**资料来源：** [src/tradingview_mcp/core/services/screener_service.py](src/tradingview_mcp/core/services/screener_service.py), [PR_BODY.md](PR_BODY.md)

---

## Tool Registration Flow

```mermaid
sequenceDiagram
    participant Server as MCP Server
    participant Registry as Tool Registry
    participant Handler as Tool Handler
    
    Server->>Registry: register_tools()
    Registry->>Handler: Instantiate tool class
    Handler->>Registry: Register name, schema, callback
    
    Note over Registry: All tools registered at startup
    
    Client->>Server: list_tools()
    Server->>Registry: get_all_tools()
    Registry-->>Client: Tool definitions
    
    Client->>Server: call_tool(name, params)
    Server->>Handler: execute(params)
    Handler-->>Server: Tool result
    Server-->>Client: JSON-RPC response
```

**资料来源：** [src/tradingview_mcp/server.py](src/tradingview_mcp/server.py)

---

## Response Format Standards

### Success Response

```json
{
  "result": {
    "status": "success",
    "data": { ... },
    "metadata": {
      "timestamp": "2024-01-15T10:30:00Z",
      "source": "tradingview-screener",
      "latency_ms": 245
    }
  }
}
```

### Error Response

```json
{
  "error": {
    "code": "EXCHANGE_NOT_FOUND",
    "message": "Exchange 'INVALID' is not supported",
    "details": {
      "supported": ["KUCOIN", "BINANCE", "NASDAQ", "NYSE"]
    }
  }
}
```

---

## Usage Examples

### Basic Market Query

```
You: "Show me top 5 crypto gainers on KuCoin in 15 minutes"

AI: [Uses: top_gainers(exchange="KUCOIN", timeframe="15", limit=5)]

🇰🇪 KuCoin Top Gainers (15m):

1. **SOLUSDT** - $142.50 (+5.2%)
2. **AVAXUSDT** - $34.20 (+4.1%)
3. **MATICUSDT** - $0.82 (+3.8%)
4. **LINKUSDT** - $14.50 (+3.2%)
5. **DOTUSDT** - $6.80 (+2.9%)
```

### Technical Analysis Request

```
You: "Analyze Bitcoin with all technical indicators"

AI: [Uses: get_technical_analysis(symbol="BTC", exchange="BINANCE")]

📊 BTC-USD Technical Analysis:

RSI (14): 58.4 → NEUTRAL
MACD: BULLISH CROSSOVER
Bollinger Bands: UPPER_50_PERCENT
ADX: 32.5 → STRONG TREND

Overall Signal: BUY (Confluence Score: 7/10)
```

### Strategy Comparison

```
You: "Compare all strategies on BTC-USD for 2 years"

AI: [Uses: compare_strategies(symbol="BTC", period="2Y")]

📈 Strategy Comparison Results:

#1 Supertrend: +31.5% | Sharpe: 2.1 | WR: 62%
#2 Bollinger:  +18.3% | Sharpe: 3.4 | WR: 75%
#3 MACD:       +12.1% | Sharpe: 1.8 | WR: 55%
#4 EMA Cross:  +8.4%  | Sharpe: 1.2 | WR: 52%
#5 RSI:        -2.1%  | Sharpe: -0.3 | WR: 45%
#6 Donchian:   -8.5%  | Sharpe: -1.1 | WR: 38%

Buy & Hold: -5.0%
```

**资料来源：** [EXAMPLES.md](EXAMPLES.md), [README.md](README.md)

---

## Configuration

### MCP Server Configuration

```json
{
  "mcpServers": {
    "tradingview-mcp": {
      "command": "uv",
      "args": [
        "tool",
        "run",
        "--from",
        "git+https://github.com/atilaahmettaner/tradingview-mcp.git",
        "tradingview-mcp"
      ]
    }
  }
}
```

### Local Development Configuration

```json
{
  "mcpServers": {
    "tradingview-mcp-local": {
      "command": "uv",
      "args": ["run", "python", "src/tradingview_mcp/server.py"],
      "cwd": "/path/to/tradingview-mcp"
    }
  }
}
```

**资料来源：** [INSTALLATION.md](INSTALLATION.md)

---

## See Also

- [Installation Guide](INSTALLATION.md) - Setup instructions for MCP clients
- [Contributing Guide](CONTRIBUTING.md) - Development standards and testing
- [OpenClaw Integration](OPENCLAW.md) - Telegram/WhatsApp bot setup
- [Examples](EXAMPLES.md) - Real-world usage scenarios

---

<a id='backtesting-engine'></a>

## Backtesting Engine

### 相关页面

相关主题：[MCP Tools Reference](#mcp-tools-reference), [Service Architecture](#service-architecture)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [src/tradingview_mcp/core/services/backtest_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/backtest_service.py)
- [src/tradingview_mcp/server.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/server.py)
- [CHANGELOG.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CHANGELOG.md)
- [CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)
- [README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)
</details>

# Backtesting Engine

The Backtesting Engine is a core component of the `tradingview-mcp` project that provides automated strategy testing capabilities using historical market data. It enables traders and developers to validate trading strategies against real price data before deploying them in live markets.

## Overview

The Backtesting Engine (v3, v0.7.0) is a pure Python implementation that requires no external backtesting libraries such as pandas or numpy. It fetches historical OHLCV (Open, High, Low, Close, Volume) data from Yahoo Finance and simulates trading strategies with realistic commission and slippage modeling.

**Key Characteristics:**

- Pure Python implementation with no pandas/numpy dependencies
- 6 built-in trading strategies
- Supports daily (1d) and hourly (1h) timeframes
- Walk-forward analysis for overfitting detection
- Full trade logging with detailed per-trade breakdowns
- Equity curve generation for performance visualization

资料来源：[backtest_service.py:1-20]()

## Architecture

The Backtesting Engine follows a layered architecture with clear separation of concerns:

```mermaid
graph TD
    subgraph "MCP Tool Layer"
        A["backtest_strategy"]
        B["compare_strategies"]
        C["walk_forward_backtest_strategy"]
    end
    
    subgraph "Service Layer"
        D["backtest_service.py"]
        E["indicators_calc.py"]
    end
    
    subgraph "Data Layer"
        F["Yahoo Finance API"]
    end
    
    A --> D
    B --> D
    C --> D
    D --> E
    D --> F
    E --> F
```

### Component Responsibilities

| Component | File | Responsibility |
|-----------|------|----------------|
| MCP Tool Layer | `server.py` | Exposes backtesting as MCP tools |
| Service Layer | `backtest_service.py` | Core backtesting logic, trade simulation |
| Indicators | `indicators_calc.py` | Technical indicator calculations |
| External Data | Yahoo Finance API | OHLCV price data retrieval |

资料来源：[server.py]() [backtest_service.py:1-50]()

## Supported Strategies

The Backtesting Engine includes 6 pre-built trading strategies:

| Strategy | Type | Description |
|----------|------|-------------|
| `rsi` | Mean Reversion | RSI oversold (<30) / overbought (>70) signals |
| `bollinger` | Mean Reversion | Bollinger Band bounce trading |
| `macd` | Momentum | MACD golden/death cross signals |
| `ema_cross` | Trend Following | EMA 20/50 Golden/Death Cross |
| `supertrend` | Trend Following | ATR-based Supertrend (🔥 most popular) |
| `donchian` | Breakout | Donchian Channel breakout (Turtle Trader style) |

资料来源：[backtest_service.py:15-22]()

### Strategy Selection Flow

```mermaid
graph TD
    A["Start Backtest"] --> B{"Strategy Valid?"}
    B -->|No| E["Return Error: Unknown strategy"]
    B -->|Yes| F["Fetch OHLCV Data"]
    F --> G{"Sufficient Data?"}
    G -->|No| H["Return Error: Not enough data"]
    G -->|Yes| I["Execute Strategy Logic"]
    I --> J["Calculate Metrics"]
    J --> K["Return Results"]
```

资料来源：[backtest_service.py:100-140]()

## MCP Tool Functions

The Backtesting Engine exposes three primary MCP tools through the server interface.

### 1. backtest_strategy

Executes a single strategy backtest on a given symbol.

**Function Signature:**
```python
@mcp.tool()
def backtest_strategy(
    symbol: str,
    strategy: str,
    period: str = "1y",
    initial_capital: float = 10000.0,
    commission_pct: float = 0.1,
    slippage_pct: float = 0.05,
    interval: str = "1d",
    include_trade_log: bool = False,
    include_equity_curve: bool = False,
) -> dict
```

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `symbol` | str | Required | Yahoo Finance symbol (AAPL, BTC-USD, SPY...) |
| `strategy` | str | Required | rsi, bollinger, macd, ema_cross, supertrend, donchian |
| `period` | str | "1y" | 1mo, 3mo, 6mo, 1y, 2y |
| `initial_capital` | float | 10000.0 | Starting capital in USD |
| `commission_pct` | float | 0.1 | Per-trade commission % |
| `slippage_pct` | float | 0.05 | Per-trade slippage % |
| `interval` | str | "1d" | 1d (daily) or 1h (hourly) |
| `include_trade_log` | bool | False | Include detailed trade log |
| `include_equity_curve` | bool | False | Include equity curve data points |

资料来源：[server.py]()

### 2. compare_strategies

Runs all 6 strategies on the same symbol and ranks by performance.

**Function Signature:**
```python
@mcp.tool()
def compare_strategies(
    symbol: str,
    period: str = "1y",
    initial_capital: float = 10000.0,
    interval: str = "1d",
) -> dict
```

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `symbol` | str | Required | Yahoo Finance symbol |
| `period` | str | "1y" | 1mo, 3mo, 6mo, 1y, 2y |
| `initial_capital` | float | 10000.0 | Starting capital in USD |
| `interval` | str | "1d" | 1d (daily) or 1h (hourly) |

资料来源：[server.py]()

### 3. walk_forward_backtest_strategy

Walk-forward backtesting to detect strategy overfitting.

**Function Signature:**
```python
@mcp.tool()
def walk_forward_backtest_strategy(
    symbol: str,
    strategy: str,
    period: str = "2y",
    initial_capital: float = 10000.0,
    commission_pct: float = 0.1,
    slippage_pct: float = 0.05,
    n_splits: int = 3,
    train_ratio: float = 0.7,
    interval: str = "1d",
) -> dict
```

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `symbol` | str | Required | Yahoo Finance symbol |
| `strategy` | str | Required | rsi, bollinger, macd, ema_cross, supertrend, donchian |
| `period` | str | "2y" | Recommended: 2y for walk-forward |
| `n_splits` | int | 3 | Number of walk-forward folds (2-10) |
| `train_ratio` | float | 0.7 | Fraction used for training |

资料来源：[server.py]()

## Walk-Forward Analysis

Walk-forward analysis is a robust method for detecting strategy overfitting. It splits historical data into multiple train/test folds to validate strategy performance on unseen data.

### Methodology

```mermaid
graph LR
    subgraph "Fold 1"
        A1["Train 70%"] --> B1["Test 30%"]
    end
    subgraph "Fold 2"
        A2["Train 70%"] --> B2["Test 30%"]
    end
    subgraph "Fold 3"
        A3["Train 70%"] --> B3["Test 30%"]
    end
```

### Robustness Scoring

| Score | Classification | Interpretation |
|-------|----------------|-----------------|
| ≥ 0.8 | ROBUST | No overfitting detected |
| ≥ 0.5 | MODERATE | Some degradation expected |
| ≥ 0.2 | WEAK | Likely overfitted |
| < 0.2 | OVERFITTED | Do not trade live |

The robustness score is calculated as: `test_return / train_return`

资料来源：[backtest_service.py:180-220]()

## Return Metrics

The backtesting engine calculates comprehensive performance metrics:

### Core Metrics

| Metric | Description |
|--------|-------------|
| Total Return % | Overall strategy return |
| Sharpe Ratio | Risk-adjusted return (annualized) |
| Calmar Ratio | Return / Maximum Drawdown |
| Max Drawdown % | Largest peak-to-trough decline |
| Win Rate % | Percentage of profitable trades |
| Profit Factor | Gross profit / Gross loss |
| Expectancy | Average trade return including losses |
| Best Trade % | Best single trade return |
| Worst Trade % | Worst single trade return |

### Interval-Aware Annualization

Sharpe ratio annualization adjusts based on timeframe:

| Interval | Annualization Factor |
|----------|---------------------|
| 1d | 252 (trading days/year) |
| 1h | 252 × 6 (trading hours/year) |

资料来源：[backtest_service.py:30-32]()

## Data Fetching

The engine retrieves OHLCV data from Yahoo Finance:

**API Endpoint:**
```
https://query1.finance.yahoo.com/v8/finance/chart/{symbol}
```

**User Agent:**
```
tradingview-mcp/0.7.0 backtest-bot
```

**Validation Rules:**

| Interval | Minimum Bars Required |
|----------|----------------------|
| 1d | 30 bars |
| 1h | 100 bars |

资料来源：[backtest_service.py:24-29]()

## Trade Simulation

The trade simulation includes realistic trading costs:

### Cost Components

| Component | Default | Description |
|-----------|---------|-------------|
| Commission | 0.1% | Per-trade commission |
| Slippage | 0.05% | Per-trade price slippage |

### Trade Log Fields

When `include_trade_log=True`, each trade includes:

| Field | Description |
|-------|-------------|
| `entry_date` | Trade entry timestamp |
| `exit_date` | Trade exit timestamp |
| `entry_price` | Entry price |
| `exit_price` | Exit price |
| `holding_days` | Days held |
| `gross_return_pct` | Gross return before costs |
| `net_return_pct` | Net return after costs |
| `cost_pct` | Total costs (commission + slippage) |
| `capital_at_entry` | Capital at entry |
| `capital_after_trade` | Capital after trade |
| `cumulative_return` | Cumulative return at this point |

### Equity Curve

When `include_equity_curve=True`, returns data points at each trade exit:

```python
{
    "equity_curve": [
        {"date": "2023-01-15", "capital": 10500.00, "drawdown_pct": 0.0},
        {"date": "2023-02-20", "capital": 10200.00, "drawdown_pct": -2.86},
        ...
    ]
}
```

资料来源：[backtest_service.py:140-180]()

## Usage Examples

### Basic Backtest
```
You: "Backtest RSI strategy for AAPL over 1 year"
→ backtest_strategy(symbol="AAPL", strategy="rsi", period="1y")
```

### Strategy Comparison
```
You: "Compare all strategies on BTC-USD for 2 years"
→ compare_strategies(symbol="BTC-USD", period="2y")

Output:
→ #1 Supertrend: +31.5% | Sharpe: 2.1 | WR: 62%
→ #2 Bollinger:  +18.3% | Sharpe: 3.4 | WR: 75%
→ Buy & Hold:    -5.0%
```

### Walk-Forward Analysis
```
You: "Is the RSI strategy overfitted for AAPL?"
→ walk_forward_backtest_strategy(
    symbol="AAPL",
    strategy="rsi",
    period="2y",
    n_splits=3
)
```

### Full Trade Log
```
You: "Show me the full trade log for the backtest"
→ backtest_strategy(
    symbol="AAPL",
    strategy="supertrend",
    period="1y",
    include_trade_log=True
)
```

资料来源：[README.md]()

## Version History

| Version | Date | Key Changes |
|---------|------|-------------|
| v0.7.0 | Latest | 1h timeframe, full trade log, equity curve, walk-forward |
| v0.6.0 | 2026-03-29 | Initial backtesting engine with 6 strategies |

资料来源：[CHANGELOG.md]()

## Error Handling

| Error Condition | Response |
|-----------------|----------|
| Unknown strategy | `{"error": "Unknown strategy 'X'. Choose: rsi, bollinger..."}` |
| Invalid period | `{"error": "Invalid period 'X'. Choose: 1mo, 3mo, 6mo, 1y, 2y"}` |
| Invalid interval | `{"error": "Invalid interval 'X'. Choose: 1d or 1h"}` |
| Data fetch failure | `{"error": "Failed to fetch data for 'X': {exception}"}` |
| Insufficient data | `{"error": "Not enough data (N bars). Try a longer period."}` |

资料来源：[backtest_service.py:100-150]()

## Disclaimer

⚠️ **Important:** Past performance does not guarantee future results. Backtested results include hypothetical trades that may not reflect actual market conditions including liquidity constraints, emotional decision-making, and execution delays.

---

<a id='sentiment-analysis'></a>

## Sentiment Analysis

### 相关页面

相关主题：[MCP Tools Reference](#mcp-tools-reference), [Service Architecture](#service-architecture)

<details>
<summary>Related Source Files</summary>

以下源码文件用于生成本页说明：

- [src/tradingview_mcp/core/services/sentiment_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/sentiment_service.py)
- [src/tradingview_mcp/core/services/news_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/multi_agent_service.py)
- [src/tradingview_mcp/core/services/multi_agent_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/multi_agent_service.py)
- [src/tradingview_mcp/server.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/server.py)
- [openclaw/trading.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/openclaw/trading.py)
- [src/tradingview_mcp/core/data/egx_sectors.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/data/egx_sectors.py)
</details>

# Sentiment Analysis

The Sentiment Analysis module is a core component of the tradingview-mcp framework that aggregates social media sentiment data—primarily from Reddit—and converts it into actionable trading signals. This module works in conjunction with technical analysis and news feeds to provide a multi-signal confluence system that helps traders understand market mood and community consensus around specific assets.

## Overview

The sentiment analysis system is designed to:

- Fetch posts from Reddit across multiple subreddit categories
- Score text content using a custom sentiment scoring algorithm
- Categorize sentiment into actionable labels (Bullish, Bearish, Neutral)
- Integrate with the broader multi-agent trading framework
- Provide confidence scoring when combined with technical indicators

The module operates as part of a three-layer analytical system that includes:

1. **Technical Analyst** — Bollinger Bands, RSI, MACD
2. **Sentiment & Momentum Analyst** — Reddit community sentiment + price momentum
3. **Risk Manager** — Volatility, drawdown risk, mean-reversion signals

资料来源：[README.md:1-50]()

## Architecture

The sentiment analysis system follows a layered architecture:

```mermaid
graph TD
    A[analyze_sentiment API] --> B[Category Selection]
    B --> C[Subreddit Groups]
    C --> D[Per-Subreddit Fetch]
    D --> E[_fetch_reddit_posts]
    E --> F[Text Extraction]
    F --> G[_score_text]
    G --> H[Score Aggregation]
    H --> I[Result Construction]
    I --> J[Sentiment Label + Breakdown]
```

### Component Structure

| Component | File | Responsibility |
|-----------|------|----------------|
| `analyze_sentiment` | `sentiment_service.py` | Main public API entry point |
| `_fetch_reddit_posts` | `sentiment_service.py` | Reddit API integration |
| `_score_text` | `sentiment_service.py` | Sentiment scoring algorithm |
| `analyze_confluence` | `server.py` | Combined technical + sentiment analysis |
| `multi_agent_analysis` | `multi_agent_service.py` | Multi-agent trading decision system |

资料来源：[src/tradingview_mcp/core/services/sentiment_service.py:1-100]()

## Subreddit Configuration

The system uses a predefined configuration of subreddit groups organized by market category:

### SUBREDDIT_GROUPS Structure

| Category | Subreddits | Target Markets |
|----------|------------|----------------|
| `crypto` | r/CryptoCurrency, r/Bitcoin, r/ethereum, r/CryptocurrencyMarket, r/SatoshiStreetBets | Cryptocurrency |
| `stocks` | r/wallstreetbets, r/stocks, r/investing, r/StockMarket | US Equities |
| `all` | Combined crypto + stocks subreddits | Multi-asset |

资料来源：[src/tradingview_mcp/core/services/sentiment_service.py:1-50]()

## API Reference

### `analyze_sentiment`

The primary function for retrieving and analyzing Reddit sentiment.

```python
def analyze_sentiment(
    symbol: str,
    category: str = "all",
    limit: int = 20,
) -> dict:
```

#### Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `symbol` | `str` | Required | Asset ticker/name (e.g., "AAPL", "BTC", "ETH", "TSLA", "THYAO") |
| `category` | `str` | `"all"` | Subreddit group: `"crypto"` \| `"stocks"` \| `"all"` |
| `limit` | `int` | `20` | Total number of posts to analyze across all subreddits |

#### Return Value

```python
{
    "sentiment_score": float,      # -1.0 to +1.0
    "sentiment_label": str,        # "Bullish" | "Bearish" | "Neutral"
    "posts_analyzed": int,         # Total posts processed
    "posts": List[dict],           # Individual post details
    "top_posts": List[dict],       # Highest-impact posts
}
```

#### Post Object Structure

| Field | Type | Description |
|-------|------|-------------|
| `title` | `str` | Post title (truncated to 120 chars) |
| `upvotes` | `int` | Reddit upvotes |
| `comments` | `int` | Number of comments |
| `sentiment` | `str` | Per-post sentiment label |

资料来源：[src/tradingview_mcp/core/services/sentiment_service.py:50-100]()

## Sentiment Scoring Algorithm

### Scoring Logic

The `_score_text` function processes raw text and returns a score:

```mermaid
graph LR
    A[Raw Text Input] --> B[Tokenize]
    B --> C[Keyword Matching]
    C --> D{Keyword Type}
    D -->|Bullish| E[Positive Increment]
    D -->|Bearish| F[Negative Increment]
    D -->|Neutral| G[Zero Score]
    E --> H[Normalize to -1...+1]
    F --> H
    G --> H
```

### Scoring Thresholds

| Score Range | Label | Description |
|-------------|-------|-------------|
| `> 0.15` | **Bullish** | Strong positive community sentiment |
| `0.05 to 0.15` | **Slightly Bullish** | Mild positive sentiment |
| `-0.05 to 0.05` | **Neutral** | Balanced or unclear sentiment |
| `-0.15 to -0.05` | **Slightly Bearish** | Mild negative sentiment |
| `< -0.15` | **Bearish** | Strong negative community sentiment |

资料来源：[src/tradingview_mcp/core/services/sentiment_service.py:30-50]()

## Multi-Agent Integration

The sentiment analysis module is a critical component of the multi-agent trading framework:

```mermaid
graph TD
    subgraph "Multi-Agent System"
        A[Technical Analyst] --> D[Debate & Score]
        B[Sentiment Analyst] --> D
        C[Risk Manager] --> D
    end
    
    subgraph "Sentiment Analyst (B)"
        B1[analyze_sentiment] --> B2[Momentum Calculation]
        B2 --> B3[Sentiment Score]
        B3 --> B4[Bullish/Bearish Label]
    end
    
    D --> E[Framework Decision]
    E --> F[STRONG BUY / BUY / HOLD / SELL / STRONG SELL]
```

### Multi-Agent Output

The framework combines signals from all three agents to produce:

| Output | Description |
|--------|-------------|
| `decision` | Final trading recommendation |
| `confidence` | Confidence level based on agent agreement |
| `scores` | Individual agent scores |
| `reasoning` | Brief explanation of the decision |

资料来源：[src/tradingview_mcp/core/services/multi_agent_service.py]()

## Confluence System

The confluence system combines technical analysis with sentiment to provide higher-confidence signals:

### Signal Agreement Matrix

| Technical Signal | Sentiment Signal | Confluence | Confidence |
|------------------|------------------|------------|------------|
| Bullish | Bullish | Technical confirmed by Sentiment | HIGH |
| Bearish | Bearish | Technical confirmed by Sentiment | HIGH |
| Bullish | Bearish | Technical conflicts with Sentiment | MIXED |
| Bearish | Bullish | Technical conflicts with Sentiment | MIXED |

资料来源：[src/tradingview_mcp/server.py:1-50]()

### Implementation

```python
def analyze_confluence(symbol, exchange, timeframe):
    tech = get_technical_analysis(symbol, exchange, timeframe)
    cat = "crypto" if exchange.upper() in ["BINANCE", "KUCOIN", "BYBIT", "MEXC"] else "stocks"
    sentiment = analyze_sentiment(symbol, category=cat)
    
    tech_momentum = tech.get("market_sentiment", {}).get("momentum", "")
    tech_bullish = tech_momentum == "Bullish"
    sent_bullish = sentiment.get("sentiment_score", 0) > 0.1
    signals_agree = tech_bullish == sent_bullish
    confidence = "HIGH" if signals_agree else "MIXED"
```

资料来源：[src/tradingview_mcp/server.py:50-100]()

## Exchange-Specific Behavior

The sentiment analysis module adapts its subreddit selection based on the target exchange:

| Exchange Category | Exchange Examples | Sentiment Category | Subreddits Used |
|-------------------|-------------------|-------------------|-----------------|
| Crypto | BINANCE, KUCOIN, BYBIT, MEXC | `crypto` | Bitcoin, ethereum, CryptoCurrency, etc. |
| Stocks | NASDAQ, NYSE | `stocks` | wallstreetbets, stocks, investing |
| Emerging Markets | EGX, BIST | Auto-detected | Appropriate regional subreddits |

资料来源：[src/tradingview_mcp/core/services/egx_sectors.py]()

## OpenClaw Integration

The sentiment analysis can be accessed via the OpenClaw Telegram bot integration:

### Available Commands

```bash
sentiment <symbol>  # Analyze Reddit sentiment for a symbol
```

### OpenClaw Trading Wrapper

The `openclaw/trading.py` wrapper provides CLI access to sentiment analysis:

```python
elif cmd == "sentiment":
    print(json.dumps(analyze_sentiment(args[0]), indent=2))
```

资料来源：[openclaw/trading.py:1-50]()

## Usage Examples

### Basic Sentiment Analysis

```python
from tradingview_mcp.core.services.sentiment_service import analyze_sentiment

# Analyze Bitcoin sentiment
result = analyze_sentiment(symbol="BTC", category="crypto", limit=20)

print(f"Sentiment Score: {result['sentiment_score']}")
print(f"Label: {result['sentiment_label']}")
print(f"Posts Analyzed: {result['posts_analyzed']}")
```

### Confluence Analysis

```python
from tradingview_mcp.server import analyze_confluence

# Full confluence analysis for Apple stock
result = analyze_confluence(
    symbol="AAPL",
    exchange="NASDAQ",
    timeframe="1D"
)

print(f"Confidence: {result['confluence']['confidence']}")
print(f"Recommendation: {result['confluence']['recommendation']}")
```

### Multi-Agent Decision

```python
from tradingview_mcp.core.services.multi_agent_service import multi_agent_analysis

# Get full multi-agent analysis
decision = multi_agent_analysis(symbol="ETH", exchange="KUCOIN")

print(f"Decision: {decision['decision']}")
print(f"Confidence: {decision['confidence']}")
```

## Limitations and Considerations

| Aspect | Limitation | Mitigation |
|--------|------------|------------|
| Data Source | Reddit only | Future Twitter/X integration planned (roadmap) |
| Real-time | Reddit API rate limits | Configurable limit parameter |
| Regional Markets | Limited non-English subreddits | Regional market focus |
| Sentiment Quality | Keyword-based scoring | Multi-agent verification system |

资料来源：[README.md:100-150]()

## Roadmap

Planned enhancements for sentiment analysis:

- [ ] **Twitter/X market sentiment** — Expand data sources beyond Reddit
- [ ] **Walk-forward backtesting** — Test sentiment signals against historical data
- [ ] **Multi-language support** — Analyze non-English social media
- [ ] **Real-time streaming** — WebSocket-based sentiment updates

资料来源：[README.md:150-180]()

## See Also

- [Technical Analysis](technical_analysis.md) — RSI, MACD, Bollinger Bands integration
- [Multi-Agent Framework](multi_agent_framework.md) — Complete agent debate system
- [Backtesting Engine](backtesting.md) — Strategy validation with sentiment signals
- [OpenClaw Integration](openclaw_integration.md) — Telegram bot deployment

---

<a id='exchange-integrations'></a>

## Multi-Exchange Integration

### 相关页面

相关主题：[MCP Tools Reference](#mcp-tools-reference)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/tradingview_mcp/coinlist](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/coinlist)
- [src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)
- [src/tradingview_mcp/core/services/egx_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/egx_service.py)
- [src/tradingview_mcp/core/services/coinlist.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/coinlist.py)
</details>

# Multi-Exchange Integration

## Overview

The Multi-Exchange Integration module enables the tradingview-mcp framework to query and analyze financial instruments across multiple global exchanges. It provides a unified abstraction layer that routes market data requests to the appropriate TradingView screener endpoint based on exchange type, symbol format, and market classification.

The system supports:
- **Cryptocurrency exchanges**: Binance, KuCoin, Bybit, MEXC
- **US stock markets**: NASDAQ, NYSE, AMEX (including NYSEARCA, PCX aliases)
- **Taiwan markets**: TWSE, TPEX
- **Egyptian Exchange**: EGX
- **Turkish market**: BIST

资料来源：[README.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/README.md)

## Architecture

```mermaid
graph TD
    subgraph "API Layer"
        A[Server Tools] --> B[Request Validation]
    end
    
    subgraph "Exchange Routing"
        B --> C[validators.py]
        C --> D{symbol_type?}
        D -->|Stock| E[EXCHANGE_SCREENER]
        D -->|Crypto| F[Direct Exchange]
        E --> G[get_tv_exchange_prefix]
        F --> H[Exchange Aliases]
    end
    
    subgraph "Data Sources"
        G --> I[screener_service.py]
        H --> J[coinlist.py]
        I --> K[TradingView Screener API]
        J --> L[Symbol Lists]
    end
    
    subgraph "Market-Specific Services"
        K --> M[egx_service.py]
        L --> N[EGX Sectors]
    end
```

## Exchange Classification System

### Core Exchange Types

The framework classifies exchanges into two primary categories: stock exchanges and cryptocurrency exchanges.

| Classification | Description | Examples |
|----------------|-------------|----------|
| `stock` | Traditional stock markets with symbol-based trading | NASDAQ, NYSE, TWSE, TPEX, EGX, BIST |
| `crypto` | Cryptocurrency exchanges with pair-based trading | KUCOIN, BINANCE, BYBIT, MEXC |

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

### Exchange Registry

The `EXCHANGE_SCREENER` set contains all exchanges that work with the TradingView screener API:

```python
EXCHANGE_SCREENER = {
    "binance", "kucoin", "bybit", "mexc",
    "nasdaq", "nyse", "amex", "nysearca", "pcx",
    "twse", "tpex", "egx", "bist"
}
```

资料来源：[src/tradingview_mcp/core/utils/validators.py:1-20](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

## Symbol Construction and Exchange Prefixes

### TradingView Symbol Format

TradingView requires symbols to be prefixed with the exchange code in the format `EXCHANGE:SYMBOL`. The framework uses the `get_tv_exchange_prefix()` function to map exchange aliases to their canonical TradingView prefix.

```python
_EXCHANGE_TV_PREFIX: Dict[str, str] = {
    "nysearca": "AMEX",
    "pcx": "AMEX",
    "tpex": "TWSE",
}
```

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

### Exchange Prefix Resolution

```mermaid
graph LR
    A[Exchange Input] --> B{sanitized lowercased}
    B --> C{Exact Match?}
    C -->|Yes| D[Return Prefix]
    C -->|No| E[Fallback: UPPERCASE]
    
    subgraph "Known Aliases"
        F[nysearca] --> D
        G[pcx] --> D
        H[tpex] --> D
    end
```

The resolution logic:
1. Input is trimmed and lowercased
2. Lookup in `_EXCHANGE_TV_PREFIX` dictionary
3. Returns mapped prefix or uppercase fallback for unknown exchanges

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

### Screener Symbol Construction

In `screener_service.py`, the `analyze_coin` function constructs full TradingView symbols:

```python
def analyze_coin(symbol: str, exchange: str = "KUCOIN") -> dict:
    # Get the TradingView exchange prefix
    tv_exchange = get_tv_exchange_prefix(exchange)
    
    # Construct full symbol for TradingView API
    if is_stock_exchange(exchange):
        tv_symbol = f"{tv_exchange}:{symbol.upper()}"
    else:
        tv_symbol = f"{symbol.upper()}"
```

资料来源：[src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)

## Exchange Alias System

### AMEX Aliases

The framework normalizes several exchange identifiers to AMEX for ETF and commodity trading:

| Alias | Canonical Name | Use Case |
|-------|----------------|----------|
| `AMEX` | AMEX | American Stock Exchange ETFs |
| `NYSEARCA` | AMEX | NYSE Arca ETFs |
| `PCX` | AMEX | Arca ETF notation |

资料来源：[PR_BODY.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/PR_BODY.md)

### Taiwan Exchange Aliases

Taiwan stock symbols are routed to TWSE with the TPEX alias for OTC trading:

| Alias | Canonical Name | Market |
|-------|----------------|--------|
| `TWSE` | TWSE | Taiwan Stock Exchange |
| `TPEX` | TWSE | Taipei Exchange (OTC) |

资料来源：[PR_BODY.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/PR_BODY.md)

## Supported Exchanges by Market

### Cryptocurrency Exchanges

| Exchange | Symbol Format | Supported Tools |
|----------|---------------|-----------------|
| Binance | `SYMBOL` | top_gainers, top_losers, bollinger_scan, coin_analysis |
| KuCoin | `SYMBOL` | All crypto tools |
| Bybit | `SYMBOL` | All crypto tools |
| MEXC | `SYMBOL` | All crypto tools (420+ pairs) |

资料来源：[CHANGELOG.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CHANGELOG.md)

### Stock Markets

| Market | Exchange Code | Currency | Symbol Format |
|--------|---------------|----------|---------------|
| US Stocks (NASDAQ) | `NASDAQ` | USD | `NASDAQ:AAPL` |
| US Stocks (NYSE) | `NYSE` | USD | `NYSE:TSLA` |
| US ETFs (AMEX) | `AMEX` | USD | `AMEX:SPY` |
| Taiwan (TWSE) | `TWSE` | TWD | `TWSE:2330` |
| Taiwan (TPEX) | `TWSE` | TWD | `TWSE:0050` |
| Egypt (EGX) | `EGX` | EGP/USD | `EGX:COMI` |
| Turkey (BIST) | `BIST` | TRY | `BIST:THYAO` |

资料来源：[src/tradingview_mcp/core/data/egx_sectors.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/data/egx_sectors.py)

## Exchange-Specific Services

### Screener Service

The `ScreenerService` class provides unified access to TradingView screener data across all supported exchanges:

```python
class ScreenerService:
    def analyze_coin(self, symbol: str, exchange: str = "KUCOIN") -> dict:
        """Analyze a coin/stock across multiple timeframes."""
        
    def screen_stocks(self, exchange: str = "NASDAQ", 
                      signal: str = "strong_buy") -> list:
        """Screen stocks by signal type on specified exchange."""
```

资料来源：[src/tradingview_mcp/core/services/screener_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/screener_service.py)

### Coinlist Service

Manages exchange-specific symbol lists for quick lookups:

```python
class CoinlistService:
    def get_exchange_symbols(self, exchange: str) -> List[str]:
        """Return available symbols for an exchange."""
    
    def validate_symbol(self, symbol: str, exchange: str) -> bool:
        """Check if symbol exists on exchange."""
```

资料来源：[src/tradingview_mcp/core/services/coinlist.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/coinlist.py)

### EGX Service

Specialized service for Egyptian Exchange with sector classification:

```python
class EgxService:
    def get_egx_sectors(self) -> Dict[str, List[str]]:
        """Return EGX symbols grouped by sector."""
    
    def get_currency(self, symbol: str) -> str:
        """Return 'USD' or 'EGP' for EGX symbol."""
```

资料来源：[src/tradingview_mcp/core/services/egx_service.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/services/egx_service.py)

## Data Flow

```mermaid
sequenceDiagram
    participant Client
    participant Server
    participant Validator
    participant ScreenerService
    participant TV_API
    
    Client->>Server: analyze_coin("2330", "TWSE")
    Server->>Validator: sanitize_exchange("TWSE")
    Validator-->>Server: "twse"
    
    Server->>Validator: get_tv_exchange_prefix("twse")
    Validator-->>Server: "TWSE"
    
    Server->>Validator: is_stock_exchange("twse")
    Validator-->>Server: True
    
    Server->>ScreenerService: analyze_coin("2330", "TWSE")
    ScreenerService->>TV_API: GET /screener?exchange=TWSE&symbol=2330
    
    TV_API-->>ScreenerService: OHLCV data + indicators
    ScreenerService-->>Server: Analysis result
    Server-->>Client: Rich analysis object
```

## Exchange Validation Functions

### sanitize_exchange()

Normalizes exchange input and validates against supported exchanges:

```python
def sanitize_exchange(ex: str, default: str = "kucoin") -> str:
    """Sanitize and validate exchange name.
    
    Args:
        ex: Exchange name to sanitize
        default: Default exchange if validation fails
        
    Returns:
        Validated exchange name in lowercase
    """
    if not ex:
        return default
    exs = ex.strip().lower()
    return exs if exs in EXCHANGE_SCREENER else default
```

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

### is_stock_exchange()

Determines if an exchange represents a traditional stock market:

```python
def is_stock_exchange(exchange: str) -> bool:
    """Return True if the exchange is a stock market (not crypto)."""
    return exchange.strip().lower() in STOCK_EXCHANGES
```

Where `STOCK_EXCHANGES` contains:
```python
STOCK_EXCHANGES = {
    "nasdaq", "nyse", "amex", "nysearca", "pcx",
    "twse", "tpex", "egx", "bist"
}
```

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

## Coinlist Directory Structure

Symbol lists are stored in `src/tradingview_mcp/coinlist/`:

```
src/tradingview_mcp/coinlist/
├── binance.txt
├── kucoin.txt
├── bybit.txt
├── mexc.txt
├── twse.txt
├── tpex.txt
├── egx.txt
├── bist.txt
└── ...
```

Each file contains one symbol per line for fast lookup without API calls.

资料来源：[src/tradingview_mcp/coinlist](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/coinlist)

## Adding New Exchange Support

### Step 1: Update Validators

Add the exchange to the core registry in `validators.py`:

```python
# Add to EXCHANGE_SCREENER
EXCHANGE_SCREENER.add("NEW_EXCHANGE")

# Add to STOCK_EXCHANGES or leave out for crypto
STOCK_EXCHANGES.add("NEW_EXCHANGE")

# Add prefix mapping if needed
_EXCHANGE_TV_PREFIX["new_exchange"] = "NEW_EXCHANGE"
```

资料来源：[src/tradingview_mcp/core/utils/validators.py](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/src/tradingview_mcp/core/utils/validators.py)

### Step 2: Create Symbol List

Create `src/tradingview_mcp/coinlist/new_exchange.txt` with one symbol per line.

### Step 3: Add Tests

Add unit tests in `tests/unit/test_exchange_fixes.py`:

```python
def test_new_exchange_in_registry():
    assert "new_exchange" in EXCHANGE_SCREENER
    
def test_new_exchange_symbol_construction():
    prefix = get_tv_exchange_prefix("new_exchange")
    assert prefix == "NEW_EXCHANGE"
```

资料来源：[CONTRIBUTING.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/CONTRIBUTING.md)

### Step 4: Integration Test

```python
from tradingview_mcp.core.services.screener_service import ScreenerService

service = ScreenerService()
result = service.screen_stocks(exchange="NEW_EXCHANGE")
```

## Testing

### Unit Tests

The test suite covers exchange routing with 69 tests:

```
73 passed in 0.17s (69 new + 4 pre-existing)
```

Key test files:
- `tests/unit/test_exchange_fixes.py` - Exchange routing tests (32 tests)
- `tests/unit/test_exchange_aliases.py` - Alias resolution tests (37 tests)

资料来源：[PR_BODY.md](https://github.com/atilaahmettaner/tradingview-mcp/blob/main/PR_BODY.md)

### Test Coverage Areas

| Test Category | Description |
|---------------|-------------|
| Alias Resolution | TWSE/TPEX → TWSE, NYSEARCA/PCX → AMEX |
| Symbol Construction | Correct format for stock vs crypto |
| Registry Integrity | All aliases in EXCHANGE_SCREENER and STOCK_EXCHANGES |
| Regression | NYSE, NASDAQ, KUCOIN, BINANCE unchanged |

## Configuration Options

### Server Configuration

Exchange settings are configured at server startup:

```python
# In server.py
exchange = sanitize_exchange(request.exchange or "kucoin")
tv_exchange = get_tv_exchange_prefix(exchange)
is_stock = is_stock_exchange(exchange)
```

### Tool Parameters

Most analysis tools accept an `exchange` parameter:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `exchange` | string | `"KUCOIN"` | Exchange identifier |
| `symbol` | string | required | Trading symbol |
| `timeframe` | string | `"1D"` | Chart timeframe |

## Troubleshooting

### Common Issues

| Issue | Cause | Solution |
|-------|-------|----------|
| Symbol not found | Wrong exchange | Verify symbol exists on target exchange |
| Empty results | Exchange not in screener | Check EXCHANGE_SCREENER |
| Wrong prefix | Missing alias mapping | Add to `_EXCHANGE_TV_PREFIX` |

### Debugging Steps

1. Check if exchange is in `EXCHANGE_SCREENER`
2. Verify symbol format matches exchange type
3. Test symbol construction with `get_tv_exchange_prefix()`
4. Validate against TradingView website directly

---

---

## Doramagic Pitfall Log

Project: atilaahmettaner/tradingview-mcp

Summary: Found 10 potential pitfall items; 2 are high/blocking. Highest priority: installation - 来源证据：Complement idea: "What happened next?" via Chart Library.

## 1. installation · 来源证据：Complement idea: "What happened next?" via Chart Library

- Severity: high
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Complement idea: "What happened next?" via Chart Library
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_b89762244f5e4c498064918f30cd560b | https://github.com/atilaahmettaner/tradingview-mcp/issues/12 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. security_permissions · 涉及密钥、隐私或敏感领域

- Severity: high
- Evidence strength: source_linked
- Finding: 项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。
- User impact: 金融、交易、隐私和密钥场景必须比普通工具更保守。
- Suggested check: 补敏感数据流、密钥存储和权限边界审查。
- Guardrail action: 敏感领域或密钥场景必须保守推荐并要求人工复核。
- Evidence: packet_text.keyword_scan | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | matched secret / private key / privacy / trading / finance keyword

## 3. installation · 来源证据：[HELP] Installation Issue:

- Severity: medium
- Evidence strength: source_linked
- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[HELP] Installation Issue:
- User impact: 可能增加新用户试用和生产接入成本。
- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- Evidence: community_evidence:github | cevd_dcb256f998e14be785fa2c939b9dba56 | https://github.com/atilaahmettaner/tradingview-mcp/issues/24 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 4. configuration · 可能修改宿主 AI 配置

- Severity: medium
- Evidence strength: source_linked
- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。
- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- Evidence: capability.host_targets | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | host_targets=mcp_host, claude, cursor, chatgpt

## 5. capability · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- Evidence: capability.assumptions | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | README/documentation is current enough for a first validation pass.

## 6. maintenance · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- Evidence: evidence.maintainer_signals | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | last_activity_observed missing

## 7. security_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- Evidence: downstream_validation.risk_items | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | no_demo; severity=medium

## 8. security_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- Evidence: risks.scoring_risks | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | no_demo; severity=medium

## 9. maintenance · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- Evidence: evidence.maintainer_signals | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | issue_or_pr_quality=unknown

## 10. maintenance · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- Evidence: evidence.maintainer_signals | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | release_recency=unknown

<!-- canonical_name: atilaahmettaner/tradingview-mcp; human_manual_source: deepwiki_human_wiki -->
