MCP TradingView Server
MCP TradingView Server
MCP-сервер (Model Context Protocol) на Python, который предоставляет данные рынка TradingView MCP-клиенту — Claude Desktop, claude.ai или любому другому совместимому клиенту. Данные получаются через tvdatafeed (OHLCV) и tradingview-ta (скринер).
Предоставляемые инструменты
Инструмент MCP | Описание |
| Исторические свечи OHLCV (акции, криптовалюты, форекс, фьючерсы) |
| Последняя свеча + изменение в % по сравнению с предыдущей |
| Технические индикаторы, мультитаймфреймовый контекст и композитная оценка |
| Фильтрация по рынку, объёму и RSI на предопределённом наборе инструментов |
tv_get_indicators подробнее
Рассчитываемые индикаторы: RSI, MACD, Bollinger Bands (с обнаружением сжатия), EMA, SMA, ATR (с уровнями стопов для длинных и коротких позиций), Стохастик, ADX (+DI/−DI), OBV, средний объём и коэффициент объёма за 20 периодов, а также обнаружение расхождений RSI.
Три опции, отключённые по умолчанию:
Параметр | Эффект |
| Добавляет недельный контекст: |
| Рассчитывает относительную силу за 1 и 3 месяца по сравнению с этим бенчмарком |
| Рассчитывает композитную техническую оценку в |
Допустимые интервалы: 1, 3, 5, 15, 30, 45 (минут), 1H, 2H,
3H, 4H, 1D, 1W, 1M.
Охват скринера
tvdatafeed не предоставляет API скринера. Поэтому tv_screener перебирает жёстко заданный предопределённый набор в MARKET_SYMBOLS (src/mcp_tradingview/client.py) и вычисляет индикаторы по каждому символу через tradingview-ta:
Рынок | Охватываемый набор |
| 29 символов Euronext Paris — CAC 40, несколько технологических midcaps, ETF, доступные для PEA |
| 20 голубых фишек Nasdaq / NYSE |
| 8 основных пар Binance |
| 6 основных пар |
Перечисление ScreenerMarket также принимает futures, india, brazil,
australia, canada, europe и hongkong, но ни для одного из этих рынков не задан набор инструментов: вызов возвращает пустой список. Чтобы активировать их, достаточно добавить запись в MARKET_SYMBOLS.
Related MCP server: tradingview-mcp
Архитектура
Client MCP (Claude Desktop, claude.ai…)
│
├── stdio ──► process local
└── SSE ──► serveur HTTP (Starlette + uvicorn)
│
├──► tvdatafeed : bougies OHLCV
└──► tradingview-ta : screener
│
└──► cache TTL en mémoireПредварительные требования
Python ≥ 3.11
Учётная запись TradingView необязательна — анонимный доступ работает, но с более строгими лимитами частоты запросов.
SDK MCP закреплён на версии
< 2.0.0: версия 2.x удаляет декораторы@server.list_tools()/@server.call_tool()и переименовываетTool.inputSchemaвTool.input_schema. Прежде чем поднять это ограничение, необходима миграция.
Установка
git clone https://github.com/mathieubernardi/tradingview_mcp.git
cd tradingview_mcp
pip install -e ".[dev]"
cp .env.example .env # puis éditer .envКонфигурация
Все переменные имеют префикс TV_ и могут передаваться либо через файл .env, либо через окружение.
Переменная | По умолчанию | Описание |
| (пусто) | Идентификатор TradingView (необязательно) |
| (пусто) | Пароль TradingView (необязательно) |
|
|
|
|
| Хост SSE-сервера |
|
| Порт SSE-сервера (1024–65535) |
|
| Площадка по умолчанию, если она не указана в вызове |
|
| Количество свечей по умолчанию |
|
| Максимальное количество свечей |
|
| Время жизни кэша в памяти ( |
|
|
|
Двойной префикс в TV_TV_USERNAME / TV_TV_PASSWORD сделан намеренно: префикс окружения TV_ добавляется к полям tv_username / tv_password.
Запуск сервера
Две эквивалентные точки входа: консольный скрипт mcp-tradingview и модуль python -m mcp_tradingview. Второй не зависит от PATH, что делает его более надёжным в Windows.
# Linux / macOS — stdio
TV_TRANSPORT=stdio python -m mcp_tradingview
# Linux / macOS — SSE
TV_TRANSPORT=sse python -m mcp_tradingview# Windows PowerShell — stdio
$env:TV_TRANSPORT = "stdio"; python -m mcp_tradingview
# Windows PowerShell — SSE
$env:TV_TRANSPORT = "sse"; python -m mcp_tradingviewИнтеграция с Claude Desktop (stdio)
Добавьте в claude_desktop_config.json — ~/Library/Application Support/Claude/ в macOS, %APPDATA%\Claude\ в Windows:
{
"mcpServers": {
"tradingview": {
"command": "python",
"args": ["-m", "mcp_tradingview"],
"env": {
"TV_TRANSPORT": "stdio",
"TV_CACHE_TTL_SECONDS": "60"
}
}
}
}Если окружение Python не является окружением по умолчанию, замените "python" на абсолютный путь к интерпретатору virtualenv. Чтобы использовать учётную запись TradingView, добавьте TV_TV_USERNAME и TV_TV_PASSWORD в блок env.
В режиме stdio сессия TradingView устанавливается лениво при первом вызове инструмента: рукопожатие MCP отвечает немедленно, и клиент не сталкивается с тайм-аутом при запуске.
Интеграция SSE
TV_TRANSPORT=sse TV_PORT=8765 python -m mcp_tradingviewEndpoint | Роль |
| SSE-поток, который нужно указать на стороне MCP-клиента |
| Канал обратной передачи сообщений клиента |
| Проверка живости, возвращает |
Разработка
pytest tests/ -v # tests
ruff check src/ tests/ # lint
mypy src/ # type checking (strict)Известные ограничения
tvdatafeed— неофициальный клиент, который полагается на веб-эндпоинты TradingView: он может перестать работать без предупреждения.tv_screenerне сканирует весь рынок, а только предопределённый набор инструментов, описанный выше.Без премиум-аккаунта TradingView данные могут задерживаться на несколько минут.
Анонимный доступ имеет значительно более строгие лимиты частоты запросов, чем авторизованная учётная запись.
Ошибки инструмента возвращаются клиенту в виде JSON
{"error": ..., "tool": ..., "arguments": ...}, а не передаются как ошибки протокола.
Структура проекта
tradingview_mcp/
├── src/mcp_tradingview/
│ ├── __init__.py # métadonnées du paquet (__version__)
│ ├── __main__.py # entrée `python -m mcp_tradingview`
│ ├── config.py # settings (pydantic-settings, préfixe TV_)
│ ├── models.py # schémas Pydantic d'entrée / sortie
│ ├── client.py # client TradingView, indicateurs, cache TTL
│ ├── tools.py # définition JSON Schema + dispatch des outils
│ └── server.py # serveur MCP (stdio + SSE) et entrée console
├── tests/
│ └── test_server.py
├── pyproject.toml
├── .env.example
├── .gitignore
├── LICENSE
└── README.mdЛицензия
Распространяется под лицензией MIT. См. файл LICENSE.
Available Tools
4 toolstv_get_historical_dataA
Fetch historical OHLCV (Open, High, Low, Close, Volume) bars for any symbol from TradingView. Supports stocks, crypto, forex, futures.
| Name | Required | Description | Default |
|---|---|---|---|
| n_bars | No | Number of bars to return | |
| symbol | Yes | Ticker symbol, e.g. 'BTCUSDT', 'AAPL', 'EURUSD' | |
| exchange | No | Exchange name, e.g. 'EURONEXT' (PEA / Paris), 'NASDAQ', 'NYSE', 'BINANCE', 'FX' | EURONEXT |
| interval | No | Chart interval: 1, 3, 5, 15, 30, 45 (min) | 1H, 2H, 3H, 4H | 1D, 1W, 1M | 1D |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description must carry the behavioral disclosure burden. It names the output content (OHLCV bars) and the supported asset classes, but it does not mention bar ordering, exchange-selection caveats for non-EURONEXT symbols, adjustment behavior, or error handling. Some useful transparency exists, but important nuances are omitted.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two short sentences with no filler. The primary action is front-loaded, and the second sentence adds useful asset-class scope without bloating the definition.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple and the schema documents all parameters, so an agent can invoke it. However, with no output schema and no annotations, the description leaves out useful invocation-relevant details such as whether exchange must match the symbol (the default is EURONEXT, which may not work for all symbols) and the ordering/shape of returned bars.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so each parameter is already documented. The description adds broad domain context ('Supports stocks, crypto, forex, futures'), but it does not add parameter-specific meaning beyond what the schema provides. The baseline 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb and resource: 'Fetch historical OHLCV bars for any symbol from TradingView.' This clearly distinguishes it from sibling tools like tv_get_quote, tv_get_indicators, and tv_screener, which serve different purposes (current quote, derived indicators, screening).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides clear context: use this tool when historical OHLCV candle data is needed. It does not explicitly say 'use tv_get_quote for current prices' or 'use tv_get_indicators for computed values,' but the historical bar framing makes the intended use apparent.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
tv_get_indicatorsA
Compute technical indicators for any symbol. Includes RSI, MACD, Bollinger Bands (+ squeeze detection), EMA, SMA, ATR (+ stop levels), Stochastic, ADX (+DI/-DI), OBV, volume MA20/ratio, RSI divergence flags. Optional: weekly multi-timeframe context (include_weekly=true), relative strength vs benchmark (benchmark_symbol), composite technical score [-1,+1] (include_score=true).
| Name | Required | Description | Default |
|---|---|---|---|
| bb_std | No | ||
| n_bars | No | ||
| symbol | Yes | ||
| exchange | No | EURONEXT | |
| interval | No | 1D | |
| bb_length | No | ||
| macd_fast | No | ||
| macd_slow | No | ||
| atr_length | No | ||
| indicators | No | ||
| rsi_length | No | ||
| ema_periods | No | ||
| macd_signal | No | ||
| sma_periods | No | ||
| atr_stop_mult | No | ATR multiplier for stop_long / stop_short levels | |
| include_score | No | Compute composite technical_score [-1,+1] and sub-scores | |
| include_weekly | No | Fetch weekly bars for weekly_rsi, weekly_adx, weekly_trend | |
| benchmark_symbol | No | Benchmark ticker for RS 1M/3M (e.g. 'CW8'). Empty = skip. | |
| benchmark_exchange | No | EURONEXT | |
| divergence_lookback | No | Bars window for RSI divergence detection |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full disclosure burden and does add useful behavioral context: RSI divergence flags, Bollinger squeeze detection, ATR stop_long/stop_short levels, the [-1,+1] composite score range, and what each optional flag produces. However, it does not reveal the return shape, that the indicators parameter defaults to ['all'] so every call computes the entire indicator set, or any data-source/error behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two dense sentences of roughly 60 words with the core purpose front-loaded and no filler. Parameter names are embedded inline (include_weekly=true, benchmark_symbol, include_score=true), making the text directly actionable for an agent without cross-referencing the schema.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a 20-parameter tool with no output schema and no annotations, the description thoroughly covers the feature and option matrix but omits the output contract: what the response contains, how weekly/benchmark/score fields appear in results, and that the default is to compute all indicators. An agent can select the tool confidently but would invoke it without knowing what it returns.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is only 25%, so the description must compensate. It maps the three optional features to their parameter names inline (include_weekly=true, benchmark_symbol, include_score=true) and its indicator inventory aligns with the indicators enum values. The many numeric tuning parameters (macd_fast, atr_length, sma_periods, etc.) are left to their self-explanatory names, which is passable but adds no real semantic depth.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource ('Compute technical indicators for any symbol') and enumerates the full indicator surface: RSI, MACD, Bollinger Bands with squeeze detection, EMA, SMA, ATR with stop levels, Stochastic, ADX, OBV, volume MA20/ratio, and RSI divergence flags. The sibling names (tv_get_historical_data, tv_get_quote, tv_screener) make this tool's distinct role unambiguous even without explicit comparison.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The opening sentence establishes a clear selection context: use this tool when computed indicators are needed, as opposed to raw bars (tv_get_historical_data), a snapshot quote (tv_get_quote), or universe filtering (tv_screener). It stops short of naming those alternatives explicitly or stating when not to use this tool, but the purpose is specific enough that an agent can route correctly.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
tv_get_quoteA
Get the latest price quote for a symbol: last OHLCV bar plus percentage change from the previous bar.
| Name | Required | Description | Default |
|---|---|---|---|
| symbol | Yes | Ticker symbol | |
| exchange | No | EURONEXT | |
| interval | No | 1D |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are present, so the description carries the full burden. It usefully discloses the output shape (last OHLCV bar plus percentage change), but it does not mention data delay, exchange handling, or how the interval parameter affects the returned bar. Acceptable but not rich.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Single sentence, front-loaded, and free of filler. Every phrase earns its place by specifying the object, the timeframe, and the included data.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple 3-parameter read tool, the description gives the core return fields, but with no output schema and no annotations it should also clarify interval/exchange behavior and the reference period for the percentage change. Adequate with clear gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is only 33%: only 'symbol' has a description, while 'exchange' and 'interval' are undocumented. The description adds no meaning for exchange or interval and does not compensate for the low coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('get'), names the resource ('latest price quote for a symbol'), and states the exact payload ('last OHLCV bar plus percentage change from the previous bar'). The words 'latest' and 'last bar' clearly distinguish it from tv_get_historical_data and the other siblings.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage for obtaining a current snapshot rather than historical data or indicators, but it never explicitly states when to choose this tool over its siblings. There are no exclusions or alternative routing hints.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
tv_screenerA
Screen stocks, crypto or forex symbols by market, volume, RSI range. Markets include 'france' (Euronext Paris — PEA) and 'america' (Nasdaq / NYSE). Returns top matches with price, volume and RSI data.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| market | No | Market to screen: 'france' (Euronext Paris / PEA), 'america' (Nasdaq + NYSE), crypto, forex, futures, etc. | france |
| max_rsi | No | ||
| min_rsi | No | ||
| min_volume | No | Minimum volume filter | |
| min_market_cap | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the burden of explaining behavior. It does disclose output fields ('price, volume and RSI data') and the market coverage for France and America. It does not explain how 'top matches' are ordered, how limit interacts with results, or whether RSI bounds are inclusive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three concise sentences that front-load the core purpose, then the key market values, then the return data. There is no filler or repetition of schema defaults.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For an optional-parameter screener with no output schema, the description provides enough to invoke it sensibly: what it screens, key market options, and what data is returned. The missing ordering/ranking criteria and the unexplained min_market_cap parameter are gaps, but the tool remains usable with defaults.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is only 33%, so the description must compensate. It adds the 'RSI range' concept and market context, but min_market_cap is completely unexplained and limit is only inferable. The description partially fills the gap but does not fully cover all six parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Screen') with a clear resource ('stocks, crypto or forex symbols') and names the key filtering dimensions. It also distinguishes itself from the sibling tools by focusing on screening/discovery rather than historical data, quotes, or indicators.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Usage context is implied: use this tool to find symbols matching market, volume, and RSI criteria. However, it never explicitly says when NOT to use it or directs the agent to alternatives like tv_get_quote or tv_get_indicators, so routing is left to inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.1.0- First observed
tv_get_historical_data - First observed
tv_get_indicators - First observed
tv_get_quote - First observed
tv_screener
TDQS
Scored across 4 tools
Each tool targets a distinct data need: historical bars, latest quote, indicator calculation, and symbol screening. The only potential overlap is RSI appearing in indicators and screener, but the intended use (computing vs scanning) is clear.
Three tools follow the `tv_get_*` verb-object pattern and all use consistent snake_case with a `tv_` prefix. `tv_screener` is the outlier because it uses a noun instead of an action verb, but it is still recognizable within the family.
Four tools is a reasonable, focused size for a market-data server, and each tool provides broad functionality (multi-symbol historical data, quotes, many indicators, and a screener). None feels redundant or unnecessary.
The server covers the core market-data workflow: retrieving history, checking current prices, computing technical analysis, and discovering symbols via screening. Minor gaps such as no dedicated symbol-search or fundamental data endpoint exist, but they are workable around for typical technical-analysis use cases.
Maintenance
Related MCP Connectors
Market Data App MCP — wraps the Market Data App API (marketdata.app)
Real-time crypto market data: candles, tickers, orderbooks across 13+ exchanges via MCP.
Create and manage trading strategies, bots, webhooks and signals from any MCP client.
- FensoryOAuthcom.fensory
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables MCP clients to control a local TradingView Desktop instance, providing tools to read chart state, change symbols and timeframes, and fetch OHLCV data.120 npm134MIT
- AlicenseBqualityCmaintenanceTradingView MCP server — real-time market data, technical indicators, screeners, and backtesting for Claude, ChatGPT, Cursor, Copilot, and any MCP client. Stocks, crypto, forex & futures across global exchanges.441MIT
- FlicenseNot gradedqualityDmaintenanceExposes TradingView data including quotes, technical ratings, historical OHLCV, and market screening through an MCP server using unofficial libraries.-
- FlicenseNot gradedqualityCmaintenanceProvides unified TradingView capabilities through one MCP server, including market data, screening, technical analysis, backtesting, sentiment, chart control via browser automation, Pine script transpilation and compilation, and alert webhooks.-