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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Directory Structure

Continue reading this section for the full explanation and source context.

Section 1. Technical Analysis Engine

Continue reading this section for the full explanation and source context.

Section 2. Backtesting System

Continue reading this section for the full explanation and source context.

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:

ObjectiveDescription
Market Data AccessProvide real-time and historical market data from multiple exchanges
Technical AnalysisCalculate 30+ technical indicators with BUY/SELL/HOLD signals
Multi-Exchange SupportCover crypto (Binance, KuCoin, Bybit), US stocks (NASDAQ, NYSE, AMEX), and regional markets
Backtesting EngineTest 6 trading strategies with institutional-grade metrics
Sentiment AnalysisAggregate 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]
    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

Sources: CONTRIBUTING.md:40-55

Core Features

1. Technical Analysis Engine

The server provides comprehensive technical analysis with 30+ indicators:

CategoryIndicators
MomentumRSI, Stochastic, CCI, Williams %R
TrendMACD, EMA Cross, Supertrend, ADX
VolatilityBollinger Bands, ATR, Standard Deviation
VolumeOBV, Volume Profile, A/D Line
Patterns15 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:

StrategyTypeDescription
rsiMean ReversionRSI oversold/overbought signals
bollingerMean ReversionBollinger Band price band breakout
macdTrend FollowingMACD golden/death cross
ema_crossTrend FollowingEMA 20/50 Golden/Death Cross
supertrendTrend FollowingATR-based Supertrend
donchianBreakoutDonchian Channel breakout (Turtle style)

Sources: README.md:65-85

3. Yahoo Finance Integration (v0.6.0)

Real-time price data integration provides:

ToolFunction
yahoo_priceReal-time quote with price, change %, 52w high/low, market state
market_snapshotGlobal overview: S&P500, NASDAQ, BTC, EUR/USD, etc.
get_prices_bulkMulti-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]
    end

Exchange Configuration

ExchangeScreener TypeSymbol Format
BINANCEcryptoBINANCE:BTCUSDT
KUCOINcryptoKUCOIN:BTCUSDT
NASDAQamericaNASDAQ:AAPL
NYSEamericaNYSE:TSLA
AMEXamericaAMEX:SPY
NYSEARCAamericaAMEX:GLD
EGXegyptEGX:COMI
TWSETaiwanTWSE: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

ToolDescription
top_gainersFind top gaining assets
top_losersFind top losing assets
screen_stocksMulti-exchange screener with 20+ filter criteria
scan_by_signalScan by signal type (oversold, trending, breakout)
coin_analysisComprehensive coin/symbol analysis

Technical Analysis Tools

ToolDescription
get_technical_analysisFull TA: RSI, MACD, Bollinger, 23 indicators
get_multiple_analysisBulk TA for multiple symbols
get_bollinger_band_analysisProprietary Β±3 BB rating system
get_stock_decision3-layer decision engine
get_candlestick_patterns15 candlestick pattern detector
get_multi_timeframe_analysisWeekly→Daily→4H→1H→15m alignment

Backtesting Tools

ToolDescription
backtest_strategyBacktest 1 of 6 strategies with Sharpe, Calmar, Expectancy
compare_strategiesRun all 6 strategies and rank by performance

Sentiment & News Tools

ToolDescription
get_reddit_sentimentReddit sentiment analysis
get_live_newsLive financial news via RSS

Sources: README.md:30-70

Installation Methods

# 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 VersionStatusNotes
3.13βœ… RecommendedPrebuilt pandas wheels available
3.14⚠️ WarningMay 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

AspectStandard
StylePEP 8 with customizations
LintingRuff
Type HintsRequired for all functions
DocstringsRequired for public functions/classes

Testing Standards

Test TypeCoverage TargetFramework
Unit TestsCore functionspytest
Integration TestsReal API callspytest
LintingAll coderuff
Type CheckingAll codemypy

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-12

Sources: 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Method 1: UV Package Manager (Recommended)

Continue reading this section for the full explanation and source context.

Section Method 2: Python Virtual Environment

Continue reading this section for the full explanation and source context.

Section Method 3: PyPI Installation (uvx)

Continue reading this section for the full explanation and source context.

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

