Doramagic Project Pack Β· Human Manual
tradingview-mcp
Related topics: System Architecture, MCP Tools Reference, Installation Guide
Project Overview
Related topics: System Architecture, MCP Tools Reference, Installation Guide
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: System Architecture, MCP Tools Reference, Installation Guide
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. Sources: 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 |
Sources: README.md:1-20
Architecture Overview
TradingView-MCP follows a modular architecture with clear separation of concerns:
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]
endDirectory 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
Sources: 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 |
Sources: README.md:45-60
2. Backtesting System
The backtesting engine supports 6 trading strategies:
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) |
Sources: 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 |
Sources: README.md:95-105
Supported Exchanges
TradingView-MCP supports multiple exchange types through the EXCHANGE_SCREENER mapping:
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]
endExchange 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 |
Sources: src/tradingview_mcp/core/utils/validators.py:80-100
Stock Exchange Classification
The system classifies exchanges using STOCK_EXCHANGES:
STOCK_EXCHANGES = frozenset({
"nyse", "nasdaq", "amex", "nysearca", "pcx",
"twse", "tpex", "egx"
})
Sources: 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 |
Sources: README.md:30-70
Installation Methods
Method 1: UV Package Manager (Recommended)
# 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
{
"mcpServers": {
"tradingview": {
"command": "uvx",
"args": ["--from", "tradingview-mcp-server", "tradingview-mcp"]
}
}
}
Sources: INSTALLATION.md:25-40
Method 3: Git Clone (Local Development)
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
uv sync
uv run python src/tradingview_mcp/server.py
Sources: CONTRIBUTING.md:15-25
Configuration Reference
Claude Desktop Config (Windows)
{
"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:
{
"mcpServers": {
"tradingview": {
"command": "uvx",
"args": ["--python", "3.13", "--from", "tradingview-mcp-server", "tradingview-mcp"]
}
}
}
Sources: INSTALLATION.md:45-55
OpenClaw Integration
TradingView-MCP can be accessed via Telegram, WhatsApp, and Discord using OpenClaw:
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]Sources: 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 |
Sources: CONTRIBUTING.md:70-95
Project Roadmap
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-12Sources: README.md:150-165
License
TradingView-MCP is released under the MIT License. See LICENSE for details.
Sources: README.md:170-172
Sources: README.md:1-20
Installation Guide
Related topics: Quick Start Guide
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Quick Start Guide
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 |
Sources: 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:
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc
Windows:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
Verify installation:
uv --version
Sources: INSTALLATION.md:15-30
#### Step 2: Clone the Repository
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
#### Step 3: Install Dependencies
uv sync
Sources: INSTALLATION.md:35-40
Method 2: Python Virtual Environment
For users who prefer traditional Python environments without UV:
Windows:
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
python -m venv .venv
.\.venv\Scripts\activate
pip install -e .
macOS/Linux:
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
python -m venv .venv
source .venv/bin/activate
pip install -e .
Sources: INSTALLATION.md:120-140
Method 3: PyPI Installation (uvx)
For quick testing without cloning:
uv tool install --python 3.13 tradingview-mcp-server
Sources: 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 |
Sources: INSTALLATION.md:55-65
#### Add Server Configuration
Open the config file and add the following:
{
"mcpServers": {
"tradingview-mcp": {
"command": "uv",
"args": [
"tool",
"run",
"--from",
"git+https://github.com/atilaahmettaner/tradingview-mcp.git",
"tradingview-mcp"
]
}
}
}
Sources: INSTALLATION.md:70-85
Windows (Direct Python Path):
{
"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"
}
}
}
Sources: INSTALLATION.md:18-25
macOS/Linux (Using UV):
{
"mcpServers": {
"tradingview-mcp-local": {
"command": "uv",
"args": ["run", "python", "src/tradingview_mcp/server.py"],
"cwd": "/path/to/your/tradingview-mcp"
}
}
}
Sources: INSTALLATION.md:105-112
Codex Plugin
The repository includes MCP-only Codex plugin metadata:
{
"mcpServers": {
"tradingview": {
"command": "uvx",
"args": [
"--from",
"tradingview-mcp-server",
"tradingview-mcp"
]
}
}
}
Sources: 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.
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]Sources: OPENCLAW.md:1-15
#### Step 1: Install Dependencies
curl -LsSf https://astral.sh/uv/install.sh | sh
source ~/.bashrc
uv tool install tradingview-mcp-server
Sources: OPENCLAW.md:8-12
#### Step 2: Configure Channel
Create or edit ~/.openclaw/openclaw.json:
{
channels: {
telegram: {
botToken: "YOUR_BOT_TOKEN_HERE",
},
},
}
Sources: OPENCLAW.md:15-22
#### Step 3: 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
Sources: OPENCLAW.md:25-33
#### Step 4: Restart OpenClaw
openclaw gateway install
systemctl --user start openclaw-gateway.service
openclaw doctor
Sources: OPENCLAW.md:55-58
Development Setup
For contributors who want to modify the code or run locally:
1. Clone and Setup
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
2. Install Development Dependencies
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync
uv sync --dev
Sources: 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 |
Sources: CONTRIBUTING.md:15-20
4. Test Locally
# 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
Sources: 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
Sources: 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 |
Sources: 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:
uv tool install --python 3.13 tradingview-mcp-server
This warms the cache so the server starts instantly.
Sources: 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:
- Explore available tools by asking your AI agent
- Try basic queries like "Show me top gainers on Binance"
- Run development tests with
uv run pytest - Review CONTRIBUTING.md for code standards
Sources: INSTALLATION.md:1-5
Quick Start Guide
Related topics: Installation Guide, MCP Tools Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Installation Guide, MCP Tools Reference
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. Sources: README.md:1
The Quick Start process involves three main stages:
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 |
Sources: 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:
uvx --from tradingview-mcp-server tradingview-mcp
This method requires no local setup and pulls the latest version from PyPI automatically. Sources: 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 |
Sources: INSTALLATION.md:15-20
#### Windows Configuration
Add the following to your claude_desktop_config.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"
}
}
}
Sources: INSTALLATION.md:24-32
#### macOS/Linux Configuration
For Unix-based systems, use uv with the run command:
{
"mcpServers": {
"tradingview-mcp-local": {
"command": "uv",
"args": ["run", "python", "src/tradingview_mcp/server.py"],
"cwd": "/path/to/your/tradingview-mcp"
}
}
}
Sources: INSTALLATION.md:55-63
#### Linux Full Path
On Linux systems, use the full path to uvx:
{
"mcpServers": {
"tradingview": {
"command": "/home/YOUR_USERNAME/.local/bin/uvx",
"args": ["--from", "tradingview-mcp-server", "tradingview-mcp"]
}
}
}
Sources: README.md:60-66
Method 3: Local Development Setup
For development or customization, clone and run from source.
#### Step 1: Clone Repository
git clone https://github.com/atilaahmettaner/tradingview-mcp.git
cd tradingview-mcp
#### Step 2: Install Dependencies
# 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
# 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/
Sources: CONTRIBUTING.md:5-20
Method 4: Pre-installed Tool
For faster subsequent launches, pre-install the package:
# 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. Sources: 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:
{
"mcpServers": {
"tradingview": {
"command": "uvx",
"args": ["--python", "3.13", "--from", "tradingview-mcp-server", "tradingview-mcp"]
}
}
}
Sources: README.md:96-107
OpenClaw Integration
For connecting to Telegram, WhatsApp, or Discord, use the OpenClaw gateway.
Step 1: Install OpenClaw Dependencies
# 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:
{
channels: {
telegram: {
botToken: "YOUR_BOT_TOKEN_HERE",
},
},
}
Step 3: Install TradingView Skill
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:
openclaw config set acp.defaultAgent main
openclaw config set gateway.mode local
Sources: 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. Sources: 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 |
Sources: 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")]
Sources: 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 |
Sources: README.md:108-125
Next Steps
After successful installation:
- Explore the technical analysis tools for indicator-based analysis
- Try the backtesting engine to test trading strategies
- Configure multi-exchange screening for global market coverage
- Review the contribution guidelines if you want to extend functionality
Sources: CONTRIBUTING.md:1-5
System Architecture
Related topics: MCP Protocol Integration, Service Architecture
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: MCP Protocol Integration, Service Architecture
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.
Sources: README.md
The server follows a layered architecture pattern with clear separation between the MCP protocol layer, business logic services, and data providers.
Source: https://github.com/atilaahmettaner/tradingview-mcp / Human Manual
MCP Protocol Integration
Related topics: System Architecture, MCP Tools Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: System Architecture, MCP Tools Reference
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
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:#fff3e0Component 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
# 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:
{
"mcpServers": {
"tradingview-mcp": {
"command": "uv",
"args": [
"tool",
"run",
"--from",
"git+https://github.com/atilaahmettaner/tradingview-mcp.git",
"tradingview-mcp"
]
}
}
}
Sources: 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:
{
"mcpServers": {
"tradingview": {
"command": "uvx",
"args": [
"--from",
"tradingview-mcp-server",
"tradingview-mcp"
]
}
}
}
Sources: README.md
Installation Methods
Method 1: Direct Installation via UV
# Install from PyPI
uv tool install tradingview-mcp-server
Sources: INSTALLATION.md
Method 2: Source Installation
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:
uv tool install --python 3.13 tradingview-mcp-server
Sources: README.md
Development Workflow
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:#c8e6c9Development 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 |
Sources: CONTRIBUTING.md
OpenClaw Integration
For messaging platforms (Telegram, WhatsApp, Discord), OpenClaw provides an alternative integration path:
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:#fff3e0OpenClaw Quick Setup
# 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
Sources: 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:
{
"mcpServers": {
"tradingview": {
"command": "uvx",
"args": ["--python", "3.13", "--from", "tradingview-mcp-server", "tradingview-mcp"]
}
}
}
Sources: README.md
Verification Steps
After installation, verify the MCP server is operational:
- Restart the AI client completely
- Ask: "Can you show me the available TradingView tools?"
- Confirm tools like
top_gainers,bollinger_scan,coin_analysisare 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
Sources: CONTRIBUTING.md
Next Steps
- Review the Technical Analysis documentation for available indicators
- Explore the Screening Tools for market filtering
- Configure your preferred AI client following the installation guide
Sources: INSTALLATION.md
Service Architecture
Related topics: System Architecture, MCP Tools Reference, Multi-Exchange Integration
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: System Architecture, MCP Tools Reference, Multi-Exchange Integration
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
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_FINService 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
Sources: 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 |
Sources: 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 |
Sources: 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 |
Sources: 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.
# 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
Sources: 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 |
Sources: 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 |
Sources: 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 |
Sources: 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 |
Sources: src/tradingview_mcp/core/services/scanner_service.py
Data Flow Architecture
Request Processing Flow
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 ResponseMulti-Timeframe Analysis Flow
The multi_timeframe_analysis function demonstrates cross-service integration:
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 --> HSources: src/tradingview_mcp/server.py
Service Configuration
Exchange Mappings
The system maintains exchange-to-screener mappings for routing:
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",
}
Sources: 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
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:
- Technical Analysis β
indicators.py+indicators_calc.py - Sentiment Analysis β
sentiment_service.py - News Analysis β
news_service.py - Price Data β
yahoo_finance_service.py
Sources: 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:
uv run pytest
uv run ruff check
uv run mypy src/
Sources: 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.
Sources: CONTRIBUTING.md:62-70
MCP Tools Reference
Related topics: Backtesting Engine, Sentiment Analysis, Multi-Exchange Integration
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Backtesting Engine, Sentiment Analysis, Multi-Exchange Integration
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.
Sources: README.md
Source: https://github.com/atilaahmettaner/tradingview-mcp / Human Manual
Backtesting Engine
Related topics: MCP Tools Reference, Service Architecture
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: MCP Tools Reference, Service Architecture
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
Sources: backtest_service.py:1-20
Architecture
The Backtesting Engine follows a layered architecture with clear separation of concerns:
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 --> FComponent 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 |
Sources: 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) |
Sources: backtest_service.py:15-22
Strategy Selection Flow
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"]Sources: 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:
@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 |
Sources: server.py
2. compare_strategies
Runs all 6 strategies on the same symbol and ranks by performance.
Function Signature:
@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) |
Sources: server.py
3. walk_forward_backtest_strategy
Walk-forward backtesting to detect strategy overfitting.
Function Signature:
@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 |
Sources: 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
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%"]
endRobustness 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
Sources: 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) |
Sources: 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 |
Sources: 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:
{
"equity_curve": [
{"date": "2023-01-15", "capital": 10500.00, "drawdown_pct": 0.0},
{"date": "2023-02-20", "capital": 10200.00, "drawdown_pct": -2.86},
...
]
}
Sources: 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
)
Sources: 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 |
Sources: 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."} |
Sources: 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.
Sources: backtest_service.py:1-20
Sentiment Analysis
Related topics: MCP Tools Reference, Service Architecture
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: MCP Tools Reference, Service Architecture
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:
- Technical Analyst β Bollinger Bands, RSI, MACD
- Sentiment & Momentum Analyst β Reddit community sentiment + price momentum
- Risk Manager β Volatility, drawdown risk, mean-reversion signals
Sources: README.md:1-50
Architecture
The sentiment analysis system follows a layered architecture:
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 |
Sources: 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 |
Sources: src/tradingview_mcp/core/services/sentiment_service.py:1-50
API Reference
`analyze_sentiment`
The primary function for retrieving and analyzing Reddit sentiment.
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
{
"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 |
Sources: 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:
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 --> HScoring 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 |
Sources: 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:
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 |
Sources: 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 |
Sources: src/tradingview_mcp/server.py:1-50
Implementation
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"
Sources: 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 |
Sources: src/tradingview_mcp/core/services/egx_sectors.py
OpenClaw Integration
The sentiment analysis can be accessed via the OpenClaw Telegram bot integration:
Available Commands
sentiment <symbol> # Analyze Reddit sentiment for a symbol
OpenClaw Trading Wrapper
The openclaw/trading.py wrapper provides CLI access to sentiment analysis:
elif cmd == "sentiment":
print(json.dumps(analyze_sentiment(args[0]), indent=2))
Sources: openclaw/trading.py:1-50
Usage Examples
Basic Sentiment Analysis
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
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
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 |
Sources: 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
Sources: README.md:150-180
See Also
- Technical Analysis β RSI, MACD, Bollinger Bands integration
- Multi-Agent Framework β Complete agent debate system
- Backtesting Engine β Strategy validation with sentiment signals
- OpenClaw Integration β Telegram bot deployment
Sources: README.md:1-50
Multi-Exchange Integration
Related topics: MCP Tools Reference
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: MCP Tools Reference
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
Sources: README.md
Architecture
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]
endExchange 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 |
Sources: src/tradingview_mcp/core/utils/validators.py
Exchange Registry
The EXCHANGE_SCREENER set contains all exchanges that work with the TradingView screener API:
EXCHANGE_SCREENER = {
"binance", "kucoin", "bybit", "mexc",
"nasdaq", "nyse", "amex", "nysearca", "pcx",
"twse", "tpex", "egx", "bist"
}
Sources: src/tradingview_mcp/core/utils/validators.py:1-20
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.
_EXCHANGE_TV_PREFIX: Dict[str, str] = {
"nysearca": "AMEX",
"pcx": "AMEX",
"tpex": "TWSE",
}
Sources: src/tradingview_mcp/core/utils/validators.py
Exchange Prefix Resolution
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
endThe resolution logic:
- Input is trimmed and lowercased
- Lookup in
_EXCHANGE_TV_PREFIXdictionary - Returns mapped prefix or uppercase fallback for unknown exchanges
Sources: src/tradingview_mcp/core/utils/validators.py
Screener Symbol Construction
In screener_service.py, the analyze_coin function constructs full TradingView symbols:
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()}"
Sources: 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 |
Sources: 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) |
Sources: 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) |
Sources: 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 |
Sources: 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:
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."""
Sources: src/tradingview_mcp/core/services/screener_service.py
Coinlist Service
Manages exchange-specific symbol lists for quick lookups:
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."""
Sources: src/tradingview_mcp/core/services/coinlist.py
EGX Service
Specialized service for Egyptian Exchange with sector classification:
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."""
Sources: src/tradingview_mcp/core/services/egx_service.py
Data Flow
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 objectExchange Validation Functions
sanitize_exchange()
Normalizes exchange input and validates against supported exchanges:
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
Sources: src/tradingview_mcp/core/utils/validators.py
is_stock_exchange()
Determines if an exchange represents a traditional stock market:
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:
STOCK_EXCHANGES = {
"nasdaq", "nyse", "amex", "nysearca", "pcx",
"twse", "tpex", "egx", "bist"
}
Sources: 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.
Sources: src/tradingview_mcp/coinlist
Adding New Exchange Support
Step 1: Update Validators
Add the exchange to the core registry in validators.py:
# 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"
Sources: 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:
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"
Sources: CONTRIBUTING.md
Step 4: Integration Test
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)
Sources: 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:
# 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
- Check if exchange is in
EXCHANGE_SCREENER - Verify symbol format matches exchange type
- Test symbol construction with
get_tv_exchange_prefix() - Validate against TradingView website directly
Sources: README.md
Doramagic Pitfall Log
Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.
First-time setup may fail or require extra isolation and rollback planning.
The project may affect permissions, credentials, data exposure, or host boundaries.
First-time setup may fail or require extra isolation and rollback planning.
Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
Doramagic Pitfall Log
Doramagic extracted 10 source-linked risk signals. Review them before installing or handing real data to the project.
1. Installation risk: Complement idea: "What happened next?" via Chart Library
- Severity: high
- Finding: Installation risk is backed by a source signal: Complement idea: "What happened next?" via Chart Library. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/atilaahmettaner/tradingview-mcp/issues/12
2. Security or permission risk: Security or permission risk needs validation
- Severity: high
- Finding: Security or permission risk is backed by a source signal: Security or permission risk needs validation. Treat it as a review item until the current version is checked.
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: packet_text.keyword_scan | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | matched secret / private key / privacy / trading / finance keyword
3. Installation risk: [HELP] Installation Issue:
- Severity: medium
- Finding: Installation risk is backed by a source signal: [HELP] Installation Issue:. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/atilaahmettaner/tradingview-mcp/issues/24
4. Configuration risk: Configuration risk needs validation
- Severity: medium
- Finding: Configuration risk is backed by a source signal: Configuration risk needs validation. Treat it as a review item until the current version is checked.
- User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: capability.host_targets | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | host_targets=mcp_host, claude, cursor, chatgpt
5. Capability assumption: README/documentation is current enough for a first validation pass.
- Severity: medium
- Finding: README/documentation is current enough for a first validation pass.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: capability.assumptions | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | README/documentation is current enough for a first validation pass.
6. Maintenance risk: Maintainer activity is unknown
- Severity: medium
- Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | last_activity_observed missing
7. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: downstream_validation.risk_items | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | no_demo; severity=medium
8. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: risks.scoring_risks | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | no_demo; severity=medium
9. Maintenance risk: issue_or_pr_quality=unknown
- Severity: low
- Finding: issue_or_pr_quality=unknownγ
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | issue_or_pr_quality=unknown
10. Maintenance risk: release_recency=unknown
- Severity: low
- Finding: release_recency=unknownγ
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | art_0685d97fbc1a4f92849cb69a812ccd46 | https://github.com/atilaahmettaner/tradingview-mcp#readme | release_recency=unknown
Source: Doramagic discovery, validation, and Project Pack records
Community Discussion Evidence
These external discussion links are review inputs, not standalone proof that the project is production-ready.
Count of project-level external discussion links exposed on this manual page.
Open the linked issues or discussions before treating the pack as ready for your environment.
Community Discussion Evidence
Doramagic exposes project-level community discussion separately from official documentation. Review these links before using tradingview-mcp with real data or production workflows.
- Complement idea: "What happened next?" via Chart Library - github / github_issue
- [[HELP] Installation Issue:](https://github.com/atilaahmettaner/tradingview-mcp/issues/24) - github / github_issue
- I built a free open-source framework that turns your AI into a multi-age - reddit / searxng_indexed
- Security or permission risk needs validation - GitHub / issue
Source: Project Pack community evidence and pitfall evidence