python-tradingview-ta

repository·main·Indexed 22 days ago

https://github.com/analyzerrest/python-tradingview-ta

An unofficial Python API wrapper for TradingView that allows developers to fetch technical analysis data, including recommendations and indicator counts, without needing Selenium. It provides the TA_Handler class for single symbol analysis, get_multiple_analysis for batch requests, and a search function for asset discovery. Supports various time intervals via the Interval class and provides access to oscillators, moving averages, and raw technical indicators.

Tokens
3.7K
Snippets
10
Records
22
Agent score
77%

What's inside tradingview-ta

  1. Important limitations and warnings

    main

    Limitations

    • Indices Support: Technical analysis for indices (index) is currently not supported by TradingView or this library.
    • Indicators: Only TradingView built-in indicators are supported. Custom Pine Script indicators are not supported.

    Warnings

    • Risk: Trading is risky, especially with automated programs. Never trade automatically without human supervision. The authors are not responsible for any monetary losses.

    Maintenance

    Keep the package up to date to receive new features and bug fixes:

    pip install -U tradingview_ta
  2. Install tradingview-ta

    main

    You can install the stable version via PyPI or the latest version directly from GitHub.

    Stable (Recommended):

    pip install tradingview_ta

    Latest (GitHub):

    pip install git+https://github.com/analyzerrest/python-tradingview-ta.git

    Requirements:

    • Python 3.6 or newer.
    • requests (automatically included during installation).
  3. Quick Start with TA_Handler

    main

    To perform technical analysis, instantiate a TA_Handler with the target symbol, screener, exchange, and time interval. Use the .get_analysis().summary method to retrieve a recommendation summary.

    Required imports:

    • TA_Handler: The main class for handling analysis requests.
    • Interval: Enum for time intervals (e.g., Interval.INTERVAL_1_DAY).
    • Exchange: Enum for exchanges (if applicable).
    from tradingview_ta import TA_Handler, Interval, Exchange
    
    tesla = TA_Handler(
        symbol="TSLA",
        screener="america",
        exchange="NASDAQ",
        interval=Interval.INTERVAL_1_DAY
    )
    print(tesla.get_analysis().summary)
    # Example output: {"RECOMMENDATION": "BUY", "BUY": 8, "NEUTRAL": 6, "SELL": 3}
  4. Configure proxies for TA_Handler and get_multiple_analysis

    main

    You can pass a proxies dictionary to both TA_Handler() and get_multiple_analysis() to route requests through a proxy server.

    Example format: proxies={'http': 'http://example.com:8080', 'https': 'https://example.com:443'}

    from tradingview_ta import TA_Handler, Interval
    
    tesla = TA_Handler(
        symbol="TSLA",
        screener="america",
        exchange="NASDAQ",
        interval=Interval.INTERVAL_1_DAY,
        proxies={'http': 'http://0.0.0.0:8080', 'https': 'https://0.0.0.0:443'}
    )
  5. Understand the Analysis object structure

    main

    The Analysis object is returned by get_analysis() and contains the computed technical data for the requested symbol. It includes:

    • summary: A dictionary with RECOMMENDATION (e.g., "BUY", "SELL", "NEUTRAL") and counts for BUY, SELL, and NEUTRAL.
    • oscillators: A dictionary containing the RECOMMENDATION, counts for BUY, SELL, NEUTRAL, and a COMPUTE dictionary with individual indicator values.
    • moving_averages: A dictionary containing the RECOMMENDATION, counts for BUY, SELL, NEUTRAL, and a COMPUTE dictionary with individual indicator values.
    • indicators: A dictionary of the raw indicator values requested.
  6. Troubleshoot 4XX errors

    main

    If you encounter HTTP 4XX errors, check the following:

    • 400 Error (Bad Request): Usually indicates an invalid request, often because the requested indicators do not exist. Refer to this list of valid indicators to verify your configuration.
    • 404 Error (Not Found): Usually indicates that the screener does not exist. Verify that your screener, symbol, and exchange are correct using this validation tool.
  7. Create a basic trading bot template

    main

    You can use TA_Handler to build a trading bot by continuously polling for recommendations and executing logic based on the RECOMMENDATION field.

    Important Considerations:

    • Risk: Trading with bots is highly risky. Always use paper trading before using real funds.
    • State Management: The last_order variable in the example below is stored in memory. If the program exits, the state is lost, and the bot will default to creating a new buy order upon restart.
    • Timing: The time.sleep() duration should ideally match the interval used in the TA_Handler to avoid redundant requests.
    # Import packages.
    from tradingview_ta import TA_Handler, Interval, Exchange
    import time
    
    # Store the last order.
    last_order = "sell"
    
    # Instantiate TA_Handler.
    handler = TA_Handler(
        symbol="SYMBOL",
        exchange="EXCHANGE",
        screener="SCREENER",
        interval="INTERVAL",
    )
    
    # Repeat forever.
    while True:
        # Retrieve recommendation.
        rec = handler.get_analysis()["RECOMMENDATION"]
    
        # Create a buy order if the recommendation is "BUY" or "STRONG_BUY" and the last order is "sell".
        # Create a sell order if the recommendation is "SELL" or "STRONG_SELL" and the last order is "buy".
        if "BUY" in rec and last_order == "sell":
            # REPLACE COMMENT: Create a buy order using your exchange's API.
            last_order = "buy"
        elif "SELL" in rec and last_order == "buy":
            # REPLACE COMMENT: Create a sell order using your exchange's API.
            last_order = "sell"
    
        # Wait for x seconds before retrieving new analysis.
        # The time should be the same as the interval.
        time.sleep(x)
  8. Get technical analysis summary with TA_Handler

    main

    To fetch technical analysis data, instantiate a TA_Handler with the required market parameters and call .get_analysis().summary.

    Parameters:

    • symbol: The ticker symbol (e.g., "TSLA").
    • screener: The market screener (e.g., "america").
    • exchange: The exchange name (e.g., "NASDAQ").
    • interval: An Interval enum value (e.g., Interval.INTERVAL_1_DAY).
    • proxies (optional): A dictionary to enable proxy support, e.g., {'http': 'http://example.com:8080'}.

    Output Format: The .summary attribute returns a dictionary containing the recommendation and counts for BUY, NEUTRAL, and SELL signals. Example: {"RECOMMENDATION": "BUY", "BUY": 8, "NEUTRAL": 6, "SELL": 3}.

    Tip: If you are unsure of the correct symbol, screener, or exchange values, use https://tvdb.analyzer.rest/ to look them up.

    from tradingview_ta import TA_Handler, Interval, Exchange
    
    tesla = TA_Handler(
        symbol="TSLA",
        screener="america",
        exchange="NASDAQ",
        interval=Interval.INTERVAL_1_DAY,
        # proxies={'http': 'http://example.com:8080'} # Uncomment to enable proxy (replace the URL).
    )
    print(tesla.get_analysis().summary)
    # Example output: {"RECOMMENDATION": "BUY", "BUY": 8, "NEUTRAL": 6, "SELL": 3}
  9. Retrieve technical analysis using get_analysis()

    main

    Calling handler.get_analysis() returns an Analysis object containing technical data.

    Key Attributes of the Analysis object:

    • summary (dict): Combined recommendation from oscillators and moving averages. Example: {'RECOMMENDATION': 'BUY', 'BUY': 12, 'SELL': 7, 'NEUTRAL': 9}.
    • oscillators (dict): Analysis based specifically on oscillators (includes a COMPUTE key with individual indicator results).
    • moving_averages (dict): Analysis based specifically on moving averages (includes a COMPUTE key with individual indicator results).
    • indicators (dict): Raw technical indicator values (e.g., RSI, MACD, EMA, SMA).
    • time (datetime.datetime): The timestamp of the retrieved data.

    Commonly used indicators:

    • Opening price: analysis.indicators["open"]
    • Closing price: analysis.indicators["close"]
    • Momentum: analysis.indicators["Mom"]
    • RSI: analysis.indicators["RSI"]
    • MACD: analysis.indicators["MACD.macd"]
    analysis = handler.get_analysis()