RequirementVersionNotes
Python3.8+ (3.10+ recommended)Required for all installation methods
UV Package ManagerLatestFast Python package manager for dependency management
MCP ClientClaude Desktop, Codex, or OpenClawThe AI agent interface
Internet ConnectionRequiredFor TradingView data access

Sources: INSTALLATION.md:1-5

Installation Methods

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

OSPath
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

CommandPurpose
uv run pytestRun the test suite
uv run ruff checkRun 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:

CategoryTools
Market Datatop_gainers, top_losers, yahoo_price, market_snapshot
Technical Analysisbollinger_scan, consecutive_candles_scan, technical_analysis
Sentimentcoin_analysis, reddit_sentiment
Backtestingbacktest, 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

IssueSolution
UV not foundAdd UV to PATH or restart terminal
Config file not foundCreate the directory and file if missing
Server won't startCheck Python version (3.8+ required)
Timeout errorsPre-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 for code standards

Sources: INSTALLATION.md:1-5

Quick Start Guide

Related topics: Installation Guide, MCP Tools Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Method 1: Quick Start with uvx

Continue reading this section for the full explanation and source context.

Section Method 2: Claude Desktop Configuration

Continue reading this section for the full explanation and source context.

Section Method 3: Local Development Setup

Continue reading this section for the full explanation and source context.

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:

RequirementMinimumRecommended
Python3.12+3.13
UV Package ManagerLatestLatest
Operating SystemWindows/macOS/LinuxUbuntu 24.04
NetworkInternet for market dataStable 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

PlatformPath
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

CategoryTools
Market Datayahoo_price, market_snapshot, get_prices_bulk
Technical Analysisget_technical_analysis, get_bollinger_band_analysis, get_stock_decision
Screeningscreen_stocks, scan_by_signal, top_gainers, top_losers
Backtestingbacktest_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

IssueCauseSolution
MCP error -32001 on WindowsPython 3.14 has no prebuilt pandasPin to Python 3.13 in config
Server won't startMissing dependenciesRun uv sync in project directory
Tools not showingClaude Desktop not restartedFully quit and relaunch
OpenClaw gateway won't startgateway.mode missingSet openclaw config set gateway.mode local

Sources: README.md:108-125

Next Steps

After successful installation:

  1. Explore the technical analysis tools for indicator-based analysis
  2. Try the backtesting engine to test trading strategies
  3. Configure multi-exchange screening for global market coverage
  4. Review the contribution guidelines if you want to extend functionality

Sources: CONTRIBUTING.md:1-5

System Architecture

Related topics: MCP Protocol Integration, Service Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Layers

Continue reading this section for the full explanation and source context.

Section Available Tools

Continue reading this section for the full explanation and source context.

Section Server Initialization

Continue reading this section for the full explanation and source context.

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:#fff3e0

Component Layers

LayerResponsibilityKey Components
AI ClientUser interaction, natural language processingClaude Desktop, Codex
MCP ProtocolStandardized communication, tool discoveryJSON-RPC 2.0 messages
ServerRequest routing, tool registrationserver.py
ServicesBusiness logic, data processingScreener, Technical Analysis
Data SourcesExternal API integrationYahoo 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 CategoryTools
Market Screeningtop_gainers, top_losers, screen_stocks, scan_by_signal
Technical Analysisget_technical_analysis, get_multiple_analysis, get_bollinger_band_analysis
Pattern Detectionget_candlestick_patterns, consecutive_candles_scan, bollinger_scan
Multi-Timeframeget_multi_timeframe_analysis, coin_analysis
Stock Decisionget_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:

PlatformConfig 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:

FilePurpose
.codex-plugin/plugin.jsonPlugin manifest
.codex-mcp.jsonMCP 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:#c8e6c9

Development Commands

CommandPurpose
uv syncInstall all dependencies
uv sync --devInstall development dependencies
uv run pytestExecute test suite
uv run ruff checkRun 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:#fff3e0

OpenClaw 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:

  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

Sources: CONTRIBUTING.md

Next Steps

Sources: INSTALLATION.md

Service Architecture

Related topics: System Architecture, MCP Tools Reference, Multi-Exchange Integration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section High-Level Architecture

Continue reading this section for the full explanation and source context.

Section Service Directory Structure

