Metadata-Version: 2.4
Name: tv-live
Version: 0.1.0
Summary: Stream OHLCV candles and indicators from TradingView — no Desktop app required
Home-page: https://github.com/TMKSuite/tv-live
Author: TMKSuite
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: websocket-client>=1.8.0
Requires-Dist: pandas>=2.0.0
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# tv-live

**Stream OHLCV candles and technical indicators from TradingView — no Desktop app required.**

Direct WebSocket connection to `data.tradingview.com`, the same protocol used by the tradingview.com website in your browser. No Node.js. No CDP. No Electron app running 24/7.

## Quick Start

```bash
pip install tv-live

# Live stream EURUSD M5 with EMA20 and ATR14
tv-live stream FX:EURUSD 5m --indicators ema20,atr14

# Bar replay — walk through 2000 bars, show signals
tv-live replay FX:EURUSD 5m -n 2000 --quiet

# List available brokers
tv-live brokers forex
```

## How It Works

```
┌──────────────┐      WebSocket       ┌─────────────────────┐
│   tv-live    │ ◄──────────────────► │ data.tradingview.com │
│  (Python)    │   ~m~ protocol       │   (TV servers)       │
└──────────────┘                      └─────────────────────┘
     │                                        │
     │  Parse timescale_update                │  Same feed as
     │  Calculate indicators locally          │  the website
     ▼                                        ▼
  OHLCV + EMA + ATR + RSI + ...
```

Unlike CDP-based MCP servers (Jackson, Londarth, tvcontrol) that scrape data from a running TradingView Desktop app via Chrome DevTools Protocol, **tv-live connects directly to the same WebSocket servers that power the tradingview.com website**. This means:

- No TV Desktop app needed
- No `--remote-debugging-port=9222` setup
- No Electron app consuming 300MB+ RAM
- Works on any machine with Python 3.10+

The protocol is TradingView's internal `~m~` format — the same messages your browser receives when you open a chart on tradingview.com. We parse `timescale_update` messages to extract OHLCV bars, then calculate technical indicators locally using formulas verified to match Pine Script v5.

## Commands

### `stream` — Live candle streaming

```
tv-live stream <SYMBOL> [INTERVAL] [OPTIONS]
```

Streams candles in real-time. Each completed bar is printed with OHLCV and optional indicator values.

**Arguments:**
- `SYMBOL` — Exchange:Pair format (e.g. `FX:EURUSD`, `OANDA:GBPUSD`). Shorthand without `:` defaults to FX broker.
- `INTERVAL` — `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `2h`, `3h`, `4h`, `1d`, `1w`, `1M` (default: `5m`)

**Options:**
| Flag | Description |
|------|-------------|
| `-i, --indicators` | Comma-separated indicators: `ema20,atr14,rsi14` |
| `-b, --broker` | Broker prefix shortcut (default: `FX`) |

**Examples:**
```bash
tv-live stream FX:EURUSD 5m -i ema20,ema50,atr14
tv-live stream OANDA:GBPUSD 15m -i rsi14
tv-live stream eurusd 1h -i ema200          # shorthand, auto-adds FX:
```

### `replay` — Bar replay with strategy signals

```
tv-live replay <SYMBOL> [INTERVAL] [OPTIONS]
```

Walks through historical bars one by one, calculating indicators cumulatively (only using bars "seen" so far) — the same way a live strategy would. Detects EMA crossover/crossunder signals and prints entry, SL, and TP for each.

**Options:**
| Flag | Description | Default |
|------|-------------|---------|
| `-n, --bars` | Number of bars to fetch | 500 |
| `-f, --file` | Load from CSV instead of WebSocket | — |
| `--ema-fast` | Fast EMA period | 20 |
| `--ema-slow` | Slow EMA period | 50 |
| `--atr` | ATR period | 14 |
| `--sl-mult` | SL multiplier × ATR | 1.5 |
| `--tp-mult` | TP multiplier × ATR | 4.0 |
| `-q, --quiet` | Show only signal summary | — |

**Examples:**
```bash
tv-live replay FX:EURUSD 5m -n 2000 --quiet
tv-live replay FX:EURUSD 15m --ema-fast 10 --ema-slow 30 --sl-mult 2.0
tv-live replay FX:EURUSD 5m -f historia_EURUSD_5m.csv
```

**Output (--quiet mode):**
```
PODSUMOWANIE SYGNALOW
=====================================================================
  LONG:  4
  SHORT: 4
  CLOSE: 7
  RAZEM: 15

  2026-06-25 01:50:00    SHORT  E=1.13533  SL=1.13554  TP=1.13476
  2026-06-25 03:20:00    LONG   E=1.13659  SL=1.13621  TP=1.13760
  ...
