tvdatafeed

repository·main·Indexed 20 days ago

https://github.com/rongardf/tvdatafeed

A Python library for downloading historical and live market data from TradingView. It allows users to retrieve up to 5000 bars of OHLCV data as pandas DataFrames across various timeframes and exchanges. The library includes the TvDatafeed class for historical data and a TvDatafeedLive subclass for handling near real-time data updates via a Seis (symbol-exchange-interval-set) and Consumer callback model.

Tokens
3K
Snippets
15
Records
16
Agent score
71%

What's inside tvdatafeed

  1. How TvDatafeedLive works

    main

    TvDatafeedLive is a subclass of TvDatafeed that provides a live data feed feature. It uses a Seis (symbol-exchange-interval-set) and Consumer model:

    1. Seis: A unique combination of symbol, exchange, and interval. Creating a seis via tvl.new_seis starts a background thread that waits for new data bars from TradingView.
    2. Consumer: A callback function registered to a seis. When a new data bar is retrieved, the consumer function is called with the seis object and the new data as a pandas DataFrame.

    Note: This provides data as close to real-time as possible via threading, but it is not true real-time data.

    from tvDatafeed import TvDatafeedLive, Interval
    
    tvl = TvDatafeedLive('username', 'password')
    seis = tvl.new_seis('ETHUSDT', 'BINANCE', Interval.in_1_hour)
    
    def my_callback(seis, data):
        print(f"New price: {data.close[0]}")
    
    tvl.new_consumer(seis, my_callback)
  2. Initialize TvDatafeed

    main

    To use TvDatafeed, import the class and initialize it with your TradingView credentials. You can also initialize it without logging in, though this may result in limited symbol availability and access.

    from tvDatafeed import TvDatafeed, Interval
    
    # With login
    username = 'YourTradingViewUsername'
    password = 'YourTradingViewPassword'
    tv = TvDatafeed(username, password)
    
    # Without login (may be limited)
    tv = TvDatafeed()
  3. Handle continuous futures contracts

    main

    When requesting data for futures, use the fut_contract parameter in get_hist() to specify which contract in the continuous series to retrieve:

    • None: Returns the cash/spot price.
    • 1: Returns the continuous current contract in front.
    • 2: Returns the continuous next contract in front.
    # Get the current continuous contract for CRUDEOIL on MCX
    tv.get_hist("CRUDEOIL", "MCX", fut_contract=1)
  4. Initialize TvDatafeed with TradingView credentials

    main

    To use tvDatafeed, you must first provide your TradingView username and password to initialize the TvDatafeed object. This object serves as the primary interface for fetching historical market data.

    from tvDatafeed import TvDatafeed
    
    username = 'YourTradingViewUserName'
    password = 'YourTradingViewPassword'
    
    tv = TvDatafeed(username=username, password=password)
  5. Get historical data in TvDatafeedLive

    main

    Both TvDatafeedLive and Seis objects support retrieving historical data.

    • tvl.get_hist(...): Same as standard TvDatafeed.get_hist, but adds an optional timeout parameter (default -1).
    • seis.get_hist(n_bars=10, timeout=-1): Retrieves history specifically for that seis instance. Defaults to 10 bars.
    # From the live instance
    data = tvl.get_hist('BTCUSDT', 'BINANCE', interval=Interval.in_1_hour, n_bars=100, timeout=10)
    
    # From a specific seis instance
    data = seis.get_hist(n_bars=50)
  6. Manage live feeds with Seis and Consumers

    main

    When using TvDatafeedLive, you can manage the lifecycle of data streams using the following methods:

    Seis Management

    • tvl.new_seis(symbol, exchange, interval, timeout=-1): Creates a new stream. The timeout parameter specifies the maximum wait time for the call (defaults to -1, no timeout).
    • tvl.del_seis(seis) or seis.del_seis(): Removes the stream.

    Consumer Management

    • tvl.new_consumer(seis, callback) or seis.new_consumer(callback): Registers a callback function. The function must accept (seis, data) where data is a pandas DataFrame.
    • tvl.del_consumer(consumer), seis.del_consumer(consumer), or consumer.del_consumer(): Removes the callback.
    # Example Consumer Callback
    def consumer_func(seis, data):
        print(f"Open price for {seis.symbol}: {data.open[0]}")
    
    # Setup
    seis = tvl.new_seis('ETHUSDT', 'BINANCE', Interval.in_1_hour)
    consumer = seis.new_consumer(consumer_func)
    
    # Cleanup
    consumer.del_consumer()
    seis.del_seis()
  7. Download historical data with get_hist

    main

    Use the tv.get_hist method to download historical data as a pandas DataFrame. It supports up to 5000 bars.

    # Example: Get NIFTY index data
    nifty_index_data = tv.get_hist(symbol='NIFTY', exchange='NSE', interval=Interval.in_1_hour, n_bars=1000)
    
    # Example: Get futures continuous contract
    nifty_futures_data = tv.get_hist(symbol='NIFTY', exchange='NSE', interval=Interval.in_1_hour, n_bars=1000, fut_contract=1)
    
    # Example: Get crude oil data
    crudeoil_data = tv.get_hist(symbol='CRUDEOIL', exchange='MCX', interval=Interval.in_1_hour, n_bars=5000, fut_contract=1)
    
    # Example: Download data for extended market hours
    extended_price_data = tv.get_hist(symbol="EICHERMOT", exchange="NSE", interval=Interval.in_1_hour, n_bars=500, extended_session=False)
  8. Supported Time Intervals

    main

    The following intervals are available via the Interval class:

    • Interval.in_1_minute
    • Interval.in_3_minute
    • Interval.in_5_minute
    • Interval.in_15_minute
    • Interval.in_30_minute
    • Interval.in_45_minute
    • Interval.in_1_hour
    • Interval.in_2_hour
    • Interval.in_3_hour
    • Interval.in_4_hour
    • Interval.in_daily
    • Interval.in_weekly
    • Interval.in_monthly
  9. Plot candlestick charts with mplfinance

    main

    The data returned by get_hist() can be plotted using mplfinance. To create a candlestick chart, pass the first N rows of your data to mpf.plot() and specify type='candle'.

    import mplfinance as mpf
    
    # Assuming etheur_data was fetched via tv.get_hist()
    mpf.plot(etheur_data.head(100), type='candle', style='yahoo', volume=True)
  10. Fetch historical data with get_hist()

    main

    Use the get_hist() method to retrieve historical market data. The method accepts the symbol, the exchange, and several optional parameters to refine the data retrieval.

    Parameters:

    • symbol (str): The ticker symbol (e.g., 'AAPL', 'BTCUSD').
    • exchange (str): The exchange name (e.g., 'NASDAQ', 'BINANCE', 'CME').
    • interval (Interval): The timeframe for the data. Use the Interval enum (e.g., Interval.in_1_hour, Interval.in_1_minute).
    • n_bars (int, optional): The number of data points to retrieve.
    • fut_contract (int, optional): Set to 1 to fetch continuous futures contracts.
    # Basic usage
    tv.get_hist('AAPL', 'NASDAQ')
    
    # Usage with interval and bar count
    nifty_data = tv.get_hist('NIFTY', 'NSE', interval=Interval.in_1_hour, n_bars=1000)
    
    # Fetching continuous futures contract
    crudeoil_data = tv.get_hist('CRUDEOIL', 'MCX', Interval.in_2_hour, n_bars=5000, fut_contract=1)