logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

tv-chart-retriever-mcp

API endpoint for acquiring visual representations of financial instrument charts from TradingView, specified by ticker and temporal frequency, yielding direct image artifacts suitable for application embedding.

Author

tv-chart-retriever-mcp logo

ertugrul59

MIT License

Quick Info

GitHub GitHub Stars 46
NPM Weekly Downloads 0
Tools 1
Last Updated 2026-02-19

Tags

tradingviewchartapistradingview chartfetch tradingviewchart images

MseeP.ai Security Assessment Badge

Advanced Server for TradingView Chart Visualization

Enhanced Concurrency Achieved: Up to 80% Throughput Gain via Browser Orchestration!

This service exposes interfaces to retrieve high-fidelity chart snapshots from TradingView. It leverages sophisticated browser instance management to dramatically increase parallel processing capabilities.

⚡ Performance Architecture Insights

Browser Instance Pooling

  • Production Core: Utilizes main_optimized.py, employing a sophisticated pool of browser contexts for maximal concurrent throughput.
  • Speed Uplift: Demonstrates 70-80% faster execution times under heavy concurrent load compared to sequential methods.
  • Parallel Capacity: Effectively manages up to 4 concurrent rendering tasks using pre-warmed browser sessions.
  • Performance Benchmarks:
  • Single Fetch: Approximately 6-8 seconds (baseline)
  • Dual Concurrent: ~3-4 seconds per instance (60-70% reduction)
  • Triple Concurrent: ~2.5-3.5 seconds per instance (up to 80% reduction)

Version Differentiation

  • main_optimized.py (Active/Production): Implements browser pooling, concurrency tuning, and internal performance telemetry.
  • main.py (Legacy): Traditional single-browser execution path, retained for historical reference or specific debugging scenarios.

Core Capabilities

  • 📈 Pooled Chart Retrieval: Generates immediate chart image artifact URLs, optimized heavily for concurrent workload management.
  • ⏱️ Telemetry Reporting: Integrated subsystem for monitoring operational statistics and performance gains.
  • 🔄 Context Management: Zero-latency request handling via persistent, ready-to-use browser contexts.
  • 🗣️ Intuitive Query Mapping: Translates human-readable time descriptions into necessary TradingView interval codes.
  • 🔧 Configuration Extensibility: Fully customizable parameters via environmental variables.
  • 🔒 Secure Session Handling: Utilizes session-based authentication credentials for accessing protected TradingView content.
  • 🖼️ Direct Base64 Output: Capability to capture images directly into base64 format for accelerated workflow integration.

Available Utilities

get_tradingview_chart_image

Synopsis: Retrieves the direct Uniform Resource Locator (URL) pointing to a TradingView chart rendering, benefiting from advanced concurrent request handling.

Performance Note: This variant yields a 70-80% performance enhancement when handling multiple simultaneous requests due to active browser context orchestration.

Parameters:

  • ticker (string): The requisite TradingView instrument identifier (e.g., "BYBIT:BTCUSDT.P", "NASDAQ:AAPL"). Mandatory.
  • interval (string): The desired temporal granularity for the chart (e.g., '1', '5', '15', '60', 'D', 'W'). Mandatory.

