Internal Architecture of the Replay Trading System in TradingView MCP
The replay trading system follows a two-layer architecture where the core layer (src/core/replay.js) orchestrates high-level operations while the tools layer (src/tools/replay.js) executes raw Chrome DevTools Protocol commands against the TradingView Desktop client.
The TradingView MCP repository provides a Multi-Command Program that automates TradingView Desktop via the Chrome DevTools Protocol (CDP). At the heart of this automation suite lies the replay trading system, implemented as a thin asynchronous wrapper that abstracts complex protocol interactions into manageable JavaScript functions.
Two-Layer Architectural Pattern
The internal architecture separates concerns into distinct layers to maintain testability and protocol isolation. This design ensures that low-level CDP implementation details never leak into consumer code while providing rich, contextual data returns.
The Tools Layer (src/tools/replay.js)
This layer implements the direct CDP communication with the TradingView Desktop application. It exports six primitive functions that map one-to-one with TradingView's native replay capabilities:
replay_start– Enters replay mode at a specific historical date.replay_step– Advances the chart by one bar.replay_autoplay– Initiates automatic playback with configurable speed (milliseconds per bar).replay_trade– Executes buy, sell, or close actions with a specified quantity.replay_status– Retrieves current replay state including date, open position, and profit/loss (P&L).replay_stop– Exits replay mode and returns the chart to real-time data.
These functions encapsulate the raw protocol messages required to control the TradingView replay engine, keeping transport logic isolated from business logic.
The Core Layer (src/core/replay.js)
The core layer imports these primitives and wraps them in user-friendly async functions. Located in src/core/replay.js, this module performs two critical responsibilities: invoking the appropriate tool function and enriching the response with current market data via quote_get from src/tools/quote.js.
Key exports include:
startReplay(date)– Initiates replay at the specified date and returns the initial price.stepReplay()– Advances one bar and fetches the new price.autoplayReplay(speed)– Starts autoplay with the specified speed.tradeReplay(action, qty)– Executes trades while returning the current market price.getReplayStatus()– Returns raw replay status without quote enrichment.stopReplay()– Terminates the replay session.
Data Flow and Quote Enrichment
A distinctive feature of this architecture is the automatic quote retrieval pattern. Most core functions call quote_get() immediately after the replay operation completes, ensuring the caller receives both the operation result and the current market price in a single response object.
For example, when stepReplay() advances to the next bar, it immediately queries the latest OHLCV data via quote_get(), returning a unified object containing the bar information and current price. This eliminates the need for separate API calls to synchronize market data with replay state.
Module Integration and Discovery
The core replay module is re-exported through src/core/index.js alongside other automation modules including chart manipulation, Pine Script integration, and indicator handling. This centralizes the API surface, allowing consumers to import all core functionality from a single entry point while maintaining logical separation in the source tree.
Practical Implementation Examples
import {
startReplay,
stepReplay,
autoplayReplay,
tradeReplay,
getReplayStatus,
stopReplay,
} from "tradingview-mcp/src/core/replay.js";
// Initialize replay at a specific historical date
const { date, price } = await startReplay("2024-01-15");
// Step through bars manually with automatic price updates
const nextBar = await stepReplay();
// Returns: { date, barInfo, price }
// Enable autoplay at 500ms per bar
await autoplayReplay(500);
// Execute simulated trades with immediate price feedback
await tradeReplay("buy", 10);
await tradeReplay("sell", 5);
// Check current P&L and position without fetching new quotes
const status = await getReplayStatus();
// Exit replay mode and return to real-time
await stopReplay();
Summary
- The replay trading system uses a two-layer architecture separating protocol concerns from business logic.
- The tools layer (
src/tools/replay.js) handles raw CDP commands for replay control, trading actions, and status queries. - The core layer (
src/core/replay.js) wraps these primitives and enriches responses with real-time quote data viaquote_get. - All core modules are aggregated in
src/core/index.jsfor streamlined imports. - This design enables automated backtesting and strategy validation against historical TradingView data while maintaining clean separation between transport protocols and application APIs.
Frequently Asked Questions
How does the replay trading system communicate with TradingView Desktop?
The system communicates via the Chrome DevTools Protocol (CDP) on port 9222. The tools layer (src/tools/replay.js) encapsulates the raw CDP commands that control TradingView's native replay functionality, translating JavaScript function calls into protocol messages that the TradingView Desktop application understands and executes.
Why does the core layer fetch quotes after every replay operation?
The core functions automatically call quote_get() to provide immediate price context for the replay step or trade action. This design pattern eliminates the need for separate API calls to retrieve market data after advancing bars or executing simulated trades, returning a unified response object containing both the operation status and current market price.
Can I use the replay tools directly without the core wrapper?
Yes, you can import functions directly from src/tools/replay.js if you need lower-level control or want to avoid the automatic quote fetching overhead. However, using the core layer (src/core/replay.js) is recommended for most use cases as it provides cleaner error handling and consolidated data returns that include both replay state and current market prices.
What information does getReplayStatus() return?
According to the implementation in src/tools/replay.js, the status function returns an object containing the current replay date, open position details, and realized or unrealized profit and loss (P&L). Unlike other core functions, getReplayStatus() does not automatically append quote data, providing a lightweight method to check replay state without additional market data queries.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →