Metadata-Version: 2.4
Name: cdp-tv
Version: 0.2.0
Summary: Python automation and data access for TradingView Desktop over CDP
License-Expression: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: THIRD_PARTY_LICENSES
Requires-Dist: websockets<17,>=15
Dynamic: license-file

# cdp-tv

[English](README.md) | [简体中文](README-CN.md)

## Overview

A synchronous Python SDK and CLI for controlling a local TradingView Desktop instance through the Chrome DevTools Protocol (CDP). It provides 83 operations and market data polling, covering the portable functionality of the reference project tradingview-mcp. This is a standalone pip package with no MCP server and no Node.js requirement.

Requires Python 3.12+ and a TradingView Desktop chart page with an active login. See [Installation and Connection](docs/INSTALLATION.md) for setup, the [SDK Guide](docs/SDK.md) for advanced usage, and the [API Reference](docs/API.md) for all parameters. Feature availability depends on the desktop version and account permissions; see [Compatibility Notes](docs/COMPATIBILITY.md) for verified coverage, [Behavior and Limitations](docs/BEHAVIOR.md) for caveats, and the [Development Guide](docs/DEVELOPMENT.md) for development details. This is an unofficial implementation licensed under [MIT](LICENSE); upstream attribution is listed in [THIRD_PARTY_LICENSES](THIRD_PARTY_LICENSES).

## Features

| Area | Capabilities |
| --- | --- |
| Charts and symbols | Chart state, symbol/timeframe/chart type settings, visible range, date navigation, symbol search |
| Market data and strategies | OHLCV, quotes, indicator values, Pine drawing data, strategy results/orders/equity, DOM depth |
| Indicators and drawings | Indicator search, addition/removal, inputs and visibility, drawing creation/query/removal |
| Pine | Source code reading/writing, diagnostics/logs, compilation, script creation/opening/saving, static analysis, server-side compilation checks |
| Replay | Start, step, autoplay, stop, status, simulated replay trading |
| Desktop and UI | Tabs, layouts, split charts, panels, keyboard/mouse input, element lookup, JavaScript execution |
| Watchlists and alerts | Watchlist symbol queries/additions/removals, price alert queries/creation/deletion |
| Utilities | Screenshots, batch processing, API diagnostics, JSONL market data polling |

## SDK Quick Start

```python
from cdp_tv import TradingView

tv = TradingView(port=9222)
tv.launch()  # Launch or reuse a desktop instance with CDP enabled

with tv:
    print(tv.get_chart_state())
    print(tv.quote_get())
    print(tv.data_get_ohlcv(count=10))
    print(tv.capture_screenshot("chart.png", region="chart"))
```

Methods use keyword arguments, for example `tv.chart_set_symbol(symbol="BINANCE:BTCUSDT")`. You can also use `tv.call("chart_set_symbol", symbol="BINANCE:BTCUSDT")`. Closing the connection does not quit TradingView.

## CLI Reference

### Entry Points and Global Options

After installation, run `cdp-tv` or `python -m cdp_tv`. For the project's virtual environment on Windows, use `.\.venv\Scripts\python.exe -m cdp_tv`. The examples below use `cdp-tv` and assume PowerShell.

```text
cdp-tv [GLOBAL_OPTIONS] [COMMAND] [COMMAND_ARGUMENTS]
cdp-tv [GLOBAL_OPTIONS] call OPERATION_NAME [COMMAND_ARGUMENTS]
```

| Global option | Description | Default |
| --- | --- | --- |
| `--host HOST` | CDP host | Environment configuration or `127.0.0.1` |
| `--port PORT` | CDP port | Environment configuration or `9222` |
| `--target-id ID` | Target a specific page | Automatically select a chart page |
| `--timeout SECONDS` | Timeout for a single CDP request | `10` seconds |
| `--operation-timeout SECONDS` | Browser workflow timeout | `60` seconds |
| `--pretty` | Pretty-print JSON output | Off |
| `-h`, `--help` | Show CLI help | — |

Place global options before the command. If no command is given, `status` runs by default. For batch operations, the timeout applies to each internal operation, rather than the entire batch.

```powershell
cdp-tv --port 9222 --pretty state
cdp-tv --target-id "ACTUAL_PAGE_ID" quote
cdp-tv tools
cdp-tv call chart_set_timeframe --timeframe 60
```

`tools` lists all operations, parameter types, required parameters, and enum values without connecting. Any operation can be invoked directly by its full name or after `call`; see the [API Reference](docs/API.md) for the complete list.

### Passing Arguments

