TradingView MCP
Provides tools for Pine Script v5/v6 development inside TradingView's Monaco editor, enabling agents to read, edit, hot-reload, check errors, and compile Pine scripts programmatically.
Allows programmatic control of TradingView Desktop charts and market intelligence, including chart navigation, OHLCV and indicator data retrieval, technical analysis, alerts, watchlists, multi-pane orchestration, and bar replay.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@TradingView MCP get the last 50 candles for AAPL on the 5-minute chart"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
TradingView MCP — Enterprise AI Market Intelligence & Chart Automation
An enterprise-grade, concurrency-safe, observable Model Context Protocol (MCP) server providing autonomous AI agents (Claude, Cursor, Antigravity, Cline) with direct real-time programmatic control, deterministic technical analysis, and multi-timeframe market intelligence on top of TradingView Desktop.
📑 Table of Contents
Related MCP server: TradingView MCP Jackson
⚡ Executive Overview
Traditional browser automation for financial charts suffers from race conditions, DOM polling stalls, context window exhaustion, and hallucinations caused by unconfirmed/live candle values.
TradingView MCP transforms TradingView Desktop into a deterministic execution engine for Large Language Models by connecting via the Chrome DevTools Protocol (CDP) directly into TradingView's internal Charting API and Monaco code editor.
Key Capabilities
Direct Chart Object Binding: Extracts exact mathematical OHLCV bars, indicator values, and custom Pine graphics directly from TradingView's in-memory data sources (
window.TradingViewApi), bypassing DOM scraping.Autonomous Pine Script IDE Integration: Programmatically reads, edits, hot-reloads, checks errors, and compiles Pine Script v5/v6 inside TradingView's Monaco editor.
Native Market Structure Analysis: Zero-dependency pure-math engine computes Swing Highs/Lows, Break of Structure (BOS), Change of Character (CHoCH), Order Blocks / Fair Value Zones, and Market Regimes natively in Node.js.
Token-Optimized Context: Returns compact statistical summaries (
summary: true), deduplicated Pine price levels, and low-token incremental delta polling (market_get_recent_changes), minimizing payload sizes and preserving context window budget.
🏛 System Architecture
The server establishes a non-blocking stdio JSON-RPC transport with the AI agent and mediates all communication with the Chromium runtime of TradingView Desktop via a dedicated FIFO mutex queue.
flowchart TB
subgraph AI_CLIENT["AI Client / LLM Agent"]
Agent["Autonomous Agent\n(Claude / Cursor / Antigravity)"]
end
subgraph MCP_SERVER["TradingView MCP Server (Node.js)"]
Transport["StdioServerTransport\n(Strict JSON-RPC 2.0)"]
Router["MCP Tool Router\n(Zod Input Validation)"]
subgraph CORE_ENGINE["Core Reliability Subsystem"]
Queue["AsyncQueue (FIFO Mutex)\n- Concurrency Lock\n- Backpressure Rejection\n- 15s Per-Task Timeout"]
StateManager["ChartStateManager\n- Generation Counter\n- Symbol/TF Hash Tracking\n- Operation Contexts"]
GenCache["Generational Cache\n- Invalidation on State Change\n- Configurable TTL"]
end
subgraph ANALYSIS_ENGINE["Market Intelligence Engine"]
Indicators["Technical Indicators\n(RSI, MACD, EMA, BB, ATR, ADX, VWAP)"]
Structure["Market Structure\n(Swings, BOS, CHoCH, Equilibrium)"]
Regimes["Regime Classifier\n(Trending, Ranging, Breakout)"]
Zones["Zone Clustering & Touch Counters"]
MTF["Multi-Timeframe Aggregator"]
end
end
subgraph TV_DESKTOP["TradingView Desktop Application"]
CDP["Chromium DevTools Protocol (Port 9222)\nPage / Runtime / Input Domains"]
V8["V8 JavaScript Context"]
TV_API["TradingViewApi & ChartWidget\n- DataSources Collection\n- MainSeriesBars (Float64Array)\n- Graphics Primitives"]
Monaco["Monaco Editor (Pine Script IDE)"]
end
Agent <==>|JSON-RPC via stdio| Transport
Transport --> Router
Router --> CORE_ENGINE
CORE_ENGINE --> ANALYSIS_ENGINE
CORE_ENGINE <==>|CDP WebSocket| CDP
CDP <==>|Runtime.evaluate| V8
V8 <==> TV_API
V8 <==> Monaco🛡 Core Engineering Pillars
1. Deterministic Market Intelligence Engine
The server includes a zero-dependency quantitative analysis module (src/analysis/) that executes mathematical models directly against confirmed historical price series:
Wilder's RSI: Exact parity with J. Welles Wilder's smoothing algorithm, handling zero-loss / zero-gain boundaries strictly without floating point drift (
avgLoss === 0 ? 100 : ...).Trend & Volatility: Exponential Moving Averages (EMA 9/20/50/200), SMA, Bollinger Bands (mean, stdDev, bandwidth, %B), and Average True Range (ATR) with True Range smoothing.
Directional Movement (ADX): Directional Movement (+DI/-DI) and smoothed Average Directional Index (ADX) to distinguish trending markets from consolidating ranges.
Market Structure (SMC / Price Action): Deterministic fractal swing detection across configurable window sizes, identifying Break of Structure (BOS), Change of Character (CHoCH), and Equilibrium / Discount / Premium zones.
Volume Anomalies & Divergences: Relative volume (RVOL) standard deviation scoring and oscillator divergences (Regular Bullish/Bearish, Hidden Bullish/Bearish).
2. Concurrency Safety & AsyncQueue Mutex
TradingView's internal charting framework cannot process concurrent asynchronous evaluations from different threads without risking state corruption or target session disconnection.
Strict FIFO Serialization: All calls to
evaluate()andevaluateAsync()are queued through anAsyncQueuemutex lock.Backpressure Protection: The queue enforces a maximum backlog depth (
maxDepth: 100). If an agent attempts to flood the server, tasks are rejected immediately with a structured[Queue_BACKPRESSURE]error rather than exhausting memory.Per-Task Timeouts: Every CDP operation has an individual 15-second timeout with an
AbortControllersignal to prevent queue starvation.
3. Zero Hardcoded Sleeps (Reactive CDP Automation)
All legacy artificial timeouts (setTimeout(500), setTimeout(2500)) have been eliminated.
Operations utilize reactive predicate polling (
waitForCondition) with 50ms intervals.The server yields control back to the agent the exact millisecond the chart acknowledges a symbol change, indicator attachment, or Monaco editor initialization.
Eliminates fixed artificial sleeps by waiting deterministically on DOM state predicates and generation updates with early exit upon resolution.
4. State Generation Tracking & Cache Invalidation
To prevent race conditions where an agent reads bar data while a timeframe change is still resolving:
Generation IDs: Every change to symbol, timeframe, or chart layout increments an atomic
generationcounter on theChartStateManager.Generational Cache: Cached indicator and OHLCV data are tagged with the active generation ID. When a state change occurs, all stale generational cache entries are instantly purged.
Cross-Contamination Guards: Tools like
data_get_ohlcvandmarket_get_contextacceptexpectedSymbolandexpectedTf. If the chart has not yet finished transitioning, the call throws a classified retryableSTALE_CHART_STATEerror.
5. Data Provenance & Anti-Hallucination Contracts
LLMs frequently hallucinate because live (unclosed) candles fluctuate after tool execution.
barClosedSeparation: Every bar returned bydata_get_ohlcvcontains a booleanbarClosedflag.closedOnlyOption: Agents can requestclosedOnly: trueto strip out the forming candle entirely, guaranteeing that backtests, pattern recognition, and indicators operate exclusively on immutable data.Token Efficiency: In addition to full arrays,
data_get_ohlcvprovidessummary: truemode returning high, low, open, close, volume, and range statistics in < 1KB of JSON.
6. Security & Protocol Purity
JS Injection Defense (CWE-94 / CWE-116): All user inputs (symbols, timeframes, script names, Pine code) are strictly serialized with
JSON.stringify()before interpolation into CDP evaluate scripts.Stdout Protocol Purity: In MCP, stdout is exclusively reserved for JSON-RPC framing. Any diagnostic message, warning, or debug log is routed strictly to
process.stderr.
7. Smart Institutional Activity Proxy Engine (Volume & Microstructure Analysis)
The server integrates an advanced quantitative volume and market-microstructure engine (src/analysis/smart-volume.js and market_get_smart_volume):
Robust Relative Volume (RVOL) & Median / MAD Anomaly Scoring: Replaces naive SMA volume filters with rolling median and Median Absolute Deviation (MAD), computing finite robust z-scores: $$\text{robustZ} = \frac{\text{Volume} - \text{Median}}{1.4826 \times \text{MAD}}$$ Gracefully handles zero MAD, flat consolidation, and outlier skew without NaN or Infinity drift.
Volume Percentile Distribution: Ranks activity across configurable lookbacks (
P50,P75,P90,P95,P99) into normalized tiers (NORMAL,ELEVATED,HIGH,EXTREME).Candle Microstructure Geometry: Computes True Range, Body Ratio, Upper/Lower Wick Ratios, and Close Location $(C - L) / (H - L)$ to measure directional conviction and rejection intensity.
Wyckoffian Effort vs Result: Models normalized relative volume (Effort) against ATR-normalized price displacement (Result) to detect
HIGH_EFFORT_LOW_RESULT(potential absorption/exhaustion) vsHIGH_EFFORT_HIGH_RESULT(initiative moves) vsLOW_EFFORT_HIGH_RESULT(low-liquidity slippage).Behavioral Pattern Proxies:
ABSORPTION_LIKE: High effort volume with limited displacement, pronounced rejection wicks, and structural support/resistance boundary interaction.INITIATIVE_BULLISH/INITIATIVE_BEARISH: Significant volume anomaly with range expansion, strong directional body, and closes near bar extremes.EXHAUSTION_BULLISH/EXHAUSTION_BEARISH: Climax volume spikes with failure to accept outside range boundaries and rejection closes.BULLISH_LIQUIDITY_SWEEP/BEARISH_LIQUIDITY_SWEEP: Probing past confirmed swing highs/lows with instantaneous recapture and volume anomalies.BREAKOUT_CONFIRMATIONvsFAILED_BREAKOUT: Multi-bar structural acceptance beyond key zones versus rejection traps.ACCUMULATION_LIKE/DISTRIBUTION_LIKE: Rolling multi-bar cluster heuristic tracking repeated absorption, close distribution bias, and boundary defense.
Transparent Smart Activity Score (0-100): Never a black box; composite score exposes explicit component weights (
volumeAnomaly,effortResult,rangeExpansion,rejection,structureInteraction,pattern).Session Awareness: Automatically classifies Gold and FX liquidity regimes (
ASIA,LONDON,NEW_YORK,LONDON_NY_OVERLAP).Feed Volume Type Transparency: Explicitly tags CFD/Forex feeds (including
OANDA:XAUUSD) asTICK_VOLUME(price update frequency) rather than centralized transaction volume, ensuring AI models never mischaracterize inferred behavior as literal institutional order-book data.Non-Repainting Guarantee: All historical metrics and closed-bar events are mathematically immutable. Live forming bars are explicitly marked with
barClosed: false.
🧰 Complete MCP Tool Catalog
The server exposes 90 purpose-built MCP tools categorized across 10 functional domains.
High-Level Market Intelligence Tools
Designed specifically for AI agents to comprehend market structure and context in a single call.
Tool Name | Key Parameters | Description |
|
| One-stop analytical call: returns market trend, regime (TRENDING/RANGING/BREAKOUT), key indicators (RSI, MACD, BB, ATR, ADX, VWAP), volume anomalies, structure (swings, BOS, CHoCH), and support/resistance zones. |
|
| Analyzes institutional-style volume activity (RVOL, robust z-score, Wyckoff effort vs result, absorption, initiative moves, exhaustion, sweeps, accumulation/distribution). |
|
| Detects swing highs/lows, higher highs/lows (HH/HL/LH/LL), Break of Structure (BOS), Change of Character (CHoCH), and range equilibrium. |
|
| Clusters price levels into horizontal support and resistance zones with touch counts, strength scores, and boundaries. |
|
| Evaluates multi-timeframe alignment across resolutions (e.g., 1D, 4H, 1H, 15m), scoring bullish/bearish consensus. |
|
| Low-token incremental delta polling: returns only new swings, structure breakouts, and volume anomalies since previous turn. |
| none | Authoritative diagnostic snapshot of connection liveness, queue depth, active generation ID, and chart readiness. |
Chart Control & Navigation Tools
Tool Name | Key Parameters | Description |
| none | Returns current chart state: symbol, timeframe, chart style, and list of all attached study entities with IDs. |
|
| Changes the active chart symbol and waits for data feed confirmation. |
|
| Changes chart resolution and waits reactively for candle resolution. |
|
| Sets chart rendering style. |
|
| Adds or removes indicators on the chart. Requires full official name (e.g., |
| none | Returns Unix timestamps and bar index boundaries for currently visible canvas. |
|
| Zooms and pans chart viewport to specific time range. |
|
| Jumps chart viewport to center on a target date. |
| none | Fetches full instrument metadata (exchange, tick size, currency, market hours). |
|
| Searches TradingView symbol database for matching tickers and exchanges. |
| none | Returns atomic state snapshot: active symbol, resolution, bar count, last bar time, generation ID. |
|
| Performs atomic scan fetching OHLCV bars across multiple resolutions sequentially without race conditions. |
Market & Study Data Retrieval Tools
Tool Name | Key Parameters | Description |
|
| Fetches historical price bars with provenance metadata, |
|
| Reads internal parameters, input values, and configurations of a specific study entity. |
| none | Scrapes Strategy Tester metrics: net profit, Sharpe ratio, max drawdown, win rate, profit factor. |
|
| Retrieves trade list from Strategy Tester (entry/exit times, prices, P&L, contracts). |
| none | Extracts equity curve points from Strategy Tester. |
|
| Fetches instantaneous quote (last price, day open/high/low/close, change %, volume). |
| none | Extracts Depth of Market (DOM) / order book bids and asks (requires DOM panel open). |
|
| Reads horizontal price levels drawn programmatically by Pine Script indicators ( |
|
| Reads text labels drawn by Pine Script indicators ( |
|
| Extracts cell contents and tabular matrices drawn by Pine Script indicators ( |
|
| Reads bounding boxes and price zones drawn by Pine Script indicators ( |
| none | Reads real-time numeric output values for all visible indicators from the chart Data Window. |
Pine Script Development & Compilation Tools
Tool Name | Key Parameters | Description |
| none | Reads source code currently open in TradingView's Pine Editor Monaco instance. |
|
| Injects Pine Script code directly into Monaco editor model. |
| none | Dispatches compilation ("Add to Chart" / "Save"). |
|
| Atomic developer loop: injects code, triggers compilation, and polls Monaco markers for syntax errors. |
| none | Retrieves compiler error messages and line-number markers from Monaco editor. |
| none | Reads log output from Pine Script console / runtime log window. |
| none | Triggers Ctrl+S shortcut inside Pine Editor. |
|
| Creates a clean new Pine Script draft from template. |
|
| Opens a saved Pine script by name from user library. |
| none | Lists all user scripts stored in TradingView account library. |
|
| Offline static analysis: detects array out-of-bounds, lookahead bias, uninitialized variables, and version deprecations. |
|
| Server-side headless compilation check via TradingView cloud compiler API without touching the UI. |
Drawing & Visual Annotation Tools
Tool Name | Key Parameters | Description |
|
| Creates drawing primitives on chart: |
| none | Lists all user drawings currently active on chart with IDs and coordinates. |
|
| Reads styling, color, line width, and coordinates of an existing drawing. |
|
| Deletes a specific drawing by ID. |
| none | Clears all user drawings from chart. |
UI Automation & Event Simulation Tools
Tool Name | Key Parameters | Description |
|
| Clicks a TradingView UI element matching selector strategy (aria-label, data-name, text, class-contains). |
|
| Opens, closes, or toggles bottom dock panels (pine-editor, strategy-tester, watchlist, alerts, trading). |
| none | Toggles chart full-screen view. |
| none | Lists saved chart layouts in user profile with layout names and IDs. |
|
| Switches active workspace to another saved layout by name or ID. |
|
| Dispatches native keyboard event (e.g., shortcuts like Enter, Escape, Ctrl+Z). |
|
| Types text characters directly via CDP Input domain into currently focused element. |
|
| Dispatches mouse move event to hover over element and trigger tooltips. |
|
| Dispatches mouse wheel scroll events across chart canvas or page. |
|
| Clicks exact pixel coordinates on window viewport. |
|
| Locates UI element and returns bounding box coordinates. |
|
| Evaluates arbitrary JavaScript expression in page context for low-level automation. |
Multi-Pane & Tab Orchestration Tools
Tool Name | Key Parameters | Description |
| none | Lists split-view chart panes in multi-chart layouts with symbols and active state. |
|
| Configures multi-pane grid layout. |
|
| Switches active focus to a specific chart pane by index (0-based). |
|
| Sets symbol on a specific pane without changing focus. |
| none | Lists all open TradingView Desktop window tabs. |
| none | Opens a new desktop tab. |
| none | Closes the currently active desktop tab. |
|
| Switches active window focus to target tab by index. |
Alerts & Watchlist Management Tools
Tool Name | Key Parameters | Description |
|
| Opens TradingView alert dialog and creates price alert. |
| none | Scrapes active alert triggers and configurations from Alert panel. |
|
| Deletes alerts via context menu. |
| none | Scrapes all symbols and quote changes from active watchlist. |
|
| Adds a symbol to current watchlist. |
Bar Replay & Simulation Engine Tools
Tool Name | Key Parameters | Description |
|
| Enters Bar Replay mode at a historical start timestamp. |
| none | Advances replay forward by exactly one bar. |
|
| Toggles automatic bar playback with speed configuration. |
|
| Executes simulated market order in replay session. |
| none | Returns current bar timestamp and position in replay. |
| none | Exits replay mode and restores real-time feed. |
Diagnostics, Health & Session Persistence Tools
Tool Name | Key Parameters | Description |
| none | Verifies CDP connection liveness, page responsiveness, and port binding. |
| none | Scans local machine for open Chrome DevTools debugging targets. |
| none | Detects visible dialogs, active bottom panels, and error modals. |
|
| Automatically locates and starts TradingView Desktop with |
|
| Executes an analytical action sequentially across multiple symbols/resolutions. |
|
| Captures lossless screenshot to disk and returns local file path (not base64, preserving tokens). |
|
| Programmatically overrides settings (length, smoothing) of an indicator. |
|
| Toggles visibility of an indicator on canvas. |
|
| Generates a multi-asset market opening briefing. |
|
| Serializes current chart view, indicators, and symbols to local session file. |
|
| Restores a saved workspace state. |
🚀 Installation & Quickstart
1. Prerequisites
Node.js: v18.0.0 or higher
TradingView Desktop: Installed on Windows, macOS, or Linux
2. Install Dependencies
git clone https://github.com/MohamedAmineBenGhouizia/trading-view-mcp.git
cd trading-view-mcp
npm install3. Build Executable Shim
npm run buildThis generates build/index.js with proper executable permissions (0o755).
4. Launch TradingView Desktop with Remote Debugging
TradingView Desktop must run with the Chrome DevTools Protocol port enabled (9222).
Windows
# Default installation path
& "$env:LOCALAPPDATA\Programs\TradingView\TradingView.exe" --remote-debugging-port=9222
# Or if installed in custom directory:
& "C:\Users\<YourUser>\Downloads\TradingView\TradingView.exe" --remote-debugging-port=9222macOS
/Applications/TradingView.app/Contents/MacOS/TradingView --remote-debugging-port=9222Linux
tradingview --remote-debugging-port=9222Automated Startup: Alternatively, call the
tv_launchtool or runnode bin/tv.js launch, which searches standard process tables and file paths to start TradingView automatically.
🚀 Antigravity Integration
TradingView MCP integrates seamlessly into Google Antigravity and Gemini Code Assist as a native Model Context Protocol provider.
1. Configuration Path
Antigravity discovers MCP servers from either the user global configuration or project workspace configuration:
Global Config:
~/.gemini/config/mcp_config.json(or%USERPROFILE%\.gemini\config\mcp_config.jsonon Windows)Symbolic Link:
~/.gemini/antigravity/mcp_config.jsonIDE Config:
~/.gemini/antigravity-ide/mcp_config.json
2. Canonical Server Definition
Ensure your mcp_config.json registers tradingview-mcp-jackson pointing to the canonical src/server.js entrypoint:
{
"mcpServers": {
"tradingview-mcp-jackson": {
"command": "node",
"args": [
"/absolute/path/to/trading-view-mcp/src/server.js"
],
"env": {
"DEBUG_TV_MCP": "false"
}
}
}
}(On Windows, use forward slashes or escaped backslashes, e.g. C:/Users/<Username>/Downloads/development/tradingview-mcp-jackson/src/server.js).
3. Prerequisites & CDP Requirements
Runtime: Node.js
>= 18.0.0available on system PATH.Port Exposure: TradingView Desktop must be launched with
--remote-debugging-port=9222.Chart Tab: Ensure at least one chart tab is open on
tradingview.com/chart/within the desktop app.
4. How to Verify Connection in Antigravity
When Antigravity starts or refreshes its tool environment:
It reads
mcp_config.jsonand startsnode src/server.js.The server outputs its initial warning banners to
stderr, keepingstdoutcompletely clean for standard JSON-RPC 2.0 messages.Antigravity performs the protocol handshake and automatically lists and registers lazy tool schemas in
~/.gemini/antigravity/mcp/tradingview-mcp-jackson/*.json.
To smoke-test the live integration directly within Antigravity or a terminal:
node scripts/smoke_test.jsExpected output:
✓ Initialize succeeded. Server: tradingview v2.1.0
✓ tools/list succeeded. Discovered 89 registered MCP tools.
✓ Verified presence of all mandatory tools in tool catalog.
✓ pine_analyze executed cleanly: success=true, issues=0
✓ SMOKE TEST COMPLETE: All MCP handshake, tool discovery, and tool call verifications passed.5. Troubleshooting Antigravity Connections
Issue | Underlying Cause | Resolution |
| Tool schema missing in | Run |
| TradingView Desktop not started with remote debugging | Launch with |
| Chart was navigating while an agent tool executed | Safe retryable condition; retry the tool call after 100ms. |
| Node.js syntax error or bad file path in config | Run |
🔌 MCP Client Configurations
Canonical Runtime Entrypoint
The canonical runtime entrypoint for all clients is src/server.js.
(Note: build/index.js is also maintained as an executable forwarder for backwards compatibility).
Claude Desktop
Add to your claude_desktop_config.json:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"tradingview": {
"command": "node",
"args": [
"/path/to/trading-view-mcp/src/server.js"
]
}
}
}Cursor IDE
Add to Cursor Settings ➔ Features ➔ MCP Servers ➔ Add New MCP Server:
Name:
tradingviewType:
commandCommand:
node /path/to/trading-view-mcp/src/server.js
VS Code / Cline / Roo Code
In .vscode/cline_mcp_settings.json:
{
"mcpServers": {
"tradingview": {
"command": "node",
"args": ["/path/to/trading-view-mcp/src/server.js"]
}
}
}💻 CLI Reference
The repository provides a standalone CLI binary (bin/tv.js) for scripting, CI pipelines, and manual testing.
# Print general help and available commands
node bin/tv.js --help
# Perform offline static analysis of a Pine Script file
node bin/tv.js pine analyze --file ./strategies/momentum.pine
# Headless compilation check via TradingView cloud compiler
node bin/tv.js pine check --file ./strategies/momentum.pine
# Fetch real-time OHLCV data summary
node bin/tv.js ohlcv --count 50 --summary
# Fetch real-time quote for a symbol
node bin/tv.js quote BTCUSD
# Launch TradingView Desktop with CDP enabled
node bin/tv.js launch --port 9222🧪 Verification & Test Architecture
The repository enforces a non-skipping, deterministic test pyramid with 100% automated verification.
┌────────────────────────┐
│ E2E Tests (79) │ Full Live TradingView Desktop Test
│ (tests/e2e.test.js) │ CDP Automation, UI, Monaco, Replay
└───────────┬────────────┘
│
┌───────────┴────────────┐
│ Integration Tests (3) │ Market Context Orchestration,
│(tests/integration.js) │ MTF Synthesis, Error Contracts
└───────────┬────────────┘
│
┌────────────────────┴────────────────────┐
│ Unit Test Suites (79) │
├─────────────────────────────────────────┤
│ • Technical Indicators & Math (11 tests)│
│ • Concurrency & Mutex Queue (6 tests) │
│ • Chaos & Cross-Contamination (5 tests) │
│ • Pine Static Analysis (13 tests) │
│ • Headless Cloud Compiler (3 tests) │
│ • Market Structure & Regimes (7 tests) │
│ • State Manager & Generational Cache (7)│
│ • Security JS Serialization (2 tests) │
│ • Error Contract Standards (5 tests) │
│ • Zones, Profiles & Divergences (3) │
│ • CLI Help & Flag Routing (13 tests) │
└─────────────────────────────────────────┘Available Test Scripts
Script | Command | Purpose |
|
| Syntactic validation of all 87 source and test files using |
|
| Deterministically generates |
|
| Runs all 12 isolated unit test suites (no external dependencies). |
|
| Validates multi-step market intelligence pipelines and error envelopes. |
|
| Verifies command routing and static analyzer CLI flags. |
|
| Executes all 82 unit, integration, and chaos test suites in sequence. |
|
| Runs all 79 live E2E tests against TradingView Desktop on port 9222. |
|
| One-shot CI/CD gatekeeper: runs |
🧠 Agent Workflow Best Practices
When integrating this MCP server into autonomous LLM agents, adhere to the following workflow patterns:
Pattern 1: Initial Chart Orientation
1. Call `market_get_context(expectedSymbol="BTCUSD", expectedTf="60")`
└── Receives trend, regime, RSI, MACD, structure (BOS/CHoCH), and S/R zones.
2. If state is STALE_CHART_STATE:
└── Retry after 100ms (chart transition was in progress).
3. Formulate analysis or trading plan based on confirmed closed bars.Pattern 2: Multi-Timeframe Consensus
1. Call `market_compare_timeframes(timeframes=["D", "240", "60", "15"])`
└── Evaluates higher-timeframe trend vs lower-timeframe entry trigger.
2. Inspect `alignment`: check whether momentum and structure agree.Pattern 3: Pine Script Iterative Development Loop
1. Call `pine_get_source` to read existing script.
2. Formulate improvements or fixes.
3. Call `pine_smart_compile(source=code)`
└── Injects code into Monaco editor and checks for compiler errors.
4. If errors returned:
└── Inspect line numbers and error strings, repair code, and re-compile.
5. If success:
└── Call `data_get_strategy_results` to evaluate backtest P&L and Sharpe ratio.Pattern 4: Low-Token Monitoring
1. Call `market_get_recent_changes(sinceTimestamp=lastPollTime)`
└── Emits only new swing points, confirmed BOS events, or volume anomalies.
└── Consumes minimal context window tokens.❓ Troubleshooting & FAQ
Q: Error: "Could not connect to TradingView via CDP (port 9222)"
Cause: TradingView Desktop is either not running or was launched without the
--remote-debugging-port=9222flag.Fix: Run
tv_launchvia MCP, or terminate TradingView and start it from terminal with--remote-debugging-port=9222. Ensure no conflicting browser is using port 9222.
Q: Error: "[Queue_BACKPRESSURE] Task queue backlog exceeded max depth"
Cause: The AI agent issued more than 100 concurrent asynchronous tool calls without awaiting responses.
Fix: Ensure your agent uses sequential or bounded parallel tool calling. The AsyncQueue prevents memory leaks by shedding excess tasks.
Q: Error: "OHLCV data symbol mismatch: expected AAPL, got BTCUSD"
Cause:
data_get_ohlcvwas invoked withexpectedSymbol="AAPL", but the chart was still rendering"BTCUSD".Fix: The tool's anti-cross-contamination guard worked as intended. The agent should call
chart_set_symbol("AAPL")and await completion before requesting bars.
Q: How do I read lines and levels drawn by my custom indicator?
Fix: Use
data_get_pine_lineswithstudy_filter="<IndicatorName>". The tool inspects TradingView's internal_graphicsprimitives and returns clean, deduplicated price levels.
📝 License
This project is licensed under the MIT License. See LICENSE for details. Based on architectural foundations by [@tradesdontlie] and [LewisWJackson], re-engineered for high-performance agentic autonomy.
Available Tools
90 toolsalert_createA
Open the TradingView alert configuration dialog and create a server-side price alert. WHEN TO USE: Call when setting conditional triggers on price levels (crossing, greater_than, less_than). SIDE EFFECTS: STATE_MUTATING (Creates an active alert in user account). LIMITATIONS: Requires market symbol to be active.
Inputs: price (required), condition (required), message.
alert_deleteA
Delete active alerts from TradingView alerts list. WHEN TO USE: Call when removing triggered, obsolete, or batch alerts. SIDE EFFECTS: STATE_MUTATING (Deletes alerts from user account). LIMITATIONS: Pass delete_all: true to clear all alerts.
Inputs: delete_all.
alert_listA
List all active and triggered alerts from the TradingView alerts panel. WHEN TO USE: Call to inspect currently active alert triggers or verify created alerts. SIDE EFFECTS: None (Read-only). LIMITATIONS: Reads alerts visible in alerts dock.
Inputs: no named parameters.
batch_runA
Execute a sequential analytical action across an array of symbols and timeframes (actions: "screenshot", "get_ohlcv", "get_strategy_results"). WHEN TO USE: Call when running automated screening, batch chart captures, or cross-asset data collection. SIDE EFFECTS: STATE_MUTATING (Sequentially navigates chart symbols/timeframes; action may write screenshot files). LIMITATIONS: Runs sequentially with configurable inter-iteration delay.
Inputs: action (required), symbols (required), delay_ms, timeframes, +1 more.
capture_screenshotA
Capture lossless PNG screenshot of TradingView window and save locally to disk (regions: "full", "chart", "strategy_tester"). Returns local filesystem path to prevent token exhaustion from raw base64. WHEN TO USE: Call when visual verification of chart patterns, drawings, or UI layout is requested by the user. SIDE EFFECTS: EXTERNAL_SIDE_EFFECT (Writes PNG image file to local screenshots directory). LIMITATIONS: Requires TradingView window to be rendered on screen.
Inputs: method, region, filename.
chart_get_multi_timeframeA
Perform atomic sequential multi-timeframe scan across multiple resolutions (e.g., D, 240, 60, 15, 5) without race conditions. WHEN TO USE: Call when needing raw OHLCV bars across several timeframes in a single coordinated operation. SIDE EFFECTS: None (Read-only - safely preserves original chart state). LIMITATIONS: Changes resolution sequentially, restoring original state upon completion.
Inputs: count, symbol, timeframes.
chart_get_snapshotA
Get authoritative atomic snapshot of chart state (symbol, resolution, lastBarTime, barCount, generation ID). WHEN TO USE: Call to verify state freshness or obtain atomic synchronization metadata without pulling full bar series. SIDE EFFECTS: None (Read-only). LIMITATIONS: Lightweight snapshot only.
Inputs: no named parameters.
chart_get_stateA
Get current chart state including active symbol, timeframe resolution, chart rendering type, and list of attached indicator study entities with their IDs. WHEN TO USE: Call to inspect the current chart configuration or retrieve indicator entity IDs prior to calling chart_manage_indicator or indicator_set_inputs. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires an active chart window.
Inputs: no named parameters.
chart_get_state_diagnosticsA
Get authoritative diagnostic state of chart, generation ID, CDP connection status, and task queue depths. WHEN TO USE: Call whenever diagnosing connection liveness, queue backpressure, or verifying generation freshness. NO SIDE EFFECTS.
Inputs: no named parameters.
chart_get_visible_rangeA
Get visible date range (unix timestamps in seconds) and bar index boundaries currently displayed on the viewport. WHEN TO USE: Call before capturing screenshots or inspecting what portion of the historical timeline is in user view. SIDE EFFECTS: None (Read-only). LIMITATIONS: Depends on active screen width and zoom level.
Inputs: no named parameters.
chart_manage_indicatorA
Add or remove a built-in or public indicator/study on the active chart. WHEN TO USE: Call to attach technical studies (e.g., "Relative Strength Index", "Bollinger Bands") or remove studies using their entity_id from chart_get_state. SIDE EFFECTS: STATE_MUTATING (Modifies chart study collection). LIMITATIONS: Must use full official TradingView indicator names (e.g., "Relative Strength Index", not "RSI").
Inputs: action (required), indicator (required), inputs, entity_id.
chart_scroll_to_dateA
Jump the chart viewport to center on a specific historical calendar date or timestamp. WHEN TO USE: Call to navigate directly to a past macroeconomic release, news event, or breakout bar. SIDE EFFECTS: STATE_MUTATING (Scrolls chart canvas). LIMITATIONS: Historical data for the specified date must be available.
Inputs: date (required).
chart_set_symbolA
Change the active chart symbol and wait for market data feed confirmation. WHEN TO USE: Call to navigate the chart to a new financial instrument before performing analysis or running strategies. SIDE EFFECTS: STATE_MUTATING (Alters active chart ticker, increments state generation, invalidates generational cache). LIMITATIONS: Requires valid TradingView ticker format (e.g., "BTCUSD", "AAPL", "ES1!", "NYMEX:CL1!").
Inputs: symbol (required).
chart_set_timeframeA
Change the chart timeframe/resolution and reactively wait for candle feed resolution. WHEN TO USE: Call when switching resolutions for multi-timeframe analysis (e.g., switching from 1D to 15m). SIDE EFFECTS: STATE_MUTATING (Alters chart resolution, increments state generation, invalidates generational cache). LIMITATIONS: Supported formats include standard minutes ("1", "5", "15", "60", "240") and calendar periods ("D", "W", "M").
Inputs: timeframe (required).
chart_set_typeA
Change chart candle rendering type (Bars, Candles, Line, Area, Renko, HeikinAshi, etc.). WHEN TO USE: Call when specific analysis requires alternate bar representations (e.g., Heikin Ashi for trend smoothing). SIDE EFFECTS: STATE_MUTATING (Modifies chart canvas display mode). LIMITATIONS: Accepts chart type name or numeric index.
Inputs: chart_type (required).
chart_set_visible_rangeA
Zoom and pan the chart canvas to display a specific date range between two unix timestamps. WHEN TO USE: Call when focusing chart context on a specific historical event or earnings release. SIDE EFFECTS: STATE_MUTATING (Alters chart viewport zoom/pan). LIMITATIONS: Timestamps must be unix seconds within historical data range.
Inputs: to (required), from (required).
data_get_equityA
Extract equity curve data points from Strategy Tester. WHEN TO USE: Call when analyzing equity drawdowns, run-ups, or plotting performance trajectory over backtest span. SIDE EFFECTS: None (Read-only). LIMITATIONS: Strategy Tester must be active on chart.
Inputs: no named parameters.
data_get_indicatorA
Get internal study parameters, input values, and configuration of a specific indicator entity by ID. WHEN TO USE: Call to inspect active parameters (e.g., RSI length or MA source) for an indicator found in chart_get_state. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires valid entity ID.
Inputs: entity_id (required).
data_get_ohlcvA
Get historical OHLCV bar data from active chart. Supports compact statistical summary mode (summary: true) for context efficiency, and closed-only filtering (closedOnly: true) to avoid unconfirmed candle hallucinations. WHEN TO USE: Call when computing quantitative models or inspecting raw price action. Use summary: true when only high/low/close bounds are needed to conserve token context. SIDE EFFECTS: None (Read-only). LIMITATIONS: Maximum 500 bars per request.
Inputs: count, summary, closedOnly, expectedTf, +1 more.
data_get_pine_boxesA
Read bounding boxes and zones drawn by Pine Script indicators (box.new) as deduplicated {high, low} price ranges. WHEN TO USE: Call when an indicator plots order blocks, fair value gaps, or consolidation boxes via box.new. SIDE EFFECTS: None (Read-only). LIMITATIONS: Only reads box primitives generated by active studies.
Inputs: verbose, study_filter.
data_get_pine_labelsA
Read text annotations and labels drawn by Pine Script indicators (label.new) paired with price coordinates. WHEN TO USE: Call when an indicator displays bias markers, order block tags, or targets via label.new. SIDE EFFECTS: None (Read-only). LIMITATIONS: Only reads labels currently existing in chart memory.
Inputs: verbose, max_labels, study_filter.
data_get_pine_linesA
Read horizontal price levels drawn programmatically by Pine Script indicators (line.new). Returns deduplicated, sorted price levels per study. WHEN TO USE: Call when an indicator draws support/resistance or session levels via line.new. Use study_filter to target specific scripts. SIDE EFFECTS: None (Read-only). LIMITATIONS: Only reads lines drawn by active Pine studies.
Inputs: verbose, study_filter.
data_get_pine_tablesA
Read table matrices drawn by Pine Script indicators (table.new) as structured rows of text. WHEN TO USE: Call when an indicator outputs dashboard summaries, session statistics, or multi-timeframe matrices in a table. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires study drawing table.new to be attached.
Inputs: study_filter.
data_get_strategy_resultsA
Extract performance metrics from the TradingView Strategy Tester panel (Net Profit, Profit Factor, Win Rate, Max Drawdown, Total Trades, Sharpe Ratio). WHEN TO USE: Call after compiling a Pine Script strategy to evaluate quantitative backtest results. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires a strategy script to be actively running on the chart with Strategy Tester panel populated.
Inputs: no named parameters.
data_get_study_valuesA
Extract real-time numerical values of all visible indicators from the chart Data Window (RSI, MACD, EMAs, custom plot() outputs). WHEN TO USE: Call when reading current indicator values directly from TradingView without recomputing in Node.js. SIDE EFFECTS: None (Read-only). LIMITATIONS: Indicators must be visible on chart.
Inputs: no named parameters.
data_get_tradesA
Extract individual trade execution log from Strategy Tester (entry/exit times, prices, contracts, P&L). WHEN TO USE: Call when conducting granular trade-by-trade review or streak analysis of a backtested Pine strategy. SIDE EFFECTS: None (Read-only). LIMITATIONS: Strategy Tester bottom panel must have trade list populated.
Inputs: max_trades.
depth_getA
Extract order book / Depth of Market (DOM) bid/ask levels from the DOM panel. WHEN TO USE: Call when analyzing order book liquidity or bid-ask imbalance. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires DOM panel to be open in TradingView.
Inputs: no named parameters.
draw_clearA
Remove all user drawing shapes and annotations from the active chart canvas. WHEN TO USE: Call when resetting or cleaning the chart canvas before drawing a fresh analysis template. SIDE EFFECTS: STATE_MUTATING (Deletes all user drawings on canvas). LIMITATIONS: Irreversible removal of canvas drawings.
Inputs: no named parameters.
draw_get_propertiesA
Get styling properties, line colors, line width, and coordinate points of an existing drawing shape by entity ID. WHEN TO USE: Call when inspecting or confirming coordinates of an annotated price level. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires entity ID from draw_list.
Inputs: entity_id (required).
draw_listA
List all user drawing shapes and annotations currently active on the chart with entity IDs, types, and coordinates. WHEN TO USE: Call before modifying or deleting drawings to locate specific drawing IDs. SIDE EFFECTS: None (Read-only). LIMITATIONS: Only reports user drawings, not Pine script drawings.
Inputs: no named parameters.
draw_remove_oneA
Delete a specific drawing shape from the chart canvas by its entity ID. WHEN TO USE: Call when removing an invalid or obsolete level while preserving other drawings. SIDE EFFECTS: STATE_MUTATING (Deletes targeted drawing shape). LIMITATIONS: Requires entity ID obtained from draw_list.
Inputs: entity_id (required).
draw_shapeA
Create and render a graphical drawing primitive on the chart (horizontal_line, vertical_line, trend_line, rectangle, text, ray). WHEN TO USE: Call when annotating key support/resistance levels, chart patterns, breakout zones, or trade entry/target targets visually. SIDE EFFECTS: STATE_MUTATING (Adds drawing primitive to chart canvas). LIMITATIONS: Requires point coordinates in unix timestamp and price values.
Inputs: point (required), shape (required), text, point2, +1 more.
indicator_set_inputsA
Programmatically override input values of an indicator entity (e.g., length, source, period, multiplier). WHEN TO USE: Call when fine-tuning parameters of an attached study without deleting and re-adding it. SIDE EFFECTS: STATE_MUTATING (Alters indicator configuration on chart). LIMITATIONS: Requires study entity ID and valid JSON inputs map.
Inputs: inputs (required), entity_id (required).
indicator_toggle_visibilityA
Show or hide an indicator/study plot on the chart canvas. WHEN TO USE: Call when decluttering the chart view before visual analysis or screenshot capture. SIDE EFFECTS: STATE_MUTATING (Toggles indicator visibility). LIMITATIONS: Requires study entity ID from chart_get_state.
Inputs: visible (required), entity_id (required).
layout_listA
List all saved chart layouts in user profile with layout names and IDs. WHEN TO USE: Call before switching layouts to discover valid layout names. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires user profile to have saved layouts.
Inputs: no named parameters.
layout_switchA
Switch active chart workspace to another saved layout by name or ID. WHEN TO USE: Call when transitioning between specialized analytical layouts (e.g. crypto vs macro). SIDE EFFECTS: STATE_MUTATING (Loads different layout, reloads charts and indicators). LIMITATIONS: Layout name or ID must exist in user account.
Inputs: name (required).
market_compare_timeframesA
Compare market regime, trend direction, momentum (RSI), and volume consensus across multiple timeframes (e.g., 1D, 4H, 1H, 15m, 5m). WHEN TO USE: Call when performing multi-timeframe top-down analysis to identify timeframe alignment or conflicts. NO SIDE EFFECTS.
Inputs: timeframes, candleCount.
market_detect_structureA
Detect deterministic market structure: Swing Highs/Lows, HH/HL/LH/LL classifications, Break of Structure (BOS), Change of Character (CHoCH), and Equilibrium/Range bounds. WHEN TO USE: Call when evaluating trend continuity or structural breakouts. NO SIDE EFFECTS.
Inputs: candleCount.
market_detect_zonesA
Detect objective horizontal support & resistance zones and price consolidation clusters with touch counts and test recency. WHEN TO USE: Call when locating key price levels for take-profit, stop-loss, or reaction areas. NO SIDE EFFECTS.
Inputs: minTouches, candleCount, tolerancePct.
market_get_contextA
Get comprehensive, multi-dimensional market context (trend, regime, key indicators, volume, market structure, and zones) in a single deterministic call. WHEN TO USE: Call when orienting yourself on a ticker/timeframe before planning actions or answering user analysis queries. LIMITATIONS: Requires price bars loaded on chart. NO SIDE EFFECTS.
Inputs: expectedTf, candleCount, includeZones, expectedSymbol, +2 more.
market_get_recent_changesA
Detect structural shifts, new swings, volume spikes, and divergences that occurred since a given timestamp or generation. WHEN TO USE: Call when periodically polling or checking what changed on the chart since your last analysis turn, saving LLM token bandwidth. NO SIDE EFFECTS.
Inputs: sinceTimestamp, sinceGeneration.
market_get_smart_volumeA
Analyze institutional-style market activity proxy (RVOL, robust z-score, Wyckoffian effort vs result, absorption, initiative moves, exhaustion, sweeps, and accumulation/distribution). WHEN TO USE: Call when evaluating volume anomalies, liquidity sweeps, or market participation conviction. NO SIDE EFFECTS. LIMITATIONS: On CFD/Forex feeds (like OANDA:XAUUSD), volume reflects tick activity rather than centralized transaction contracts; activity is inferred/heuristic.
Inputs: session, lookback, expectedTf, sensitivity, +2 more.
morning_briefA
Scan user watchlist, read indicator values across symbols, and extract structured market data for a pre-market or daily briefing according to rules.json. WHEN TO USE: Call at the start of a trading day to synthesize cross-asset market bias and momentum. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires rules.json in workspace or specified via rules_path.
Inputs: rules_path.
pane_focusA
Switch active user focus to a specific chart pane by index (0-based). WHEN TO USE: Call before executing chart operations targeted at a secondary pane in a multi-chart layout. SIDE EFFECTS: STATE_MUTATING (Changes active chart focus). LIMITATIONS: Index must be valid within pane_list.
Inputs: index (required).
pane_listA
List all chart panes in the current split-view workspace with their active symbols, resolutions, and focus state. WHEN TO USE: Call before manipulating multi-chart layouts to discover pane indices. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires multi-chart layout active to list multiple panes.
Inputs: no named parameters.
pane_set_layoutA
Change the chart grid layout grid (e.g., single "s", "2h", "2v", "4" quad grid). WHEN TO USE: Call when configuring multi-chart views for correlated assets or multi-timeframe monitoring. SIDE EFFECTS: STATE_MUTATING (Alters window grid division and creates/destroys chart panes). LIMITATIONS: Layout codes: s, 2h, 2v, 2-1, 1-2, 3h, 3v, 4, 6, 8.
Inputs: layout (required).
pane_set_symbolA
Set financial ticker symbol directly on a specific pane index without changing active focus. WHEN TO USE: Call when populating multi-pane grids with correlated tickers (e.g. BTCUSD on pane 0, ETHUSD on pane 1). SIDE EFFECTS: STATE_MUTATING (Changes symbol on target pane). LIMITATIONS: Target pane index must exist.
Inputs: index (required), symbol (required).
pine_analyzeA
Run offline static analysis on Pine Script source code: detects array out-of-bounds, unguarded array.get/first/last, invalid loop ranges, lookahead bias, and deprecated syntax. WHEN TO USE: Call before compiling code to verify correctness without needing a live TradingView connection. SIDE EFFECTS: None (Read-only offline parser). LIMITATIONS: Static AST parsing only; does not execute runtime logic.
Inputs: source (required).
pine_checkA
Compile Pine Script via TradingView remote compiler API without touching the UI. Returns compilation errors and warnings. WHEN TO USE: Call for headless validation of Pine Script code before opening editor or chart. SIDE EFFECTS: EXTERNAL_SIDE_EFFECT (Sends code to TradingView cloud compiler endpoint). LIMITATIONS: Requires active internet connection to reach TradingView servers.
Inputs: source (required).
pine_compileA
Trigger compilation ("Add to Chart" or "Save & Update") for the script currently in the Pine Editor. WHEN TO USE: Call after setting source code to apply the indicator or strategy to the chart canvas. SIDE EFFECTS: STATE_MUTATING (Attaches or updates study/strategy on chart canvas). LIMITATIONS: Pine Editor must be open with code loaded.
Inputs: no named parameters.
pine_get_consoleA
Read runtime logs and compiler messages from the Pine Editor console window (e.g., log.info(), log.error(), log.warning()). WHEN TO USE: Call when debugging Pine Script runtime behavior or inspecting custom log outputs. SIDE EFFECTS: None (Read-only). LIMITATIONS: Console output must be enabled in the script.
Inputs: no named parameters.
pine_get_errorsA
Retrieve compiler error messages, line numbers, and syntax markers from Monaco editor model. WHEN TO USE: Call immediately after compilation if errors occur to pinpoint line numbers and syntax issues. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires Pine Editor to be open.
Inputs: no named parameters.
pine_get_sourceA
Get current Pine Script source code from the active TradingView Monaco editor model. WHEN TO USE: Call before refactoring, fixing errors, or saving an existing Pine script. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires Pine Editor bottom dock panel to be open.
Inputs: no named parameters.
pine_list_scriptsA
List all user-saved Pine Scripts in TradingView personal library. WHEN TO USE: Call to inspect available saved scripts before opening one with pine_open. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires user to be logged in to TradingView.
Inputs: no named parameters.
pine_newA
Create a new blank Pine Script draft in the editor from a standard template (indicator, strategy, or library). WHEN TO USE: Call when starting a new script from scratch rather than modifying existing code. SIDE EFFECTS: STATE_MUTATING (Clears current editor and loads starter template). LIMITATIONS: Unsaved changes in active editor will be overwritten.
Inputs: type (required).
pine_openA
Open a saved Pine Script from user library by name. WHEN TO USE: Call to load a specific user script into the Pine Editor. SIDE EFFECTS: STATE_MUTATING (Loads chosen script into editor). LIMITATIONS: Script name must match a script in user library.
Inputs: name (required).
pine_saveA
Save the current Pine Script to user library via keyboard shortcut (Ctrl+S / Cmd+S). WHEN TO USE: Call when persisting edits to a saved script in TradingView cloud storage. SIDE EFFECTS: STATE_MUTATING (Saves script changes to user account). LIMITATIONS: Requires Pine Editor to be active.
Inputs: no named parameters.
pine_set_sourceA
Inject Pine Script source code directly into the active Monaco editor model. WHEN TO USE: Call when deploying new Pine Script code, applying bug fixes, or loading templates. SIDE EFFECTS: STATE_MUTATING (Replaces entire Monaco editor text buffer). LIMITATIONS: Requires Pine Editor panel to be open.
Inputs: source (required).
pine_smart_compileA
Execute atomic developer compilation loop: detects appropriate compile button, triggers build, polls for Monaco markers, and reports compile status. WHEN TO USE: Preferred tool for compiling Pine Script code directly into the active chart. SIDE EFFECTS: STATE_MUTATING (Modifies chart study state). LIMITATIONS: Requires Pine Editor panel to be open.
Inputs: no named parameters.
quote_getA
Get real-time market quote snapshot for a ticker (last price, day open/high/low/close, change %, volume). WHEN TO USE: Call for quick price checks without loading historical bar series. SIDE EFFECTS: None (Read-only). LIMITATIONS: Uses current chart ticker if symbol omitted.
Inputs: symbol.
replay_autoplayA
Toggle automatic bar playback in replay mode with configurable speed. WHEN TO USE: Call when letting historical playback run continuously at set speed. SIDE EFFECTS: STATE_MUTATING (Starts or pauses replay autoplay). LIMITATIONS: Requires Replay mode to be active.
Inputs: speed.
replay_startA
Enter TradingView Bar Replay mode at a specified historical date or first available bar. WHEN TO USE: Call when initiating historical simulated forward-testing or practicing trade executions bar by bar. SIDE EFFECTS: STATE_MUTATING (Switches chart into Replay mode, rewinds visible price action). LIMITATIONS: Requires market symbol with historical data at chosen date.
Inputs: date.
replay_statusA
Get current status of Bar Replay mode (active, current replay timestamp, position). WHEN TO USE: Call to check whether chart is currently in replay mode and what timestamp is displaying. SIDE EFFECTS: None (Read-only). LIMITATIONS: None.
Inputs: no named parameters.
replay_stepA
Advance replay forward by exactly one candle bar. WHEN TO USE: Call during manual forward simulation to reveal subsequent market price action step by step. SIDE EFFECTS: STATE_MUTATING (Advances replay state by one bar). LIMITATIONS: Requires Replay mode to be active.
Inputs: no named parameters.
replay_stopA
Exit Replay mode and restore the live real-time chart data feed. WHEN TO USE: Call when finishing simulation practice to return chart to current live market conditions. SIDE EFFECTS: STATE_MUTATING (Exits replay mode and jumps to live feed). LIMITATIONS: Closes any active replay session.
Inputs: no named parameters.
replay_tradeA
Execute a simulated trade action in replay mode (buy, sell, or close position). WHEN TO USE: Call when taking practice trades against historical bar replay data. SIDE EFFECTS: STATE_MUTATING (Updates simulated paper trading position in replay). LIMITATIONS: Requires Replay mode to be active.
Inputs: action (required).
session_getA
Retrieve archived session briefing from local session history. Returns today's brief if available, otherwise previous session. WHEN TO USE: Call when reviewing past daily biases or comparing today's price action against previous morning briefings. SIDE EFFECTS: None (Read-only filesystem read). LIMITATIONS: Requires previously saved session file.
Inputs: date.
session_saveA
Save generated session brief markdown or analysis summary to local session archive (~/.tradingview-mcp/sessions/YYYY-MM-DD.json). WHEN TO USE: Call after completing a morning briefing or daily market analysis to archive observations for future reference. SIDE EFFECTS: EXTERNAL_SIDE_EFFECT (Writes session JSON file to local disk). LIMITATIONS: None.
Inputs: brief (required), date.
symbol_infoA
Get comprehensive instrument metadata for the active symbol (ticker name, exchange, instrument type, tick size, currency, market hours). WHEN TO USE: Call when determining tick precision, pip calculation rules, or exchange session times. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires an active instrument loaded on chart.
Inputs: no named parameters.
symbol_searchA
Search TradingView database for symbols, exchanges, and financial instruments matching a keyword query. WHEN TO USE: Call to resolve ambiguous ticker names or locate the exact exchange ticker (e.g. searching "crude oil" or "ES"). SIDE EFFECTS: None (Read-only). LIMITATIONS: Relies on TradingView symbol search backend.
Inputs: query (required), type.
tab_closeA
Close the currently active chart tab in TradingView Desktop. WHEN TO USE: Call when finished with a temporary workspace tab to release system memory. SIDE EFFECTS: STATE_MUTATING (Closes active tab). LIMITATIONS: Will not close window if only one tab remains.
Inputs: no named parameters.
tab_listA
List all open TradingView desktop application tabs with index, title, and active focus status. WHEN TO USE: Call before managing application tabs to locate specific tab indices. SIDE EFFECTS: None (Read-only). LIMITATIONS: Operates across TradingView Desktop tabs.
Inputs: no named parameters.
tab_newA
Open a new chart tab in TradingView Desktop window. WHEN TO USE: Call when opening a fresh chart workspace without disrupting the current tab. SIDE EFFECTS: STATE_MUTATING (Creates new desktop window tab). LIMITATIONS: TradingView Desktop must support multi-tab mode.
Inputs: no named parameters.
tab_switchA
Switch active desktop window focus to a target tab by index (0-based). WHEN TO USE: Call when toggling between multiple open chart tabs. SIDE EFFECTS: STATE_MUTATING (Changes active tab focus). LIMITATIONS: Index must be valid within tab_list.
Inputs: index (required).
tv_discoverA
Inspect and discover available TradingView internal API paths, chart widgets, and exposed methods in the active window context. WHEN TO USE: Call when debugging Charting API availability or probing supported internal features. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires an active, loaded chart page.
Inputs: no named parameters.
tv_health_checkA
Verify CDP connection liveness to TradingView Desktop and return active chart state. WHEN TO USE: Call at session start or when diagnosing connectivity failures before attempting chart commands. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires TradingView Desktop running with remote debugging enabled on port 9222.
Inputs: no named parameters.
tv_launchA
Launch TradingView Desktop with Chrome DevTools Protocol (remote debugging) enabled on target port. Auto-detects executable path across Windows, macOS, and Linux. WHEN TO USE: Call automatically when tv_health_check fails due to TradingView not running. SIDE EFFECTS: EXTERNAL_SIDE_EFFECT (Spawns desktop application process, optionally terminates existing instances). LIMITATIONS: Requires TradingView Desktop to be installed on the local system.
Inputs: port, kill_existing.
tv_ui_stateA
Get real-time UI state of TradingView window: detects open/closed bottom panels, visible dialogs, active tabs, and enabled control buttons. WHEN TO USE: Call before interacting with UI panels (Pine Editor, Strategy Tester) to ensure target DOM elements are present. SIDE EFFECTS: None (Read-only). LIMITATIONS: Assumes standard desktop window hierarchy.
Inputs: no named parameters.
ui_clickA
Click a TradingView DOM element matching selector strategy (aria-label, data-name, text, class-contains). WHEN TO USE: Call when interacting with custom buttons, dropdowns, or navigation elements not covered by high-level tools. SIDE EFFECTS: STATE_MUTATING (Dispatches click event to DOM element). LIMITATIONS: Target element must be present in DOM.
Inputs: by (required), value (required).
ui_evaluateA
Evaluate arbitrary JavaScript expression directly in the TradingView page context. WHEN TO USE: Call for specialized low-level browser automation or retrieving unexposed DOM properties. SIDE EFFECTS: STATE_MUTATING (Arbitrary JavaScript execution in page context). LIMITATIONS: Advanced tool; expressions run within page sandbox.
Inputs: expression (required).
ui_find_elementA
Locate a UI element by text, aria-label, or CSS selector and return its bounding box coordinates and visibility. WHEN TO USE: Call to verify element existence and obtain coordinates before clicking or hovering. SIDE EFFECTS: None (Read-only DOM query). LIMITATIONS: Scans active DOM tree.
Inputs: query (required), strategy.
ui_fullscreenA
Toggle TradingView window chart fullscreen mode. WHEN TO USE: Call when expanding chart canvas for clean screenshot captures or presentation view. SIDE EFFECTS: STATE_MUTATING (Toggles fullscreen mode). LIMITATIONS: None.
Inputs: no named parameters.
ui_hoverA
Dispatch mouse move event to hover over a UI element matching selector strategy. WHEN TO USE: Call to trigger tooltips, dropdown menus, or interactive hover states. SIDE EFFECTS: STATE_MUTATING (Dispatches mouse move events). LIMITATIONS: Element must be rendered in DOM.
Inputs: by (required), value (required).
ui_keyboardA
Dispatch native keyboard key press or key combination (e.g., Enter, Escape, Alt+S, Ctrl+Z) via CDP Input domain. WHEN TO USE: Call when triggering application keyboard shortcuts or dismissing modals. SIDE EFFECTS: STATE_MUTATING (Dispatches keystroke events to focused window element). LIMITATIONS: Requires appropriate window focus.
Inputs: key (required), modifiers.
ui_mouse_clickA
Dispatch mouse click event at exact pixel coordinates (x, y) on the window canvas. WHEN TO USE: Call when clicking a non-DOM canvas target or specific pixel coordinate. SIDE EFFECTS: STATE_MUTATING (Dispatches mouse click at coordinate). LIMITATIONS: Coordinates must be within viewport bounds.
Inputs: x (required), y (required), button, double_click.
ui_open_panelA
Open, close, or toggle bottom dock panels in TradingView window (pine-editor, strategy-tester, watchlist, alerts, trading). WHEN TO USE: Call before interacting with Pine Editor or Strategy Tester to ensure panel visibility. SIDE EFFECTS: STATE_MUTATING (Alters bottom panel visibility state). LIMITATIONS: Supported panels: pine-editor, strategy-tester, watchlist, alerts, trading.
Inputs: panel (required), action (required).
ui_scrollA
Dispatch mouse wheel scroll events across chart canvas or page in specified direction. WHEN TO USE: Call when scrolling through long lists, logs, or panning canvas. SIDE EFFECTS: STATE_MUTATING (Dispatches wheel events). LIMITATIONS: Default amount is 300px.
Inputs: direction (required), amount.
ui_type_textA
Type text characters directly into currently focused input or textarea element via CDP Input domain. WHEN TO USE: Call when filling out search fields, alert parameters, or text inputs. SIDE EFFECTS: STATE_MUTATING (Inserts text into focused DOM field). LIMITATIONS: Target element must be actively focused.
Inputs: text (required).
watchlist_addA
Add a financial instrument/ticker to the active TradingView watchlist. WHEN TO USE: Call when tracking a newly discovered symbol for continued monitoring. SIDE EFFECTS: STATE_MUTATING (Adds symbol to user watchlist). LIMITATIONS: Symbol must be valid on TradingView.
Inputs: symbol (required).
watchlist_getA
Get all financial symbols from current TradingView watchlist with real-time last price, absolute price change, and percentage change. WHEN TO USE: Call when scanning market watchlists or monitoring asset universe for opportunities. SIDE EFFECTS: None (Read-only). LIMITATIONS: Requires watchlist to have symbols loaded.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 90 tools
Many tools are distinct, but with 90 tools there is notable overlap: multiple state/diagnostic tools (chart_get_state, chart_get_snapshot, chart_get_state_diagnostics, tv_health_check), multiple compile tools (pine_compile, pine_smart_compile, pine_check), and multiple click tools (ui_click, ui_mouse_click). Descriptions with WHEN TO USE help mitigate but ambiguity remains.
Consistent snake_case with prefix_verb_noun pattern across all domains (chart_, pine_, data_, draw_, etc.). Minor variations like get_ vs set_ but consistent within prefixes.
90 tools is excessive for a single MCP server, far beyond the typical 3-15 range. While the domain is complex, many low-level UI automation tools could be consolidated, making the set unwieldy for an agent.
Covers chart manipulation, data extraction, Pine Script editing, drawings, alerts, replay, panes, tabs, layouts, watchlists, session archiving, and market analysis. No obvious gaps in lifecycle coverage for a TradingView automation server.
Related MCP Connectors
Autonomous cloud agent tasks: real browser + your tools, structured evidence-backed results.
Real Chrome for coding agents over MCP: browse, replay playbooks, human takeover, HIPAA & BAA.
Cloud browser, web extraction, screenshots, and remote CDP tools for AI agents.
Guardrails for trading agents. Built-in risk management, 100+ tools for strategy R&D, 12+ venues.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables automated control of TradingView Desktop via Chrome DevTools Protocol with 78+ tools for chart manipulation, Pine Script development, and indicator analysis. Supports automated morning briefs for session bias generation, replay trading practice, and multi-pane layouts with secure local-only data processing.2-
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to interact with TradingView Desktop via Chrome DevTools Protocol for automated morning briefs, chart analysis, Pine script development, and trading workflows.88 npm-
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with TradingView Desktop charts via Chrome DevTools Protocol, supporting chart analysis, Pine Script development, drawing, alerts, and replay automation.-
- FlicenseBqualityCmaintenanceEnables AI-assisted chart analysis, Pine Script development, and live order execution on TradingView Desktop via Chrome DevTools Protocol, supporting connected brokers for trading workflows.97-