PINE LIBRARY

Request

█  OVERVIEW


This library is a tool for Pine Script™ programmers that consolidates access to a wide range of lesser-known data feeds available on TradingView, including metrics from the FRED database, FINRA short sale volume, open interest, and COT data. The functions in this library simplify requests for these data feeds, making them easier to retrieve and use in custom scripts.



█  CONCEPTS


Federal Reserve Economic Data (FRED)

FRED (Federal Reserve Economic Data) is a comprehensive online database curated by the Federal Reserve Bank of St. Louis. It provides free access to extensive economic and financial data from U.S. and international sources. FRED includes numerous economic indicators such as GDP, inflation, employment, and interest rates. Additionally, it provides financial market data, regional statistics, and international metrics such as exchange rates and trade balances.

Sourced from reputable organizations, including U.S. government agencies, international institutions, and other public and private entities, FRED enables users to analyze over 825,000 time series, download their data in various formats, and integrate their information into analytical tools and programming workflows.

On TradingView, FRED data is available from ticker identifiers with the "FRED:" prefix. Users can search for FRED symbols in the "Symbol Search" window, and Pine scripts can retrieve data for these symbols via `request.*()` function calls.


FINRA Short Sale Volume

FINRA (the Financial Industry Regulatory Authority) is a non-governmental organization that supervises and regulates U.S. broker-dealers and securities professionals. Its primary aim is to protect investors and ensure integrity and transparency in financial markets.

FINRA's Short Sale Volume data provides detailed information about daily short-selling activity across U.S. equity markets. This data tracks the volume of short sales reported to FINRA's trade reporting facilities (TRFs), including shares sold on FINRA-regulated Alternative Trading Systems (ATSs) and over-the-counter (OTC) markets, offering transparent access to short-selling information not typically available from exchanges. This data helps market participants, researchers, and regulators monitor trends in short-selling and gain insights into bearish sentiment, hedging strategies, and potential market manipulation. Investors often use this data alongside other metrics to assess stock performance, liquidity, and overall trading activity.

It is important to note that FINRA's Short Sale Volume data does not consolidate short sale information from public exchanges and excludes trading activity that is not publicly disseminated.

TradingView provides ticker identifiers for requesting Short Sale Volume data with the format "FINRA:<symbol>_SHORT_VOLUME", where "<symbol>" is a supported U.S. equities symbol (e.g., "AAPL").


Open Interest (OI)

Open interest is a cornerstone indicator of market activity and sentiment in derivatives markets such as options or futures. In contrast to volume, which measures the number of contracts opened or closed within a period, OI measures the number of outstanding contracts that are not yet settled. This distinction makes OI a more robust indicator of how money flows through derivatives, offering meaningful insights into liquidity, market interest, and trends. Many traders and investors analyze OI alongside volume and price action to gain an enhanced perspective on market dynamics and reinforce trading decisions.

TradingView offers many ticker identifiers for requesting OI data with the format "<id>_OI", where "<id>" represents a derivative instrument's ticker ID (e.g., "COMEX:GC1!").


Commitment of Traders (COT)

Commitment of Traders data provides an informative weekly breakdown of the aggregate positions held by various market participants, including commercial hedgers, non-commercial speculators, and small traders, in the U.S. derivative markets. Tallied and managed by the Commodity Futures Trading Commission (CFTC), these reports provide traders and analysts with detailed insight into an asset's open interest and help them assess the actions of various market players. COT data is valuable for gaining a deeper understanding of market dynamics, sentiment, trends, and liquidity, which helps traders develop informed trading strategies.

TradingView has numerous ticker identifiers that provide access to time series containing data for various COT metrics. To learn about COT ticker IDs and how they work, see our LibraryCOT publication.



█  USING THE LIBRARY


Common function characteristics

 • This library's functions construct ticker IDs with valid formats based on their specified parameters, then use them as the `symbol` argument in request.security() to retrieve data from the specified context.
 • Most of these functions automatically select the timeframe of a data request because the data feeds are not available for all timeframes.
 • All the functions have two overloads. The first overload of each function uses values with the "simple" qualifier to define the requested context, meaning the context does not change after the first script execution. The second accepts "series" values, meaning it can request data from different contexts across executions.
 • The `gaps` parameter in most of these functions specifies whether the returned data is `na` when a new value is unavailable for request. By default, its value is `false`, meaning the call returns the last retrieved data when no new data is available.
 • The `repaint` parameter in applicable functions determines whether the request can fetch the latest unconfirmed values from a higher timeframe on realtime bars, which might repaint after the script restarts. If `false`, the function only returns confirmed higher-timeframe values to avoid repainting. The default value is `true`.


`fred()`

The `fred()` function retrieves the most recent value of a specified series from the Federal Reserve Economic Data (FRED) database. With this function, programmers can easily fetch macroeconomic indicators, such as GDP and unemployment rates, and use them directly in their scripts.

How it works

The function's `fredCode` parameter accepts a "string" representing the unique identifier of a specific FRED series. Examples include "GDP" for the "Gross Domestic Product" series and "UNRATE" for the "Unemployment Rate" series. Over 825,000 codes are available. To access codes for available series, search the FRED website.

The function adds the "FRED:" prefix to the specified `fredCode` to construct a valid FRED ticker ID (e.g., "FRED:GDP"), which it uses in request.security() to retrieve the series data.

Example Usage

This line of code requests the latest value from the Gross Domestic Product series and assigns the returned value to a `gdpValue` variable:



`finraShortSaleVolume()`

The `finraShortSaleVolume()` function retrieves EOD data from a FINRA Short Sale Volume series. Programmers can call this function to retrieve short-selling information for equities listed on supported exchanges, namely NASDAQ, NYSE, and NYSE ARCA.

How it works

The `symbol` parameter determines which symbol's short sale volume information is retrieved by the function. If the value is na, the function requests short sale volume data for the chart's symbol. The argument can be the name of the symbol from a supported exchange (e.g., "AAPL") or a ticker ID with an exchange prefix ("NASDAQ:AAPL"). If the `symbol` contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", or "BATS".

The function constructs a ticker ID in the format "FINRA:ticker_SHORT_VOLUME", where "ticker" is the symbol name without the exchange prefix (e.g., "AAPL"). It then uses the ticker ID in request.security() to retrieve the available data.

Example Usage

This line of code retrieves short sale volume for the chart's symbol and assigns the result to a `shortVolume` variable:

This example requests short sale volume for the "NASDAQ:AAPL" symbol, irrespective of the current chart:



`openInterestFutures()` and `openInterestCrypto()`

The `openInterestFutures()` function retrieves EOD open interest (OI) data for futures contracts. The `openInterestCrypto()` function provides more granular OI data for cryptocurrency contracts.

How they work

The `openInterestFutures()` function retrieves EOD closing OI information. Its design is focused primarily on retrieving OI data for futures, as only EOD OI data is available for these instruments. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe.

The `openInterestCrypto()` function retrieves opening, high, low, and closing OI data for a cryptocurrency contract on a specified timeframe. Unlike `openInterest()`, this function can also retrieve granular data from intraday timeframes.

Both functions contain a `symbol` parameter that determines the symbol for which the calls request OI data. The functions construct a valid OI ticker ID from the chosen symbol by appending "_OI" to the end (e.g., "CME:ES1!_OI").

The `openInterestFutures()` function requests and returns a two-element tuple containing the futures instrument's EOD closing OI and a "bool" condition indicating whether OI is rising.

The `openInterestCrypto()` function requests and returns a five-element tuple containing the cryptocurrency contract's opening, high, low, and closing OI, and a "bool" condition indicating whether OI is rising.

Example usage

This code line calls `openInterest()` to retrieve EOD OI and the OI rising condition for a futures symbol on the chart, assigning the values to two variables in a tuple:

This line retrieves the EOD OI data for "CME:ES1!", irrespective of the current chart's symbol:


