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:_SHORT_VOLUME", where "" 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 "_OI", where "" 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:
float gdpValue = fred("GDP")
`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:
float shortVolume = finraShortSaleVolume(syminfo.tickerid)
This example requests short sale volume for the "NASDAQ:AAPL" symbol, irrespective of the current chart:
float shortVolume = finraShortSaleVolume("NASDAQ:AAPL")
`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:
= openInterestFutures(syminfo.tickerid)
This line retrieves the EOD OI data for "CME:ES1!", irrespective of the current chart's symbol:
= openInterestFutures("CME:ES1!")
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:
= openInterestCrypto(syminfo.tickerid, timeframe.period)
This call retrieves OI OHLC and rising information for "BINANCE:BTCUSDT.P" on the "1D" timeframe:
= openInterestCrypto("BINANCE:BTCUSDT.P", "1D")
`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:
+------------------------------+------------------------+
| Legacy (COT) Metric Names | Directions |
+------------------------------+------------------------+
| Open Interest | No direction |
| Noncommercial Positions | Long, Short, Spreading |
| Commercial Positions | Long, Short |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No direction |
| Traders Noncommercial | Long, Short, Spreading |
| Traders Commercial | Long, Short |
| Traders Total Reportable | Long, Short |
| Concentration Gross LT 4 TDR | Long, Short |
| Concentration Gross LT 8 TDR | Long, Short |
| Concentration Net LT 4 TDR | Long, Short |
| Concentration Net LT 8 TDR | Long, Short |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names | Directions |
+-----------------------------------+------------------------+
| Open Interest | No Direction |
| Producer Merchant Positions | Long, Short |
| Swap Positions | Long, Short, Spreading |
| Managed Money Positions | Long, Short, Spreading |
| Other Reportable Positions | Long, Short, Spreading |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No Direction |
| Traders Producer Merchant | Long, Short |
| Traders Swap | Long, Short, Spreading |
| Traders Managed Money | Long, Short, Spreading |
| Traders Other Reportable | Long, Short, Spreading |
| Traders Total Reportable | Long, Short |
| Concentration Gross LE 4 TDR | Long, Short |
| Concentration Gross LE 8 TDR | Long, Short |
| Concentration Net LE 4 TDR | Long, Short |
| Concentration Net LE 8 TDR | Long, Short |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| Financial (COT3) Metric Names | Directions |
+-------------------------------+------------------------+
| Open Interest | No Direction |
| Dealer Positions | Long, Short, Spreading |
| Asset Manager Positions | Long, Short, Spreading |
| Leveraged Funds Positions | Long, Short, Spreading |
| Other Reportable Positions | Long, Short, Spreading |
| Total Reportable Positions | Long, Short |
| Nonreportable Positions | Long, Short |
| Traders Total | No Direction |
| Traders Dealer | Long, Short, Spreading |
| Traders Asset Manager | Long, Short, Spreading |
| Traders Leveraged Funds | Long, Short, Spreading |
| Traders Other Reportable | Long, Short, Spreading |
| Traders Total Reportable | Long, Short |
| Concentration Gross LE 4 TDR | Long, Short |
| Concentration Gross LE 8 TDR | Long, Short |
| Concentration Net LE 4 TDR | Long, Short |
| Concentration Net LE 8 TDR | Long, Short |
+-------------------------------+------------------------+
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:
float nonCommercialLong = commitmentOfTraders("Noncommercial Positions", "Long", false)
This example retrieves "Managed Money Positions (Short)" data, with options included, from the "Disaggregated" report:
float disaggregatedData = commitmentOfTraders("Managed Money Positions", "Short", true, "", "Disaggregated")
█ 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: ( ) 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: ( ) 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.
Metrics
analytics_tablesLibrary "analytics_tables"
📝 Description
This library provides the implementation of several performance-related statistics and metrics, presented in the form of tables.
The metrics shown in the afforementioned tables where developed during the past years of my in-depth analalysis of various strategies in an atempt to reason about the performance of each strategy.
The visualization and some statistics where inspired by the existing implementations of the "Seasonality" script, and the performance matrix implementations of @QuantNomad and @ZenAndTheArtOfTrading scripts.
While this library is meant to be used by my strategy framework "Template Trailing Strategy (Backtester)" script, I wrapped it in a library hoping this can be usefull for other community strategy scripts that will be released in the future.
🤔 How to Guide
To use the functionality this library provides in your script you have to import it first!
Copy the import statement of the latest release by pressing the copy button below and then paste it into your script. Give a short name to this library so you can refer to it later on. The import statement should look like this:
import jason5480/analytics_tables/1 as ant
There are three types of tables provided by this library in the initial release. The stats table the metrics table and the seasonality table.
Each one shows different kinds of performance statistics.
The table UDT shall be initialized once using the `init()` method.
They can be updated using the `update()` method where the updated data UDT object shall be passed.
The data UDT can also initialized and get updated on demend depending on the use case
A code example for the StatsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(SideStats.new(), SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var statsTable = ant.StatsTable.new().init(ant.getTablePos('TOP', 'RIGHT'))
statsTable.update(statsData)
A code example for the MetricsTable is the following:
var ant.StatsData statsData = ant.StatsData.new()
statsData.update(ant.SideStats.new(), ant.SideStats.new(), 0)
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var metricsTable = ant.MetricsTable.new().init(ant.getTablePos('BOTTOM', 'RIGHT'))
metricsTable.update(statsData, 10)
A code example for the SeasonalityTable is the following:
var ant.SeasonalData seasonalData = ant.SeasonalData.new().init(Seasonality.monthOfYear)
seasonalData.update()
if (barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed))
var seasonalTable = ant.SeasonalTable.new().init(seasonalData, ant.getTablePos('BOTTOM', 'LEFT'))
seasonalTable.update(seasonalData)
🏋️♂️ Please refer to the "EXAMPLE" regions of the script for more advanced and up to date code examples!
Special thanks to @Mrcrbw for the proposal to develop this library and @DCNeu for the constructive feedback 🏆.
getTablePos(ypos, xpos)
Get table position compatible string
Parameters:
ypos (simple string) : The position on y axise
xpos (simple string) : The position on x axise
Returns: The position to be passed to the table
method init(this, pos, height, width, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor)
Initialize the stats table object with the given colors in the given position
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts height. By default, 0 auto-adjusts the width based on the text inside the cells
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, pos, height, width, neutralBgColor)
Initialize the metrics table object with the given colors in the given position
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
pos (simple string) : The table position string
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
neutralBgColor (simple color) : The background color with transparency when neutral
method init(this, seas)
Initialize the seasonal data
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
seas (simple Seasonality) : The seasonality of the matrix data
method init(this, data, pos, maxNumOfYears, height, width, extended, neutralTxtColor, neutralBgColor)
Initialize the seasonal table object with the given colors in the given position
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonality data of the table
pos (simple string) : The table position string
maxNumOfYears (simple int) : The maximum number of years that fit into the table
height (simple float) : The height of the table as a percentage of the charts height. By default, 0 auto-adjusts the height based on the text inside the cells
width (simple float) : The width of the table as a percentage of the charts width. By default, 0 auto-adjusts the width based on the text inside the cells
extended (simple bool) : The seasonal table with extended columns for performance
neutralTxtColor (simple color) : The text color when neutral
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, wins, losses, numOfInconclusiveExits)
Update the strategy info data of the strategy
Namespace types: StatsData
Parameters:
this (StatsData) : The strategy statistics object
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (int) : The number of inconclusive trades
method update(this, stats, positiveTxtColor, negativeTxtColor, negativeBgColor, neutralBgColor)
Update the stats table object with the given data
Namespace types: StatsTable
Parameters:
this (StatsTable) : The stats table object
stats (StatsData) : The stats data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
method update(this, stats, buyAndHoldPerc, positiveTxtColor, negativeTxtColor, positiveBgColor, negativeBgColor)
Update the metrics table object with the given data
Namespace types: MetricsTable
Parameters:
this (MetricsTable) : The metrics table object
stats (StatsData) : The stats data to update the table
buyAndHoldPerc (float) : The buy and hold percetage
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
method update(this)
Update the seasonal data based on the season and eon timeframe
Namespace types: SeasonalData
Parameters:
this (SeasonalData) : The seasonal data object
method update(this, data, positiveTxtColor, negativeTxtColor, neutralTxtColor, positiveBgColor, negativeBgColor, neutralBgColor, timeBgColor)
Update the seasonal table object with the given data
Namespace types: SeasonalTable
Parameters:
this (SeasonalTable) : The seasonal table object
data (SeasonalData) : The seasonal cell data to update the table
positiveTxtColor (simple color) : The text color when positive
negativeTxtColor (simple color) : The text color when negative
neutralTxtColor (simple color) : The text color when neutral
positiveBgColor (simple color) : The background color with transparency when positive
negativeBgColor (simple color) : The background color with transparency when negative
neutralBgColor (simple color) : The background color with transparency when neutral
timeBgColor (simple color) : The background color of the time gradient
SideStats
Object that represents the strategy statistics data of one side win or lose
Fields:
numOf (series int)
sumFreeProfit (series float)
freeProfitStDev (series float)
sumProfit (series float)
profitStDev (series float)
sumGain (series float)
gainStDev (series float)
avgQuantityPerc (series float)
avgCapitalRiskPerc (series float)
avgTPExecutedCount (series float)
avgRiskRewardRatio (series float)
maxStreak (series int)
StatsTable
Object that represents the stats table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
StatsData
Object that represents the statistics data of the strategy
Fields:
wins (SideStats)
losses (SideStats)
numOfInconclusiveExits (series int)
avgFreeProfitStr (series string)
freeProfitStDevStr (series string)
lossFreeProfitStDevStr (series string)
avgProfitStr (series string)
profitStDevStr (series string)
lossProfitStDevStr (series string)
avgQuantityStr (series string)
MetricsTable
Object that represents the metrics table
Fields:
table (series table) : The actual table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
SeasonalData
Object that represents the seasonal table dynamic data
Fields:
seasonality (series Seasonality)
eonToMatrixRow (map)
numOfEons (series int)
mostRecentMatrixRow (series int)
balances (matrix)
returnPercs (matrix)
maxDDs (matrix)
eonReturnPercs (array)
eonCAGRs (array)
eonMaxDDs (array)
SeasonalTable
Object that represents the seasonal table
Fields:
table (series table) : The actual table
headRows (series int) : The number of head rows of the table
headColumns (series int) : The number of head columns of the table
eonRows (series int) : The number of eon rows of the table
seasonColumns (series int) : The number of season columns of the table
statsRows (series int)
statsColumns (series int) : The number of stats columns of the table
rows (series int) : The number of rows of the table
columns (series int) : The number of columns of the table
extended (series bool) : Whether the table has additional performance statistics
Day/Week/Month Metrics (Zeiierman)█ Overview
The Day/Week/Month Metrics (Zeiierman) indicator is a powerful tool for traders looking to incorporate historical performance into their trading strategy. It computes statistical metrics related to the performance of a trading instrument on different time scales: daily, weekly, and monthly. Breaking down the performance into daily, weekly, and monthly metrics provides a granular view of the instrument's behavior.
The indicator requires the chart to be set on a daily timeframe.
█ Key Statistics
⚪ Day in month
The performance of financial markets can show variability across different days within a month. This phenomenon, often referred to as the "monthly effect" or "turn-of-the-month effect," suggests that certain days of the month, especially the first and last days, tend to exhibit higher than average returns in many stock markets around the world. This effect is attributed to various factors including payroll contributions, investment of monthly dividends, and psychological factors among traders and investors.
⚪ Edge
The Edge calculation identifies days within a month that consistently outperform the average monthly trading performance. It provides a statistical advantage by quantifying how often trading on these specific days yields better returns than the overall monthly average. This insight helps traders understand not just when returns might be higher, but also how reliable these patterns are over time. By focusing on days with a higher "Edge," traders can potentially increase their chances of success by aligning their strategies with historically more profitable days.
⚪ Month
Historically, the stock market has exhibited seasonal trends, with certain months showing distinct patterns of performance. One of the most well-documented patterns is the "Sell in May and go away" phenomenon, suggesting that the period from November to April has historically brought significantly stronger gains in many major stock indices compared to the period from May to October. This pattern highlights the potential impact of seasonal investor sentiment and activities on market performance.
⚪ Day in week
Various studies have identified the "day-of-the-week effect," where certain days of the week, particularly Monday and Friday, show different average returns compared to other weekdays. Historically, Mondays have been associated with lower or negative average returns in many markets, a phenomenon often linked to the settlement of trades from the previous week and negative news accumulation over the weekend. Fridays, on the other hand, might exhibit positive bias as investors adjust positions ahead of the weekend.
⚪ Week in month
The performance of markets can also vary within different weeks of the month, with some studies suggesting a "week of the month effect." Typically, the first and the last week of the month may show stronger performance compared to the middle weeks. This pattern can be influenced by factors such as the timing of economic reports, monthly investment flows, and options and futures expiration dates which tend to cluster around these periods, affecting investor behavior and market liquidity.
█ How It Works
⚪ Day in Month
For each day of the month (1-31), the script calculates the average percentage change between the opening and closing prices of a trading instrument. This metric helps identify which days have historically been more volatile or profitable.
It uses arrays to store the sum of percentage changes for each day and the total occurrences of each day to calculate the average percentage change.
⚪ Month
The script calculates the overall gain for each month (January-December) by comparing the closing price at the start of a month to the closing price at the end, expressed as a percentage. This metric offers insights into which months might offer better trading opportunities based on historical performance.
Monthly gains are tracked using arrays that store the sum of these gains for each month and the count of occurrences to calculate the average monthly gain.
⚪ Day in Week
Similar to the day in the month analysis, the script evaluates the average percentage change between the opening and closing prices for each day of the week (Monday-Sunday). This information can be used to assess which days of the week are typically more favorable for trading.
The script uses arrays to accumulate percentage changes and occurrences for each weekday, allowing for the calculation of average changes per day of the week.
⚪ Week in Month
The script assesses the performance of each week within a month, identifying the gain from the start to the end of each week, expressed as a percentage. This can help traders understand which weeks within a month may have historically presented better trading conditions.
It employs arrays to track the weekly gains and the number of weeks, using a counter to identify which week of the month it is (1-4), allowing for the calculation of average weekly gains.
█ How to Use
Traders can use this indicator to identify patterns or trends in the instrument's performance. For example, if a particular day of the week consistently shows a higher percentage of bullish closes, a trader might consider this in their strategy. Similarly, if certain months show stronger performance historically, this information could influence trading decisions.
Identifying High-Performance Days and Periods
Day in Month & Day in Week Analysis: By examining the average percentage change for each day of the month and week, traders can identify specific days that historically have shown higher volatility or profitability. This allows for targeted trading strategies, focusing on these high-performance days to maximize potential gains.
Month Analysis: Understanding which months have historically provided better returns enables traders to adjust their trading intensity or capital allocation in anticipation of seasonally stronger or weaker periods.
Week in Month Analysis: Identifying which weeks within a month have historically been more profitable can help traders plan their trades around these periods, potentially increasing their chances of success.
█ Settings
Enable or disable the types of statistics you want to display in the table.
Table Size: Users can select the size of the table displayed on the chart, ranging from "Tiny" to "Auto," which adjusts based on screen size.
Table Position: Users can choose the location of the table on the chart
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Blockunity Address Synthesis (BAS)Track the address status of the various cryptoassets and their evolution.
The Idea
The goal is to provide a simple tool for visualizing the evolution of different types of crypto addresses.
How to Use
This tool is to be used as fundamental information. It is not intended for investment or trading purposes.
Elements
Active Addresses
Active Addresses represent the subset of total addresses that made one or more on-chain transaction on a given day.
New Addresses
New Addresses refer to addresses that receive their first deposit in the selected crypto-asset.
Zero Balance Addresses
Zero Balance Addresses are addresses that transferred out (potentially sold) all of their holdings for the selected crypto-asset.
Total Addresses
Total Addresses refer to the overall count of unique addresses that have been created on a blockchain network.
Settings
In the settings, you can :
Adjust line smoothing (in terms of number of days).
Change the lookback period used to calculate the different variations.
Display or not the different address types (for better visualization, Total Addresses should be shown alone).
Show or hide labels and configure their offset.
Lastly, you can modify all table parameters.
Rolling Risk-Adjusted Performance RatiosThis simple indicator calculates and provides insights into different performance metrics of an asset - Sharpe, Sortino and Omega Ratios in particular. It allows users to customize the lookback period and select their preferred data source for evaluation of an asset.
Sharpe Ratio:
The Sharpe Ratio measures the risk-adjusted return of an asset by considering both the average return and the volatility or riskiness of the investment. A higher Sharpe Ratio indicates better risk-adjusted performance. It allows investors to compare different assets or portfolios and assess whether the returns adequately compensate for the associated risks. A higher Sharpe Ratio implies that the asset generates more return per unit of risk taken.
Sortino Ratio:
The Sortino Ratio is a variation of the Sharpe Ratio that focuses specifically on the downside risk or volatility of an asset. It takes into account only the negative deviations from the average return (downside deviation). By considering downside risk, the Sortino Ratio provides a more refined measure of risk-adjusted performance, particularly for investors who are more concerned with minimizing losses. A higher Sortino Ratio suggests that the asset has superior risk-adjusted returns when considering downside volatility.
Omega Ratio:
The Omega Ratio measures the probability-weighted ratio of gains to losses beyond a certain threshold or target return. It assesses the skewed nature of an asset's returns by differentiating between positive and negative returns and assigning more weight to extreme gains or losses. The Omega Ratio provides insights into the potential asymmetry of returns, highlighting the potential for significant positive or negative outliers. A higher Omega Ratio indicates a higher probability of achieving large positive returns compared to large negative returns.
Utility:
Performance Evaluation: Provides assessment of an asset's performance, considering both returns and risk factors.
Risk Comparison: Allows for comparing the risk-adjusted returns of different assets or portfolios. Helps identify investments with better risk-reward trade-offs.
Risk Management: Assists in managing risk exposure by evaluating downside risks and volatility.
Cobra's CryptoMarket VisualizerCobra's Crypto Market Screener is designed to provide a comprehensive overview of the top 40 marketcap cryptocurrencies in a table\heatmap format. This indicator incorporates essential metrics such as Beta, Alpha, Sharpe Ratio, Sortino Ratio, Omega Ratio, Z-Score, and Average Daily Range (ADR). The table utilizes cell coloring resembling a heatmap, allowing for quick visual analysis and comparison of multiple cryptocurrencies.
The indicator also includes a shortened explanation tooltip of each metric when hovering over it's respected cell. I shall elaborate on each here for anyone interested.
Metric Descriptions:
1. Beta: measures the sensitivity of an asset's returns to the overall market returns. It indicates how much the asset's price is likely to move in relation to a benchmark index. A beta of 1 suggests the asset moves in line with the market, while a beta greater than 1 implies the asset is more volatile, and a beta less than 1 suggests lower volatility.
2. Alpha: is a measure of the excess return generated by an investment compared to its expected return, given its risk (as indicated by its beta). It assesses the performance of an investment after adjusting for market risk. Positive alpha indicates outperformance, while negative alpha suggests underperformance.
3. Sharpe Ratio: measures the risk-adjusted return of an investment or portfolio. It evaluates the excess return earned per unit of risk taken. A higher Sharpe ratio indicates better risk-adjusted performance, as it reflects a higher return for each unit of volatility or risk.
4. Sortino Ratio: is a risk-adjusted measure similar to the Sharpe ratio but focuses only on downside risk. It considers the excess return per unit of downside volatility. The Sortino ratio emphasizes the risk associated with below-target returns and is particularly useful for assessing investments with asymmetric risk profiles.
5. Omega Ratio: measures the ratio of the cumulative average positive returns to the cumulative average negative returns. It assesses the reward-to-risk ratio by considering both upside and downside performance. A higher Omega ratio indicates a higher reward relative to the risk taken.
6. Z-Score: is a statistical measure that represents the number of standard deviations a data point is from the mean of a dataset. In finance, the Z-score is commonly used to assess the financial health or risk of a company. It quantifies the distance of a company's financial ratios from the average and provides insight into its relative position.
7. Average Daily Range: ADR represents the average range of price movement of an asset during a trading day. It measures the average difference between the high and low prices over a specific period. Traders use ADR to gauge the potential price range within which an asset might fluctuate during a typical trading session.
Utility:
Comprehensive Overview: The indicator allows for monitoring up to 40 cryptocurrencies simultaneously, providing a consolidated view of essential metrics in a single table.
Efficient Comparison: The heatmap-like coloring of the cells enables easy visual comparison of different cryptocurrencies, helping identify relative strengths and weaknesses.
Risk Assessment: Metrics such as Beta, Alpha, Sharpe Ratio, Sortino Ratio, and Omega Ratio offer insights into the risk associated with each cryptocurrency, aiding risk assessment and portfolio management decisions.
Performance Evaluation: The Alpha, Sharpe Ratio, and Sortino Ratio provide measures of a cryptocurrency's performance adjusted for risk. This helps assess investment performance over time and across different assets.
Market Analysis: By considering the Z-Score and Average Daily Range (ADR), traders can evaluate the financial health and potential price volatility of cryptocurrencies, aiding in trade selection and risk management.
Features:
Reference period optimization, alpha and ADR in particular
Source calculation
Table sizing and positioning options to fit the user's screen size.
Tooltips
Important Notes -
1. The Sharpe, Sortino and Omega ratios cell coloring threshold might be subjective, I did the best I can to gauge the median value of each to provide more accurate coloring sentiment, it may change in the future.
The median values are : Sharpe -1, Sortino - 1.5, Omega - 20.
2. Limitations - Some cryptos have a Z-Score value of NaN due to their short lifetime, I tried to overcome this issue as with the rest of the metrics as best I can. Moreover, it limits the time horizon for replay mode to somewhere around Q3 of 2021 and that's with using the split option of the top half, to remain with the older cryptos.
3. For the beginner Pine enthusiasts, I recommend scimming through the script as it serves as a prime example of using key features, to name a few : Arrays, User Defined Functions, User Defined Types, For loops, Switches and Tables.
4. Beta and Alpha's benchmark instrument is BTC, due to cryptos volatility I saw no reason to use SPY or any other asset for that matter.
NET BSP NET BSP derived from Buying & Selling Pressure which is a volatility indicator that monitors average metrics of green and red candles separately.
We could navigate more confidently through market with projected market balance.
BSP allowed us to track and analyze the ongoing performance of bullish and bearish impulsive waves and their corrections.
Due to unintuitive way of measuring decline with SP going up, I decided to remake it into more intuitive version with better precision.
When we encounter the fall it's better to have declining values of tool to be able to cover it visually with ease.
One of the solutions was to create a sense of balance of Buying Pressure against Selling Pressure.
Since we are oriented by growth, it'd be more logical to summarize the market balance with BP - SP
Comparison:
When Buying and Selling Pressure are equal, NET BSP would be at 0.
NETBSP > 0 and NETBSP > NETBSP = 🟢
NETBSP > 0 and NETBSP < NETBSP = 🟡
NETBSP < 0 and NETBSP < NETBSP = 🔴
NETBSP < 0 and NETBSP > NETBSP = 🟡
Hence, we get visualized stages of uptrends and downtrends which allows to evaluate chances and estimations of upcoming counter-waves.
Also, it is worth to note that output clearly shows how one wave is derived from another in terms of sizing.
Feel free to adjust NET BSP arguments to adapt sensitivity to the timeframe you're working on.
Buying & Selling PressureBuying and selling pressure is a volatility indicator which denotes the balance between buyers and sellers inside candlestick.
You set the length to average it just like ATR. But This offers further break down of participants of the market.
Pretty much at any condition of the market the indicator can filter out interesting details to make trading decisions faster or confirm them.
So keep it simple we have two lines
🟢 Green → buying pressure
🔴 Red → selling pressure
If green is rising → Price most likely will grow
If green is rising and red is falling → Price will grow at higher probability
If red is rising → Price most likely will fall
If red is rising and green is falling → Price will fall at higher probability
When they both grow or fall → wait till one of them goes opposite way.
╳ Crossings can indicate turning points for bigger price swings.
Technically by very act of intersecting means that Buying and Selling Pressure are equal.
Can be used for Demand/Supply analysis and evaluate the support/resistance levels.
Candle Fill % MeterFor use with Hollow Candles
Fills Candles based on either the value of the RSI or coppock scaled to fit properly between the open and close. Makes for a compact visual with lot's of information given. Toggle bells and whistles in settings such as arrows to indicate the direction of the value being measured, dividing levels, fill from candle open all the time instead of the bottom up and more.
Strategy BackTest Display Statistics - TraderHalaiThis script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs.
Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author.
Full credit to the original author of this script. It can be found here: www.tradingview.com
I decided to modify the script by simplifying it down and make it easier to integrate into existing strategies, using simple copy and paste, by relying on existing tradingview strategy backtester inputs. I have also added 3 additional performance metrics:
- Max Run Up
- Average Win per trade
- Average Loss per trade
As this is a work in progress, I will look to add in more performance metrics in future, as I further develop this script.
Feel free to use this display panel in your scripts and strategies.
Thanks and enjoy :)
Bitcoin OnChain & Other MetricsHi all,
In these troubled times, going back to fundamentals can sometimes be a good idea 😊
I put this one up using data retrieved from “Nasdaq Data Link” and their “Blockchain.com” database.
Here is a good place to analyses some Bitcoin data “outside” its price action with 25 different data sets.
Just go to the settings menu and display the ones you are interested in.
If you want me to add more metrics, feel free to DM or comment below!
Hope you enjoy 😉
MicroStrategy MetricsA script showing all the key MSTR metrics. I will update the script every time degen Saylor sells some more office furniture to buy BTC.
All based around valuing MSTR, aside from its BTC holdings. I.e. the true market cap = enterprise value - BTC holdings. Hence, you're left with the value of the software business + any premium/discount decided by investors.
From this we can derive:
- BTC Holdings % of enterprise value
- Correlation to BTC (in this case we use CME futures...may change this)
- Equivalent Share Price (true market cap divided by shares outstanding)
- P/E Ratio (equivalent share price divided by quarterly EPS estimates x 4)
- Price to FCF Ratio (true market cap divided by FCF (ttm))
- Price to Revenue (^ but with total revenue (ttm))