| Syntax | Description |
| --- | --- |
| `--parameter-name VALUE` or `--parameter-name=VALUE` | Pass a parameter explicitly; hyphens become underscores, so `--entity-id` maps to `entity_id` |
| Positional arguments | Fill unassigned parameters in the order defined by `tools` metadata; explicit parameters are recommended for complex calls |
| `--boolean-parameter` | Equivalent to `true`; use `--boolean-parameter=false` to pass `false` |
| `--json JSON_OBJECT` | Provide multiple parameters at once; JSON keys use the operation's original parameter names |
| `--json -` | Read a JSON object from standard input; useful for arguments containing quotes in PowerShell |
| `--source-file PATH` | Read a UTF-8 file as the `source` parameter for Pine operations |

Pass strings directly; use JSON syntax for numbers, arrays, and objects. The CLI uses `--from` for time range parameters, while the Python SDK uses `from_`. Quote argument values that contain spaces using your shell's quoting rules.

```powershell
cdp-tv ohlcv --count 10 --summary
cdp-tv ohlcv --count 10 --summary=false
cdp-tv type Candles
'{"symbols":["BINANCE:BTCUSDT"],"action":"get_ohlcv","delay_ms":0}' | cdp-tv call batch_run --json -
cdp-tv pine check --source-file example.pine
```

### Common Commands

Uppercase words in the table below are placeholders to replace, and square brackets indicate optional arguments. Prefix every command in the table with `cdp-tv`.

| Command | Operation / purpose |
| --- | --- |
| `status` | `tv_health_check`: connection and chart status |
| `launch [--port PORT] [--kill-existing]` | `tv_launch`: launch the app; `--kill-existing` closes existing windows, so save your work first |
| `state` | `chart_get_state`: chart, timeframe, and indicators |
| `quote [--symbol SYMBOL]` | `quote_get`: latest bar quote; requesting another symbol temporarily switches the chart |
| `ohlcv [--count N] [--summary]` | `data_get_ohlcv`: bars or a summary |
| `values` | `data_get_study_values`: indicator values |
| `symbol SYMBOL` | `chart_set_symbol`: switch symbols |
| `timeframe TIMEFRAME` | `chart_set_timeframe`: for example, `60` or `D` |
| `type TYPE` | `chart_set_type`: for example, `Candles`, `Line`, or `0`–`9` |
| `info` | `symbol_info`: current symbol information |
| `search QUERY [--type TYPE]` | `symbol_search`: search for symbols |
| `range` | `chart_get_visible_range`: read the visible time range |
| `scroll DATE` | `chart_scroll_to_date`: navigate to a date or Unix timestamp in seconds |
| `screenshot [--path PATH] [--region REGION] [--wait-for-render]` | `capture_screenshot`: save a PNG; regions are `full`, `chart`, and `strategy_tester` |
| `discover` | `tv_discover`: check internal API availability |
| `ui-state` | `tv_ui_state`: read UI state |

```powershell
cdp-tv symbol BINANCE:BTCUSDT
cdp-tv timeframe 60
cdp-tv screenshot --path chart.png --region chart --wait-for-render
'{"from":1727740800,"to":1727827200}' | cdp-tv call chart_set_visible_range --json -
```

### Command Groups

Hyphens and underscores are interchangeable in subcommands, for example `pine smart-compile` and `pine smart_compile`. Where subcommands or enum values are separated by commas or slashes in the table, choose one when running the command.