This example uses `openInterestCrypto()` to retrieve OHLC OI data and the OI rising condition for a cryptocurrency contract on the chart, sampled at the chart's timeframe. It assigns the returned values to five variables in a tuple:

This call retrieves OI OHLC and rising information for "BINANCE:BTCUSDT.P" on the "1D" timeframe:



`commitmentOfTraders()`

The `commitmentOfTraders()` function retrieves data from the Commitment of Traders (COT) reports published by the Commodity Futures Trading Commission (CFTC). This function significantly simplifies the COT request process, making it easier for programmers to access and utilize the available data.

How It Works

This function's parameters determine different parts of a valid ticker ID for retrieving COT data, offering a streamlined alternative to constructing complex COT ticker IDs manually. The `metricName`, `metricDirection`, and `includeOptions` parameters are required. They specify the name of the reported metric, the direction, and whether it includes information from options contracts.

The function also includes several optional parameters. The `CFTCCode` parameter allows programmers to request data for a specific report code. If unspecified, the function requests data based on the chart symbol's root prefix, base currency, or quoted currency, depending on the `mode` argument. The call can specify the report type ("Legacy", "Disaggregated", or "Financial") and metric type ("All", "Old", or "Other") with the `typeCOT` and `metricType` parameters.

Explore the CFTC website to find valid report codes for specific assets. To find detailed information about the metrics included in the reports and their meanings, see the CFTC's Explanatory Notes.

View the function's documentation below for detailed explanations of its parameters. For in-depth information about COT ticker IDs and more advanced functionality, refer to our previously published COT library.

Available metrics

Different COT report types provide different metrics. The tables below list all available metrics for each type and their applicable directions:



Example usage

This code line retrieves "Noncommercial Positions (Long)" data, without options information, from the "Legacy" report for the chart symbol's root, base currency, or quote currency:

This example retrieves "Managed Money Positions (Short)" data, with options included, from the "Disaggregated" report:




█  NOTES


 • This library uses dynamic requests, allowing dynamic ("series") arguments for the parameters defining the context (ticker ID, timeframe, etc.) of a `request.*()` function call. With this feature, a single `request.*()` call instance can flexibly retrieve data from different feeds across historical executions. Additionally, scripts can use such calls in the local scopes of loops, conditional structures, and even exported library functions, as demonstrated in this script. All scripts coded in Pine Script™ v6 have dynamic requests enabled by default. To learn more about the behaviors and limitations of this feature, see the Dynamic requests section of the Pine Script™ User Manual.
 • The library's example code offers a simple demonstration of the exported functions. The script retrieves available data using the function specified by the "Series type" input. The code requests a FRED series or COT (Legacy), FINRA Short Sale Volume, or Open Interest series for the chart's symbol with specific parameters, then plots the retrieved data as a step-line with diamond markers.



Look first. Then leap.



█  EXPORTED FUNCTIONS


This library exports the following functions:

fred(fredCode, gaps)
  Requests a value from a specified Federal Reserve Economic Data (FRED) series. FRED is a comprehensive source that hosts numerous U.S. economic datasets. To explore available FRED datasets and codes, search for specific categories or keywords at fred.stlouisfed.org/. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
    fredCode (series string): The unique identifier of the FRED series. The function uses the value to create a valid ticker ID for retrieving FRED data in the format `"FRED:fredCode"`. For example, `"GDP"` refers to the "Gross Domestic Product" series ("FRED:GDP"), and `"GFDEBTN"` refers to the "Federal Debt: Total Public Debt" series ("FRED:GFDEBTN").
    gaps (simple bool): Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
  Returns: (float) The value from the requested FRED series.

finraShortSaleVolume(symbol, gaps, repaint)
  Requests FINRA daily short sale volume data for a specified symbol from one of the following exchanges: NASDAQ, NYSE, NYSE ARCA. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
    symbol (series string): The symbol for which to request short sale volume data. If the specified value contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", "BATS".
    gaps (simple bool): Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
    repaint (simple bool): Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: (float) The short sale volume for the specified symbol or the chart's symbol.

