tvkit is a Python library that fetches real-time stock data from TradingView, including price, market cap, P/E ratio, ROE, and more for stocks from multiple countries. Easily access and analyze financial metrics for global markets.
Project description
tvkit
tvkit — Async Python client for TradingView market data.
Access real-time and historical TradingView data with a modern async Python API. Designed for quantitative research, trading tools, and data pipelines.
Features
- Real-time OHLCV streaming via WebSocket with async generators
- Automatic reconnection with exponential backoff — transient disconnects recovered transparently
- Historical data retrieval by bar count or explicit date range
- Automatic segmented fetching for large historical OHLCV date ranges (TradingView historical depth limits still apply)
- Multi-market scanner: 69 global markets, 101+ financial metrics
- Multi-format data export: Polars DataFrames, JSON, CSV
- Symbol format auto-conversion:
EXCHANGE-SYMBOLandEXCHANGE:SYMBOLboth accepted - Async symbol validation with retry and flexible format support
- Full type safety with Pydantic models throughout
- Python 3.11+ with async/await and context manager patterns
Installation
Available on PyPI: https://pypi.org/project/tvkit/
uv add tvkit # recommended
pip install tvkit
Quick Example
import asyncio
from tvkit.api.chart.ohlcv import OHLCV
async def main() -> None:
async with OHLCV() as client:
# Fetch last 10 daily bars for Apple
bars = await client.get_historical_ohlcv(
exchange_symbol="NASDAQ:AAPL",
interval="1D",
bars_count=10,
)
for bar in bars:
print(bar.timestamp, bar.close)
# 2024-01-10 00:00:00 189.34
asyncio.run(main())
See more working examples in examples/.
Authenticated Sessions
Authenticate with your TradingView account to unlock larger historical data windows beyond the anonymous 5,000-bar limit. See TradingView Pricing for the full plan comparison.
| Plan | Max bars per fetch |
|---|---|
| Basic (free) | 5,000 |
| Essential / Plus | 10,000 |
| Premium | 20,000 |
| Ultimate | 40,000 |
# Browser cookie extraction — Chrome or Firefox (must be logged in to TradingView)
async with OHLCV(browser="chrome") as client:
await client.wait_until_ready() # optional: wait for probe-confirmed max_bars
account = client.account
if account:
print(f"Tier: {account.tier}, max_bars: {account.max_bars}")
bars = await client.get_historical_ohlcv(
exchange_symbol="NASDAQ:AAPL",
interval="1D",
bars_count=10_000,
)
# Firefox
async with OHLCV(browser="firefox") as client: ...
# Direct token injection (CI/CD — no browser required)
async with OHLCV(auth_token=os.environ["TVKIT_AUTH_TOKEN"]) as client: ...
# Anonymous (default — no changes required)
async with OHLCV() as client: ...
Environment variables (alternative to kwargs):
export TVKIT_BROWSER=chrome # equivalent to OHLCV(browser="chrome")
export TVKIT_AUTH_TOKEN=<token> # equivalent to OHLCV(auth_token=...)
Troubleshooting:
BrowserCookieError— not logged in to TradingView in the browser; log in and retryProfileFetchError— session expired; log out and back in to TradingView
More details: Authenticated Sessions Guide · Account Capabilities · Auth Reference
Automatic Reconnection
Reconnection is on by default — no changes needed to existing call sites:
async with OHLCV() as client:
# Transient disconnects are recovered automatically (5 attempts, 1s–30s backoff).
async for bar in client.get_ohlcv("NASDAQ:AAPL", "1D"):
print(bar.close)
Tune it for long-running pipelines:
from tvkit.api.chart import OHLCV, StreamConnectionError
async with OHLCV(max_attempts=10, base_backoff=2.0, max_backoff=60.0) as client:
try:
async for bar in client.get_ohlcv("NASDAQ:AAPL", "1D"):
print(bar.close)
except StreamConnectionError:
print("Stream permanently lost after all attempts")
Symbol Format Reference
| Market | Example |
|---|---|
| US Equity | NASDAQ:AAPL |
| Crypto | BINANCE:BTCUSDT |
| Index / Macro | INDEX:NDFI |
Canonical format: EXCHANGE:SYMBOL. Dash notation (EXCHANGE-SYMBOL) is automatically converted.
See concepts/symbols.md for the full reference.
Documentation
Full documentation index → docs/index.md
Getting Started
- Installation — Python version, uv, pip, source install, verification
- Quickstart — Four self-contained examples in under 15 lines each
- First Script — Annotated walkthrough from install to first data fetch
Concepts
- Symbols — Format rules, exchange prefixes, auto-conversion
- Intervals — All supported timeframes and format strings
- Streaming vs Historical — When to use each method
- Scanner Columns — Column sets and when to use each
- Account Capabilities — Plan tiers, bar limits, and capability detection
Guides
- Historical Data — Bar count mode, date-range mode, Polars integration
- Real-time Streaming — WebSocket streaming, multiple symbols, reconnection
- Authenticated Sessions — Browser cookies, token injection, capability detection
- Scanner — 69 global markets, filters, sorting, regional analysis
- Exporting Data — DataExporter, CSV, JSON, Polars with metadata
- Macro Indicators — INDEX:NDFI, USI:PCC, regime detection
Reference
- Chart API — OHLCV client: all methods, parameters, return types
- Authentication — tvkit.auth — AuthManager, TradingViewCredentials, TradingViewAccount
- Chart Utils — Interval validation, timestamp utilities
- Scanner API — ScannerService interface and filter syntax
- Markets — All 69 markets, regions, exchange identifiers
- Export API — DataExporter interface and export formats
- Full Reference Index
Architecture
- System Overview — Four modules, async rationale, module dependencies
- WebSocket Protocol — TradingView message format, session lifecycle
Development
- Release Process — Quality gates, version bump, publish
- Testing Strategy — Test organisation, mocking, coverage
- Architecture Decisions — Key decisions with rationale
Support
- FAQ — Symbol formats, bar limits, async requirement, disconnect handling
- Roadmap — Planned features
- Why tvkit — Design goals, vs rolling your own WebSocket
- Limitations — Bar caps, rate limits, data coverage gaps
- Data Sources — TradingView data origin, real-time vs delayed
Examples
Working scripts in examples/ — clone the repo and run immediately.
Why tvkit
TradingView provides powerful market data but does not offer an official Python SDK. tvkit implements the TradingView WebSocket protocol and provides:
- A clean async Python API
- Strong typing via Pydantic
- Structured OHLCV models
- High-level data utilities (export, scanners)
Without needing to reverse-engineer the protocol yourself. See docs/why-tvkit.md for the full rationale.
Stability
tvkit is under active development. The public API is expected to remain stable within minor versions. Breaking changes will follow semantic versioning.
Contributing
See CONTRIBUTING.md for the development environment setup, quality gate commands, and pull request process.
Quality gates before every commit:
uv run ruff check .
uv run ruff format .
uv run mypy tvkit/
uv run python -m pytest tests/ -v
License
MIT — see LICENSE
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tvkit-0.11.0.tar.gz.
File metadata
- Download URL: tvkit-0.11.0.tar.gz
- Upload date:
- Size: 211.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
91cdeee9fc28ae8b4dee61699aa52f38bdeaac832b6b37e24fa7600b2872dc5c
|
|
| MD5 |
9cbad20d8bd677db3131eb01f4ec0b6c
|
|
| BLAKE2b-256 |
44d9099afe9212719fec94a27ecc832d9c9aa9871bc8b7ebda676bd5e34edf9a
|
File details
Details for the file tvkit-0.11.0-py3-none-any.whl.
File metadata
- Download URL: tvkit-0.11.0-py3-none-any.whl
- Upload date:
- Size: 157.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1b17aa497e586a89578ef024e0e76f8e3decf5ba3aedf5b8ba7e7f26a9caac81
|
|
| MD5 |
523e6980a442f0c1f96fd94a2a43352c
|
|
| BLAKE2b-256 |
19ff267d8bd99da735dde591f3e1b2a57d90dc750dbf7a9af409e2fc8ef76d9b
|