| Group | Subcommands | Arguments and purpose |
| --- | --- | --- |
| `pine` | `get`, `errors`, `console`, `list` | Source code, diagnostics, logs, and saved script list |
| `pine` | `set`, `analyze`, `check` | `--source-file PATH` or `--source SOURCE`; write source code, analyze offline, or check on the server |
| `pine` | `compile`, `smart-compile`, `save` | Compile the current editor contents or save the script; server-side processing may continue after compilation returns |
| `pine` | `new`, `open` | `new --type indicator/strategy/library`; `open --name NAME` |
| `data` | `lines`, `labels`, `tables`, `boxes` | Supports `--study-filter TEXT`; lines, labels, and boxes support `--verbose`; labels support `--max-labels N` |
| `data` | `strategy`, `trades`, `equity`, `depth` | Strategy results, orders, equity, and DOM depth; orders support `--max-trades N` |
| `data` | `indicator` | `--entity-id ID`: indicator inputs and visibility |
| `indicator` | `search`, `add` | `--query TEXT`; search supports `--limit N`, and add supports `--match TEXT --section TEXT` |
| `indicator` | `get`, `set`, `toggle` | All require `--entity-id ID`; `set` also requires `--inputs JSON_OBJECT`, and `toggle` requires `--visible` or `--visible=false` |
| `indicator` | `remove ID` | Remove an indicator; this shortcut takes one positional ID argument |
| `draw` | `list`, `get`, `remove`, `clear` | `get/remove` requires `--entity-id ID`; `clear` removes all drawings |
| `draw` | `shape` | `--shape NAME --point JSON_OBJECT`; optional `--point2`, `--overrides`, and `--text`; points contain `time/price` |
| `pane` | `list`, `layout`, `focus`, `symbol` | `layout --layout CODE`; `focus --index N`; `symbol --index N --symbol SYMBOL` |
| `tab` | `list`, `new`, `switch`, `close` | `new` supports `--layout NAME --name NAME`; `switch --index N`; indices start at `0` |
| `layout` | `list`, `new`, `switch` | `new` supports `--name NAME`; `switch --name NAME` also accepts a layout ID |
| `watchlist` | `get`, `add`, `add-bulk`, `remove` | `add --symbol SYMBOL`; bulk addition and removal use `--symbols JSON_ARRAY` |
| `replay` | `status`, `start`, `step`, `autoplay`, `stop`, `trade` | `start` supports `--date YYYY-MM-DD`; `autoplay` supports `--speed MILLISECONDS`; `trade --action buy/sell/close` |
| `alert` | `list`, `create`, `delete` | `create --condition crossing/greater_than/less_than --price PRICE [--message TEXT]`; delete with `--alert-id ID` or `--delete-all` |
| `ui` | `find`, `click`, `hover` | Find with `--query TEXT [--strategy text/aria-label/css]`; click/hover with `--by aria-label/data-name/text/class-contains --value TEXT` |
| `ui` | `panel`, `fullscreen` | Panels require `--panel pine-editor/strategy-tester/watchlist/alerts/trading --action open/close/toggle` |
| `ui` | `keyboard`, `type` | `keyboard --key KEY [--modifiers JSON_ARRAY]`; modifiers are `alt/ctrl/meta/shift`; `type --text TEXT` |
| `ui` | `scroll`, `mouse` | `scroll --direction up/down/left/right [--amount PIXELS]`; `mouse --x X --y Y [--button left/right/middle] [--double-click]` |
| `ui` | `eval` | `--expression JAVASCRIPT`: execute an expression on the chart page |

Replay `speed` is a delay in milliseconds, with supported values of `100`, `143`, `200`, `300`, `1000`, `2000`, `3000`, `5000`, and `10000`. Each `autoplay` call toggles between playing and paused. Alert changes, watchlist additions/removals, and Pine saves write to the current account. See the [API Reference](docs/API.md) and [Behavior and Limitations](docs/BEHAVIOR.md) for additional parameters and behavioral constraints.

```powershell
cdp-tv indicator search --query RSI --limit 5
cdp-tv tab list
cdp-tv tab switch --index 0
cdp-tv ui panel --panel pine-editor --action open
'{"key":"s","modifiers":["ctrl"]}' | cdp-tv ui keyboard --json -
```

### Polling and Batch Operations

```text
cdp-tv stream KIND [--interval SECONDS] [--count N] [--duration SECONDS] [--filter TEXT] [--all-samples]
cdp-tv call batch_run --json JSON_OBJECT
```

| Polling parameter | Description |
| --- | --- |
| `KIND` | One of `quote/bars/values/lines/labels/tables/all`; `all` reads the latest bar from every chart pane |
| `--interval` | Seconds to wait after each sample; defaults to `1` |
| `--count` | Maximum number of samples, including samples omitted from output by deduplication; unlimited by default |
| `--duration` | Maximum polling duration in seconds; unlimited by default; does not forcibly interrupt requests already in progress |
| `--filter` | Filter lines, labels, and tables by indicator name |
| `--all-samples` | Output every sample; by default, only changes are emitted |

`batch_run` requires a `symbols` array and an `action` (one of `screenshot/get_ohlcv/get_strategy_results`). Optional parameters are a `timeframes` array, `delay_ms` (default `2000`), `ohlcv_count` (default `100`), and `output_dir` (default `screenshots`). After execution, it attempts to restore the symbol and timeframe independently. Results include `failed`, `restored`, and `restore_error`.

```powershell
cdp-tv stream quote --interval 1 --count 3
cdp-tv stream all --duration 30 --all-samples
'{"symbols":["BINANCE:BTCUSDT"],"timeframes":["60","D"],"action":"get_ohlcv","ohlcv_count":10}' | cdp-tv call batch_run --json -
```

### Output and Exit Codes

Regular operations write JSON to standard output, while streaming operations write one JSON object per line. Operation errors include `success: false`, `error`, and `error_type`; help and argparse argument errors use plain text. `--pretty` affects only regular output and does not change the stream's JSONL format.

| Exit code | Meaning |
| --- | --- |
| `0` | The operation returned normally; for `pine_check`, you must still inspect `compiled`, since the exit code alone does not indicate successful source compilation |
| `1` | Operation or argument processing failed |
| `2` | An argparse argument error in the CLI entry point or `stream` command |
| `130` | Interrupted by the user with Ctrl+C |