openInterestFutures(symbol, gaps, repaint)
  Requests EOD open interest (OI) and OI rising information for a valid futures symbol. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
    symbol (series string): The symbol for which to request open interest data.
    gaps (simple bool): Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
    repaint (simple bool): Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: ([float, bool]) A tuple containing the following values:
    - The closing OI value for the symbol.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.

openInterestCrypto(symbol, timeframe, gaps, repaint)
  Requests opening, high, low, and closing open interest (OI) data and OI rising information for a valid cryptocurrency contract on a specified timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
    symbol (series string): The symbol for which to request open interest data.
    timeframe (series string): The timeframe of the data request. If the timeframe is lower than the chart's timeframe, it causes a runtime error.
    gaps (simple bool): Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
    repaint (simple bool): Optional. If `true` and the `timeframe` represents a higher timeframe, the function returns unconfirmed values from the timeframe on realtime bars, which repaint when the script restarts its executions. If `false`, it returns only confirmed higher-timeframe values to avoid repainting. The default is `true`.
  Returns: ([float, float, float, float, bool]) A tuple containing the following values:
    - The opening, high, low, and closing OI values for the symbol, respectively.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.

commitmentOfTraders(metricName, metricDirection, includeOptions, CFTCCode, typeCOT, mode, metricType)
  Requests Commitment of Traders (COT) data with specified parameters. This function provides a simplified way to access CFTC COT data available on TradingView. Calls to this function count toward a script's `request.*()` call limit. For more advanced tools and detailed information about COT data, see TradingView's LibraryCOT library.
  Parameters:
    metricName (series string): One of the valid metric names listed in the library's documentation and source code.
    metricDirection (series string): Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Consult the library's documentation or code to see which direction values apply to the specified metric.
    includeOptions (series bool): If `true`, the COT symbol includes options information. Otherwise, it does not.
    CFTCCode (series string): Optional. The CFTC code for the asset. For example, wheat futures (root "ZW") have the code "001602". If one is not specified, the function will attempt to get a valid code for the chart symbol's root, base currency, or main currency.
    typeCOT (series string): Optional. The type of report to request. Possible values are: "Legacy", "Disaggregated", "Financial". The default is "Legacy".
    mode (series string): Optional. Specifies the information the function extracts from a symbol. Possible modes are:
  - "Root": The function extracts the futures symbol's root prefix information (e.g., "ES" for "ESH2020").
  - "Base currency": The function extracts the first currency from a currency pair (e.g., "EUR" for "EURUSD").
  - "Currency": The function extracts the currency of the symbol's quoted values (e.g., "JPY" for "TSE:9984" or "USDJPY").
  - "Auto": The function tries the first three modes (Root -> Base currency -> Currency) until it finds a match.
  The default is "Auto". If the specified mode is not available for the symbol, it causes a runtime error.
    metricType (series string): Optional. The metric type. Possible values are: "All", "Old", "Other". The default is "All".
  Returns: (float) The specified Commitment of Traders data series. If no data is available, it causes a runtime error.
commitmentsoftradersdatafeedseconomicindicatorsfinraFederal Reserve Economic DatametricsOpen Interestsentimentalanalysisshortsstatisticstechindicator

ספריית Pine

ברוח TradingView אמיתית, המחבר פרסם קוד Pine זה כספריית קוד פתוח כדי שמתכנתי Pine אחרים מהקהילה שלנו יוכלו לעשות בו שימוש חוזר. כל הכבוד למחבר! אתה יכול להשתמש בספרייה זו באופן פרטי או בפרסומים אחרים בקוד פתוח, אך שימוש חוזר בקוד זה בפרסום כפוף לכללי הבית.


Share TradingView with a friend:
tradingview.com/share-your-love/

Read more about the new tools and features we're building for you: tradingview.com/blog/en/
גם על:

כתב ויתור