Continue reading this section for the full explanation and source context.

Section 1. Backtest Service

Continue reading this section for the full explanation and source context.

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_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

Sources: CONTRIBUTING.md:62-70

Service Components

1. Backtest Service

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

FeatureDescription
Strategy TypesRSI, Bollinger Bands, MACD, EMA Cross, Supertrend, Donchian
MetricsWin Rate, Sharpe Ratio, Calmar Ratio, Max Drawdown, Profit Factor
Commission SimulationRealistic 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.

ExchangeScreener Type
Binance, KuCoin, Bybit+Crypto screener
NASDAQ, NYSEUS stocks
TWSE, TPEXTaiwan stocks
AMEX, NYSEARCA, PCXETFs and specialty securities
EGXEgyptian exchange

Sources: src/tradingview_mcp/core/services/screener_service.py

3. Indicators Service

The indicators service orchestrates calculation of 30+ technical indicators.

CategoryIndicators
MomentumRSI, MACD, Stochastic, CCI, Williams %R
TrendEMA, SMA, Supertrend, ADX
VolatilityBollinger Bands, ATR, Standard Deviation
VolumeOBV, 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.

FunctionPurpose
Community DetectionIdentifies relevant subreddits for symbols
Sentiment ScoringQuantifies bullish/bearish community sentiment
IntegrationCombines 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 TypeContent
Financial NewsMarket news, earnings reports
Sector NewsIndustry-specific developments
Macro NewsEconomic 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 PointDescription
PriceCurrent and historical prices
ChangesDaily, weekly, yearly change percentages
52-Week RangeHigh/low boundaries
Market StatePre-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 TypeDetection
Candlestick15 candlestick patterns (Doji, Hammer, Engulfing, etc.)
TechnicalBollinger Band breakouts, volume spikes
Signal-basedOversold/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 Response

Multi-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 --> H

Sources: 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:

  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

Sources: openclaw/SKILL.md

Testing Architecture

Unit Tests

Services are validated through dedicated unit test files:

Test FileCoverage
tests/unit/test_exchange_fixes.pyExchange validation, symbol construction
tests/unit/test_exchange_aliases.pyAlias 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:

PrincipleImplementation
Separation of ConcernsEach service handles a single domain
ReusabilityShared indicators_calc.py for all indicator calculations
TestabilityIndependent services with clear interfaces
ExtensibilityEasy to add new exchanges or indicators
ComposabilityServices 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

Section Related Pages

Continue reading this section for the full explanation and source context.

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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Responsibilities

Continue reading this section for the full explanation and source context.

Section Strategy Selection Flow

Continue reading this section for the full explanation and source context.

Section 1. backteststrategy

Continue reading this section for the full explanation and source context.

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 --> F

Component Responsibilities

ComponentFileResponsibility
MCP Tool Layerserver.pyExposes backtesting as MCP tools
Service Layerbacktest_service.pyCore backtesting logic, trade simulation
Indicatorsindicators_calc.pyTechnical indicator calculations
External DataYahoo Finance APIOHLCV price data retrieval

Sources: server.py backtest_service.py:1-50

Supported Strategies

The Backtesting Engine includes 6 pre-built trading strategies:

StrategyTypeDescription
rsiMean ReversionRSI oversold (<30) / overbought (>70) signals
bollingerMean ReversionBollinger Band bounce trading
macdMomentumMACD golden/death cross signals
ema_crossTrend FollowingEMA 20/50 Golden/Death Cross
supertrendTrend FollowingATR-based Supertrend (πŸ”₯ most popular)
donchianBreakoutDonchian 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:

ParameterTypeDefaultDescription
symbolstrRequiredYahoo Finance symbol (AAPL, BTC-USD, SPY...)
strategystrRequiredrsi, bollinger, macd, ema_cross, supertrend, donchian
periodstr"1y"1mo, 3mo, 6mo, 1y, 2y
initial_capitalfloat10000.0Starting capital in USD
commission_pctfloat0.1Per-trade commission %
slippage_pctfloat0.05Per-trade slippage %
intervalstr"1d"1d (daily) or 1h (hourly)
include_trade_logboolFalseInclude detailed trade log
include_equity_curveboolFalseInclude 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:

