How the CDP Connection Handles Retries and Reconnection in TradingView MCP

The TradingView MCP implements a resilient CDP connection manager in src/connection.js that combines lazy health-checks, exponential backoff with up to 5 retry attempts, and explicit target reconnection to maintain stable Chrome DevTools Protocol sessions with the TradingView desktop client.

The tradesdontlie/tradingview-mcp repository provides a Model Context Protocol (MCP) server for automating TradingView interactions via the Chrome DevTools Protocol (CDP). Understanding how the CDP connection handles retries and reconnection in TradingView MCP is essential for building reliable trading automation scripts that survive network hiccups, client restarts, and tab switches.

Core Connection Architecture in src/connection.js

The connection logic centers on three core mechanisms that work together to ensure robust communication with the TradingView desktop application.

Lazy Client Initialization with Health Checks

According to lines 55-60 in src/connection.js, the getClient() function implements lazy initialization coupled with proactive health validation. Before returning a cached client, it evaluates a trivial expression ('1') to verify the CDP session is still alive. If the health check fails, the cached client is cleared and a fresh connection is established automatically.

Exponential Backoff Retry Strategy

As implemented in lines 69-92, the connect() method implements a retry loop with exponential backoff. It attempts to locate a TradingView chart target and open a CDP session up to MAX_RETRIES (5) times. After each failure, the system waits BASE_DELAY * 2^n milliseconds, capped at 30 seconds, before retrying. If all attempts fail, a descriptive error is thrown to signal connection failure.

Explicit Target Reconnection

The reconnectTo(targetId) function (lines 101-108) handles intentional switching between targets, such as when users change browser tabs. This method closes any existing CDP client, clears cached state, and calls connect(targetId) to attach to a specific tab, guaranteeing subsequent calls operate on the newly selected chart.

Connection Lifecycle and Error Handling

The CDP connection follows a strict lifecycle to ensure reliability:

  1. Initial Request – When a library function like evaluate() or getChartApi() calls getClient(), the system checks for an existing healthy connection.
  2. Target Discovery – If no valid client exists, connect() invokes findChartTarget() to locate an appropriate TradingView chart page.
  3. Domain Enablement – Upon successful connection, the client enables required CDP domains: Runtime, Page, and DOM.
  4. Failure Recovery – Any connection error (e.g., ECONNREFUSED, missing target) triggers the retry loop with exponential backoff before surfacing the error.
  5. Target Migration – When switching contexts, reconnectTo() forces a fresh connection to the specified target ID, ensuring all subsequent evaluations run against the correct chart.

Practical Implementation Examples

Automatic Retry Handling During Evaluation

import { evaluate } from './src/connection.js';

async function getCurrentPrice() {
  // getClient() automatically retries up to 5 times if the CDP socket is unavailable
  return await evaluate(
    'window.TradingViewApi._activeChartWidgetWV.value()._chartWidget.model().symbol().ticker'
  );
}

Manual Reconnection After Tab Switching

import { reconnectTo, getChartApi, evaluate } from './src/connection.js';

async function switchToTab(tabId) {
  // Force a new CDP connection to the specified target
  await reconnectTo(tabId);
  
  // Now safe to query the new chart
  const chartPath = await getChartApi();
  return await evaluate(`${chartPath}.priceScale()`);
}

Low-Level Client Access for Custom Commands

import { getClient } from './src/connection.js';

async function listAllTargets() {
  const client = await getClient(); // includes automatic retry logic
  const { result } = await client.Target.getTargets();
  return result.targets;
}

Key Files and Dependencies

  • src/connection.js: Core CDP connection logic, retry mechanisms, and reconnection helpers (lines 55-108).
  • src/core/chart.js and src/core/pine.js: Higher-level consumers that rely on the connection manager for TradingView interactions.
  • src/tools/health.js: Exposes the tv_health_check command that leverages the connection health check.
  • tests/e2e.test.js: Integration tests verifying the CDP connection workflow under various failure scenarios.

Summary

  • The connection manager uses lazy initialization with explicit health checks ('1' evaluation) to detect stale clients before use.
  • Exponential backoff with 5 maximum retries and 30-second delay caps ensures resilience against transient CDP failures.
  • reconnectTo(targetId) provides deterministic target switching for handling tab changes or explicit context migrations.
  • Required CDP domains (Runtime, Page, DOM) are automatically enabled upon successful connection establishment.
  • All high-level operations in src/core/ automatically inherit the retry logic through the centralized getClient() function.

Frequently Asked Questions

How many times does TradingView MCP retry a failed CDP connection?

The system attempts to connect up to 5 times (MAX_RETRIES), using an exponential backoff strategy where the delay doubles after each failure, capped at 30 seconds between attempts. This logic resides in the connect() function within src/connection.js.

What happens if the TradingView desktop client restarts while the MCP server is running?

The next call to getClient() will detect the stale connection during its health check (evaluating '1'), clear the cached client, and trigger a fresh connection attempt through the retry loop. This ensures the automation recovers without manual intervention.

Can I force the MCP to connect to a specific TradingView tab?

Yes. Use the reconnectTo(targetId) function, which closes the existing CDP client and establishes a new connection to the specified target ID. This ensures all subsequent evaluations target that specific chart, which is essential after switching tabs or opening new charts.

Which CDP domains are required for TradingView MCP to function?

The connection manager enables three essential Chrome DevTools Protocol domains upon successful connection: Runtime for JavaScript execution, Page for page lifecycle events, and DOM for document manipulation. These are enabled immediately after the CDP socket is established.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →