[MAD MBS] L3 Float Operations & ML-NormalizersFirst of all:
This indicator is not a standalone tool ; it relies on other script series for its inputs.
This script is an indicator designed for multi-path float operations with integrated machine learning normalizers.
It supports up to four distinct paths, each customizable with multiple sources, factors, and operations.
Users can perform various mathematical operations on price data, including addition, subtraction, multiplication, division, and percentage changes, as well as more advanced tasks like double and triple moving averages or power operations.
The script also integrates several normalization methods (e.g., Min-Max, Z-Score, Robust) to standardize data—an important step for machine learning models.
Each path supports multiple smoothing techniques (e.g., EMA, SMA, and specialized Ehlers smoothers) to further refine the output.
Designed to handle multiple data inputs simultaneously, this tool is especially useful for traders looking to analyze and normalize data from different price sources.
The combination of advanced mathematical operations, normalization techniques, and smoothing enhances data management, aiding in more effective trading decisions.
Here you can see a single path, out of the four possible:
Details to the screenshot:
First Series
Second Series
Option to override the second series with a custom constant (or when normalizing, use the length instead)
The first selection box sets the mathematical operation or activates the normalizer.
The second selection box sets the normalization method.
The third selection box sets the final smoothing technique, followed by parameters for smoothing length.
These settings are repeated identically for Paths 2–4.
At the bottom of the setup, there's a general offset option (add the 'close' price for overlay purposes).
Additionally, there's an option to display a line at zero for centered results.
Statistics
Tail ProbabilitiesThe Tail Probabilities indicator offers a sophisticated analysis of potential price distributions, providing traders with a probabilistic framework for forecasting future price behavior based on historical data. By estimating the likelihood of the price closing above or below specified thresholds, the indicator assists in evaluating market sentiment, volatility, and associated risks. The probability calculations are derived from a user-defined analysis window, which operates independently of the transform length window. The transform length parameter dictates the volume of historical data utilized in the calculations, and it must correspond to the window length applied in the mean and standard deviation lines indicator to ensure consistency in visual representation.
Overview of Plotted Probabilities
This indicator plots three core probabilities and their moving averages, involving four primary user inputs:
User Inputs
Tail Type: Allows the user to choose between analyzing the left tail (representing downside risk) or the right tail (representing upside potential).
Transform Window Length (Bars): Specifies the amount of historical data used to calculate the mean and standard deviation. This value must align with the window length applied in the mean and standard deviation lines indicator .
Analysis Period (Bars): Defines the number of historical bars used for probability analysis, setting the window over which probabilities are computed.
SMA Length (Bars): Specifies the length of the simple moving average (SMA) used to plot the historical average of the calculated probabilities. The SMA Length input allows users to plot a simple moving average of the calculated probabilities, providing a smoother historical average and helping to identify trends in the probability values over time.
Key Probabilities Plotted
Probability to Close Above or Below Upper Bound: Represents the likelihood that the price will close above or below an upper threshold derived from the mean and standard deviation lines indicator . This measure helps identify potential for significant upward or downward price movement, depending on the current price relative to the threshold.
Probability to Close Above or Below Mean: Indicates the probability of the closing price being either above or below the mean level, reflecting historical price tendencies and suggesting the presence of skewness in the price distribution.
Probability to Close Above or Below Lower Bound: Reflects the likelihood of the price closing above or below a lower threshold, offering insights into potential risk and directional movement.
The indicator adjusts based on the chosen tail type ("Left" or "Right"), thereby enabling users to assess both potential upward and downward price movements, making it adaptable to varying market conditions.
How Probabilities Are Calculated
The probabilities are calculated through a detailed analysis of historical price data over a user-specified analysis window. Below is an outline of the key steps involved in these calculations:
Calculate Mean and Standard Deviation: The mean and standard deviation are computed using the transform length window, which defines the historical data range employed.
Define Bounds: Upper, mean, and lower bounds are established based on the calculated mean and standard deviation, allowing identification of significant levels within the price distribution.
Count Events: The frequency with which the closing price crosses above or below these bounds is counted over the user-specified probability analysis window.
Calculate Probabilities: Probabilities are then computed as the percentage of observed events relative to the total number of observations in the analysis window.
For example, the probability of closing above the upper bound is calculated as:
Probability = (Number of times price closes above the upper bound) / (Total number of observations in the analysis window) * 100
Practical Usage
Risk Management: The indicator provides a quantitative measure of the probability of extreme price movements, aiding traders in setting stop-loss and take-profit levels based on statistical expectations.
Trend Analysis: The probability of closing above the mean can also serve as an indicator of potential skewness in the price distribution. Values above 50 indicate a right-skewed distribution, while values below 50 indicate a left-skewed distribution for the right tail probability. For the left tail probability, values over 50 indicate a left skew and values below 50 indicate a right skew in the distribution.
Scenario Analysis: By focusing on either the left or right tail, traders can quickly determine whether to prioritize downside protection or capitalize on upside potential. Depending on market conditions and whether the trader is long or short, both upward and downward movements can be analyzed, enabling a comprehensive risk assessment.
Limitations
While the Tail Probabilities indicator provides valuable probabilistic insights based on historical data, it is crucial to understand that historical performance does not guarantee future outcomes. Market dynamics are subject to rapid changes, and relying exclusively on historical probabilities may result in inaccurate assessments. Traders should use this indicator in conjunction with other technical analysis tools, fundamental analysis, and an understanding of broader market conditions to ensure robust decision-making.
Summary
The Tail Probabilities indicator is an advanced tool designed for traders seeking a probabilistic perspective on market behavior. By providing critical insights into the potential distribution of prices beyond significant thresholds, the indicator supports informed decision-making, whether in trending or uncertain market environments.
Universal Ratio Trend Matrix [InvestorUnknown]The Universal Ratio Trend Matrix is designed for trend analysis on asset/asset ratios, supporting up to 40 different assets. Its primary purpose is to help identify which assets are outperforming others within a selection, providing a broad overview of market trends through a matrix of ratios. The indicator automatically expands the matrix based on the number of assets chosen, simplifying the process of comparing multiple assets in terms of performance.
Key features include the ability to choose from a narrow selection of indicators to perform the ratio trend analysis, allowing users to apply well-defined metrics to their comparison.
Drawback: Due to the computational intensity involved in calculating ratios across many assets, the indicator has a limitation related to loading speed. TradingView has time limits for calculations, and for users on the basic (free) plan, this could result in frequent errors due to exceeded time limits. To use the indicator effectively, users with any paid plans should run it on timeframes higher than 8h (the lowest timeframe on which it managed to load with 40 assets), as lower timeframes may not reliably load.
Indicators:
RSI_raw: Simple function to calculate the Relative Strength Index (RSI) of a source (asset price).
RSI_sma: Calculates RSI followed by a Simple Moving Average (SMA).
RSI_ema: Calculates RSI followed by an Exponential Moving Average (EMA).
CCI: Calculates the Commodity Channel Index (CCI).
Fisher: Implements the Fisher Transform to normalize prices.
Utility Functions:
f_remove_exchange_name: Strips the exchange name from asset tickers (e.g., "INDEX:BTCUSD" to "BTCUSD").
f_remove_exchange_name(simple string name) =>
string parts = str.split(name, ":")
string result = array.size(parts) > 1 ? array.get(parts, 1) : name
result
f_get_price: Retrieves the closing price of a given asset ticker using request.security().
f_constant_src: Checks if the source data is constant by comparing multiple consecutive values.
Inputs:
General settings allow users to select the number of tickers for analysis (used_assets) and choose the trend indicator (RSI, CCI, Fisher, etc.).
Table settings customize how trend scores are displayed in terms of text size, header visibility, highlighting options, and top-performing asset identification.
The script includes inputs for up to 40 assets, allowing the user to select various cryptocurrencies (e.g., BTCUSD, ETHUSD, SOLUSD) or other assets for trend analysis.
Price Arrays:
Price values for each asset are stored in variables (price_a1 to price_a40) initialized as na. These prices are updated only for the number of assets specified by the user (used_assets).
Trend scores for each asset are stored in separate arrays
// declare price variables as "na"
var float price_a1 = na, var float price_a2 = na, var float price_a3 = na, var float price_a4 = na, var float price_a5 = na
var float price_a6 = na, var float price_a7 = na, var float price_a8 = na, var float price_a9 = na, var float price_a10 = na
var float price_a11 = na, var float price_a12 = na, var float price_a13 = na, var float price_a14 = na, var float price_a15 = na
var float price_a16 = na, var float price_a17 = na, var float price_a18 = na, var float price_a19 = na, var float price_a20 = na
var float price_a21 = na, var float price_a22 = na, var float price_a23 = na, var float price_a24 = na, var float price_a25 = na
var float price_a26 = na, var float price_a27 = na, var float price_a28 = na, var float price_a29 = na, var float price_a30 = na
var float price_a31 = na, var float price_a32 = na, var float price_a33 = na, var float price_a34 = na, var float price_a35 = na
var float price_a36 = na, var float price_a37 = na, var float price_a38 = na, var float price_a39 = na, var float price_a40 = na
// create "empty" arrays to store trend scores
var a1_array = array.new_int(40, 0), var a2_array = array.new_int(40, 0), var a3_array = array.new_int(40, 0), var a4_array = array.new_int(40, 0)
var a5_array = array.new_int(40, 0), var a6_array = array.new_int(40, 0), var a7_array = array.new_int(40, 0), var a8_array = array.new_int(40, 0)
var a9_array = array.new_int(40, 0), var a10_array = array.new_int(40, 0), var a11_array = array.new_int(40, 0), var a12_array = array.new_int(40, 0)
var a13_array = array.new_int(40, 0), var a14_array = array.new_int(40, 0), var a15_array = array.new_int(40, 0), var a16_array = array.new_int(40, 0)
var a17_array = array.new_int(40, 0), var a18_array = array.new_int(40, 0), var a19_array = array.new_int(40, 0), var a20_array = array.new_int(40, 0)
var a21_array = array.new_int(40, 0), var a22_array = array.new_int(40, 0), var a23_array = array.new_int(40, 0), var a24_array = array.new_int(40, 0)
var a25_array = array.new_int(40, 0), var a26_array = array.new_int(40, 0), var a27_array = array.new_int(40, 0), var a28_array = array.new_int(40, 0)
var a29_array = array.new_int(40, 0), var a30_array = array.new_int(40, 0), var a31_array = array.new_int(40, 0), var a32_array = array.new_int(40, 0)
var a33_array = array.new_int(40, 0), var a34_array = array.new_int(40, 0), var a35_array = array.new_int(40, 0), var a36_array = array.new_int(40, 0)
var a37_array = array.new_int(40, 0), var a38_array = array.new_int(40, 0), var a39_array = array.new_int(40, 0), var a40_array = array.new_int(40, 0)
f_get_price(simple string ticker) =>
request.security(ticker, "", close)
// Prices for each USED asset
f_get_asset_price(asset_number, ticker) =>
if (used_assets >= asset_number)
f_get_price(ticker)
else
na
// overwrite empty variables with the prices if "used_assets" is greater or equal to the asset number
if barstate.isconfirmed // use barstate.isconfirmed to avoid "na prices" and calculation errors that result in empty cells in the table
price_a1 := f_get_asset_price(1, asset1), price_a2 := f_get_asset_price(2, asset2), price_a3 := f_get_asset_price(3, asset3), price_a4 := f_get_asset_price(4, asset4)
price_a5 := f_get_asset_price(5, asset5), price_a6 := f_get_asset_price(6, asset6), price_a7 := f_get_asset_price(7, asset7), price_a8 := f_get_asset_price(8, asset8)
price_a9 := f_get_asset_price(9, asset9), price_a10 := f_get_asset_price(10, asset10), price_a11 := f_get_asset_price(11, asset11), price_a12 := f_get_asset_price(12, asset12)
price_a13 := f_get_asset_price(13, asset13), price_a14 := f_get_asset_price(14, asset14), price_a15 := f_get_asset_price(15, asset15), price_a16 := f_get_asset_price(16, asset16)
price_a17 := f_get_asset_price(17, asset17), price_a18 := f_get_asset_price(18, asset18), price_a19 := f_get_asset_price(19, asset19), price_a20 := f_get_asset_price(20, asset20)
price_a21 := f_get_asset_price(21, asset21), price_a22 := f_get_asset_price(22, asset22), price_a23 := f_get_asset_price(23, asset23), price_a24 := f_get_asset_price(24, asset24)
price_a25 := f_get_asset_price(25, asset25), price_a26 := f_get_asset_price(26, asset26), price_a27 := f_get_asset_price(27, asset27), price_a28 := f_get_asset_price(28, asset28)
price_a29 := f_get_asset_price(29, asset29), price_a30 := f_get_asset_price(30, asset30), price_a31 := f_get_asset_price(31, asset31), price_a32 := f_get_asset_price(32, asset32)
price_a33 := f_get_asset_price(33, asset33), price_a34 := f_get_asset_price(34, asset34), price_a35 := f_get_asset_price(35, asset35), price_a36 := f_get_asset_price(36, asset36)
price_a37 := f_get_asset_price(37, asset37), price_a38 := f_get_asset_price(38, asset38), price_a39 := f_get_asset_price(39, asset39), price_a40 := f_get_asset_price(40, asset40)
Universal Indicator Calculation (f_calc_score):
This function allows switching between different trend indicators (RSI, CCI, Fisher) for flexibility.
It uses a switch-case structure to calculate the indicator score, where a positive trend is denoted by 1 and a negative trend by 0. Each indicator has its own logic to determine whether the asset is trending up or down.
// use switch to allow "universality" in indicator selection
f_calc_score(source, trend_indicator, int_1, int_2) =>
int score = na
if (not f_constant_src(source)) and source > 0.0 // Skip if you are using the same assets for ratio (for example BTC/BTC)
x = switch trend_indicator
"RSI (Raw)" => RSI_raw(source, int_1)
"RSI (SMA)" => RSI_sma(source, int_1, int_2)
"RSI (EMA)" => RSI_ema(source, int_1, int_2)
"CCI" => CCI(source, int_1)
"Fisher" => Fisher(source, int_1)
y = switch trend_indicator
"RSI (Raw)" => x > 50 ? 1 : 0
"RSI (SMA)" => x > 50 ? 1 : 0
"RSI (EMA)" => x > 50 ? 1 : 0
"CCI" => x > 0 ? 1 : 0
"Fisher" => x > x ? 1 : 0
score := y
else
score := 0
score
Array Setting Function (f_array_set):
This function populates an array with scores calculated for each asset based on a base price (p_base) divided by the prices of the individual assets.
It processes multiple assets (up to 40), calling the f_calc_score function for each.
// function to set values into the arrays
f_array_set(a_array, p_base) =>
array.set(a_array, 0, f_calc_score(p_base / price_a1, trend_indicator, int_1, int_2))
array.set(a_array, 1, f_calc_score(p_base / price_a2, trend_indicator, int_1, int_2))
array.set(a_array, 2, f_calc_score(p_base / price_a3, trend_indicator, int_1, int_2))
array.set(a_array, 3, f_calc_score(p_base / price_a4, trend_indicator, int_1, int_2))
array.set(a_array, 4, f_calc_score(p_base / price_a5, trend_indicator, int_1, int_2))
array.set(a_array, 5, f_calc_score(p_base / price_a6, trend_indicator, int_1, int_2))
array.set(a_array, 6, f_calc_score(p_base / price_a7, trend_indicator, int_1, int_2))
array.set(a_array, 7, f_calc_score(p_base / price_a8, trend_indicator, int_1, int_2))
array.set(a_array, 8, f_calc_score(p_base / price_a9, trend_indicator, int_1, int_2))
array.set(a_array, 9, f_calc_score(p_base / price_a10, trend_indicator, int_1, int_2))
array.set(a_array, 10, f_calc_score(p_base / price_a11, trend_indicator, int_1, int_2))
array.set(a_array, 11, f_calc_score(p_base / price_a12, trend_indicator, int_1, int_2))
array.set(a_array, 12, f_calc_score(p_base / price_a13, trend_indicator, int_1, int_2))
array.set(a_array, 13, f_calc_score(p_base / price_a14, trend_indicator, int_1, int_2))
array.set(a_array, 14, f_calc_score(p_base / price_a15, trend_indicator, int_1, int_2))
array.set(a_array, 15, f_calc_score(p_base / price_a16, trend_indicator, int_1, int_2))
array.set(a_array, 16, f_calc_score(p_base / price_a17, trend_indicator, int_1, int_2))
array.set(a_array, 17, f_calc_score(p_base / price_a18, trend_indicator, int_1, int_2))
array.set(a_array, 18, f_calc_score(p_base / price_a19, trend_indicator, int_1, int_2))
array.set(a_array, 19, f_calc_score(p_base / price_a20, trend_indicator, int_1, int_2))
array.set(a_array, 20, f_calc_score(p_base / price_a21, trend_indicator, int_1, int_2))
array.set(a_array, 21, f_calc_score(p_base / price_a22, trend_indicator, int_1, int_2))
array.set(a_array, 22, f_calc_score(p_base / price_a23, trend_indicator, int_1, int_2))
array.set(a_array, 23, f_calc_score(p_base / price_a24, trend_indicator, int_1, int_2))
array.set(a_array, 24, f_calc_score(p_base / price_a25, trend_indicator, int_1, int_2))
array.set(a_array, 25, f_calc_score(p_base / price_a26, trend_indicator, int_1, int_2))
array.set(a_array, 26, f_calc_score(p_base / price_a27, trend_indicator, int_1, int_2))
array.set(a_array, 27, f_calc_score(p_base / price_a28, trend_indicator, int_1, int_2))
array.set(a_array, 28, f_calc_score(p_base / price_a29, trend_indicator, int_1, int_2))
array.set(a_array, 29, f_calc_score(p_base / price_a30, trend_indicator, int_1, int_2))
array.set(a_array, 30, f_calc_score(p_base / price_a31, trend_indicator, int_1, int_2))
array.set(a_array, 31, f_calc_score(p_base / price_a32, trend_indicator, int_1, int_2))
array.set(a_array, 32, f_calc_score(p_base / price_a33, trend_indicator, int_1, int_2))
array.set(a_array, 33, f_calc_score(p_base / price_a34, trend_indicator, int_1, int_2))
array.set(a_array, 34, f_calc_score(p_base / price_a35, trend_indicator, int_1, int_2))
array.set(a_array, 35, f_calc_score(p_base / price_a36, trend_indicator, int_1, int_2))
array.set(a_array, 36, f_calc_score(p_base / price_a37, trend_indicator, int_1, int_2))
array.set(a_array, 37, f_calc_score(p_base / price_a38, trend_indicator, int_1, int_2))
array.set(a_array, 38, f_calc_score(p_base / price_a39, trend_indicator, int_1, int_2))
array.set(a_array, 39, f_calc_score(p_base / price_a40, trend_indicator, int_1, int_2))
a_array
Conditional Array Setting (f_arrayset):
This function checks if the number of used assets is greater than or equal to a specified number before populating the arrays.
// only set values into arrays for USED assets
f_arrayset(asset_number, a_array, p_base) =>
if (used_assets >= asset_number)
f_array_set(a_array, p_base)
else
na
Main Logic
The main logic initializes arrays to store scores for each asset. Each array corresponds to one asset's performance score.
Setting Trend Values: The code calls f_arrayset for each asset, populating the respective arrays with calculated scores based on the asset prices.
Combining Arrays: A combined_array is created to hold all the scores from individual asset arrays. This array facilitates further analysis, allowing for an overview of the performance scores of all assets at once.
// create a combined array (work-around since pinescript doesn't support having array of arrays)
var combined_array = array.new_int(40 * 40, 0)
if barstate.islast
for i = 0 to 39
array.set(combined_array, i, array.get(a1_array, i))
array.set(combined_array, i + (40 * 1), array.get(a2_array, i))
array.set(combined_array, i + (40 * 2), array.get(a3_array, i))
array.set(combined_array, i + (40 * 3), array.get(a4_array, i))
array.set(combined_array, i + (40 * 4), array.get(a5_array, i))
array.set(combined_array, i + (40 * 5), array.get(a6_array, i))
array.set(combined_array, i + (40 * 6), array.get(a7_array, i))
array.set(combined_array, i + (40 * 7), array.get(a8_array, i))
array.set(combined_array, i + (40 * 8), array.get(a9_array, i))
array.set(combined_array, i + (40 * 9), array.get(a10_array, i))
array.set(combined_array, i + (40 * 10), array.get(a11_array, i))
array.set(combined_array, i + (40 * 11), array.get(a12_array, i))
array.set(combined_array, i + (40 * 12), array.get(a13_array, i))
array.set(combined_array, i + (40 * 13), array.get(a14_array, i))
array.set(combined_array, i + (40 * 14), array.get(a15_array, i))
array.set(combined_array, i + (40 * 15), array.get(a16_array, i))
array.set(combined_array, i + (40 * 16), array.get(a17_array, i))
array.set(combined_array, i + (40 * 17), array.get(a18_array, i))
array.set(combined_array, i + (40 * 18), array.get(a19_array, i))
array.set(combined_array, i + (40 * 19), array.get(a20_array, i))
array.set(combined_array, i + (40 * 20), array.get(a21_array, i))
array.set(combined_array, i + (40 * 21), array.get(a22_array, i))
array.set(combined_array, i + (40 * 22), array.get(a23_array, i))
array.set(combined_array, i + (40 * 23), array.get(a24_array, i))
array.set(combined_array, i + (40 * 24), array.get(a25_array, i))
array.set(combined_array, i + (40 * 25), array.get(a26_array, i))
array.set(combined_array, i + (40 * 26), array.get(a27_array, i))
array.set(combined_array, i + (40 * 27), array.get(a28_array, i))
array.set(combined_array, i + (40 * 28), array.get(a29_array, i))
array.set(combined_array, i + (40 * 29), array.get(a30_array, i))
array.set(combined_array, i + (40 * 30), array.get(a31_array, i))
array.set(combined_array, i + (40 * 31), array.get(a32_array, i))
array.set(combined_array, i + (40 * 32), array.get(a33_array, i))
array.set(combined_array, i + (40 * 33), array.get(a34_array, i))
array.set(combined_array, i + (40 * 34), array.get(a35_array, i))
array.set(combined_array, i + (40 * 35), array.get(a36_array, i))
array.set(combined_array, i + (40 * 36), array.get(a37_array, i))
array.set(combined_array, i + (40 * 37), array.get(a38_array, i))
array.set(combined_array, i + (40 * 38), array.get(a39_array, i))
array.set(combined_array, i + (40 * 39), array.get(a40_array, i))
Calculating Sums: A separate array_sums is created to store the total score for each asset by summing the values of their respective score arrays. This allows for easy comparison of overall performance.
Ranking Assets: The final part of the code ranks the assets based on their total scores stored in array_sums. It assigns a rank to each asset, where the asset with the highest score receives the highest rank.
// create array for asset RANK based on array.sum
var ranks = array.new_int(used_assets, 0)
// for loop that calculates the rank of each asset
if barstate.islast
for i = 0 to (used_assets - 1)
int rank = 1
for x = 0 to (used_assets - 1)
if i != x
if array.get(array_sums, i) < array.get(array_sums, x)
rank := rank + 1
array.set(ranks, i, rank)
Dynamic Table Creation
Initialization: The table is initialized with a base structure that includes headers for asset names, scores, and ranks. The headers are set to remain constant, ensuring clarity for users as they interpret the displayed data.
Data Population: As scores are calculated for each asset, the corresponding values are dynamically inserted into the table. This is achieved through a loop that iterates over the scores and ranks stored in the combined_array and array_sums, respectively.
Automatic Extending Mechanism
Variable Asset Count: The code checks the number of assets defined by the user. Instead of hardcoding the number of rows in the table, it uses a variable to determine the extent of the data that needs to be displayed. This allows the table to expand or contract based on the number of assets being analyzed.
Dynamic Row Generation: Within the loop that populates the table, the code appends new rows for each asset based on the current asset count. The structure of each row includes the asset name, its score, and its rank, ensuring that the table remains consistent regardless of how many assets are involved.
// Automatically extending table based on the number of used assets
var table table = table.new(position.bottom_center, 50, 50, color.new(color.black, 100), color.white, 3, color.white, 1)
if barstate.islast
if not hide_head
table.cell(table, 0, 0, "Universal Ratio Trend Matrix", text_color = color.white, bgcolor = #010c3b, text_size = fontSize)
table.merge_cells(table, 0, 0, used_assets + 3, 0)
if not hide_inps
table.cell(table, 0, 1,
text = "Inputs: You are using " + str.tostring(trend_indicator) + ", which takes: " + str.tostring(f_get_input(trend_indicator)),
text_color = color.white, text_size = fontSize), table.merge_cells(table, 0, 1, used_assets + 3, 1)
table.cell(table, 0, 2, "Assets", text_color = color.white, text_size = fontSize, bgcolor = #010c3b)
for x = 0 to (used_assets - 1)
table.cell(table, x + 1, 2, text = str.tostring(array.get(assets, x)), text_color = color.white, bgcolor = #010c3b, text_size = fontSize)
table.cell(table, 0, x + 3, text = str.tostring(array.get(assets, x)), text_color = color.white, bgcolor = f_asset_col(array.get(ranks, x)), text_size = fontSize)
for r = 0 to (used_assets - 1)
for c = 0 to (used_assets - 1)
table.cell(table, c + 1, r + 3, text = str.tostring(array.get(combined_array, c + (r * 40))),
text_color = hl_type == "Text" ? f_get_col(array.get(combined_array, c + (r * 40))) : color.white, text_size = fontSize,
bgcolor = hl_type == "Background" ? f_get_col(array.get(combined_array, c + (r * 40))) : na)
for x = 0 to (used_assets - 1)
table.cell(table, x + 1, x + 3, "", bgcolor = #010c3b)
table.cell(table, used_assets + 1, 2, "", bgcolor = #010c3b)
for x = 0 to (used_assets - 1)
table.cell(table, used_assets + 1, x + 3, "==>", text_color = color.white)
table.cell(table, used_assets + 2, 2, "SUM", text_color = color.white, text_size = fontSize, bgcolor = #010c3b)
table.cell(table, used_assets + 3, 2, "RANK", text_color = color.white, text_size = fontSize, bgcolor = #010c3b)
for x = 0 to (used_assets - 1)
table.cell(table, used_assets + 2, x + 3,
text = str.tostring(array.get(array_sums, x)),
text_color = color.white, text_size = fontSize,
bgcolor = f_highlight_sum(array.get(array_sums, x), array.get(ranks, x)))
table.cell(table, used_assets + 3, x + 3,
text = str.tostring(array.get(ranks, x)),
text_color = color.white, text_size = fontSize,
bgcolor = f_highlight_rank(array.get(ranks, x)))
Third-order moment by TonymontanovThe "Third-order moment" indicator is designed to help traders identify asymmetries and potential turning points in a financial instrument's price distribution over a specified period. By calculating the skewness of the price distribution, this indicator provides insights into the potential future movement direction of the market.
User Parameters:
- Length: This parameter defines the number of bars (or periods) used to compute the mean and third-order moment. A longer length provides a broader historical context, which may smooth out short-term volatility.
- Source: The data input for calculations, defaulting to the closing price of each bar, although users can select alternatives like open, high, low, or any custom value to suit their analysis preferences.
Operational Algorithm:
1. Mean Calculation:
- The indicator begins by calculating the arithmetic mean of the selected data source over the specified period.
2. Third-order Moment Calculation:
- A deviation from the mean is calculated for each data point. These deviations are then cubed to capture any asymmetry in the price distribution.
- The third-order moment is determined by summing these cubed deviations over the specified length and dividing by the number of periods, providing a measure of skewness.
3. Graphical Representation:
- The indicator plots the third-order moment as a column plot. The color of the columns changes based on the sign of the moment: green for positive and red for negative, suggesting bullish and bearish skewness, respectively.
- A zero line is included to help visualize transitions between positive and negative skewness clearly.
- Additionally, the background color shifts depending on whether the third-order moment is above or below zero, further highlighting the prevailing market sentiment.
The "Third-order moment" indicator is a valuable tool for traders looking to gauge the market's skewness, helping identify potential trend continuations or reversals. By understanding the dominance of positive or negative skewness, traders can make more informed decisions.
Asymmetric volatilityThe "Asymmetric Volatility" indicator is designed to visualize the differences in volatility between upward and downward price movements of a selected instrument. It operates on the principle of analyzing price movements over a specified time period, with particular focus on the symmetrical evaluation of both price rises and falls.
User Parameters:
- Length: This parameter specifies the number of bars (candles) used to calculate the average volatility. The larger the value, the longer the time period, and the smoother the volatility data will be.
- Source: This represents the input data for the indicator calculations. By default, the close value of each bar is used, but the user can choose another data source (such as open, high, low, or any custom value).
Operational Algorithm:
1. Movement Calculation:
- UpMoves: Computed as the positive difference between the current bar value and the previous bar value, if it is greater than zero.
- DownMoves: Computed as the positive difference between the previous bar value and the current bar value, if it is greater than zero.
2. Volatility Calculation:
- UpVolatility: This is the arithmetic mean of the UpMoves values over the specified period.
- DownVolatility: This is the arithmetic mean of the DownMoves values over the specified period.
3. Graphical Representation:
- The indicator displays two plots: upward and downward volatility, represented by green and red lines, respectively.
- The background color changes based on which volatility is dominant: a green background indicates that upward volatility prevails, while a red background indicates downward volatility.
The indicator allows traders to quickly assess in which direction the market is more volatile at the moment, which can be useful for making trading decisions and evaluating the current market situation.
Statistics plot1. setting the price range
At the beginning of the script, set the price range (interval). Price ranges are used to divide prices into several groups (buckets) and record how many prices have been reached within each group. For example, setting the price range to “10” will divide the price into intervals 0-10, 10-20, 20-30, and so on.
The price range can also be set manually by the user or automatically calculated based on the initial price. This allows for flexibility in adjusting price ranges for different assets and different time frames.
2. aggregate the number of times a price is reached
Record how many times the price reached each price range (e.g., 100-110, 110-120, etc.). This aggregate data is stored in a data structure called an array.
Each element of the array corresponds to a price range, and when a price reaches that range, the corresponding array value is incremented by one. This process is performed in real time, tracking price movements.
3. initializing and extending price ranges
The first bar of the script (when the chart is first loaded) divides the price ranges into several groups and initializes a count of 0 for each range.
When a price reaches a new range, the array is expanded as needed to add the new price range. This allows the script to work with any price movement, even if the price range continues to grow.
4. visualize the number of price arrivals with a histogram
The aggregated number of arrivals per price range is visually displayed in the form of a histogram. This histogram is designed to allow the user to see at a glance which price range is being reached most frequently.
For example, if prices frequently reach the 100-110 range, the histogram bar corresponding to that range will appear higher than the other ranges. This allows you to visually identify price “dwell points” or support and resistance levels.
5. display of moving averages
A moving average (MA) of the number of times a price has been reached is drawn above the histogram. Moving averages are indicators that show a smooth trend for the number of price arrivals and are useful for understanding the overall direction of price movements.
The duration of the moving average (how many data points it is calculated based on) can be set by the user. This allows for flexible analysis of short or long term price trends. 6.
6. price range tracking and labeling
The script keeps track of which price range the current price is located in. Based on this, information related to the current price range is displayed on the chart as labels.
In particular, labels indicate the beginning and end points of the price range, including which range the price was in at the beginning and which range the price reached at the end. These labels are a useful feature to visually identify price ranges on the chart.
7. labeling of current price range
To confirm which price range the current price is in, when a price reaches a specific price range, a label corresponding to that price range is displayed. This label indicates the position of the price in real-time, allowing traders to visually track where the current price is in the area.
8. calculating the start and end points of the range
The script calculates the start and end points of a range with a non-zero number of price arrivals to find the minimum and maximum of the range. This calculation allows you to see where prices are concentrated within a range.
9. out-of-range price processing
When a price reaches outside the range, the script automatically adds the array element corresponding to that price range and inserts the data in the appropriate location for the count. This allows the script to follow the price as it moves unexpectedly.
Daily Seasonality [YuL]This indicator calculates average returns for trading days across specified number of years in the past and displays this as a histogram. In addition, it displays EMA of these values as filled area plot.
Indicator uses ordinal number of trading day in a year, i.e. January 3rd may be 1st trading day, January 4th - 2nd trading day, etc.
Large green or red areas may mean that there is a strong seasonal factor at these dates that may support, launch, or break a trend.
It only works on daily timeframe at the moment. Maximum number of years it can look back is 15.
Financial GrowthOverview
The script named "Financial Growth" is written in Pine Script v5.
It is designed to display various financial metrics and ratios in a tabular format on TradingView charts.
The code pulls financial data like revenue, net income, EPS, etc., and presents these metrics along with ratios such as P/E, D/E, and others.
The table can display these values for different time periods such as quarterly, yearly, or trailing twelve months (TTM).
Additionally, it can show QoQ (Quarter-over-Quarter), YoY (Year-over-Year), and CAGR (Compound Annual Growth Rate) changes for selected financial items.
The code includes plotting options for visual representation of financial data and labels.
Explanation of Code Sections
Revision Notes
The revision notes indicate changes made in different versions of the code.
Each version update introduces new financial metrics and code restructuring.
Indicator Definition
indicator("Financial Growth", overlay=false, format=format.volume): Defines a standalone indicator with the name "Financial Growth". The overlay=false parameter ensures it is not overlaid on the chart but shown in a separate panel.
Text Sizes and Table Positions
Different text sizes and table positions are defined using variables such as text_size_SMALL, tb_pos_POS01, etc.
These variables help in formatting the visual display of the table and labels.
Financial Items
The script defines several financial items like revenue, net income, EPS, EBITDA, debt, and ratios such as ROE, ROA, and D/E.
Each financial item is assigned a corresponding unique identifier, e.g., _revenue_id = 'TOTAL_REVENUE'.
Calculated Financial Ratios
Ratios such as P/E, P/BV, P/S, and P/FCF are calculated using:
price_to_earning
price_to_book_value
price_to_sales
price_to_free_cash_flow
These calculations are done using request.financial function calls.
User Inputs
The code uses input functions to allow users to select financial items and time periods:
financial_item_selection_01 and financial_item_selection_02 enable the selection of financial metrics.
period_selection allows users to choose between periods like FQ (Fiscal Quarter), FY (Fiscal Year), and TTM (Trailing Twelve Months).
Users can control the table's visibility and the display of QoQ, YoY, and CAGR changes using input.bool() settings.
Financial Data Retrieval
The function retreive_financial_data(_financial_item, _period) retrieves financial data based on the selected financial item and period.
It uses the request.financial function to get data for a specific ticker.
Table Creation and Formatting
The script uses table.new() to create a table for displaying financial data.
The table’s headers and values are populated using custom functions like header_column, date_column, and value_column.
QoQ, YoY, and CAGR columns are conditionally displayed based on the user’s input settings.
Plotting Data
The script can also plot the selected financial metrics using the plot() function.
Labels for plotted data are created using the label.new() function.
Handling of Bar States
The barstate.islast condition ensures that the table and plots are only updated at the last bar state, which optimizes performance and prevents unnecessary calculations.
Code Formatting and Optimization
Proper use of variables, functions, and conditional statements adheres to TradingView’s guidelines for efficient Pine Script development.
The use of ignore_invalid_symbol=true in request.financial calls ensures the script handles non-existent financial data gracefully.
Key Functions
is_calculated_data(_financial_item)
Determines whether a given financial item is a calculated metric (e.g., P/E, P/BV) instead of being directly available from TradingView’s data.
get_financial_id(_financial_item)
Returns the financial identifier based on the selected item (e.g., TOTAL_REVENUE for revenue).
get_value_formating(_financial_item)
Returns the appropriate value divider, suffix, and formatting style based on the selected financial item.
create_array(arrayId, val)
Adds a new value to a specified array, used for storing historical financial data for table display.
get_cagr(_data_array, _id, _idmax)
Calculates the compound annual growth rate (CAGR) based on the given data array and index.
Statistical Volatility° [Pro+] (Joshuuu)Introduction:
Statistical Volatility is a custom-built indicator designed to help traders track the historical range volatility of each individual candle of a given Timeframe. Compared to traditional volatility metrics, or lookback-based volatility calculations, this indicator is focused on the idea of Time-based volatility.
Description:
Whether you are looking at intraday price movements or weekly trends, this tool provides a clear, visual representation of the average range each candle typically covers. By understanding these volatility patterns, traders can observe when markets are likely to expand or consolidate, based on Time.
To obtain this insightful metrics, all available candle range data is normalized; values are therefore represented as a percentage of the maximum historical Time volatility, indicating how each candle range compares relative to the highest value. This allows for an easy comparison of volatility across different Time periods.
Key Features:
Detailed Volatility Tracking: The Statistical Volatility indicator enables traders to track the volatility of each candle throughout the day, week, or month, depending on the selected Timeframe. It helps to identify statistical Times of expansion or consolidation, beyond what current price data may showcase.
Timeframe Adaptability: On lower timeframes such as the 5 Minute Timeframe, the indicator calculates and plots the statistical range for each 5 Minute candle of the day, respectively. On higher timeframes, such as 1 Hour Timeframe or above, the ranges are plotted for each candle of the week, respectively. This adaptability ensures the indicator is versatile enough for day traders, scalpers, and swing traders alike; maintaining a highly granular yet versatile statistical edge.
Flexible Display Options: Traders can choose between different visualization methods, in form of a Heatmap or a Barchart, to display the volatility calculations. The heatmap offers a simple visualization of the data, relying entirely on the color gradient to display volatility. On the other hand, the Barchart gives more flexibility to the analyst by providing a more detailed visual analysis, with the ability of overlaying and comparing the current Time-based volatility.
How Traders Can Use Statistical Volatility (Joshuuu) Effectively:
Data-Based Optimization: By understanding when the market typically experiences its largest or smallest moves, traders can better frame the current narrative. Especially when backtesting, this information can help optimize analysts' entry mechanisms thanks to the introduction of a Time-based statistical component.
Asset-Specific Insights: Currencies like Forex pairs (i.e. FOREXCOM:EURUSD , FOREXCOM:AUDUSD ) or other Asset Classes tied to a particular geographical location (i.e. CME_MINI:NQ1! in the United States, XETR:DAX in Germany), experience volatility spikes during the operational hours of major banks. Each asset has its own “active” Time when liquidity and volatility are higher, tied to when their corresponding markets are open. This makes Statistical Volatility particularly useful for traders who focus on multiple assets across different time zones.
Usage Guidance:
Add Statistical Volatility (Joshuuu) to your TradingView chart.
Customize your preferred volatility calculation type, gradient colors, and plot styles.
Use the volatility graphic to monitor current and upcoming shifts in volatility.
Incorporate Statistical Volatility (Joshuuu) into your existing statistical strategies to fine-tune your interpretation of market behaviour.
These tools are available ONLY on the TradingView platform.
Terms and Conditions
Our charting tools are products provided for informational and educational purposes only and do not constitute financial, investment, or trading advice. Our charting tools are not designed to predict market movements or provide specific recommendations. Users should be aware that past performance is not indicative of future results and should not be relied upon for making financial decisions. By using our charting tools, the purchaser agrees that the seller and the creator are not responsible for any decisions made based on the information provided by these charting tools. The purchaser assumes full responsibility and liability for any actions taken and the consequences thereof, including any loss of money or investments that may occur as a result of using these products. Hence, by purchasing these charting tools, the customer accepts and acknowledges that the seller and the creator are not liable nor responsible for any unwanted outcome that arises from the development, the sale, or the use of these products. Finally, the purchaser indemnifies the seller from any and all liability. If the purchaser was invited through the Friends and Family Program, they acknowledge that the provided discount code only applies to the first initial purchase of the Toodegrees Premium Suite subscription. The purchaser is therefore responsible for cancelling – or requesting to cancel – their subscription in the event that they do not wish to continue using the product at full retail price. If the purchaser no longer wishes to use the products, they must unsubscribe from the membership service, if applicable. We hold no reimbursement, refund, or chargeback policy. Once these Terms and Conditions are accepted by the Customer, before purchase, no reimbursements, refunds or chargebacks will be provided under any circumstances.
By continuing to use these charting tools, the user acknowledges and agrees to the Terms and Conditions outlined in this legal disclaimer.
Volume CalendarDescription:
The indicator displays a calendar with Volume data for up to 6 last months. It is designed to work on any timeframe, but works best on Daily and below. It is also consistent in that it displays the same data even if you go to lower timeframes like 5 minutes (even though the data is used is Daily).
Features:
- displays volume data for last N months (volume, volume change, % of weekly, monthly and yearly volume)
- display total volume for each month
- display monthly sentiment
- find dates with volume spikes
Inputs:
- Number of months -> how many last months of data to display (from 1 to 6)
- Volume Type -> display only Bullish, only Bearish or all volume
- Cell color is based on -> Volume - the brighter the cell the higher volume was on that day; Volume Change - the brighter the cell the higher was the volume change that day; Volume Spike - the brighter the cell the higher was volume spike that day (volume spike is based on volume being above its average over last N candles)
- Cell color timeframe -> Weekly - the cell color is calculated comparing volume of that cell with weekly volume; Monthly - comparing volume with monthly volume
- Use volume for sentiment -> take the volume into account when calculating monthly sentiment (otherwise calculate it based on number of Bullish and Bearish days in the month)
- Spike Average Period -> period of the moving average used for spike calculation
- Spike Threshold -> current volume must be this many times greater than the average for it to be considered a spike
- Table Size -> size of the table
- Theme -> colouring of the table
VATICAN BANK CARTELVATICAN BANK CARTEL - Precision Signal Detection for Buyers.
The VATICAN BANK CARTEL indicator is a highly sophisticated tool designed specifically for buyers, helping them identify key market trends and generate actionable buy signals. Utilizing advanced algorithms, this indicator employs a multi-variable detection mechanism that dynamically adapts to price movements, offering real-time insights to assist in executing profitable buy trades. This indicator is optimized solely for identifying buying opportunities, ensuring that traders are equipped to make well-timed entries and exits, without signals for shorting or selling.
The recommended settings for VATICAN BANK CARTEL indicator is as follows:-
Depth Engine = 20,30,40,50,100.
Deviation Engine = 3,5,7,15,20.
Backstep Engine = 15,17,20,25.
NOTE:- But you can also use this indicator as per your setting, whichever setting gives you best results use that setting.
Key Features:
1.Adaptive Depth, Deviation, and Backstep Inputs:
The core of this indicator is its customizable Depth Engine, Deviation Engine, and Backstep Engine parameters. These inputs allow traders to adjust the sensitivity of the trend detection algorithm based on specific market conditions:
Depth: Defines how deep the indicator scans historical price data for potential trend reversals.
Deviation: Determines the minimum required price fluctuation to confirm a market movement.
Backstep: Sets the retracement level to filter false signals and maintain the accuracy of trend detection.
2. Visual Signal Representation:
The VATICAN BANK CARTEL plots highly visible labels on the chart to mark trend reversals. These labels are customizable in terms of size and transparency, ensuring clarity in various chart environments. Traders can quickly spot buying opportunities with green labels and potential square-off points with red labels, focusing exclusively on buy-side signals.
3.Real-Time Alerts:
The indicator is equipped with real-time alert conditions to notify traders of significant buy or square-off buy signals. These alerts, which are triggered based on the indicator’s internal signal logic, ensure that traders never miss a critical market movement on the buy side.
4.Custom Label Size and Transparency:
To enhance visual flexibility, the indicator allows the user to adjust label size (from small to large) and transparency levels. This feature provides a clean, adaptable view suited for different charting styles and timeframes.
How It Works:
The VATICAN BANK CARTEL analyzes the price action using a sophisticated algorithm that considers historical low and high points, dynamically detecting directional changes. When a change in market direction is detected, the indicator plots a label at the key reversal points, helping traders confirm potential entry points:
- Buy Signal (Green): Indicates potential buying opportunities based on a trend reversal.
- Square-Off Buy Signal (Red): Marks the exit point for open buy positions, allowing traders to take profits or protect capital from potential market reversals.
Note: This indicator is exclusively designed to provide signals for buyers. It does not generate sell or short signals, making it ideal for traders focused solely on identifying optimal buying opportunities in the market.
Customizable Parameters:
- Depth Engine: Fine-tunes the historical data analysis for signal generation.
- Deviation Engine: Adjusts the minimum price change required for detecting trends.
- Backstep Engine: Controls the indicator's sensitivity to retracements, minimizing false signals.
- Labels Transparency: Adjusts the opacity of the labels, ensuring they integrate seamlessly into any chart layout.
- Buy and Sell Colors: Customizable color options for buy and square-off buy labels to match your preferred color scheme.
- Label Size: Select between five different label sizes for optimal chart visibility.
Ideal For:
This indicator is ideal for both beginner and experienced traders looking to enhance their buying strategy with a highly reliable, visual, and alert-driven tool. The VATICAN BANK CARTEL adapts to various timeframes, making it suitable for day traders, swing traders, and long-term investors alike—focused exclusively on buying opportunities.
Benefits and Applications:
1.Intraday Trading: The VATICAN BANK CARTEL indicator is particularly well-suited for intraday trading, as it provides accurate and timely "buy" and "square-off buy" signals based on the current market dynamics.
2.Trend-following Strategies: Traders who employ trend-following strategies can leverage the indicator's ability to identify the overall market direction, allowing them to align their trades with the dominant trend.
3.Swing Trading: The dynamic price tracking and signal generation capabilities of the indicator can be beneficial for swing traders, who aim to capture medium-term price movements.
Security Measures:
1. The code includes a security notice at the beginning, indicating that it is subject to the Mozilla Public License 2.0, which is a reputable open-source license.
2. The code does not appear to contain any obvious security vulnerabilities or malicious content that could compromise user data or accounts.
NOTE:- This indicator is provided under the Mozilla Public License 2.0 and is subject to its terms and conditions.
Disclaimer: The usage of VATICAN BANK CARTEL indicator might or might not contribute to your trading capital(money) profits and losses and the author is not responsible for the same.
IMPORTANT NOTICE:
While the indicator aims to provide reliable "buy" and "square-off buy" signals, it is crucial to understand that the market can be influenced by unpredictable events, such as natural disasters, political unrest, changes in monetary policies, or economic crises. These unforeseen situations may occasionally lead to false signals generated by the VATICAN BANK CARTEL indicator.
Users should exercise caution and diligence when relying on the indicator's signals, as the market's behavior can be unpredictable, and external factors may impact the accuracy of the signals. It is recommended to thoroughly backtest the indicator's performance in various market conditions and to use it as one of the many tools in a comprehensive trading strategy, rather than solely relying on its output.
Ultimately, the success of the VATICAN BANK CARTEL indicator will depend on the user's ability to adapt it to their specific trading style, market conditions, and risk management approach. Continuous monitoring, analysis, and adjustment of the indicator's settings may be necessary to maintain its effectiveness in the ever-evolving financial markets.
DEVELOPER:- yashgode9
PineScript:- version:- 5
This indicator aims to enhance trading decision-making by combining DEPTH, DEVIATION, BACKSTEP with custom signal generation, offering a comprehensive tool for traders seeking clear "buy" and "square-off buy" signals on the TradingView platform.
Adaptive Gaussian MA For Loop [BackQuant]Adaptive Gaussian MA For Loop
PLEASE Read the following carefully before applying this indicator to your trading system. Knowing the core logic behind the tools you're using allows you to integrate them into your strategy with confidence and precision.
Introducing BackQuant's Adaptive Gaussian Moving Average For Loop (AGMA FL) — a sophisticated trading indicator that merges the Gaussian Moving Average (GMA) with adaptive volatility to provide dynamic trend analysis. This unique indicator further enhances its effectiveness by utilizing a for-loop scoring mechanism to detect potential shifts in market direction. Let's dive into the components, the rationale behind them, and how this indicator can be practically applied to your trading strategies.
Understanding the Gaussian Moving Average (GMA)
The Gaussian Moving Average (GMA) is a smoothed moving average that applies Gaussian weighting to price data. Gaussian weighting gives more significance to data points near the center of the lookback window, making the GMA particularly effective at reducing noise while maintaining sensitivity to changes in price direction. In contrast to simpler moving averages like the SMA or EMA, GMA provides a more refined smoothing function, which can help traders follow the true trend in volatile markets.
In this script, the GMA is calculated over a defined Calculation Period (default 14), applying a Gaussian filter to smooth out market fluctuations and provide a clearer view of underlying trends.
Adaptive Volatility: A Dynamic Edge
The Adaptive feature in this indicator gives it the ability to adjust its sensitivity based on current market volatility. If the Adaptive option is enabled, the GMA uses a standard deviation-based volatility measure (with a default period of 20) to dynamically adjust the width of the Gaussian filter, allowing the GMA to react faster in volatile markets and more slowly in calm conditions. This dynamic nature ensures that the GMA stays relevant across different market environments.
When the Adaptive setting is disabled, the script defaults to a constant standard deviation value (default 1.0), providing a more stable but less responsive smoothing function.
Why Use Adaptive Gaussian Moving Average?
The Gaussian Moving Average already provides smoother results than standard moving averages, but by adding an adaptive component, the indicator becomes even more responsive to real-time price changes. In fast-moving or highly volatile markets, this adaptation allows traders to react quicker to emerging trends. Conversely, in quieter markets, it reduces over-sensitivity to minor fluctuations, thus lowering the risk of false signals.
For-Loop Scoring Mechanism
The heart of this indicator lies in its for-loop scoring system, which evaluates the smoothed price data (the GMA) over a specified range, comparing it to previous values. This scoring system assigns a numerical value based on whether the current GMA is higher or lower than previous values, creating a trend score.
Long Signals: These are generated when the for-loop score surpasses the Long Threshold (default set at 40), signaling that the GMA is gaining upward momentum, potentially identifying a favorable buying opportunity.
Short Signals: These are triggered when the score crosses below the Short Threshold (default set at -10), indicating that the market may be losing strength and that a selling or shorting opportunity could be emerging.
Thresholds & Customization Options
This indicator offers a high degree of flexibility, allowing you to fine-tune the settings according to your trading style and risk preferences:
Calculation Period: Adjust the lookback period for the Gaussian filter, affecting how smooth or responsive the indicator is to price changes.
Adaptive Mode: Toggle the adaptive feature on or off, allowing the GMA to dynamically adjust based on market volatility or remain consistent with a fixed standard deviation.
Volatility Settings: Control the standard deviation period for adaptive mode, fine-tuning how quickly the GMA responds to shifts in volatility.
For-Loop Settings: Modify the start and end points for the for-loop score calculation, adjusting the depth of analysis for trend signals.
Thresholds for Signals: Set custom long and short thresholds to determine when buy or sell signals should be generated.
Visualization Options: Choose to color bars based on trend direction, plot signal lines, or adjust the background color to reflect current market sentiment visually.
Trading Applications
The Adaptive Gaussian MA For Loop can be applied to a variety of trading styles and markets. Here are some key ways you can use this indicator in practice:
Trend Following: The combination of Gaussian smoothing and adaptive volatility helps traders stay on top of market trends, identifying significant momentum shifts while filtering out noise. The for-loop scoring system enhances this by providing a numerical representation of trend strength, making it easier to spot when a new trend is emerging or when an existing one is gaining strength.
Mean Reversion: For traders looking to capitalize on short-term market corrections, the adaptive nature of this indicator makes it easier to identify when price action is deviating too far from its smoothed trend, allowing for strategic entries and exits based on overbought or oversold conditions.
Swing Trading: With its ability to capture medium-term price movements while avoiding the noise of short-term fluctuations, this indicator is well-suited for swing traders who aim to profit from market reversals or short-to-mid-term trends.
Volatility Management: The adaptive feature allows the indicator to adjust dynamically in volatile markets, ensuring that it remains responsive in times of increased uncertainty while avoiding unnecessary noise in calmer periods. This makes it an effective tool for traders who want to manage risk by staying in tune with changing market conditions.
Final Thoughts
The Adaptive Gaussian MA For Loop is a powerful and flexible indicator that merges the elegance of Gaussian smoothing with the adaptability of volatility-based adjustments. By incorporating a for-loop scoring mechanism, this indicator provides traders with a comprehensive view of market trends and potential trade opportunities.
It’s important to test the settings on historical data and adapt them to your specific trading style, timeframe, and market conditions. As with any technical tool, the AGMA For Loop should be used in conjunction with other indicators and solid risk management practices for the best results.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Two Pole Butterworth For Loop [BackQuant]Two Pole Butterworth For Loop
PLEASE read the following carefully, as understanding the underlying concepts and logic behind the indicator is key to incorporating it into your trading system in a sound and methodical manner.
Introducing BackQuant's Two Pole Butterworth For Loop (2P BW FL) — an advanced indicator that fuses the power of the Two Pole Butterworth filter with a dynamic for-loop scoring mechanism. This unique approach is designed to extract actionable trading signals by smoothing out price data and then analyzing it using a comparative scoring method. Let's delve into how this indicator works, why it was created, and how it can be used in various trading scenarios.
Understanding the Two Pole Butterworth Filter
The Butterworth filter is a signal processing tool known for its smooth response and minimal distortion. It's often used in electronic and communication systems to filter out unwanted noise. In trading, the Butterworth filter can be applied to price data to smooth out the volatility, providing traders with a clearer view of underlying trends without the whipsaws often associated with market noise.
The Two Pole Butterworth variant further enhances this effect by applying the filter with two poles, effectively creating a sharper transition between the passband and stopband. In simple terms, this allows the filter to follow the price action more closely, reacting to changes while maintaining smoothness.
In this script, the Two Pole Butterworth filter is applied to the Calculation Source (default is set to the closing price), creating a smoothed price series that serves as the foundation for further analysis.
Why Use a Two Pole Butterworth Filter?
The Two Pole Butterworth filter is chosen for its ability to reduce lag while maintaining a smooth output. This makes it an ideal choice for traders who want to capture trends without being misled by short-term volatility or market noise. By filtering the price data, the Two Pole Butterworth enables traders to focus on the broader market movements and avoid false signals.
The For-Loop Scoring Mechanism
In addition to the Butterworth filter, this script uses a for-loop scoring system to evaluate the smoothed price data. The for-loop compares the current value of the filtered price (referred to as "subject") to previous values over a defined range (set by the start and end input). The score is calculated based on whether the subject is higher or lower than the previous points, and the cumulative score is used to determine the strength of the trend.
Long and Short Signal Logic
Long Signals: A long signal is triggered when the score surpasses the Long Threshold (default set at 40). This suggests that the price has built sufficient upward momentum, indicating a potential buying opportunity.
Short Signals: A short signal is triggered when the score crosses under the Short Threshold (default set at -10). This indicates weakening price action or a potential downtrend, signaling a possible selling or shorting opportunity.
By utilizing this scoring system, the indicator identifies moments when the price momentum is shifting, helping traders enter positions at opportune times.
Customization and Visualization Options
One of the strengths of this indicator is its flexibility. Traders can customize various settings to fit their personal trading style or adapt it to different markets and timeframes:
Calculation Periods: Adjust the lookback period for the Butterworth filter, allowing for shorter or longer smoothing depending on the desired sensitivity.
Threshold Levels: Set the long and short thresholds to define when signals should be triggered, giving you control over the balance between sensitivity and specificity.
Signal Line Width and Colors: Customize the visual presentation of the indicator on the chart, including the width of the signal line and the colors used for long and short conditions.
Candlestick and Background Colors: If desired, the indicator can color the candlesticks or the background according to the detected trend, offering additional clarity at a glance.
Trading Applications
This Two Pole Butterworth For Loop indicator is versatile and can be adapted to various market conditions and trading strategies. Here are a few use cases where this indicator shines:
Trend Following: The Butterworth filter smooths the price data, making it easier to follow trends and identify when they are gaining or losing strength. The for-loop scoring system enhances this by providing a clear indication of how strong the current trend is compared to recent history.
Mean Reversion: For traders looking to identify potential reversals, the indicator’s ability to compare the filtered price to previous values over a range of periods allows it to spot moments when the trend may be losing steam, potentially signaling a reversal.
Swing Trading: The combination of smoothing and scoring allows swing traders to capture short to medium-term price movements by filtering out the noise and focusing on significant shifts in momentum.
Risk Management: By providing clear long and short signals, this indicator helps traders manage their risk by offering well-defined entry and exit points. The smooth nature of the Butterworth filter also reduces the risk of getting caught in false signals due to market noise.
Final Thoughts
The Two Pole Butterworth For Loop indicator offers traders a powerful combination of smoothing and scoring to detect meaningful trends and shifts in price momentum. Whether you are a trend follower, swing trader, or someone looking to refine your entry and exit points, this indicator provides the tools to make more informed trading decisions.
As always, it's essential to backtest the indicator on historical data and tailor the settings to your specific trading style and market. While the Butterworth filter helps reduce noise and smooth trends, no indicator can predict the future with absolute certainty, so it should be used in conjunction with other tools and sound risk management practices.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Crypto Heatmap [Pinescriptlabs]🌟 Crypto Heatmap is a visual tool that enables quick and efficient visualization of price behavior and percentage changes of various cryptocurrencies.
📊 It generates a heatmap to show variations in daily closing prices, helping traders quickly identify assets with the most movement.
📈 Percentage Change Calculation: It calculates the difference between the current price and the previous day's price, updating with each ticker.
✨ It uses a dynamic approach that adjusts colors based on market movements, making it easier to detect trading opportunities.
👀 You will notice for a moment that some cells disappear; this is because the table updates with each ticker to show real-time changes.
Español:
🌟 Crypto Heatmap es una herramienta visual que permite una rápida y eficiente visualización del comportamiento de precios y cambios porcentuales de varias criptomonedas.
📊 Genera un mapa de calor para mostrar las variaciones en los precios de cierre diario, ayudando a los traders a identificar rápidamente los activos con mayor movimiento.
📈 Cálculo del cambio porcentual: Calcula la diferencia entre el precio actual y el del día anterior, actualizándose en cada ticker.
✨ Utiliza un enfoque dinámico que ajusta los colores según los movimientos del mercado, facilitando la detección de oportunidades de trading.
Aquí tienes la traducción al español:
👀 **Observarás por un momento que algunas celdas desaparecen; esto es porque la tabla se actualiza en cada ticker para mostrar el cambio en tiempo real.**
2024 - Seasonality - Open to CloseScript Description:
This Pine Script is designed to visualise **seasonality** in the financial markets by calculating the **open-to-close percentage change** for each month of a selected asset. It creates a **heatmap** table to display the monthly performance over multiple years. The script provides detailed statistical summaries, including:
- **Average monthly percentage changes**
- **Standard deviation** of the changes
- **Percentage of months with positive returns**
The script also allows users to adjust colour intensities for positive and negative values, specify which year to start from, and skip specific months. Key metrics such as averages, standard deviations, and percentages of positive months can be toggled on or off based on user preferences. The result is a clear, visual representation of how an asset typically performs month by month, aiding in seasonality analysis.
Candle Data AnalyzerCandle Data Analyzer
Overview
The Candle Data Analyzer is a powerful TradingView script designed to provide traders with insights into price action patterns within specific time sessions. By analyzing historical candle data, this indicator offers predictive suggestions for future price movements, helping traders make more informed decisions.
Key Features
**Custom Session Analysis**: Analyze price action within user-defined time sessions.
**Bias Selection**: Choose between Bullish, Bearish, or Neutral bias for predictions.
**Daily/Weekly Toggle**: Option to use daily or weekly results for broader context.
**Visual Predictions**: Display predicted high, low, and open levels for the next session.
**Detailed Statistics**: View average time and price movements for highs and lows.
**Interactive Table**: Optional table display showing current and historical data.
How It Works
1. The script collects and analyzes candle data from user-defined sessions.
2. It calculates average time and price movements for highs and lows.
3. Based on the selected bias, it predicts the next session's open, high, and low levels.
4. These predictions are visually represented on the chart using colored lines.
5. A detailed statistics table can be displayed for in-depth analysis.
Usage Guide
Setup
1. Add the indicator to your chart.
2. Configure the session time in the format "HHMM-HHMM" (e.g., "0300-0500" for 3:00 AM to 5:00 AM).
3. Select your bias: Bullish, Bearish, or Neutral.
4. Choose whether to use daily results or not.
5. Decide if you want to display the detailed statistics table.
Interpreting the Results
**Blue Line**: Open level for the next session.
**Green Line**: Predicted high level for the next session.
**Red Line**: Predicted low level for the next session.
**Vertical Lines**: Estimated times for the high (green) and low (red) to occur.
Using the Statistics Table
If enabled, the table provides:
- Previous session's OHLC data with timestamps.
- Average price movements (as percentages) from open to high and open to low.
- Average time for highs and lows to occur (in minutes).
- Count of analyzed candles matching the selected bias.
Trading Applications
**Session Trading**: Use predictions to plan entries and exits for session-based trading strategies.
**Risk Management**: Set stop-loss and take-profit levels based on predicted price ranges.
**Trend Analysis**: Compare current price action to predicted levels to gauge trend strength.
**Time-Based Strategies**: Utilize timing predictions for high-probability trade entries.
Best Practices
- Combine this indicator with other technical analysis tools for confirmation.
- Regularly adjust the session times and bias to adapt to changing market conditions.
- Use the statistics table to gain deeper insights into historical price patterns.
- Remember that predictions are based on averages and should not be considered guaranteed outcomes.
Conclusion
The Candle Data Analyzer offers a unique approach to understanding and predicting price action within specific time frames. By leveraging historical data and user-defined parameters, it provides traders with valuable insights to enhance their trading strategies and decision-making processes.
Future Developments
- Weekly and Daily Projections
- User defined line styles
Every $5 (3 Up, 3 Down) GOLD onlyDescription :
This indicator plots customizable horizontal lines spaced every $5 on the XAUUSD chart, with exactly 3 lines above and 3 lines below the nearest $5 level from the current price.
Key Features :
Line Spacing: The lines are plotted at $5 intervals starting from the nearest whole $5 price below the current price (e.g., $1900, $1905, etc.).
Customizable Line Color : Users can select the color of the lines via the indicator settings, making it adaptable to different chart themes and styles.
Customizable Line Style : The indicator allows you to choose from the following line styles:
Solid : Continuous line.
Dashed: Dashed line for a more discrete visual.
Dotted: Dotted line for minimalistic visibility.
Visibility Control : The indicator limits the number of lines to 3 above and 3 below the current price, keeping the chart clean and uncluttered while providing key levels of interest.
Use Cases :
Support and Resistance Identification: Easily spot key psychological levels in $5 increments, useful for identifying potential support or resistance zones in XAUUSD trading.
Price Action Monitoring : Traders can visually track how XAUUSD interacts with specific price levels spaced by $5 increments.
Customization Options :
Color Selection: Modify the line color to match your chart theme or highlight important levels.
Line Style: Select between solid, dashed, or dotted lines to customize the look of your chart.
This indicator is ideal for XAUUSD traders looking for clear, customizable visual levels on their charts to aid in decision-making, whether you're tracking price action or setting targets for entry and exit.
DTT Volatility Grid [Pro+] (NINE/ANARR)Introduction:
This tool is designed to automate the Digital Time Theory (DTT) framework created by Ivan and Anarr, and leverage the DTT Volatility Grid to navigate the advanced realm of Time-based statistical trading.
Description:
Built upon the proprietary Digital Time Theory (DTT), this script equips traders with an edge in analyzing Time and price-based market behaviour. It is designed for intraday traders of all asset classes, and breaks down the entire Daily range into Time Models and Inner Time Intervals. This tool is powered by data-driven insights, helping traders anticipate expansions, understand Time distortions, and assess market volatility at specific Times of the trading day.
Key Features:
Time-Based Models and Volatility Awareness: The indicator automatically populates the chart with DTT's Time Models. These Time Models, represented by specific Time Intervals, are engineered to highlight volatility injections within key sessions, offering traders clear insights into market dynamics and potential shifts.
Average Model Range Probability (AMRP): Know the average volatility expected for specific Time Models and use AMRP Levels (and Standard Deviation) to gauge the probability of a range break or failure, based on historical price action and Time data.
Root Candles and Liquidity Draws: Visualize Root Candles as draws on liquidity, showcasing premium and discount areas, and the starting point of a Time based price movement. Understand how the opening price and equilibrium of each Root Candle can serve as a framework for your trade executions. Distribution or accumulation above or below Root Candles can also be observed and utilized.
Extended Visualization: Observe prior Model Ranges into the current Time Model, including the High, Low, and Equilibrium from the previous Time Models, helping traders visualize potential support or resistance areas.
Lookback Periods and Model Count: Use customizable lookback periods to adjust the number of past models, providing further insight into market behaviour over a chosen historical range. This can help to keep charts clean and organized with one model displayed or multiple for backtesting purposes.
Detailed Data Table: The real-Time data table allows traders to view the AMRP and range data for selected models, providing an easy reference for model behaviour and volatility dynamics. The table can depict all Time Model average ranges for reference and study, providing insights to whether the previous models have exceeded their historical range volatility, or not.
Customization Options: Customize Time Intervals with various styles (solid, dashed, dotted) and choose different colors for each model or interval. You can also select which historical models to display, alongside customizable labels.
How Traders Can Use DTT Volatility Grid Effectively:
Understand Premium and Discount Areas: By tracking Time-based ranges and using DTT's Root Candles and Previous Model Equilibrium, traders can quickly assess whether price is trading in premium or discount territory during intraday sessions.
Expecting Volatility and Time-Sensitive Trades: Knowing when a move is nearing exhaustion or when Time-based distortions are likely to cause an expansion allows traders to stay ahead of sudden market shifts. The Inner Intervals and Root Candles in combination, highlight the volatility ranges across various Timeframes, giving traders insights into which Times of the day are likely to experience heightened market activity as per DTT.
Avoiding Low Volatility Periods: The AMRP system helps traders identify times of the day where price action is likely to slow down or become choppy, encouraging traders to step aside or reduce risk during these times. If the AMRP was extended above the average of the previous Time model and the current model depicts an average range probability of low volatility, then traders can sit out in anticipation for a model with higher volatility.
Usage Guidance:
Add DTT Volatility Grid (NINE/ANARR) to your TradingView chart.
Customize your preferred time intervals, model history, and visual settings for your session.
Use the data table to track average model ranges and probabilities, ensuring you align your trades with key levels.
Incorporate DTT Volatility Grid (NINE/ANARR) into your existing strategies to fine-tune your entries and exits based on data-driven insights into volatility and price behaviour.
These tools are available ONLY on the TradingView platform.
Terms and Conditions
Our charting tools are products provided for informational and educational purposes only and do not constitute financial, investment, or trading advice. Our charting tools are not designed to predict market movements or provide specific recommendations. Users should be aware that past performance is not indicative of future results and should not be relied upon for making financial decisions. By using our charting tools, the purchaser agrees that the seller and the creator are not responsible for any decisions made based on the information provided by these charting tools. The purchaser assumes full responsibility and liability for any actions taken and the consequences thereof, including any loss of money or investments that may occur as a result of using these products. Hence, by purchasing these charting tools, the customer accepts and acknowledges that the seller and the creator are not liable nor responsible for any unwanted outcome that arises from the development, the sale, or the use of these products. Finally, the purchaser indemnifies the seller from any and all liability. If the purchaser was invited through the Friends and Family Program, they acknowledge that the provided discount code only applies to the first initial purchase of the Toodegrees Premium Suite subscription. The purchaser is therefore responsible for cancelling – or requesting to cancel – their subscription in the event that they do not wish to continue using the product at full retail price. If the purchaser no longer wishes to use the products, they must unsubscribe from the membership service, if applicable. We hold no reimbursement, refund, or chargeback policy. Once these Terms and Conditions are accepted by the Customer, before purchase, no reimbursements, refunds or chargebacks will be provided under any circumstances.
By continuing to use these charting tools, the user acknowledges and agrees to the Terms and Conditions outlined in this legal disclaimer.
Forex - Lot size calculatorThis indicator is specifically designed for Forex traders who need a convenient lot size calculator directly on their charts. It allows users to input their account balance, risk percentage, and stop-loss distance in pips to easily determine the appropriate lot size for a given trade, ensuring effective risk management.
Key Features:
Lot Size Calculation: Automatically calculates the lot size based on user-defined inputs: account balance, risk percentage, and stop-loss distance.
Error Handling: The indicator only works with Forex pairs. If applied to non-Forex assets, a clear and prominent red error message will appear in the bottom-right corner of the chart, reminding the user that this script is intended exclusively for Forex trading.
Simple Visualization: The calculated lot size is displayed in an easy-to-read table directly on the chart.
How to Use:
Add the indicator to a Forex chart.
Enter your account balance, risk percentage, and stop-loss pips in the input fields.
The indicator will display the calculated lot size for the chosen Forex pair.
Important Notes:
This script is intended only for Forex assets. If used on other instruments (e.g., stocks, crypto, indices), an error message will be shown.
Always validate lot sizes with your broker, as there can be slight variations depending on broker specifications and leverage settings.
Triangular Arbitrage [Starbots]Triangular arbitrage in crypto refers to a trading strategy that exploits price discrepancies between three different cryptocurrencies or currency pairs on the same exchange.
The idea is to make a series of trades that ultimately result in a profit without the risk typically involved in trading. It works by taking advantage of the inefficiencies in the pricing of cryptocurrency pairs.
Here’s how it works:
Identify the Discrepancy: A trader finds a pricing mismatch between three cryptocurrencies. For example, they identify that the exchange rates between BTC/ETH, ETH/USDT, and BTC/USDT pairs are not aligned in a way that satisfies arbitrage-free conditions.
Three Trades:
Trade 1: Start with one cryptocurrency, say USDT (Tether).
Trade 2: Use USDT to buy ETH.
Trade 3: Use ETH to buy BTC.
Final Trade: Finally, convert the BTC back into USDT.
Profit: If the exchange rates between these pairs are out of sync, the trader can end up with more USDT (or the initial cryptocurrency) than they started with. This is because the temporary price inefficiency allowed them to buy low and sell high across different pairs.
Example:
Initial position: You have 10,000 USDT.
Step 1: You buy ETH with USDT (at a rate of 1 ETH = 2000 USDT), getting 5 ETH.
Step 2: You buy BTC with ETH (at a rate of 1 BTC = 2.5 ETH), getting 2 BTC.
Step 3: You sell BTC back for USDT (at a rate of 1 BTC = 5200 USDT), getting 10,400 USDT.
This results in a profit of 400 USDT after completing the cycle, assuming no fees or slippage.
Key Points:
Risk-Free (In Theory): In theory, triangular arbitrage is risk-free because you’re taking advantage of price discrepancies and not market trends.
High Speed Required: Since the inefficiencies in the crypto market are usually very short-lived, this strategy often requires bots or automated systems to execute trades quickly.
Fees and Slippage: In reality, exchange fees, trading volume, and slippage (the difference between the expected price and the actual execution price) can eat into profits and should be carefully considered.
Triangular arbitrage opportunities arise in crypto markets due to the high volatility and fragmentation across different trading pairs and exchanges.
________________________________________________________________
Recommended Binance pairs: DOGE/BTC, TRX/BTC, LINK/BTC, RUNE/BTC, FET/BTC, WIF/BTC,.. Make sure they have big daily volume when you swap them.
You typically have 30 seconds to 2 minutes to complete all three orders, but the main challenge is slippage, especially if the trading volume is low.
<>How to use indicator?
For example, open the DOGE/BTC chart on Binance and set the timeframe to 30 seconds or 1 minute.
In the first input, enter DOGE/USDT, the symbol that's on the left of your slash (DOGE/BTC), and in the second, enter BTC/USDT, the symbol that's on the right of your slash (DOGE/BTC).
Next, select the investment and commissions option.
Indicator will automatically calculate the discrepancies between these three different cryptocurrency pairs and show you when it's profitable to trade it on the chart.
Follow the indicator's suggested orders and capitalize on the price discrepancies between the three cryptocurrencies on the same exchange. This is how Triangular Arbitrage work.
Indicator Test with Conditions TableOverview: The "Indicator Test with Conditions Table" is a customizable trading strategy developed using Pine Script™ for the TradingView platform. It allows users to define complex entry conditions for both long and short positions based on various technical indicators and price levels.
Key Features:
Customizable Input Conditions:
Users can configure up to three input conditions for both long and short entries, each with its own logical operator (AND/OR) for combining conditions.
Input conditions can be based on:
Price Sources: Users can select any price data (e.g., close, open, high, low) for each condition.
Comparison Operators: Users can choose from a variety of operators, including:
Greater than (>)
Greater than or equal to (>=)
Less than (<)
Less than or equal to (<=)
Equal to (=)
Not equal to (!=)
Crossover (crossover)
Crossunder (crossunder)
Logical Operators:
The strategy provides options for combining conditions using logical operators (AND/OR) for greater flexibility in defining entry criteria.
Dynamic Condition Evaluation:
The strategy evaluates the defined conditions dynamically, checking whether they are enabled before proceeding with the comparison.
Users can toggle conditions on and off using boolean inputs, allowing for quick adjustments without modifying the code.
Visual Feedback:
A table is displayed on the chart, providing real-time status updates on the conditions and whether they are enabled. This enhances user experience by allowing easy monitoring of the strategy's logic.
Order Execution:
The strategy enters long or short positions based on the combined conditions' evaluations, automatically executing trades when the criteria are met.
How to Use:
Set Up Input Conditions:
Navigate to the strategy’s input settings to configure your desired price sources, operators, and logical combinations for long and short conditions.
Monitor Conditions:
Observe the condition table displayed at the bottom right of the chart to see which conditions are enabled and their current evaluations.
Adjust Strategy Parameters:
Modify the conditions, logical operators, and input sources as needed to optimize the strategy for different market scenarios or trading styles.
Execution:
Once the conditions are met, the strategy will automatically enter trades based on the defined logic.
Conclusion: The "Indicator Test with Conditions Table" strategy is a robust tool for traders looking to implement customized trading logic based on various market conditions. Its flexibility and real-time monitoring capabilities make it suitable for both novice and experienced traders.
GBP Index vs CAD Index Currency OscillatorGBP vs CAD Currency Oscillator
This custom oscillator compares the relative strength of GBP (British Pound) and CAD (Canadian Dollar) against a basket of other currencies to determine potential overbought and oversold conditions. The indicator is designed to help traders evaluate momentum shifts and identify possible trend reversals between these two currencies, not just the GBPCAD pair.
How it Works:
Currency Index Calculation:
The oscillator calculates the average percentage change in 7 key GBP pairs (GBPUSD, EURGBP, GBPJPY, GBPAUD, GBPNZD, GBPCAD, and GBPCHF).
Similarly, it calculates the average percentage change for 7 key CAD pairs (USDCAD, EURCAD, CADJPY, AUDCAD, NZDCAD, GBPCAD, and CADCHF).
Stochastic Oscillator:
The indicator calculates a 0-100 oscillator for both the GBP and CAD currency indices based on the highest high and lowest low over a user-defined lookback period (default is 14 anlthough 60 works great on 1m chart).
The oscillator is smoothed using a simple moving average (default smoothing period is 3) to reduce noise and improve visual clarity.
Overbought/Oversold Conditions:
Overbought: When both the GBP and CAD oscillators exceed 80, the background turns red, indicating potential overbought conditions.
Oversold: When both oscillators fall below 20, the background turns green, signaling possible oversold conditions.
Crossovers:
When the GBP oscillator crosses above the CAD oscillator, a green dot appears at the bottom of the chart, signaling potential GBP strength.
When the GBP oscillator crosses below the CAD oscillator, a red dot appears, signaling potential CAD strength.
How to Use:
Overbought/Oversold Conditions: Use the red and green background highlights to spot potential overbought or oversold market conditions, helping you identify possible turning points.
Customization Options:
Lookback Period: You can adjust the lookback period for the stochastic calculation, allowing for sensitivity tuning (default: 14).
Smoothing Period: Control the degree of smoothing applied to the oscillators (default: 3).
This oscillator is ideal for traders focused on trading GBP and CAD pairs, offering a comparative analysis that can assist in better decision-making based on relative currency strength.
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