```

### `brokers` — List available exchanges

```
tv-live brokers forex     # Forex brokers
tv-live brokers crypto    # Crypto exchanges
tv-live brokers stock     # Stock exchanges
tv-live brokers index     # Index/CFD prefixes
tv-live brokers all       # Everything
```

### `info` — Configuration reference

```bash
tv-live info              # Show supported intervals and indicators
```

## Available Indicators

All indicators use the **same formulas as Pine Script v5** — verified by cross-referencing 200 M5 bars against TradingView Desktop (CDP). Close prices match 99.5% of bars; the remaining 0.5% differ by ≤2 ticks.

| Indicator | CLI flag | Parameters | Pine Script |
|-----------|----------|------------|-------------|
| EMA | `emaN` | period=N | `ta.ema(close, N)` |
| SMA | `smaN` | period=N | `ta.sma(close, N)` |
| ATR | `atrN` | period=N | `ta.atr(N)` — RMA smoothing |
| RSI | `rsiN` | period=N | `ta.rsi(close, N)` — RMA smoothing |
| MACD | `macd` | fast=12, slow=26, sig=9 | `ta.macd(close, 12, 26, 9)` |
| Bollinger Bands | `bb` | period=20, std=2 | `ta.bb(close, 20, 2)` |
| VWAP | `vwap` | — | `ta.vwap` |

### Formula accuracy

| Indicator | Our formula | Pine Script | Verified difference |
|-----------|------------|-------------|-------------------|
| EMA(20) | `ewm(span=20, adjust=False)` | `ta.ema(close, 20)` | 0.00001 (1 tick) |
| EMA(50) | `ewm(span=50, adjust=False)` | `ta.ema(close, 50)` | 0.00001 (1 tick) |
| ATR(14) | `rma(tr, 14)` = `ewm(alpha=1/14)` | `ta.atr(14)` | ⚖️ Identical smoothing |
| RSI(14) | `rma(gain, 14)` = `ewm(alpha=1/14)` | `ta.rsi(close, 14)` | ⚖️ Identical smoothing |

## Data Format

Every bar returned by the stream has the following structure:

```json
{
  "time": "2026-06-26 13:40:00",
  "open": 1.13997,
  "high": 1.14002,
  "low": 1.13982,
  "close": 1.13989,
  "volume": 389,
  "symbol": "FX:EURUSD"
}
```

This is the same OHLCV format as Jackson MCP's `data_get_ohlcv`, plus a `symbol` field. Timestamps are Python datetime objects (convertible to Unix with `.timestamp()`).

## Python API

```python
from tv_live import TvLiveStream

# Basic streaming
stream = TvLiveStream("FX:EURUSD", "5m")

def on_candle(bar, history):
    """Called on every completed candle."""
    print(f"{bar['time']} | O={bar['open']:.5f} C={bar['close']:.5f} V={bar['volume']}")

stream.on_candle = on_candle
stream.on_connect = lambda sym, tf: print(f"Connected: {sym} {tf}")
stream.on_disconnect = lambda reason: print(f"Disconnected: {reason}")

# Start in a background thread (non-blocking)
thread = stream.start_in_thread()

# Later: access data
print(f"Collected {stream.bar_count} bars")
df = stream.df  # pandas DataFrame with all bars

# Stop
stream.stop()
```

### Replay engine

```python
from tv_live.replay import ReplayEngine

engine = ReplayEngine(
    symbol="FX:EURUSD",
    interval="5m",
    ema_fast=20, ema_slow=50,
    atr_period=14,
    sl_mult=1.5, tp_mult=4.0,
)

# From TradingView WebSocket
engine.load_from_websocket(n_bars=2000)

# Or from CSV
engine.load_from_csv("historia_EURUSD_5m.csv")

# Run and get signals
signals = engine.run(verbose=False)
for s in signals:
    print(f"{s['time']} {s['action']} {s.get('entry', s.get('price'))}")
```

## Why This Over CDP-Based MCP Servers?

There are several open-source TradingView MCP servers (Jackson, Londarth, tvcontrol, Ferrox Labs) that connect via Chrome DevTools Protocol to a locally running TradingView Desktop app.

| Feature | tv-live | CDP-Based MCP |
|---------|---------|---------------|
| TV Desktop required | **No** | Yes (must run 24/7) |
| RAM usage | ~30 MB | ~300 MB+ (Electron) |
| Language | Python | Node.js |
| Install | `pip install tv-live` | git clone + npm install + debug port config |
| Max historical bars | **5000+** | 500 (hardcoded) |
| Bar replay | Yes (standalone) | Yes (via CDP) |
| OHLCV data | Yes | Yes |
| Technical indicators | Yes (local, verified) | Yes (read from TV data window) |
| Pine Script editing | No | Yes |
| Strategy tester metrics | No | Yes |
| Chart screenshots | No | Yes |
| Pine graphics (lines, labels) | No | Yes |
| Alert management | No | Yes |
| Replay mode (visual) | No | Yes |

**Bottom line:** if you need to **control** TradingView (edit Pine Script, take screenshots, manage alerts, use bar replay visually), use a CDP-based MCP server. If you need **data** — OHLCV streaming, indicators, bar replay for strategy validation — tv-live gives you the same quality with zero infrastructure overhead.

## Limitations

tv-live connects to TradingView's **public data feed** (`unauthorized_user_token`). This is the same feed that powers charts for non-logged-in visitors on tradingview.com. As a result:

- **No Pine Script access** — can't read, write, compile, or debug Pine Script code
- **No strategy tester data** — can't access backtest metrics, trade lists, or equity curves from TV's Strategy Tester
- **No Pine Script graphics** — can't read lines, labels, tables, or boxes drawn by custom indicators
- **No DOM/order book** — can't access depth of market data
- **No chart control** — can't change chart type, add indicators, or manage layouts
- **No screenshots** — can't capture chart images

These are all features that require direct interaction with the TradingView Desktop app's internal state — only accessible via CDP.

## Project Structure

```
tv-live/
  tv_live/
    __init__.py        # v0.1.0
    cli.py             # CLI: stream, replay, brokers, info
    stream.py          # WebSocket engine + ping/reconnect
    replay.py          # Bar replay + strategy simulation
    indicators.py      # EMA, SMA, ATR, RSI, MACD, BB, VWAP
    brokers.py         # Broker/Exchange registry (forex, crypto, stock, index)
  setup.py             # pip install
  README.md
```

## License

MIT — do whatever you want with it.

---

Built as an alternative to CDP-based TradingView MCP servers. If you need the extra capabilities (Pine Script, screenshots, etc.), check out [LewisWJackson/tradingview-mcp-jackson](https://github.com/LewisWJackson/tradingview-mcp-jackson) — it pairs nicely with tv-live for data-only workloads.
