tradingview-screener

repository·master·Indexed 19 days ago

https://github.com/shner-elmo/tradingview-screener

A Python wrapper for TradingView's official /screener API that allows users to query stocks, crypto, options, and more using a SQL-like syntax without web scraping. Version 3.2.1 provides a Query interface to select columns, apply filters via the Column class, and manage pagination. It supports specialized functions for different markets (stocks, crypto, forex, etc.), multiple timeframes, and real-time data access via session cookies.

Tokens
6.5K
Snippets
25
Records
27
Agent score
77%

What's inside tradingview-screener

  1. Access different timeframes for fields

    master

    Many fields (like prices and indicators) support multiple timeframes using a pipe | syntax. Use the following mapping for column names:

    TimeframeColumn Syntax
    1 Minutefield|1
    5 Minutesfield|5
    15 Minutesfield|15
    30 Minutesfield|30
    1 Hourfield|60
    2 Hoursfield|120
    4 Hoursfield|240
    1 Dayfield
    1 Weekfield|1W
    1 Monthfield|1M
  2. Access real-time data using session cookies

    master

    To access real-time (streaming) data instead of delayed data, you must pass authenticated session cookies to .get_scanner_data(cookies=...).

    rookiepy can automatically extract cookies from your local browser session.

    1. pip install rookiepy
    2. Load cookies:
    import rookiepy
    cookies = rookiepy.to_cookiejar(rookiepy.chrome(['.tradingview.com']))
    1. Pass to query:
    Query().get_scanner_data(cookies=cookies)

    Option 2: Manual Extraction

    1. Log in to TradingView.
    2. Open Developer Tools (Ctrl + Shift + I) -> Application tab.
    3. Navigate to Storage > Cookies > https://www.tradingview.com/.
    4. Copy the value of sessionid.
    5. Pass as a dictionary:
    cookies = {'sessionid': '<your-session-id>'}
    Query().get_scanner_data(cookies=cookies)

    Option 3: Authenticate via API

    Note: This method is prone to CAPTCHA and account flagging due to login frequency restrictions.

    from http.cookiejar import CookieJar
    import requests
    from tradingview_screener import Query
    
    def authenticate(username: str, password: str) -> CookieJar:
        session = requests.Session()
        r = session.post(
           'https://www.tradingview.com/accounts/signin/', 
           headers={'User-Agent': 'Mozilla/5.0', 'Referer': 'https://www.tradingview.com'},
           data={'username': username, 'password': password, 'remember': 'on'},
           timeout=60,
        )
        r.raise_for_status()
        if r.json().get('error'):
            raise Exception(f'Failed to authenticate: \n{r.json()}')
        return session.cookies
    
    cookies = authenticate('<your-username>', '<your-password>')
    Query().get_scanner_data(cookies=cookies)
  3. Basic usage with Query.select() and get_scanner_data()

    master

    To perform a simple query, instantiate a Query object, use .select() to specify the columns/fields you want to retrieve, and call .get_scanner_data() to execute the request. By default, the result is limited to 50 rows.

    from tradingview_screener import Query
    
    x = (Query()
     .select('name', 'close', 'volume', 'market_cap_basic')
     .get_scanner_data())
    print(x)
  4. Filter data using where() and where2()

    master

    The Query class provides two ways to filter data:

    1. where(*expressions): Used for simple filtering where all provided expressions are joined with the AND operator. It accepts FilterOperationDict objects (typically created via Column comparisons).
    2. where2(operation): Used for complex logical filtering involving nested AND and OR operators. The argument must be wrapped in And() or Or() functions.

    Logical Operators

    • And(*expressions): Joins expressions with an AND logic.
    • Or(*expressions): Joins expressions with an OR logic.
    from tradingview_screener import Query, And, Or
    from tradingview_screener.column import Column
    
    # Simple AND filtering via where()
    Query().where(Column('close') >= 350, Column('volume') > 1000000)
    
    # Complex nested filtering via where2()
    Query().where2(
        Or(
            And(Column('type') == 'stock', Column('typespecs').has(['common'])),
            Column('type') == 'dr'
        )
    )
  5. Build advanced queries with filtering and ordering

    master

    You can build complex queries by chaining methods. Use col() to reference specific fields for logical operations in .where(). Supported methods include:

    • .select(*fields): Specify columns to retrieve.
    • .where(*conditions): Apply SQL-like filtering (supports AND/OR logic).
    • .order_by(field, ascending=True/False): Sort results.
    • .offset(n): Skip the first n rows.
    • .limit(n): Restrict the number of rows returned.
    from tradingview_screener import Query, col
    
    (Query()
     .select('name', 'close', 'close|1', 'close|5', 'volume', 'relative_volume_10d_calc')
     .where(
         col('market_cap_basic').between(1_000_000, 50_000_000),
         col('relative_volume_10d_calc') > 1.2,
         col('MACD.macd|1') >= col('MACD.signal|1')  # 1 minute MACD
     )
     .order_by('volume', ascending=False)
     .offset(5)
     .limit(25)
     .get_scanner_data())
  6. Use specialized screener functions for different markets

    master

    The package provides top-level functions to quickly target specific markets. These functions return a Query object, allowing you to chain further methods like .select() or .where().

    Available screener functions:

    • stocks(country)
    • crypto()
    • crypto_dex()
    • coin()
    • forex()
    • futures()
    • bond()
    • cfd()
    • options(symbol)
    from tradingview_screener import stocks, crypto, options
    
    # top stocks by market cap in Italy
    stocks('italy').limit(5).get_scanner_data()
    
    # top CEX crypto pairs by 24 h volume
    crypto().limit(5).get_scanner_data()
    
    # AAPL options chain
    options('NASDAQ:AAPL').limit(5).get_scanner_data()
  7. Sort, Limit, and Offset query results

    master

    Control the order and pagination of your results using these methods:

    • .order_by(column, ascending=True, nulls_first=False): Sorts by the specified column. Set ascending=False for descending order.
    • .limit(limit): Sets the maximum number of records to return.
    • .offset(offset): Sets the number of records to skip.
    (Query()
        .order_by('volume', ascending=False)
        .limit(50)
        .offset(10)
        .get_scanner_data())
  8. Perform percentage-based comparisons with Column

    master

    The Column class provides specialized methods for comparing a field against another column or value using percentage thresholds. This is useful for technical analysis (e.g., checking if price is a certain percentage above an EMA).

    • above_pct(column, pct): Checks if the column is above the target by a multiplier pct (e.g., 1.03 for 3%).
    • below_pct(column, pct): Checks if the column is below the target by a multiplier pct.
    • between_pct(column, pct1, [pct2]): Checks if the percentage difference is within a range.
    • not_between_pct(column, pct1, [pct2]): Checks if the percentage difference is outside a range.
    from tradingview_screener.column import Column
    
    # Close is > 3% above VWAP
    cond1 = Column('close').above_pct('VWAP', 1.03)
    
    # Close is > 150% above 52-week low
    cond2 = Column('close').above_pct('price_52_week_low', 2.5)
    
    # Percentage change between Close and EMA200 is between 20% and 50%
    cond3 = Column('close').between_pct('EMA200', 1.2, 1.5)
  9. Access stock screeners with `stocks()`

    master

    Use stocks(market: str) to create a Query object for stocks (including common, preferred, DRs, and non-ETF funds). The results are filtered to primary listings and sorted by market cap in descending order.

    Parameters:

    • market: The market or country to scan (e.g., 'america', 'italy', 'germany'). Defaults to 'america'.
    from tradingview_screener import stocks
    
    # Get US stocks
    query = stocks(market='america')
    
    # Get Italian stocks
    query = stocks(market='italy')
  10. Set markets and asset classes

    master

    Use .set_markets(*markets) to define which market or country to scan.

    • If a single market is provided, the query targets that specific market URL.
    • If multiple markets are provided, the query targets the global market URL.

    Supported values include countries (e.g., 'italy', 'america') and asset classes (e.g., 'crypto', 'forex', 'futures', 'options', 'cfd', 'bonds').

    # Single market
    Query().set_markets('italy')
    
    # Multiple markets (uses global URL)
    Query().set_markets('america', 'israel', 'hongkong')
    
    # Asset classes
    Query().set_markets('crypto', 'forex')
  11. Select specific columns in a Query

    master

    Use the .select() method to specify which data fields you want to retrieve. You can pass either string names of the columns or Column objects.

    Available columns can be found in the project's Fields documentation.

    # Using strings
    Query().select('open', 'high', 'low', 'VWAP')
    
    # Using Column objects
    from tradingview_screener.column import Column
    Query().select(Column('open'), Column('high'))