Intrabar DistributionThe Intrabar Distribution publication is an extension of the Intrabar BoxPlot publication. Besides a boxplot, it showcases price and volume distribution using intrabar Lower Timeframe (LTF) values (close) which can be displayed on the chart or in a separate pane.
🔶 USAGE
Intrabar Distribution has several features, users can display:
Recent candle for comparison against the other features
Boxplot of recent candle
Price distribution (optionally displayed as a curve)
Volume distribution
🔹 Recent candle / Boxplot
The middle 50% intrabar close values (Interquartile range, or IQR) are shown as a box, where the upper limit is percentile 75 (p75), and the lower limit is percentile 25 (p25). The dashed lines show the addition/subtraction of 1.5*IQR. All values out of range are considered outliers. They are displayed as white dots within the IQR*1.5 range or white X's when beyond the IQR*3 range (extreme outliers).
By showing the middle 50% intrabar values through a box, we can more easily see where the intrabar activity is mainly situated.
Note in the example above an upward-directed candle with a negative volume delta, displayed as a red box and dot (see further).
As seen in the following example, compared against the recent candle (grey candle at the left), most of the intrabar activity lies just beneath the opening price.
Note that results will be more accurate when more data is available, which can be done by making the difference between the current timeframe and the intrabar timeframe large enough.
🔹 Price / Volume distribution
The price and volume distribution can be helpful for highlighting areas of interest.
Here, we can see two areas where intrabar closing prices are mainly positioned.
The following example shows three successive bars. The recent bar is displayed on the left side, together with the volume distribution. The boxplot and price distribution are displayed on the right.
You can see the difference between volume and price distribution.
At the first bar, most price activity is at the top, while most of the volume was generated at the bottom; in other words, the price got briefly in the bottom region, with high volume before it returned.
At the second bar, price and volume are relatively equally distributed, which fits for indecisiveness.
The third bar shows more volume at a higher region; most intrabar closing prices are above the closing price.
Following example shows the same with 'Curve shaped' enabled (Settings: 'Price Distribution')
When 'Curve shaped' is enabled, lines/labels are shown with the standard deviation distance.
A blue 'guide line' can be enabled for easier interpretation.
🔹 Volume Delta
When there is a discrepancy between the delta volume and direction of the candle, this will be displayed as follows:
Red candle: when the sum of the volume of green intrabars is higher than the sum of the volume of red intrabars, the 'mean dot' will be coloured green.
Green candle: when the sum of the volume of red intrabars is higher than the sum of the volume of green intrabars, the 'mean dot' will be coloured red.
🔶 DETAILS
The intrabar values are sorted and split in parts/sections. The number of values in each section is displayed as a white line
The same principle applies to volume distribution, where the sum of volume per section is displayed as an orange area.
The boxplot displays several price values
Last close price
Highest / lowest intrabar close price
Median
p25 / p75
🔹 LTF settings
When 'Auto' is enabled (Settings, LTF), the LTF will be the nearest possible x times smaller TF than the current TF. When 'Premium' is disabled, the minimum TF will always be 1 minute to ensure TradingView plans lower than Premium don't get an error.
Examples with current Daily TF (when Premium is enabled):
500 : 3 minute LTF
1500 (default): 1 minute LTF
5000: 30 seconds LTF (1 minute if Premium is disabled)
🔶 SETTINGS
Location: Chart / Pane (when pane is opted, move the indicator to a separate pane as well)
Parts: divides the intrabar close values into parts/sections
Offset: offsets every drawing at once
Width: width of drawings, only applicable on "location: chart"
Label size: size of price labels
🔹 LTF
LTF: LTF setting
Auto + multiple: Adjusts the initial set LTF
Premium: Enable when your TradingView plan is Premium or higher
🔹 Current Bar
Display toggle + color setting
Offset: offsets only the 'Current Bar' drawing
🔹 Intrabar Boxplot
Display toggle + Colors, dependable on different circumstances.
Up: Price goes up, with more bullish than bearish intrabar volume.
Up-: Price goes up, with more bearish than bullish intrabar volume.
Down: Price goes down, with more bearish than bullish intrabar volume.
Down+: Price goes down, with more bullish than bearish intrabar volume.
Offset: offsets only the 'Boxplot' drawing
🔹 Price distribution
Display toggle + Color.
Curve Shaped
Guide Lines: Display 2 blue lines
Display Price: Show price of 'x' standard deviation
Offset: offsets only the 'Price distribution' drawing
Label size: size of price labels (standard deviation)
🔹 Volume distribution
Display toggle + Color.
Offset: offsets only the 'Volume distribution' drawing
🔹 Table
Show TF: Show intrabar Timeframe.
Textcolor
Size Table: Text Size
Statistics
Intrabar BoxPlotThe Intrabar BoxPlot publication highlights an uncommon technique by displaying statistical intrabar Lower Timeframe (LTF) values on the chart.
🔶 USAGE
🔹 Middle 50% Boxes
By showing the middle 50% intrabar values through a box, we can more easily see where the intrabar activity is mainly situated.
The middle 50% intrabar values are referred to from here on as Interquartile range (IQR).
In this example, the successive IQRs form a channel where the price eventually breaks out.
Disproportionately distributed values can give insights which can be used to find potential support/resistance areas.
IQR gaps can give valuable information as well. Potentially, the price can return to these gaps.
Seeing the IQR areas against regular candles gives an alternative image of the underlying price movements.
🔹 Highest volume Price level
The script displays the price level with the highest volume situated, dependable on the user's source setting. Setting the source at 'close' will only display intrabar close values; the same goes for high, low, ...
As seen in the above example, the volume levels can aid in finding support/resistance.
🔹 Median
The location of the median off all intrabar values is displayed as a coloured dot: green when the close price is higher than the opening price and red if otherwise. The median can give valuable insights into price movements.
🔹 Outliers
Medium (white dots) and extreme (white X) outliers, in combination with the IQR box, can help identify potential areas of interest.
🔹 Volume Delta
When there is a discrepancy between the delta volume and direction of the candle, this will be displayed as follows:
Green candle: when the sum of the volume of red intrabars is higher than the sum of the volume of green intrabars, the candle will be coloured orange.
Red candle: when the sum of the volume of green intrabars is higher than the sum of the volume of red intrabars, the candle will be coloured blue.
🔹 Highlight Boxplot only
Probably the easiest way to display boxplot only is by changing the Bar's style to Bars .
🔶 DETAILS
All intrabar values (Lower TimeFrame - LTF) are sorted and evaluated. Values can be close , high , low , ... by selecting this in Settings ( source ).
The middle 50% of all values are displayed as a box; this contains the values between percentile 25 (p25) and percentile 75 (p75). The value of percentile rank 75 means 75% of all values are lower. The value of percentile rank 25 means 25% of all values are lower, or 75% is higher.
The difference between p75 and p25 is also known as Interquartile range (IQR)
IQR is used to check for outliers.
Wiki: Boxplot , Interquartile range
Extreme high: maximum value, higher than p75 + IQR*3
Max outlier high: maximum value, higher than p75 + IQR*1.5 but lower than p75 + IQR*3
Max: maximum value, lower than p75 + IQR*1.5
Min: minimum value, higher than p25 - IQR*1.5
Min outlier low: minimum value, lower than p25 - IQR*1.5 but higher than p25 - IQR*3
Extreme low: minimum value, lower than p25 - IQR*3
Max and min must not be interpreted with the current candle high/low.
🔹 Example: Length of chart-puppets
The following example can make it easier to digest. Forty "chart-puppets" are sorted by their length.
The p25 value is 97
The p50 value is 120
The p75 value is 149
75% of all "chart-puppets" are smaller than p75, and 25% is larger than p75.
50% of all "chart-puppets" are smaller than p50, and 50% is larger than p50 (= median).
25% of all "chart-puppets" are smaller than p25, and 75% is larger than p25.
IQR = 149 - 97 = 52
Extreme outlier limit max: p75 + IQR*3 = 149 + 52*3 = 305
Mild outlier limit max: p75 + IQR*1.5 = 149 + 52*1.5 = 227
Mild outlier limit min: p25 - IQR*1.5 = 97 - 52*1.5 = 19
Extreme outlier limit min: p25 - IQR*3 = 97 - 52*3 = -59
In this example there are no outliers to be found, all values are located between p25 - IQR*1.5 (19) and p75 + IQR*1.5. (227)
🔹 Source settings
Note that results are dependable on the chosen source (settings). When, for example, close is chosen as the source, only intrabar close prices are included. This means a low or high can stretch further then the min or max.
Here we can see different results with different source settings
🔹 LTF settings
When 'Auto' is enabled (Settings, LTF), the LTF will be the nearest possible x times smaller TF than the current TF. When 'Premium' is disabled, the minimum TF will always be 1 minute to ensure TradingView plans lower than Premium don't get an error.
Examples with current Daily TF (when Premium is enabled):
500 : 3 minute LTF
1500 (default): 1 minute LTF
5000: 30 seconds LTF (1 minute if Premium is disabled)
🔶 SETTINGS
Source: Set source at close, high, low,...
🔹 LTF
LTF: LTF setting
Auto + multiple: Adjusts the initial set LTF
Premium: Enable when your TradingView plan is Premium or higher
🔹 Intrabar Delta : Colors, dependable on different circumstances.
Up: Price goes up, with more bullish than bearish intrabar volume.
Up-: Price goes up, with more bearish than bullish intrabar volume.
Down: Price goes down, with more bearish than bullish intrabar volume.
Down+: Price goes down, with more bullish than bearish intrabar volume.
🔹 Table
Show table: Show details at the top right corner
Show TF: Show LTF at the bottom right corner
Text color/table size
See DETAILS for more information
Market Flow Volatility Oscillator (AiBitcoinTrend)The Market Flow Volatility Oscillator (AiBitcoinTrend) is a cutting-edge technical analysis tool designed to evaluate and classify market volatility regimes. By leveraging Gaussian filtering and clustering techniques, this indicator provides traders with clear insights into periods of high and low volatility, helping them adapt their strategies to evolving market conditions. Built for precision and clarity, it combines advanced mathematical models with intuitive visual feedback to identify trends and volatility shifts effectively.
👽 How the Indicator Works
👾 Volatility Classification with Gaussian Filtering
The indicator detects volatility levels by applying Gaussian filters to the price series. Gaussian filters smooth out noise while preserving significant price movements. Traders can adjust the smoothing levels using sigma parameters, enabling greater flexibility:
Low Sigma: Emphasizes short-term volatility.
High Sigma: Captures broader trends with reduced sensitivity to small fluctuations.
👾 Clustering Algorithm for Regime Detection
The core of this indicator is its clustering model, which classifies market conditions into two distinct regimes:
Low Volatility Regime: Calm periods with reduced market activity.
High Volatility Regime: Intense periods with heightened price movements.
The clustering process works as follows:
A rolling window of data is analyzed to calculate the standard deviation of price returns.
Two cluster centers are initialized using the 25th and 75th percentiles of the data distribution.
Each price volatility value is assigned to the nearest cluster based on its distance to the centers.
The cluster centers are refined iteratively, providing an accurate and adaptive classification.
👾 Oscillator Generation with Slope R-Values
The indicator computes Gaussian filter slopes to generate oscillators that visualize trends:
Oscillator Low: Captures low-frequency market behavior.
Oscillator High: Tracks high-frequency, faster-changing trends.
The slope is measured using the R-value of the linear regression fit, scaled and adjusted for easier interpretation.
👽 Applications
👾 Trend Trading
When the oscillator rises above 0.5, it signals potential bullish momentum, while dips below 0.5 suggest bearish sentiment.
👾 Pullback Detection
When the oscillator peaks, especially in overbought or oversold zones, provide early warnings of potential reversals.
👽 Indicator Settings
👾 Oscillator Settings
Sigma Low/High: Controls the smoothness of the oscillators.
Smaller Values: React faster to price changes but introduce more noise.
Larger Values: Provide smoother signals with longer-term insights.
👾 Window Size and Refit Interval
Window Size: Defines the rolling period for cluster and volatility calculations.
Shorter windows: adapt faster to market changes.
Longer windows: produce stable, reliable classifications.
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
True CB Premium - USDT/USD adjustedCoinbase Discount/Premium indicator with adjustment for USDT/USD price volatility.
Time Blocks Indicator with EMA Signals (UTC+2)This indicator shows the posable time's when retracement can happen during the London session
A "Time Blocks Indicator with EMA Signals" is a technical analysis tool that combines the concept of time-based price blocks with the signals generated by Exponential Moving Averages (EMAs) to identify potential trading opportunities by highlighting specific price levels within a given timeframe, where EMA crossovers or trend changes might occur, providing a more focused view on potential entry and exit points
VIX Spike StrategyThis script implements a trading strategy based on the Volatility Index (VIX) and its standard deviation. It aims to enter a long position when the VIX exceeds a certain number of standard deviations above its moving average, which is a signal of a volatility spike. The position is then exited after a set number of periods.
VIX Symbol (vix_symbol): The input allows the user to specify the symbol for the VIX index (typically "CBOE:VIX").
Standard Deviation Length (stddev_length): The number of periods used to calculate the standard deviation of the VIX. This can be adjusted by the user.
Standard Deviation Multiplier (stddev_multiple): This multiplier is used to determine how many standard deviations above the moving average the VIX must exceed to trigger a long entry.
Exit Periods (exit_periods): The user specifies how many periods after entering the position the strategy will exit the trade.
Strategy Logic:
Data Loading: The script loads the VIX data, both for the current timeframe and as a rescaled version for calculation purposes.
Standard Deviation Calculation: It calculates both the moving average (SMA) and the standard deviation of the VIX over the specified period (stddev_length).
Entry Condition: A long position is entered when the VIX exceeds the moving average by a specified multiple of its standard deviation (calculated as vix_mean + stddev_multiple * vix_stddev).
Exit Condition: After the position is entered, it will be closed after the user-defined number of periods (exit_periods).
Visualization:
The VIX is plotted in blue.
The moving average of the VIX is plotted in orange.
The threshold for the VIX, which is the moving average plus the standard deviation multiplier, is plotted in red.
The background turns green when the entry condition is met, providing a visual cue.
Sources:
The VIX is often used as a measure of market volatility, with high values indicating increased uncertainty in the market.
Standard deviation is a statistical measure of the variability or dispersion of a set of data points. In financial markets, it is used to measure the volatility of asset prices.
References:
Bollerslev, T. (1986). "Generalized Autoregressive Conditional Heteroskedasticity." Journal of Econometrics.
Black, F., & Scholes, M. (1973). "The Pricing of Options and Corporate Liabilities." Journal of Political Economy.
Brazil Real Interest RateEste script foi criado para calcular e exibir a Taxa de Juros Real, permitindo compreender o impacto da inflação sobre os juros nominais do mercado. Ele utiliza dois indicadores principais: a taxa de juros nominal, que reflete os juros antes de considerar a inflação, e a taxa de inflação anual, que mede o aumento dos preços em um ano.
O script funciona da seguinte forma: ele obtém diariamente os dados da taxa de juros nominal (representada pelo contrato futuro DI1) e da inflação anual (indicada pelo BRIRYY). Esses valores são processados para calcular a taxa de juros real, utilizando a fórmula de Fisher, que ajusta os juros nominais ao descontar o efeito da inflação. O resultado é uma medida mais precisa do retorno ou custo real, considerando o poder de compra.
Depois de realizar o cálculo, o script exibe a Taxa de Juros Real diretamente no gráfico, representada por uma linha verde. Isso permite acompanhar, de forma clara e visual, como a inflação e os juros afetam o cenário econômico ao longo do tempo.
This script was created to calculate and display the Real Interest Rate, allowing us to understand the impact of inflation on nominal market interest rates. It uses two main indicators: the nominal interest rate, which reflects interest rates before considering inflation, and the annual inflation rate, which measures the increase in prices over a year.
The script works as follows: it obtains daily data on the nominal interest rate (represented by the DI1 futures contract) and annual inflation (indicated by BRIRYY). These values are processed to calculate the real interest rate, using the Fisher formula, which adjusts nominal interest rates by discounting the effect of inflation. The result is a more accurate measure of real return or cost, considering purchasing power.
After performing the calculation, the script displays the Real Interest Rate directly on the graph, represented by a green line. This allows you to monitor, clearly and visually, how inflation and interest rates affect the economic scenario over time.
12 Month Difference - YoY ComparisonEste script foi desenvolvido para calcular e exibir a variação percentual do preço de um ativo nos últimos 12 meses, de forma simples e visual. Ele utiliza dados históricos de preços e apresenta o resultado diretamente no gráfico, permitindo ao usuário acompanhar a relação entre o valor atual e o valor de 12 meses atrás.
O cálculo é baseado em um período de 12 meses, que equivale a 252 dias úteis no mercado financeiro. O script primeiro identifica o preço atual do ativo e o compara com o preço registrado há exatamente 252 dias úteis. A diferença entre esses dois valores é transformada em uma variação percentual, o que facilita a análise de desempenho do ativo ao longo do período.
Além disso, o script define uma cor para destacar o resultado:
Verde, se a variação percentual for positiva (indicando crescimento).
Vermelho, se a variação for negativa (indicando queda).
O valor calculado é exibido de forma prática no canto inferior direito do gráfico, como uma tabela flutuante. Essa tabela contém o texto "Relação 12M" e o valor percentual correspondente, permitindo uma leitura rápida.
Embora o resultado seja calculado para todos os momentos no gráfico, ele é mostrado apenas como uma tabela no último ponto confirmado da série histórica, ou seja, no momento mais recente com dados disponíveis. Além disso, o script inclui o valor da relação na legenda do gráfico, mas ele está oculto visualmente para evitar sobrecarregar o layout.
Esse indicador é útil para analisar rapidamente o desempenho de um ativo ao longo de um ano, ajudando investidores e analistas a entenderem tendências e mudanças no mercado.
This script was developed to calculate and display the percentage change in the price of an asset over the last 12 months, in a simple and visual way. It uses historical price data and displays the result directly on the chart, allowing the user to monitor the relationship between the current value and the value from 12 months ago.
The calculation is based on a 12-month period, which is equivalent to 252 business days in the financial market. The script first identifies the current price of the asset and compares it with the price recorded exactly 252 business days ago. The difference between these two values is transformed into a percentage change, which makes it easier to analyze the asset's performance over the period.
In addition, the script defines a color to highlight the result:
Green, if the percentage change is positive (indicating growth).
Red, if the change is negative (indicating a decline).
The calculated value is displayed conveniently in the bottom right corner of the chart, as a floating table. This table contains the text "12M Ratio" and the corresponding percentage value, allowing for quick reading.
Although the result is calculated for all points in time on the chart, it is only displayed as a table at the last confirmed point in the historical series, i.e. the most recent point in time with available data. In addition, the script includes the ratio value in the chart legend, but it is visually hidden to avoid cluttering the layout.
This indicator is useful for quickly analyzing the performance of an asset over a year, helping investors and analysts understand trends and changes in the market.
Adjust Asset for Future Interest (Brazil)Este script foi criado para ajustar o preço de um ativo com base na taxa de juros DI11!, que reflete a expectativa do mercado para os juros futuros. O objetivo é mostrar como o valor do ativo seria influenciado se fosse diretamente ajustado pela variação dessa taxa de juros.
Como funciona?
Preço do Ativo
O script começa capturando o preço de fechamento do ativo que está sendo visualizado no gráfico. Esse é o ponto de partida para o cálculo.
Taxa de Juros DI11!
Em seguida, ele busca os valores diários da taxa DI11! no mercado. Esta taxa é uma referência de juros de curto prazo, usada para ajustes financeiros e projeções econômicas.
Fator de Ajuste
Com a taxa de juros DI11!, o script calcula um fator de ajuste simples:
Fator de Ajuste
=
1
+
DI11
100
Fator de Ajuste=1+
100
DI11
Esse fator traduz a taxa percentual em um multiplicador aplicado ao preço do ativo.
Cálculo do Ativo Ajustado
Multiplica o preço do ativo pelo fator de ajuste para obter o valor ajustado do ativo. Este cálculo mostra como o preço seria se fosse diretamente influenciado pela variação da taxa DI11!.
Exibição no Gráfico
O script plota o preço ajustado do ativo como uma linha azul no gráfico, com maior espessura para facilitar a visualização. O resultado é uma curva que reflete o impacto teórico da taxa de juros DI11! sobre o ativo.
Utilidade
Este indicador é útil para entender como as taxas de juros podem influenciar ativos financeiros de forma hipotética. Ele é especialmente interessante para analistas que desejam avaliar a relação entre o mercado de renda variável e as condições de juros no curto prazo.
This script was created to adjust the price of an asset based on the DI11! interest rate, which reflects the market's expectation for future interest rates. The goal is to show how the asset's value would be influenced if it were directly adjusted by the variation of this interest rate.
How does it work?
Asset Price
The script starts by capturing the closing price of the asset that is being viewed on the chart. This is the starting point for the calculation.
DI11! Interest Rate
The script then searches for the daily values of the DI11! rate in the market. This rate is a short-term interest reference, used for financial adjustments and economic projections.
Adjustment Factor
With the DI11! interest rate, the script calculates a simple adjustment factor:
Adjustment Factor
=
1
+
DI11
100
Adjustment Factor=1+
100
DI11
This factor translates the percentage rate into a multiplier applied to the asset's price.
Adjusted Asset Calculation
Multiplies the asset price by the adjustment factor to obtain the adjusted asset value. This calculation shows how the price would be if it were directly influenced by the variation of the DI11! rate.
Display on the Chart
The script plots the adjusted asset price as a blue line on the chart, with greater thickness for easier visualization. The result is a curve that reflects the theoretical impact of the DI11! interest rate on the asset.
Usefulness
This indicator is useful for understanding how interest rates can hypothetically influence financial assets. It is especially interesting for analysts who want to assess the relationship between the equity market and short-term interest rate conditions.
QTALibrary "QTA"
This is simple library for basic Quantitative Technical Analysis for retail investors. One example of it being used can be seen here ().
calculateKellyRatio(returns)
Parameters:
returns (array) : An array of floats representing the returns from bets.
Returns: The calculated Kelly Ratio, which indicates the optimal bet size based on winning and losing probabilities.
calculateAdjustedKellyFraction(kellyRatio, riskTolerance, fedStance)
Parameters:
kellyRatio (float) : The calculated Kelly Ratio.
riskTolerance (float) : A float representing the risk tolerance level.
fedStance (string) : A string indicating the Federal Reserve's stance ("dovish", "hawkish", or neutral).
Returns: The adjusted Kelly Fraction, constrained within the bounds of .
calculateStdDev(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The standard deviation of the returns, or 0 if insufficient data.
calculateMaxDrawdown(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The maximum drawdown as a percentage.
calculateEV(avgWinReturn, winProb, avgLossReturn)
Parameters:
avgWinReturn (float) : The average return from winning bets.
winProb (float) : The probability of winning a bet.
avgLossReturn (float) : The average return from losing bets.
Returns: The calculated Expected Value of the bet.
calculateTailRatio(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The Tail Ratio, or na if the 5th percentile is zero to avoid division by zero.
calculateSharpeRatio(avgReturn, riskFreeRate, stdDev)
Parameters:
avgReturn (float) : The average return of the investment.
riskFreeRate (float) : The risk-free rate of return.
stdDev (float) : The standard deviation of the investment's returns.
Returns: The calculated Sharpe Ratio, or na if standard deviation is zero.
calculateDownsideDeviation(returns)
Parameters:
returns (array) : An array of floats representing the returns.
Returns: The standard deviation of the downside returns, or 0 if no downside returns exist.
calculateSortinoRatio(avgReturn, downsideDeviation)
Parameters:
avgReturn (float) : The average return of the investment.
downsideDeviation (float) : The standard deviation of the downside returns.
Returns: The calculated Sortino Ratio, or na if downside deviation is zero.
calculateVaR(returns, confidenceLevel)
Parameters:
returns (array) : An array of floats representing the returns.
confidenceLevel (float) : A float representing the confidence level (e.g., 0.95 for 95% confidence).
Returns: The Value at Risk at the specified confidence level.
calculateCVaR(returns, varValue)
Parameters:
returns (array) : An array of floats representing the returns.
varValue (float) : The Value at Risk threshold.
Returns: The average Conditional Value at Risk, or na if no returns are below the threshold.
calculateExpectedPriceRange(currentPrice, ev, stdDev, confidenceLevel)
Parameters:
currentPrice (float) : The current price of the asset.
ev (float) : The expected value (in percentage terms).
stdDev (float) : The standard deviation (in percentage terms).
confidenceLevel (float) : The confidence level for the price range (e.g., 1.96 for 95% confidence).
Returns: A tuple containing the minimum and maximum expected prices.
calculateRollingStdDev(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling standard deviation of returns.
calculateRollingVariance(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling variance of returns.
calculateRollingMean(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling mean of returns.
calculateRollingCoefficientOfVariation(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling coefficient of variation of returns.
calculateRollingSumOfPercentReturns(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling sum of percent returns.
calculateRollingCumulativeProduct(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling cumulative product of returns.
calculateRollingCorrelation(priceReturns, volumeReturns, window)
Parameters:
priceReturns (array) : An array of floats representing the price returns.
volumeReturns (array) : An array of floats representing the volume returns.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling correlation.
calculateRollingPercentile(returns, window, percentile)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
percentile (int) : An integer representing the desired percentile (0-100).
Returns: An array of floats representing the rolling percentile of returns.
calculateRollingMaxMinPercentReturns(returns, window)
Parameters:
returns (array) : An array of floats representing the returns.
window (int) : An integer representing the rolling window size.
Returns: A tuple containing two arrays: rolling max and rolling min percent returns.
calculateRollingPriceToVolumeRatio(price, volData, window)
Parameters:
price (array) : An array of floats representing the price data.
volData (array) : An array of floats representing the volume data.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the rolling price-to-volume ratio.
determineMarketRegime(priceChanges)
Parameters:
priceChanges (array) : An array of floats representing the price changes.
Returns: A string indicating the market regime ("Bull", "Bear", or "Neutral").
determineVolatilityRegime(price, window)
Parameters:
price (array) : An array of floats representing the price data.
window (int) : An integer representing the rolling window size.
Returns: An array of floats representing the calculated volatility.
classifyVolatilityRegime(volatility)
Parameters:
volatility (array) : An array of floats representing the calculated volatility.
Returns: A string indicating the volatility regime ("Low" or "High").
method percentPositive(thisArray)
Returns the percentage of positive non-na values in this array.
This method calculates the percentage of positive values in the provided array, ignoring NA values.
Namespace types: array
Parameters:
thisArray (array)
_candleRange()
_PreviousCandleRange(barsback)
Parameters:
barsback (int) : An integer representing how far back you want to get a range
redCandle()
greenCandle()
_WhiteBody()
_BlackBody()
HighOpenDiff()
OpenLowDiff()
_isCloseAbovePreviousOpen(length)
Parameters:
length (int)
_isCloseBelowPrevious()
_isOpenGreaterThanPrevious()
_isOpenLessThanPrevious()
BodyHigh()
BodyLow()
_candleBody()
_BodyAvg(length)
_BodyAvg function.
Parameters:
length (simple int) : Required (recommended is 6).
_SmallBody(length)
Parameters:
length (simple int) : Length of the slow EMA
Returns: a series of bools, after checking if the candle body was less than body average.
_LongBody(length)
Parameters:
length (simple int)
bearWick()
bearWick() function.
Returns: a SERIES of FLOATS, checks if it's a blackBody(open > close), if it is, than check the difference between the high and open, else checks the difference between high and close.
bullWick()
barlength()
sumbarlength()
sumbull()
sumbear()
bull_vol()
bear_vol()
volumeFightMA()
volumeFightDelta()
weightedAVG_BullVolume()
weightedAVG_BearVolume()
VolumeFightDiff()
VolumeFightFlatFilter()
avg_bull_vol(userMA)
avg_bull_vol(int) function.
Parameters:
userMA (int)
avg_bear_vol(userMA)
avg_bear_vol(int) function.
Parameters:
userMA (int)
diff_vol(userMA)
diff_vol(int) function.
Parameters:
userMA (int)
vol_flat(userMA)
vol_flat(int) function.
Parameters:
userMA (int)
_isEngulfingBullish()
_isEngulfingBearish()
dojiup()
dojidown()
EveningStar()
MorningStar()
ShootingStar()
Hammer()
InvertedHammer()
BearishHarami()
BullishHarami()
BullishBelt()
BullishKicker()
BearishKicker()
HangingMan()
DarkCloudCover()
Enhanced Effort vs Result Analysis V.2How to Use in Trading
A. Confirm Breakouts
Check if the Effort-Result Ratio or Z-Score spikes above the Upper Band or Z > +2:
Suggests a strong, efficient price move.
Supports breakout continuation.
B. Identify Reversal or Exhaustion
Look for Effort-Result Ratio or Z-Score dropping below the Lower Band or Z < -2:
Indicates high effort but low price movement (inefficiency).
Often signals potential trend reversal or consolidation.
C. Assess Efficiency of Trends
Use Relative Efficiency Index (REI):
REI near 1 during a trend → Confirms strength (efficient movement).
REI near 0 → Weak or inefficient movement, likely signaling exhaustion.
D. Evaluate Volume-Price Relationship
Monitor the Volume-Price Correlation:
Positive correlation (+1): Confirms price is driven by volume.
Negative correlation (-1): Indicates divergence; price moves independently of volume (potential warning signal).
3. Example Scenarios
Scenario 1: Breakout Confirmation
Effort-Result Ratio spikes above the Upper Band.
Z-Score exceeds +2.
REI approaches 1.
Volume-Price Correlation is positive (near +1).
Action: Strong breakout confirmation → Trend continuation likely.
Scenario 2: Reversal or Exhaustion
Effort-Result Ratio drops below the Lower Band.
Z-Score is below -2.
REI approaches 0.
Volume-Price Correlation weakens or turns negative.
Action: Signals trend exhaustion → Watch for reversal or consolidation.
Scenario 3: Range-Bound Market
Effort-Result Ratio stays within the Bollinger Bands.
Z-Score remains between -1 and +1.
REI fluctuates around 0.5 (neutral efficiency).
Volume-Price Correlation hovers near 0.
Action: Normal conditions → Look for breakout signals before acting.
*IMPORTANT*
There is a problem with the overlay ... How to fix some of it
The Standard Deviation bands dont work while the other variable activated so Id suggest deselecting them. The fix for this is to make sure you have the background selected and by doing this it will highlight on the chart ( you may need to increase the opacity ) when the bands ( Second standard deviation) are touched.
- Also you can use them all at once if you can but you do not need to
Future Interest Indexed by AssetEste script em Pine Script calcula e exibe o índice dos juros futuros (DI1) em relação ao preço de um ativo, utilizando o preço de fechamento do ativo e a taxa de juros futuros (DI1). O cálculo é realizado dividindo a taxa de juros pelos preços do ativo, resultando no índice indice_juros. Para evitar a divisão por zero, o script verifica se o preço do ativo é válido e não nulo. O índice calculado é então plotado em um painel inferior no gráfico, representado por uma linha azul, permitindo aos usuários observar a relação entre a taxa de juros futuros e o preço do ativo de forma clara e intuitiva.
This Pine Script script calculates and displays the future interest rate (DI1) in relation to the price of an asset, using the asset's closing price and the future interest rate (DI1). The calculation is carried out by dividing the interest rate by the asset prices, resulting in the index_interest index. To avoid division by zero, the script checks that the asset's price is valid and not null. The calculated index is then plotted in a lower panel on the chart, represented by a blue line, allowing users to observe the relationship between the future interest rate and the asset price clearly and intuitively.
Asset Indexed by Future Interest
Este script em Pine Script calcula e exibe o índice de um ativo em relação à taxa de juros futuros (DI1) em um painel inferior. Ele obtém o preço de fechamento do ativo e a taxa de juros futuros DI1!, e em seguida, calcula o índice do ativo dividindo o preço do ativo pela taxa de juros futuros. Para evitar a divisão por zero, o script realiza uma validação para garantir que o valor da taxa de juros não seja nulo ou zero. O índice calculado é então plotado no painel inferior, em uma linha verde, permitindo que os usuários visualizem a relação entre o preço do ativo e os juros futuros de curto prazo. Esse índice pode ser útil para analisar como a taxa de juros influencia o comportamento do ativo.
This script in Pine Script calculates and displays the ratio of an asset to the future interest rate (DI1) in a lower panel. It obtains the asset's closing price and the future interest rate DI1!, and then calculates the asset index by dividing the asset price by the future interest rate. To avoid division by zero, the script performs validation to ensure that the interest rate value is not null or zero. The calculated index is then plotted in the bottom panel, in a green line, allowing users to visualize the relationship between the asset's price and short-term future interest. This index can be useful for analyzing how the interest rate influences the asset's behavior.
Brazil Real Interest RateEste script foi criado para calcular e exibir a Taxa de Juros Real, permitindo compreender o impacto da inflação sobre os juros nominais do mercado. Ele utiliza dois indicadores principais: a taxa de juros nominal, que reflete os juros antes de considerar a inflação, e a taxa de inflação anual, que mede o aumento dos preços em um ano.
O script funciona da seguinte forma: ele obtém diariamente os dados da taxa de juros nominal (representada pelo contrato futuro DI1) e da inflação anual (indicada pelo BRIRYY). Esses valores são processados para calcular a taxa de juros real, utilizando a fórmula de Fisher, que ajusta os juros nominais ao descontar o efeito da inflação. O resultado é uma medida mais precisa do retorno ou custo real, considerando o poder de compra.
Depois de realizar o cálculo, o script exibe a Taxa de Juros Real diretamente no gráfico, representada por uma linha verde. Isso permite acompanhar, de forma clara e visual, como a inflação e os juros afetam o cenário econômico ao longo do tempo.
This script was created to calculate and display the Real Interest Rate, allowing us to understand the impact of inflation on nominal market interest rates. It uses two main indicators: the nominal interest rate, which reflects interest rates before considering inflation, and the annual inflation rate, which measures the increase in prices over a year.
The script works as follows: it obtains daily data on the nominal interest rate (represented by the DI1 futures contract) and annual inflation (indicated by BRIRYY). These values are processed to calculate the real interest rate, using the Fisher formula, which adjusts nominal interest rates by discounting the effect of inflation. The result is a more accurate measure of real return or cost, considering purchasing power.
After performing the calculation, the script displays the Real Interest Rate directly on the graph, represented by a green line. This allows you to monitor, clearly and visually, how inflation and interest rates affect the economic scenario over time.
lib_divergenceLibrary "lib_divergence"
offers a commonly usable function to detect divergences. This will take the default RSI or other symbols / indicators / oscillators as source data.
divergence(osc, pivot_left_bars, pivot_right_bars, div_min_range, div_max_range, ref_low, ref_high, min_divergence_offset_fraction, min_divergence_offset_dev_len, min_divergence_offset_atr_mul)
Detects Divergences between Price and Oscillator action. For bullish divergences, look at trend lines between lows. For bearish divergences, look at trend lines between highs. (strong) oscillator trending, price opposing it | (medium) oscillator trending, price trend flat | (weak) price opposite trending, oscillator trend flat | (hidden) price trending, oscillator opposing it. Pivot detection is only properly done in oscillator data, reference price data is only compared at the oscillator pivot (speed optimization)
Parameters:
osc (float) : (series float) oscillator data (can be anything, even another instrument price)
pivot_left_bars (simple int) : (simple int) optional number of bars left of a confirmed pivot point, confirming it is the highest/lowest in the range before and up to the pivot (default: 5)
pivot_right_bars (simple int) : (simple int) optional number of bars right of a confirmed pivot point, confirming it is the highest/lowest in the range from and after the pivot (default: 5)
div_min_range (simple int) : (simple int) optional minimum distance to the pivot point creating a divergence (default: 5)
div_max_range (simple int) : (simple int) optional maximum amount of bars in a divergence (default: 50)
ref_low (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: low)
ref_high (float) : (series float) optional reference range to compare the oscillator pivot points to. (default: high)
min_divergence_offset_fraction (simple float) : (simple float) optional scaling factor for the offset zone (xDeviation) around the last oscillator H/L detecting following equal H/Ls (default: 0.01)
min_divergence_offset_dev_len (simple int) : (simple int) optional lookback distance for the deviation detection for the offset zone around the last oscillator H/L detecting following equal H/Ls. Used as well for the ATR that does the equal H/L detection for the reference price. (default: 14)
min_divergence_offset_atr_mul (simple float) : (simple float) optional scaling factor for the offset zone (xATR) around the last price H/L detecting following equal H/Ls (default: 1)
@return A tuple of deviation flags.
Effort vs Result with Std DevSummary Table:
Condition Effort-Result Ratio Interpretation
High Volume, Big Price Move Above +2 SD Strong move, efficient effort.
High Volume, Small Price Move Below Mean / -2 SD Weak move, possible exhaustion.
Low Volume, Big Price Move Above Mean / +2 SD Efficient effort, momentum strong.
Low Volume, Small Price Move Near Mean Market indecision, low activity.
Watermark with dynamic variables [BM]█ OVERVIEW
This indicator allows users to add highly customizable watermark messages to their charts. Perfect for branding, annotation, or displaying dynamic chart information, this script offers advanced customization options including dynamic variables, text formatting, and flexible positioning.
█ CONCEPTS
Watermarks are overlay messages on charts. This script introduces placeholders — special keywords wrapped in % signs — that dynamically replace themselves with chart-related data. These watermarks can enhance charts with context, timestamps, or branding.
█ FEATURES
Dynamic Variables : Replace placeholders with real-time data such as bar index, timestamps, and more.
Advanced Customization : Modify text size, color, background, and alignment.
Multiple Messages : Add up to four independent messages per group, with two groups supported (A and B).
Positioning Options : Place watermarks anywhere on the chart using predefined locations.
Timezone Support : Display timestamps in a preferred timezone with customizable formats.
█ INPUTS
The script offers comprehensive input options for customization. Each Watermark (A and B) contains identical inputs for configuration.
Watermark settings are divided into two levels:
Watermark-Level Settings
These settings apply to the entire watermark group (A/B):
Show Watermark: Toggle the visibility of the watermark group on the chart.
Position: Choose where the watermark group is displayed on the chart.
Reverse Line Order: Enable to reverse the order of the lines displayed in Watermark A.
Message-Level Settings
Each watermark contains up to four configurable messages. These messages can be independently customized with the following options:
Message Content: Enter the custom text to be displayed. You can include placeholders for dynamic data.
Text Size: Select from predefined sizes (Tiny, Small, Normal, Large, Huge) or specify a custom size.
Text Alignment and Colors:
- Adjust the alignment of the text (Left, Center, Right).
- Set text and background colors for better visibility.
Format Time: Enable time formatting for this watermark message and configure the format and timezone. The settings for each message include message content, text size, alignment, and more. Please refer to Formatting dates and times for more details on valid formatting tokens.
█ PLACEHOLDERS
Placeholders are special keywords surrounded by % signs, which the script dynamically replaces with specific chart-related data. These placeholders allow users to insert dynamic content, such as bar information or timestamps, into watermark messages.
Below is the complete list of currently available placeholders:
bar_index , barstate.isconfirmed , barstate.isfirst , barstate.ishistory , barstate.islast , barstate.islastconfirmedhistory , barstate.isnew , barstate.isrealtime , chart.is_heikinashi , chart.is_kagi , chart.is_linebreak , chart.is_pnf , chart.is_range , chart.is_renko , chart.is_standard , chart.left_visible_bar_time , chart.right_visible_bar_time , close , dayofmonth , dayofweek , dividends.future_amount , dividends.future_ex_date , dividends.future_pay_date , earnings.future_eps , earnings.future_period_end_time , earnings.future_revenue , earnings.future_time , high , hl2 , hlc3 , hlcc4 , hour , last_bar_index , last_bar_time , low , minute , month , ohlc4 , open , second , session.isfirstbar , session.isfirstbar_regular , session.islastbar , session.islastbar_regular , session.ismarket , session.ispostmarket , session.ispremarket , syminfo.basecurrency , syminfo.country , syminfo.currency , syminfo.description , syminfo.employees , syminfo.expiration_date , syminfo.industry , syminfo.main_tickerid , syminfo.mincontract , syminfo.minmove , syminfo.mintick , syminfo.pointvalue , syminfo.prefix , syminfo.pricescale , syminfo.recommendations_buy , syminfo.recommendations_buy_strong , syminfo.recommendations_date , syminfo.recommendations_hold , syminfo.recommendations_sell , syminfo.recommendations_sell_strong , syminfo.recommendations_total , syminfo.root , syminfo.sector , syminfo.session , syminfo.shareholders , syminfo.shares_outstanding_float , syminfo.shares_outstanding_total , syminfo.target_price_average , syminfo.target_price_date , syminfo.target_price_estimates , syminfo.target_price_high , syminfo.target_price_low , syminfo.target_price_median , syminfo.ticker , syminfo.tickerid , syminfo.timezone , syminfo.type , syminfo.volumetype , ta.accdist , ta.iii , ta.nvi , ta.obv , ta.pvi , ta.pvt , ta.tr , ta.vwap , ta.wad , ta.wvad , time , time_close , time_tradingday , timeframe.isdaily , timeframe.isdwm , timeframe.isintraday , timeframe.isminutes , timeframe.ismonthly , timeframe.isseconds , timeframe.isticks , timeframe.isweekly , timeframe.main_period , timeframe.multiplier , timeframe.period , timenow , volume , weekofyear , year
█ HOW TO USE
1 — Add the Script:
Apply "Watermark with dynamic variables " to your chart from the TradingView platform.
2 — Configure Inputs:
Open the script settings by clicking the gear icon next to the script's name.
Customize visibility, message content, and appearance for Watermark A and Watermark B.
3 — Utilize Placeholders:
Add placeholders like %bar_index% or %timenow% in the "Watermark - Message" fields to display dynamic data.
Empty lines in the message box are reflected on the chart, allowing you to shift text up or down.
Using in the message box translates to a new line on the chart.
4 — Preview Changes:
Adjust settings and view updates in real-time on your chart.
█ EXAMPLES
Branding
DodgyDD's charts
Debugging
█ LIMITATIONS
Only supports variables defined within the script.
Limited to four messages per watermark.
Visual alignment may vary across different chart resolutions or zoom levels.
Placeholder parsing relies on correct input formatting.
█ NOTES
This script is designed for users seeking enhanced chart annotation capabilities. It provides tools for dynamic, customizable watermarks but is not a replacement for chart objects like text labels or drawings. Please ensure placeholders are properly formatted for correct parsing.
Additionally, this script can be a valuable tool for Pine Script developers during debugging . By utilizing dynamic placeholders, developers can display real-time values of variables and chart data directly on their charts, enabling easier troubleshooting and code validation.
Up and Downwhat is "Up and Down"?
It is an indicator designed to show you in detail on the chart and warn you when there is an increase or decrease in the market at a level that you consider important.
what it does?
When the price difference between a top and bottom is greater than the level you selected (the default input is 10 percent), it indicates this along with the percentage value on the chart. Then, it indicates the start and end points with lines so that you can see the change from where to where. It shows the price's current percentage distance from the last bottom or top in the upper right corner.
it also colors the candles so you can better understand how fast the price is moving. The greener the candles, the stronger the rise, and conversely, the greater the decline, the redder the candles. Of course, if you set an alarm, it will tell you in which trading pair, in which time period, at what percentage and in which direction there is a movement.
how it does it?
It uses a moving average with a short length to find bottoms and tops. It then measures the distance from the last peak to the bottom and expresses it as a percentage. It uses momentum using the moving average as a source to paint the candles. To compress this momentum between the values 255 and 0, I used a formula that I also used in my limited fisher transform work (because the inputs in the color.rgb function take values between 0 and 255). It was a bit challenging to use the lines correctly, but with the "ta.valuewhen" function and a little experimenting, they were I made sure they were drawn correctly.
how to use it?
It is quite simple to use. First, select the minimum interval you want to receive alarms. If you make this value too high, you will not receive any alarms; if you make it too low, you will receive too many alarms. Choose the range that will benefit you most for the trading pair you are using. Then all you have to do is set an alarm. When you set an alarm, leave the note section blank and the indicator will send you the necessary information.
Mastering ATR for Smart Stop Loss and Take Profit PlacementUsing the ATR indicator to set Stop Loss and Take Profit levels provides a dynamic and flexible way to manage risk based on the volatility of the market. This method ensures that your SL and TP are always in tune with current market conditions, preventing unnecessary stop-outs while maximizing the potential for profit. The table in the script makes it easy to view your calculated levels directly on the chart, improving your trading efficiency.
If you're looking for a more automated way to manage your trades, integrating ATR-based SL and TP can be a powerful tool in your strategy.
Happy Trading!
Crypto Market Cap Momentum Analyzer (AiBitcoinTrend)The Crypto Market Cap Momentum Analyzer (AiBitcoinTrend) is a robust tool designed to uncover trading opportunities by blending market cap analysis and momentum dynamics. Inspired by research-backed quantitative strategies, this indicator helps traders identify trend-following and mean-reversion setups in the cryptocurrency market by evaluating recent performance and market cap size.
This indicator classifies cryptocurrencies into market cap quintiles and ranks them based on their 2-week momentum. It then suggests potential trades—whether to go long, anticipate reversals, or simply hold—based on the crypto's market cap group and momentum trends.
👽 How the Indicator Works
👾 Market Cap Classification
The indicator categorizes cryptocurrencies into one of five market cap groups based on user-defined inputs:
Large Cap: Highest market cap tier
Upper Mid Cap: Second highest group
Mid Cap: Middle-tier market caps
Lower Mid Cap: Slightly below the mid-tier
Small Cap: Lowest market cap tier
This classification dynamically adjusts based on the provided market cap data, ensuring that you’re always working with a representative market structure.
👾 Momentum Calculation
By default, the indicator uses a 2-week momentum measure (e.g., a 14-day lookback when set to daily). It compares a cryptocurrency’s current price to its price 14 bars ago, thereby quantifying its short-term performance. Users can adjust the momentum period and rebalance period to capture shorter or longer-term trends depending on their trading style.
👾 Dynamic Ranking and Trade Suggestions
After assigning cryptos to size quintiles, the indicator sorts them by their momentum within each quintile. This two-step process results in:
Long Trade: For smaller market cap groups (Small, Lower Mid, Mid Cap) that have low (bottom-quintile) momentum, anticipating a trend continuation or breakout.
Reversal Trade: For the largest market cap group (Large Cap) that shows low momentum, expecting a mean-reversion back to equilibrium.
Hold: In scenarios where the coin’s momentum doesn’t present a strong contrarian or trend-following signal.
👽 Applications
👾 Trend-Following in Smaller Caps: Identify small or mid-cap cryptos with low momentum that might be poised for a breakout or sustained trend.
👾 Mean-Reversion in Large Caps: Pinpoint large-cap cryptocurrencies experiencing a temporary lull in performance, potentially ripe for a rebound.
👽 Why It Works in Crypto
The cryptocurrency market is heavily driven by retail investor sentiment and volatility. Research shows that:
Small-Cap Cryptos: Tend to experience higher volatility and speculative trends, making them ideal for momentum trades.
Large-Cap Cryptos: Exhibit more predictable behavior, making them suitable for mean-reversion strategies when momentum is low.
This indicator captures these dynamics to give traders a strategic edge in identifying both momentum and reversal opportunities.
👽 Indicator Settings
👾 Rebalance Period: The frequency at which momentum and trade suggestions are recalculated (Daily, Weekly, Monthly).
Shorter Periods (Daily): Fast updates, suitable for short-term trades, but more noise.
Longer Periods (Weekly/Monthly): Smoother signals, ideal for swing trading and more stable trends.
👾 Momentum Period: The lookback period for momentum calculation (default is 14 bars).
Shorter Periods: More responsive but prone to noise.
Longer Periods : Reflects broader trends, reducing sensitivity to short-term fluctuations.
Disclaimer: This information is for entertainment purposes only and does not constitute financial advice. Please consult with a qualified financial advisor before making any investment decisions.
CandleCandle: A Comprehensive Pine Script™ Library for Candlestick Analysis
Overview
The Candle library, developed in Pine Script™, provides traders and developers with a robust toolkit for analyzing candlestick data. By offering easy access to fundamental candlestick components like open, high, low, and close prices, along with advanced derived metrics such as body-to-wick ratios, percentage calculations, and volatility analysis, this library enables detailed insights into market behavior.
This library is ideal for creating custom indicators, trading strategies, and backtesting frameworks, making it a powerful resource for any Pine Script™ developer.
Key Features
1. Core Candlestick Data
• Open : Access the opening price of the current candle.
• High : Retrieve the highest price.
• Low : Retrieve the lowest price.
• Close : Access the closing price.
2. Candle Metrics
• Full Size : Calculates the total range of the candle (high - low).
• Body Size : Computes the size of the candle’s body (open - close).
• Wick Size : Provides the combined size of the upper and lower wicks.
3. Wick and Body Ratios
• Upper Wick Size and Lower Wick Size .
• Body-to-Wick Ratio and Wick-to-Body Ratio .
4. Percentage Calculations
• Upper Wick Percentage : The proportion of the upper wick size relative to the full candle size.
• Lower Wick Percentage : The proportion of the lower wick size relative to the full candle size.
• Body Percentage and Wick Percentage relative to the candle’s range.
5. Candle Direction Analysis
• Determines if a candle is "Bullish" or "Bearish" based on its closing and opening prices.
6. Price Metrics
• Average Price : The mean of the open, high, low, and close prices.
• Midpoint Price : The midpoint between the high and low prices.
7. Volatility Measurement
• Calculates the standard deviation of the OHLC prices, providing a volatility metric for the current candle.
Code Architecture
Example Functionality
The library employs a modular structure, exporting various functions that can be used independently or in combination. For instance:
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © DevArjun
//@version=6
indicator("Candle Data", overlay = true)
import DevArjun/Candle/1 as Candle
// Body Size %
bodySize = Candle.BodySize()
// Determining the candle direction
candleDirection = Candle.CandleDirection()
// Calculating the volatility of the current candle
volatility = Candle.Volatility()
// Plotting the metrics (for demonstration)
plot(bodySize, title="Body Size", color=color.blue)
label.new(bar_index, high, candleDirection, style=label.style_circle)
Scalability
The modularity of the Candle library allows seamless integration into more extensive trading systems. Functions can be mixed and matched to suit specific analytical or strategic needs.
Use Cases
Trading Strategies
Developers can use the library to create strategies based on candle properties such as:
• Identifying long-bodied candles (momentum signals).
• Detecting wicks as potential reversal zones.
• Filtering trades based on candle ratios.
Visualization
Plotting components like body size, wick size, and directional labels helps visualize market behavior and identify patterns.
Backtesting
By incorporating volatility and ratio metrics, traders can design and test strategies on historical data, ensuring robust performance before live trading.
Education
This library is a great tool for teaching candlestick analysis and how each component contributes to market behavior.
Portfolio Highlights
Project Objective
To create a Pine Script™ library that simplifies candlestick analysis by providing comprehensive metrics and insights, empowering traders and developers with advanced tools for market analysis.
Development Challenges and Solutions
• Challenge : Achieving high precision in calculating ratios and percentages.
• Solution : Implemented robust mathematical operations and safeguarded against division-by-zero errors.
• Challenge : Ensuring modularity and scalability.
• Solution : Designed functions as independent modules, allowing flexible integration.
Impact
• Efficiency : The library reduces the time required to calculate complex candlestick metrics.
• Versatility : Supports various trading styles, from scalping to swing trading.
• Clarity : Clean code and detailed documentation ensure usability for developers of all levels.
Conclusion
The Candle library exemplifies the power of Pine Script™ in simplifying and enhancing candlestick analysis. By including this project in your portfolio, you showcase your expertise in:
• Financial data analysis.
• Pine Script™ development.
• Creating tools that solve real-world trading challenges.
This project demonstrates both technical proficiency and a keen understanding of market analysis, making it an excellent addition to your professional portfolio.
Library "Candle"
A comprehensive library to access and analyze the basic components of a candlestick, including open, high, low, close prices, and various derived metrics such as full size, body size, wick sizes, ratios, percentages, and additional analysis metrics.
Open()
Open
@description Returns the opening price of the current candle.
Returns: float - The opening price of the current candle.
High()
High
@description Returns the highest price of the current candle.
Returns: float - The highest price of the current candle.
Low()
Low
@description Returns the lowest price of the current candle.
Returns: float - The lowest price of the current candle.
Close()
Close
@description Returns the closing price of the current candle.
Returns: float - The closing price of the current candle.
FullSize()
FullSize
@description Returns the full size (range) of the current candle (high - low).
Returns: float - The full size of the current candle.
BodySize()
BodySize
@description Returns the body size of the current candle (open - close).
Returns: float - The body size of the current candle.
WickSize()
WickSize
@description Returns the size of the wicks of the current candle (full size - body size).
Returns: float - The size of the wicks of the current candle.
UpperWickSize()
UpperWickSize
@description Returns the size of the upper wick of the current candle.
Returns: float - The size of the upper wick of the current candle.
LowerWickSize()
LowerWickSize
@description Returns the size of the lower wick of the current candle.
Returns: float - The size of the lower wick of the current candle.
BodyToWickRatio()
BodyToWickRatio
@description Returns the ratio of the body size to the wick size of the current candle.
Returns: float - The body to wick ratio of the current candle.
UpperWickPercentage()
UpperWickPercentage
@description Returns the percentage of the upper wick size relative to the full size of the current candle.
Returns: float - The percentage of the upper wick size relative to the full size of the current candle.
LowerWickPercentage()
LowerWickPercentage
@description Returns the percentage of the lower wick size relative to the full size of the current candle.
Returns: float - The percentage of the lower wick size relative to the full size of the current candle.
WickToBodyRatio()
WickToBodyRatio
@description Returns the ratio of the wick size to the body size of the current candle.
Returns: float - The wick to body ratio of the current candle.
BodyPercentage()
BodyPercentage
@description Returns the percentage of the body size relative to the full size of the current candle.
Returns: float - The percentage of the body size relative to the full size of the current candle.
WickPercentage()
WickPercentage
@description Returns the percentage of the wick size relative to the full size of the current candle.
Returns: float - The percentage of the wick size relative to the full size of the current candle.
CandleDirection()
CandleDirection
@description Returns the direction of the current candle.
Returns: string - "Bullish" if the candle is bullish, "Bearish" if the candle is bearish.
AveragePrice()
AveragePrice
@description Returns the average price of the current candle (mean of open, high, low, and close).
Returns: float - The average price of the current candle.
MidpointPrice()
MidpointPrice
@description Returns the midpoint price of the current candle (mean of high and low).
Returns: float - The midpoint price of the current candle.
Volatility()
Volatility
@description Returns the standard deviation of the OHLC prices of the current candle.
Returns: float - The volatility of the current candle.
Median Deviation Suite [InvestorUnknown]The Median Deviation Suite uses a median-based baseline derived from a Double Exponential Moving Average (DEMA) and layers multiple deviation measures around it. By comparing price to these deviation-based ranges, it attempts to identify trends and potential turning points in the market. The indicator also incorporates several deviation types—Average Absolute Deviation (AAD), Median Absolute Deviation (MAD), Standard Deviation (STDEV), and Average True Range (ATR)—allowing traders to visualize different forms of volatility and dispersion. Users should calibrate the settings to suit their specific trading approach, as the default values are not optimized.
Core Components
Median of a DEMA:
The foundation of the indicator is a Median applied to the 7-day DEMA (Double Exponential Moving Average). DEMA aims to reduce lag compared to simple or exponential moving averages. By then taking a median over median_len periods of the DEMA values, the indicator creates a robust and stable central tendency line.
float dema = ta.dema(src, 7)
float median = ta.median(dema, median_len)
Multiple Deviation Measures:
Around this median, the indicator calculates several measures of dispersion:
ATR (Average True Range): A popular volatility measure.
STDEV (Standard Deviation): Measures the spread of price data from its mean.
MAD (Median Absolute Deviation): A robust measure of variability less influenced by outliers.
AAD (Average Absolute Deviation): Similar to MAD, but uses the mean absolute deviation instead of median.
Average of Deviations (avg_dev): The average of the above four measures (ATR, STDEV, MAD, AAD), providing a combined sense of volatility.
Each measure is multiplied by a user-defined multiplier (dev_mul) to scale the width of the bands.
aad = f_aad(src, dev_len, median) * dev_mul
mad = f_mad(src, dev_len, median) * dev_mul
stdev = ta.stdev(src, dev_len) * dev_mul
atr = ta.atr(dev_len) * dev_mul
avg_dev = math.avg(aad, mad, stdev, atr)
Deviation-Based Bands:
The indicator creates multiple upper and lower lines based on each deviation type. For example, using MAD:
float mad_p = median + mad // already multiplied by dev_mul
float mad_m = median - mad
Similar calculations are done for AAD, STDEV, ATR, and the average of these deviations. The indicator then determines the overall upper and lower boundaries by combining these lines:
float upper = f_max4(aad_p, mad_p, stdev_p, atr_p)
float lower = f_min4(aad_m, mad_m, stdev_m, atr_m)
float upper2 = f_min4(aad_p, mad_p, stdev_p, atr_p)
float lower2 = f_max4(aad_m, mad_m, stdev_m, atr_m)
This creates a layered structure of volatility envelopes. Traders can observe which layers price interacts with to gauge trend strength.
Determining Trend
The indicator generates trend signals by assessing where price stands relative to these deviation-based lines. It assigns a trend score by summing individual signals from each deviation measure. For instance, if price crosses above the MAD-based upper line, it contributes a bullish point; crossing below an ATR-based lower line contributes a bearish point.
When the aggregated trend score crosses above zero, it suggests a shift towards a bullish environment; crossing below zero indicates a bearish bias.
// Define Trend scores
var int aad_t = 0
if ta.crossover(src, aad_p)
aad_t := 1
if ta.crossunder(src, aad_m)
aad_t := -1
var int mad_t = 0
if ta.crossover(src, mad_p)
mad_t := 1
if ta.crossunder(src, mad_m)
mad_t := -1
var int stdev_t = 0
if ta.crossover(src, stdev_p)
stdev_t := 1
if ta.crossunder(src, stdev_m)
stdev_t := -1
var int atr_t = 0
if ta.crossover(src, atr_p)
atr_t := 1
if ta.crossunder(src, atr_m)
atr_t := -1
var int adev_t = 0
if ta.crossover(src, adev_p)
adev_t := 1
if ta.crossunder(src, adev_m)
adev_t := -1
int upper_t = src > upper ? 3 : 0
int lower_t = src < lower ? 0 : -3
int upper2_t = src > upper2 ? 1 : 0
int lower2_t = src < lower2 ? 0 : -1
float trend = aad_t + mad_t + stdev_t + atr_t + adev_t + upper_t + lower_t + upper2_t + lower2_t
var float sig = 0
if ta.crossover(trend, 0)
sig := 1
else if ta.crossunder(trend, 0)
sig := -1
Practical Usage and Calibration
Default settings are not optimized: The given parameters serve as a starting point for demonstration. Users should adjust:
median_len: Affects how smooth and lagging the median of the DEMA is.
dev_len and dev_mul: Influence the sensitivity of the deviation measures. Larger multipliers widen the bands, potentially reducing false signals but introducing more lag. Smaller multipliers tighten the bands, producing quicker signals but potentially more whipsaws.
This flexibility allows the trader to tailor the indicator for various markets (stocks, forex, crypto) and time frames.
Backtesting and Performance Metrics
The code integrates with a backtesting library that allows traders to:
Evaluate the strategy historically
Compare the indicator’s signals with a simple buy-and-hold approach
Generate performance metrics (e.g., mean returns, Sharpe Ratio, Sortino Ratio) to assess historical effectiveness.
Disclaimer
No guaranteed results: Historical performance does not guarantee future outcomes. Market conditions can vary widely.
User responsibility: Traders should combine this indicator with other forms of analysis, appropriate risk management, and careful calibration of parameters.