ParameterTypeDefaultDescription
symbolstrRequiredYahoo Finance symbol
periodstr"1y"1mo, 3mo, 6mo, 1y, 2y
initial_capitalfloat10000.0Starting capital in USD
intervalstr"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:

ParameterTypeDefaultDescription
symbolstrRequiredYahoo Finance symbol
strategystrRequiredrsi, bollinger, macd, ema_cross, supertrend, donchian
periodstr"2y"Recommended: 2y for walk-forward
n_splitsint3Number of walk-forward folds (2-10)
train_ratiofloat0.7Fraction 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%"]
    end

Robustness Scoring

ScoreClassificationInterpretation
β‰₯ 0.8ROBUSTNo overfitting detected
β‰₯ 0.5MODERATESome degradation expected
β‰₯ 0.2WEAKLikely overfitted
< 0.2OVERFITTEDDo 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

MetricDescription
Total Return %Overall strategy return
Sharpe RatioRisk-adjusted return (annualized)
Calmar RatioReturn / Maximum Drawdown
Max Drawdown %Largest peak-to-trough decline
Win Rate %Percentage of profitable trades
Profit FactorGross profit / Gross loss
ExpectancyAverage 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:

IntervalAnnualization Factor
1d252 (trading days/year)
1h252 Γ— 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:

IntervalMinimum Bars Required
1d30 bars
1h100 bars

Sources: backtest_service.py:24-29

Trade Simulation

The trade simulation includes realistic trading costs:

Cost Components

ComponentDefaultDescription
Commission0.1%Per-trade commission
Slippage0.05%Per-trade price slippage

Trade Log Fields

When include_trade_log=True, each trade includes:

FieldDescription
entry_dateTrade entry timestamp
exit_dateTrade exit timestamp
entry_priceEntry price
exit_priceExit price
holding_daysDays held
gross_return_pctGross return before costs
net_return_pctNet return after costs
cost_pctTotal costs (commission + slippage)
capital_at_entryCapital at entry
capital_after_tradeCapital after trade
cumulative_returnCumulative 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

VersionDateKey Changes
v0.7.0Latest1h timeframe, full trade log, equity curve, walk-forward
v0.6.02026-03-29Initial backtesting engine with 6 strategies

Sources: CHANGELOG.md

Error Handling

Error ConditionResponse
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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Component Structure

Continue reading this section for the full explanation and source context.

Section SUBREDDITGROUPS Structure

Continue reading this section for the full explanation and source context.

Section analyzesentiment

Continue reading this section for the full explanation and source context.

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:

  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

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

ComponentFileResponsibility
analyze_sentimentsentiment_service.pyMain public API entry point
_fetch_reddit_postssentiment_service.pyReddit API integration
_score_textsentiment_service.pySentiment scoring algorithm
analyze_confluenceserver.pyCombined technical + sentiment analysis
multi_agent_analysismulti_agent_service.pyMulti-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

CategorySubredditsTarget Markets
cryptor/CryptoCurrency, r/Bitcoin, r/ethereum, r/CryptocurrencyMarket, r/SatoshiStreetBetsCryptocurrency
stocksr/wallstreetbets, r/stocks, r/investing, r/StockMarketUS Equities
allCombined crypto + stocks subredditsMulti-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

ParameterTypeDefaultDescription
symbolstrRequiredAsset ticker/name (e.g., "AAPL", "BTC", "ETH", "TSLA", "THYAO")
categorystr"all"Subreddit group: "crypto" \"stocks" \"all"
limitint20Total 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

FieldTypeDescription
titlestrPost title (truncated to 120 chars)
upvotesintReddit upvotes
commentsintNumber of comments
sentimentstrPer-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 --> H

Scoring Thresholds

Score RangeLabelDescription
> 0.15BullishStrong positive community sentiment
0.05 to 0.15Slightly BullishMild positive sentiment
-0.05 to 0.05NeutralBalanced or unclear sentiment
-0.15 to -0.05Slightly BearishMild negative sentiment
< -0.15BearishStrong 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:

