Skip to main content

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

Python 3.11+ License: MIT Async/Await Type Safety PyPI

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-SYMBOL and EXCHANGE:SYMBOL both 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 retry
  • ProfileFetchError — 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

Guides

Reference

Architecture

Development

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tvkit-0.7.0.tar.gz (160.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tvkit-0.7.0-py3-none-any.whl (127.0 kB view details)

Uploaded Python 3

File details

Details for the file tvkit-0.7.0.tar.gz.

File metadata

  • Download URL: tvkit-0.7.0.tar.gz
  • Upload date:
  • Size: 160.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for tvkit-0.7.0.tar.gz
Algorithm Hash digest
SHA256 2ec90c524b1d26fd6a2c803cce3a68dba85cd8d06520d655d4f4187ab10ea416
MD5 2b293097456bc157b26fbff6fda9821f
BLAKE2b-256 dae41fa8a671216787003d773f4baf73d141eb4a6e3339871f2cafbd5aa34502

See more details on using hashes here.

File details

Details for the file tvkit-0.7.0-py3-none-any.whl.

File metadata

  • Download URL: tvkit-0.7.0-py3-none-any.whl
  • Upload date:
  • Size: 127.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for tvkit-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d4bcb8d4c0b2e268af1eb8cd5c88b25f6c4bca22dfd251bf16cdff6ad9fda7a0
MD5 14583fe90b010f71f12c180fe1ca2835
BLAKE2b-256 d2cb5c7d5307400a5e76d9cc339f5511636ab9791290cba092dd298d6e196519

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page