Returns:

  • (string): A data URI scheme string (e.g., data:image/png;base64,...) or a standard CDN link (https://s3.tradingview.com/snapshots/...).

Exceptions Thrown:

  • Error (MCP Standard): Signifying scraper failure modes:
  • 400: Malformed input parameters (ticker or interval invalid).
  • 503: Scraper execution failure during rendering process.
  • 500: Unforeseen internal server exception.

get_performance_stats

Synopsis: Queries the operational performance metrics gathered by the optimized TradingView service instance.

Returns:

  • Comprehensive statistics detailing request latency, realized improvement over baseline, and current state of the browser cluster.

Illustrative Return Data:

🚀 OPTIMIZED TRADINGVIEW MCP SERVER PERFORMANCE STATS
• Total Requests: 12
• Average Time: 3.30s
• Performance Improvement: 70.8%
• Browsers in Pool: 4
• Max Concurrent: 4

Natural Language Interface Mappings

  • Get the {interval} chart for {ticker}
  • Handles mappings for colloquial time descriptions (e.g., "one minute", "hourly", "daily") to standard TradingView codes.
  • Show me the daily TradingView chart for {ticker}
  • Specifically targets the daily aggregation period ('D').
  • Fetch TradingView chart image for {ticker} on the {interval} timeframe
  • Comprehensive invocation supporting explicit timeframe specification.

Deployment Preparation

  1. Environment Initialization: bash # Navigate to project root cd tradingview-chart-mcp # Create isolated Python environment python3 -m venv .venv
  2. Environment Activation:

    • Unix/Linux/macOS: bash source .venv/bin/activate
    • **Windows (Shells supporting source): bash source .venv/Scripts/activate
    • **Windows (CMD): bash .venv\Scripts\activate.bat
    • **Windows (PowerShell): bash .venv\Scripts\Activate.ps1 (Note: PowerShell execution policy adjustment might be necessary: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser)

    Your shell prompt should now be prefixed with (.venv).

  3. Dependency Installation (Post-Activation): bash pip install -r requirements.txt

  4. Configuration Setup (Local Execution):
    • Duplicate .env.example to .env.
    • Populate .env with your session identifiers (TRADINGVIEW_SESSION_ID and TRADINGVIEW_SESSION_ID_SIGN), obtained from your logged-in browser cookies.
    • Optional scraper parameters (e.g., MCP_SCRAPER_HEADLESS) can be adjusted in .env for local development.
  5. WebDriver Prerequisite: Ensure chromedriver is discoverable within the system PATH, or configure the underlying scraper script if path specification is supported.

Server Execution Modes

Production Optimized Flow

python main_optimized.py

Legacy Fallback Flow

python main.py

Command Line Modifiers

# Listen over HTTP on port 8003
python main_optimized.py --transport streamable-http --port 8003

# Explicitly enable required authentication methods
python main_optimized.py --auth

# Override default concurrency limit
python main_optimized.py --max-concurrent 6

# Force sequential execution (disables pooling)
python main_optimized.py --disable-pooling

🧪 Load Simulation Testing

Test server resilience using agent-emulation scripts located in the tests directory:

cd tests/

# Sequential timing verification (5 iterations)
python test_mcp_agent_style.py --runs 5 --ticker BYBIT:BTCUSDT.P --interval 240

# Test throughput under specified concurrency load
python test_mcp_agent_style.py --concurrent 3 --ticker BYBIT:BTCUSDT.P --interval 240

# Diverse symbol/timeframe concurrent testing
python test_mcp_agent_style.py --concurrent 4 --ticker NASDAQ:AAPL --interval 15
python test_mcp_agent_style.py --concurrent 2 --ticker BYBIT:ETHUSDT.P --interval D

Expected Performance Outcomes

  • Sequential Runs: Average time around 6-8s per artifact.
  • Parallel Load (3x): Latency drops to 2.5-3.5s per artifact (70-80% efficiency gain).
  • Reliability: Targetting 100% success rate under managed load.
  • Capacity: Smooth handling of up to 4 parallel rendering tasks.

⚙️ Internal Mechanisms

Browser Orchestration Strategy

  • Pre-Warming: 4 browser contexts maintained in an active state.
  • Concurrency Safety: Thread-safe access management via appropriate locking primitives.
  • Rate Control: Asynchronous semaphore utilized for precise request throttling.
  • Metrics Capture: Real-time collection of operational timings and resource utilization.
  • Lifecycle Management: Robust procedures for browser initialization and clean shutdown.

Clipboard Capture Feature (MCP_SCRAPER_USE_SAVE_SHORTCUT)

This feature allows the system to write the rendered chart image content directly to the client's clipboard as a base64 encoded Data URL, bypassing external URL retrieval.

Advantages:

  • Speed: Eliminates network overhead associated with downloading image files.
  • Robustness: Decouples final artifact delivery from TradingView's external storage infrastructure.
  • Offline Readiness: Usable once the initial chart page is rendered.
  • Direct Utility: Base64 payload is immediately consumable by subsequent processes.

Configuration Directives:

# Activate base64 clipboard capture (Default behavior)
MCP_SCRAPER_USE_SAVE_SHORTCUT=True

# Revert to traditional screenshot link retrieval
MCP_SCRAPER_USE_SAVE_SHORTCUT=False

Practical Application Examples

Registered Functionality:

  • get_tradingview_chart_image(ticker: str, interval: str): The high-performance, pooled chart retrieval mechanism.

Sample Invocations (Natural Language):

  • "Obtain the chart corresponding to NASDAQ:AAPL on the 15 minute setting."
  • "Display the daily chart visualization for BYBIT:BTCUSDT.P."
  • "Retrieve the visual chart artifact for COINBASE:ETHUSD using the 60 minute cadence."

Terminating the Virtual Environment

To exit the isolated environment:

deactivate

Contingency Procedures

Should the performance-tuned service exhibit instability:

  1. Disable Context Pooling:

bash python main_optimized.py --disable-pooling

  1. Switch to Legacy Implementation:

bash python main.py

  1. Enable Verbose Logging: bash python main_optimized.py --log-level DEBUG

📊 Operational Telemetry

The enhanced server provides continuous monitoring hooks:

  • Request success ratio tracking.
  • Average response latency reporting.
  • Quantification of performance uplift.
  • Real-time browser pool occupancy status.
  • Concurrency handling statistics.

Access these diagnostics via invoking get_performance_stats or reviewing server console output.

🔌 Integration with MCP Clients (Claude/Cursor)

Configuration credentials can be supplied via two primary pathways:

  1. Local File-Based Configuration (.env): Used exclusively when executing the server script directly (e.g., python main.py) for local debugging.
  2. Client-Injected Environment Variables (Recommended for Deployment): When invoked by an MCP host (Claude/Cursor), variables injected by the client take precedence over any settings found in a local .env file.

Integration for Claude Desktop

  1. Locate and edit the Claude Desktop configuration file:
    • Windows: %APPDATA%\Claude\claude_desktop_config.json
    • macOS: ~/Library/Application\ Support/Claude/claude_desktop_config.json
  2. Merge the following structure into the mcpServers section, substituting absolute paths and your credentials:

    json { "mcpServers": { "tradingview-chart-mcp": { "command": "/absolute/path/to/your/tradingview-chart-mcp/.venv/bin/python3", "args": ["/absolute/path/to/your/tradingview-chart-mcp/main.py"], "env": { "TRADINGVIEW_SESSION_ID": "YOUR_SESSION_ID_HERE", "TRADINGVIEW_SESSION_ID_SIGN": "YOUR_SESSION_ID_SIGN_HERE" // Optional overrides: "MCP_SCRAPER_HEADLESS": "False" } } // ... existing servers ... } }

  3. Update path placeholders (command, args).

  4. Insert your actual TradingView session key and signature.
  5. Restart the Claude application to load the new configuration.

Integration for Cursor

  1. Navigate to Cursor Settings -> MCP -> Edit User MCP Config (~/.cursor/mcp.json).
  2. Merge the configuration block into the mcpServers object, similarly providing absolute paths and credentials:

    json { "mcpServers": { "tradingview-chart-mcp": { "command": "/absolute/path/to/your/tradingview-chart-mcp/.venv/bin/python3", "args": ["/absolute/path/to/your/tradingview-chart-mcp/main.py"], "env": { "TRADINGVIEW_SESSION_ID": "YOUR_SESSION_ID_HERE", "TRADINGVIEW_SESSION_ID_SIGN": "YOUR_SESSION_ID_SIGN_HERE" // Optional overrides: "MCP_SCRAPER_HEADLESS": "False" } } // ... existing servers ... } }

  3. Adjust path references and insert credentials.

  4. Restart Cursor.

Automated Installation via Smithery

To deploy this chart retriever automatically via Smithery for Claude Desktop:

npx -y @smithery/cli install @ertugrul59/tradingview-chart-mcp --client claude

Configuration Variables

The scraper's behavior is controlled by the following environmental parameters:

  • TRADINGVIEW_SESSION_ID: Essential TradingView cookie identifier (Mandatory).
  • TRADINGVIEW_SESSION_ID_SIGN: Essential TradingView cookie signature (Mandatory).
  • MCP_SCRAPER_HEADLESS: Boolean flag to run the browser invisibly (Default: True).
  • MCP_SCRAPER_WINDOW_WIDTH: Initial browser viewport width (Default: 1920).
  • MCP_SCRAPER_WINDOW_HEIGHT: Initial browser viewport height (Default: 1080).
  • MCP_SCRAPER_USE_SAVE_SHORTCUT: Determines artifact sourcing: base64 clipboard capture vs. CDN URL (Default: True).
  • MCP_SCRAPER_CHART_PAGE_ID: Option to specify a dedicated chart page ID, if necessary (Optional).

Data Capture Method Rationale

The MCP_SCRAPER_USE_SAVE_SHORTCUT setting directly impacts data delivery by switching between two distinct capture mechanisms:

Enabled (True): Clipboard Data URI Extraction

This method simulates the keyboard shortcut (Shift+Ctrl+S / Shift+Cmd+S) to pull the image data directly into the clipboard as a base64 payload, resulting in superior performance and reliability.

Disabled (False): Traditional Screenshot Link Retrieval

This reverts to an older method (Alt+S) which generates a URL pointing to a static image hosted on TradingView's Content Delivery Network (CDN).

Configuration Example:

# Prioritize speed: Use base64 clipboard data (Recommended)
MCP_SCRAPER_USE_SAVE_SHORTCUT=True

# Fallback: Use CDN screenshot URLs
MCP_SCRAPER_USE_SAVE_SHORTCUT=False

Deactivating the Virtual Environment

deactivate

Reference Documentation (XMLHttpRequest Context): XMLHttpRequest (XHR) is a standardized JavaScript object interface enabling asynchronous HTTP communication between a client-side script and a remote server subsequent to the initial page load. This mechanism forms the bedrock of Ajax technology. Historically, server interaction relied heavily on full page reloads via standard hyperlinks or form submissions. XHR was conceived by Microsoft Outlook developers around 2000 and first appeared in Internet Explorer 5 (1999) using proprietary ActiveX identifiers. By IE7 (2006), the standardized XMLHttpRequest identifier became universally supported across major browser engines (Gecko, Safari, Opera). The W3C formalized the specification starting in 2006, later adopting Level 2 features related to progress monitoring and cross-origin requests, before the standard was transitioned to WHATWG maintenance as a living document utilizing Web IDL.

See Also

`