OutputDescription
decisionFinal trading recommendation
confidenceConfidence level based on agent agreement
scoresIndividual agent scores
reasoningBrief 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 SignalSentiment SignalConfluenceConfidence
BullishBullishTechnical confirmed by SentimentHIGH
BearishBearishTechnical confirmed by SentimentHIGH
BullishBearishTechnical conflicts with SentimentMIXED
BearishBullishTechnical conflicts with SentimentMIXED

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 CategoryExchange ExamplesSentiment CategorySubreddits Used
CryptoBINANCE, KUCOIN, BYBIT, MEXCcryptoBitcoin, ethereum, CryptoCurrency, etc.
StocksNASDAQ, NYSEstockswallstreetbets, stocks, investing
Emerging MarketsEGX, BISTAuto-detectedAppropriate 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

AspectLimitationMitigation
Data SourceReddit onlyFuture Twitter/X integration planned (roadmap)
Real-timeReddit API rate limitsConfigurable limit parameter
Regional MarketsLimited non-English subredditsRegional market focus
Sentiment QualityKeyword-based scoringMulti-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

Sources: README.md:1-50

Multi-Exchange Integration

Related topics: MCP Tools Reference

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Exchange Types

Continue reading this section for the full explanation and source context.

Section Exchange Registry

Continue reading this section for the full explanation and source context.

Section TradingView Symbol Format

Continue reading this section for the full explanation and source context.

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]
    end

Exchange Classification System

Core Exchange Types

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

ClassificationDescriptionExamples
stockTraditional stock markets with symbol-based tradingNASDAQ, NYSE, TWSE, TPEX, EGX, BIST
cryptoCryptocurrency exchanges with pair-based tradingKUCOIN, 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
    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

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:

AliasCanonical NameUse Case
AMEXAMEXAmerican Stock Exchange ETFs
NYSEARCAAMEXNYSE Arca ETFs
PCXAMEXArca ETF notation

Sources: PR_BODY.md

Taiwan Exchange Aliases

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

AliasCanonical NameMarket
TWSETWSETaiwan Stock Exchange
TPEXTWSETaipei Exchange (OTC)

Sources: PR_BODY.md

Supported Exchanges by Market

Cryptocurrency Exchanges

ExchangeSymbol FormatSupported Tools
BinanceSYMBOLtop_gainers, top_losers, bollinger_scan, coin_analysis
KuCoinSYMBOLAll crypto tools
BybitSYMBOLAll crypto tools
MEXCSYMBOLAll crypto tools (420+ pairs)

Sources: CHANGELOG.md

Stock Markets

MarketExchange CodeCurrencySymbol Format
US Stocks (NASDAQ)NASDAQUSDNASDAQ:AAPL
US Stocks (NYSE)NYSEUSDNYSE:TSLA
US ETFs (AMEX)AMEXUSDAMEX:SPY
Taiwan (TWSE)TWSETWDTWSE:2330
Taiwan (TPEX)TWSETWDTWSE:0050
Egypt (EGX)EGXEGP/USDEGX:COMI
Turkey (BIST)BISTTRYBIST: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 object

Exchange 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:

Sources: PR_BODY.md

Test Coverage Areas

Test CategoryDescription
Alias ResolutionTWSE/TPEX β†’ TWSE, NYSEARCA/PCX β†’ AMEX
Symbol ConstructionCorrect format for stock vs crypto
Registry IntegrityAll aliases in EXCHANGE_SCREENER and STOCK_EXCHANGES
RegressionNYSE, 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:

ParameterTypeDefaultDescription
exchangestring"KUCOIN"Exchange identifier
symbolstringrequiredTrading symbol
timeframestring"1D"Chart timeframe

Troubleshooting

Common Issues

IssueCauseSolution
Symbol not foundWrong exchangeVerify symbol exists on target exchange
Empty resultsExchange not in screenerCheck EXCHANGE_SCREENER
Wrong prefixMissing alias mappingAdd 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

Sources: README.md

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high Complement idea: "What happened next?" via Chart Library

First-time setup may fail or require extra isolation and rollback planning.

high Security or permission risk needs validation

The project may affect permissions, credentials, data exposure, or host boundaries.

medium [HELP] Installation Issue:

First-time setup may fail or require extra isolation and rollback planning.

medium Configuration risk needs validation

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.

Sources 4

Count of project-level external discussion links exposed on this manual page.

Use Review before install

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.

Source: Project Pack community evidence and pitfall evidence