
How to Export TradingView Chart Data for Python Analysis
Table of Contents
- Introduction
- What Is Exporting TradingView Chart Data
- Why Exporting TradingView Chart Data Matters for Traders and Investors
- Core Concepts
- Step‑by‑Step Guide
- Practical Tips for Better Results
- Common Mistakes to Avoid
- Frequently Asked Questions
- Conclusion
Introduction
When the S&P 500 surged sharply last month, a wave of quant‑oriented traders rushed to see whether a simple moving‑average crossover would have signaled the rally early enough. The chart on TradingView displayed the crossover in vivid color, yet the platform does not hand the raw numbers over to a Python backtester. That missing link forces analysts either to re‑type each price point—a painstaking exercise—or to hunt for a dependable export routine.
If you have ever spent an evening copying OHLC values from a chart, you recognize the friction. The problem grows exponentially when the target is five years of daily bars for AAPL or minute‑level BTC/USD candles that feed a reinforcement‑learning loop. A clean export pipeline eliminates manual transcription errors, preserves exact timestamps, and lets you feed the data straight into pandas, zipline, backtrader, or any library that expects a tidy DataFrame.
This article walks you through three reproducible ways to export TradingView chart data into Python: a manual CSV pull via the widget endpoint, a Pine Script‑driven extraction that captures custom indicators, and a WebSocket stream for real‑time bar updates. By the end, you will have a checklist that keeps data quality high and a set of scripts you can schedule to run automatically.
What Is Exporting TradingView Chart Data
Exporting TradingView chart data means taking the price series, indicator values, or any custom calculation that appears on a TradingView pane and writing it to a machine‑readable file—most commonly CSV or JSON. Once the file lands on your disk, a Python script can read it with pandas.read_csv or pandas.read_json, transform it into a DataFrame, and hand it off to a backtesting engine without any guesswork about column order or time zones.
Example: A trader needs the daily open, high, low, close, and volume for the S&P 500 ticker SPX covering the last five years. By exporting the chart, the trader receives a CSV with roughly 1,260 rows, each row timestamped to the market close. Loading the file with pd.read_csv('spx_daily.csv') makes the series instantly available for a 200‑day moving‑average calculation or a more elaborate statistical test.
Why Exporting TradingView Chart Data Matters for Traders and Investors
Professional desks treat data as the raw material of any systematic edge. When a strategy depends on precise bar alignment, a missing minute or a mis‑aligned time zone can flip a backtest from profitable to losing in an instant.
Who uses it: Quant researchers at hedge funds, algorithmic developers building crypto bots, and retail traders who love TradingView’s charting but need the underlying series for statistical analysis.
When it matters: During market‑wide events—Fed rate decisions, earnings seasons, or geopolitical shocks—traders often re‑run models on the freshest data. A fast export eliminates the latency of manual copying and lets the analyst focus on model adjustments rather than data wrangling.
Ignoring it: Relying solely on visual inspection leaves you exposed to pattern‑recognition bias. Without exported data you cannot run robust statistical tests, compute Sharpe ratios, or perform Monte Carlo simulations that stress‑test a strategy under varied volatility regimes.
Pine Script Extraction via request.security
Pine Script executes on TradingView’s servers and can pull historical series from any ticker using the request.security function. By assigning the result to a series variable and plotting it, you also expose the values in the data window. The “Export data” button that appears there writes the series to a CSV file.
Scenario: A developer wants the 14‑period Relative Strength Index (RSI) for EUR/USD alongside raw OHLC. The script calls request.security("FX:EURUSD", "60", close) for price and ta.rsi(close, 14) for the indicator. When the chart loads, the data window lists both series; clicking “Export data” produces a CSV with timestamp, price, and RSI columns ready for Python ingestion.
TradingView Widget CSV/JSON Download Endpoints
The public charting widget hides a REST endpoint that returns the displayed series in CSV or JSON when a user appends ?download=1 (or ?format=json) to the widget URL. The endpoint respects the chart’s timeframe and symbol, delivering a clean file without writing any Pine Script.
Scenario: An analyst embeds a widget for the Nasdaq‑100 ticker NDX on a research portal. By appending ?download=1 to the widget’s source URL, a server request returns a JSON array of timestamps and close prices. A simple requests.get call in Python fetches the payload, which can be turned into a DataFrame with pd.DataFrame.from_records.
WebSocket Streaming of Real‑Time Bar Data for Python
For strategies that need live updates—such as a high‑frequency crypto arbitrage bot—polling the chart is too slow. TradingView offers a WebSocket service that streams a bar as soon as it closes. The socket emits a compact binary packet containing open, high, low, close, and volume.
Scenario: A quant builds a reinforcement‑learning environment that trains on 1‑minute BTC/USD candles. By connecting to TradingView’s WebSocket endpoint, the Python process receives each new minute bar within milliseconds of the exchange’s timestamp. The data is appended to an in‑memory pandas DataFrame, allowing the agent to react to the latest market move without the latency of HTTP requests.
Step 1 — Choose the Export Method that Fits Your Workflow
First, decide whether you need bulk historical data, custom indicator values, or a live stream. For a one‑off backtest of AAPL’s five‑year daily series, the widget CSV endpoint is fastest. If you must capture a bespoke indicator, write a Pine Script that outputs the series. For live trading, set up the WebSocket client.
Step 2 — Retrieve the Data and Save It Locally
Historical CSV: Open the TradingView chart for the desired symbol, set the timeframe, then add ?download=1 to the URL and press Enter. The browser prompts a download of symbol_timeframe.csv.
Pine Script Export: After publishing the script, open the data window (Ctrl + D). Click the “Export data” icon; the file script_output.csv appears in your downloads folder.
WebSocket: Use Python’s websocket-client library to connect to wss://data.tradingview.com/socket. Send a subscription message that specifies the symbol and resolution, for example {"sessionid":"123","symbol":"BINANCE:BTCUSDT","resolution":"1"}. The server streams JSON packets; write each packet to a line‑delimited file btcstream.jsonl.
Step 3 — Load the File into Python and Verify Integrity
text
import pandas as pd
df = pd.read_csv('symbol_timeframe.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
df.set_index('timestamp', inplace=True)
assert df.isnull().sum().sum() == 0, "Missing values detected"
For JSON‑lines files, use pd.read_json('btcstream.jsonl', lines=True). After loading, compare the row count to the expected number—1,260 daily bars for a five‑year equity series, for instance—to catch truncated downloads.
Step 4 — Integrate the Data with Your Backtesting Engine
If you run backtrader, feed the DataFrame via bt.feeds.PandasData(dataname=df). For zipline, create a DataPortal that reads the CSV. The crucial point is to keep timestamp alignment consistent with the engine’s timezone settings—U.S. equities typically use America/New_York, while crypto data defaults to UTC.
Step 5 — Automate the Pipeline for Ongoing Research
Wrap the download steps in a Python function that runs nightly via a cron job (Linux) or Task Scheduler (Windows). Store each file with a date stamp, e.g., AAPLdaily_2024-07-31.csv, to maintain version control. Consider using Git LFS or an S3 bucket for long‑term archival, and always respect TradingView’s data‑use policy as well as any licensing restrictions imposed by the SEC or CFTC for regulated symbols.
Practical Tips for Better Results
- Align time zones early. Convert all timestamps to UTC before merging datasets; mismatched zones cause off‑by‑one‑hour errors in intraday backtests.
- Trim unnecessary columns. Dropping columns you never use—such as volume for a price‑only model—reduces memory pressure when handling high‑frequency data.
- Validate against an exchange feed. Cross‑check the first and last rows of the exported CSV with a trusted source such as the NYSE or Binance API to catch any truncation or latency issues.
- Cache the request. If you repeatedly download the same five‑year series, store the file locally and refresh only when a new bar appears. This saves bandwidth and avoids hitting rate‑limit blocks.
- Watch for TradingView rate limits. The widget endpoint allows a limited number of downloads per hour; implement exponential back‑off if you receive a 429 response.
- Use compression. Save large historical files as gzip (
.csv.gz) to speed up I/O; pandas reads compressed CSVs natively. - Document the source. Include a header line in the CSV that records the original URL, export date, and any applied filters. An audit trail is useful for compliance reviews, especially when the data informs client‑facing research.
Common Mistakes to Avoid
- Assuming the chart’s timezone matches the exchange—this leads to misaligned bar boundaries.
- Exporting only the visible window—TradingView limits export to the loaded range; scroll to the full history before downloading.
- Neglecting data‑type conversion—treating timestamps as strings can break resampling logic.
- Overlooking indicator lag—exported indicator values reflect the script’s calculation period; forgetting the lag skews signal timing.
- Violating TradingView’s terms of service—using automated scrapers without permission can result in account suspension.
- Skipping integrity checks—silent NaNs or duplicate rows corrupt backtest results.
How to export TradingView chart data to CSV?
Open the chart, set the desired timeframe, then add
?download=1to the URL and press Enter. The browser will prompt a CSV download containing timestamp, open, high, low, close, and volume columns.
What file formats does TradingView support for export?
The primary format is CSV via the download endpoint. Some widget URLs also return JSON when ?format=json is appended. Pine Script’s data window can export to CSV only; there is no native Excel export.
Why does TradingView limit historical data export?
TradingView’s free tier imposes limits to protect server resources and to encourage subscription upgrades. The platform also respects exchange licensing agreements that restrict bulk historical distribution.
When should I use the TradingView REST API versus manual download?
Use the REST API (or widget endpoint) when you need automated, repeatable downloads for many symbols or frequent updates. Manual download is acceptable for a one‑off analysis of a single ticker.
Can I export indicator values from TradingView?
Yes. By embedding the indicator in a Pine Script and exposing the series in the data window, you can click “Export data” to obtain a CSV that includes both price and indicator columns.
Is exporting TradingView data legal for backtesting?
Exporting data for personal research complies with TradingView’s terms, provided you do not redistribute the raw data commercially. For regulated assets, ensure the use aligns with SEC or CFTC guidelines on data handling and record‑keeping.
Conclusion
The most important lesson is that a reliable export pipeline turns TradingView’s visual insights into quantitative inputs you can test, iterate, and automate. Start by picking the method that matches your time horizon—CSV for historical backtests, Pine Script for custom indicators, or WebSocket for live‑time strategies—then script a nightly download and run a quick integrity check before feeding the data into your backtester.
Remember, no data source guarantees future performance; always assess model risk, respect licensing rules, and keep position sizes modest until a strategy proves strong across out‑of‑sample periods. Happy coding, and trade responsibly.
—
This article is for educational purposes only and does not constitute investment advice. Trading and investing carry risk of loss; never invest more than you can afford to lose.
Last reviewed: August 2026