TASC 2025.03 A New Solution, Removing Moving Average Lag█ OVERVIEW
This script implements a novel technique for removing lag from a moving average, as introduced by John Ehlers in the "A New Solution, Removing Moving Average Lag" article featured in the March 2025 edition of TASC's Traders' Tips .
█ CONCEPTS
In his article, Ehlers explains that the average price in a time series represents a statistical estimate for a block of price values, where the estimate is positioned at the block's center on the time axis. In the case of a simple moving average (SMA), the calculation moves the analyzed block along the time axis and computes an average after each new sample. Because the average's position is at the center of each block, the SMA inherently lags behind price changes by half the data length.
As a solution to removing moving average lag, Ehlers proposes a new projected moving average (PMA) . The PMA smooths price data while maintaining responsiveness by calculating a projection of the average using the data's linear regression slope.
The slope of linear regression on a block of financial time series data can be expressed as the covariance between prices and sample points divided by the variance of the sample points. Ehlers derives the PMA by adding this slope across half the data length to the SMA, creating a first-order prediction that substantially reduces lag:
PMA = SMA + Slope * Length / 2
In addition, the article includes methods for calculating predictions of the PMA and the slope based on second-order and fourth-order differences. The formulas for these predictions are as follows:
PredictPMA = PMA + 0.5 * (Slope - Slope ) * Length
PredictSlope = 1.5 * Slope - 0.5 * Slope
Ehlers suggests that crossings between the predictions and the original values can help traders identify timely buy and sell signals.
█ USAGE
This indicator displays the SMA, PMA, and PMA prediction for a specified series in the main chart pane, and it shows the linear regression slope and prediction in a separate pane. Analyzing the difference between the PMA and SMA can help to identify trends. The differences between PMA or slope and its corresponding prediction can indicate turning points and potential trade opportunities.
The SMA plot uses the chart's foreground color, and the PMA and slope plots are blue by default. The plots of the predictions have a green or red hue to signify direction. Additionally, the indicator fills the space between the SMA and PMA with a green or red color gradient based on their differences:
Users can customize the source series, data length, and plot colors via the inputs in the "Settings/Inputs" tab.
█ NOTES FOR Pine Script® CODERS
The article's code implementation uses a loop to calculate all necessary sums for the slope and SMA calculations. Ported into Pine, the implementation is as follows:
pma(float src, int length) =>
float PMA = 0., float SMA = 0., float Slope = 0.
float Sx = 0.0 , float Sy = 0.0
float Sxx = 0.0 , float Syy = 0.0 , float Sxy = 0.0
for count = 1 to length
float src1 = src
Sx += count
Sy += src
Sxx += count * count
Syy += src1 * src1
Sxy += count * src1
Slope := -(length * Sxy - Sx * Sy) / (length * Sxx - Sx * Sx)
SMA := Sy / length
PMA := SMA + Slope * length / 2
However, loops in Pine can be computationally expensive, and the above loop's runtime scales directly with the specified length. Fortunately, Pine's built-in functions often eliminate the need for loops. This indicator implements the following function, which simplifies the process by using the ta.linreg() and ta.sma() functions to calculate equivalent slope and SMA values efficiently:
pma(float src, int length) =>
float Slope = ta.linreg(src, length, 0) - ta.linreg(src, length, 1)
float SMA = ta.sma(src, length)
float PMA = SMA + Slope * length * 0.5
To learn more about loop elimination in Pine, refer to this section of the User Manual's Profiling and optimization page.
Regressions
UM-Optimized Linear Regression ChannelDESCRIPTION
This indicator was inspired by Dr. Stoxx at drstoxx.com. Shout out to him and his services for introducing me to this idea. This indicator is a slightly different take on the standard linear regression indicator.
It uses two standard deviations to draw bands and dynamically attempts to best-fit the data lookback period using an R-squared statistical measure. The R-squared value ranges between zero and one with zero being no fit to the data at all and 1 being a 100% match of the data to linear regression line. The R-squared calculation is weighted exponentially to give more weight to the most recent data.
The label provides the number of periods identified as the optimal best-fit period, the type of loopback period determination (Manual or Auto) and the R-squared value (0-100, 100% being a perfect fit). >=90% is a great fit of the data to the regression line. <50% is a difficult fit and more or less considered random data.
The lookback mode can also be set manually and defaults to a value of 100 periods.
DEFAULTS
The defaults are 1.5 and 2.0 for standard deviation. This creates 2 bands above and below the regression line. The default mode for best-fit determination with "Auto" selected in the dropdown. When manual mode is selected, the default is 100. The modes, manual lookback periods, colors, and standard deviations are user-configurable.
HOW TO USE
Overlay this indicator on any chart of any timeframe. Look for turning points at extremes in the upper and lower bands. Look for crossovers of the centerline. Look at the Auto-determination for best fit. Compare this to your favorite Manual mode setting (Manual Mode is set to 100 by default lookback periods.)
When price is at an extreme, look for turnarounds or reversals. Use your favorite indicators, in addition to this indicator, to determine reversals. Try this indicator against your favorite securities and timeframes.
CHART EXAMPLE
The chart I used for an example is the daily chart of IWM. I illustrated the extremes with white text. This is where I consider proactively exiting an existing position and/or begin looking for a reversal.
CandelaCharts - Fib Retracement (OTE) 📝 Overview
The CandelaCharts Fib Retracement (OTE) indicator is a precision tool designed to help traders identify Optimal Trade Entry (OTE) levels based on Fibonacci retracement principles, as taught in ICT (Inner Circle Trader) methodology.
This indicator automatically plots Fibonacci retracement levels between a selected swing high and swing low, highlighting the key OTE zone between the 61.8% and 78.6% retracement levels—a prime area for potential reversals in trending markets.
📦 Features
Automatic & Custom lookback modes
Customizable fib levels
Dynamic coloring
Reverse & extend
⚙️ Settings
Lookback: Controls the number of bars to look back. You can choose between **Automatic** or **Custom** mode.
Line Style: Sets the line style for the Fibonacci levels.
Levels: 0, 0.236, 0.0.382, 0.500, 0.620, 0.705, 0.790, 0.886, 1.000. Allows you to toggle the visibility of Fibonacci levels.
Dynamic Coloring: Colors Fibonacci levels according to trend direction.
Show Labels: Shows the price value at each Fibonacci level.
Reverse: Flips the Fibonacci levels in the opposite direction.
Extend Left: Extends the Fibonacci levels to the left.
⚡️ Showcase
Dynamic Coloring
Manual Coloring
Fib Retracement
Extended
Custom Length
📒 Usage
Using the CandelaCharts Fib Retracement (OTE) is pretty straightforward—just follow these steps to spot high-probability trade setups and refine your entries.
Identify the Trend – Determine whether the market is in an uptrend or downtrend.
Select Swing Points – The indicator automatically plots from the most recent swing high to swing low (or vice versa).
Wait for Price to Enter OTE Zone – Look for price action confirmation within the optimal entry zone (61.8%-78.6%).
Enter the Trade – Consider longs in an uptrend at the OTE zone, and shorts in a downtrend.
Set Stop & Target – Place stops below/above the swing low/high and target extension levels (127.2%, 161.8%).
🎯 Key takeways
The CandelaCharts Fib Retracement (OTE) is a must-have tool for traders looking to refine their entries and maximize risk-reward potential with precision-based ICT trading strategies. 🚀
🚨 Alerts
The indicator does not provide any alerts!
⚠️ Disclaimer
Trading involves significant risk, and many participants may incur losses. The content on this site is not intended as financial advice and should not be interpreted as such. Decisions to buy, sell, hold, or trade securities, commodities, or other financial instruments carry inherent risks and are best made with guidance from qualified financial professionals. Past performance is not indicative of future results.
Linear Regression Channel [TradingFinder] Existing Trend Line🔵 Introduction
The Linear Regression Channel indicator is one of the technical analysis tool, widely used to identify support, resistance, and analyze upward and downward trends.
The Linear Regression Channel comprises five main components : the midline, representing the linear regression line, and the support and resistance lines, which are calculated based on the distance from the midline using either standard deviation or ATR.
This indicator leverages linear regression to forecast price changes based on historical data and encapsulates price movements within a price channel.
The upper and lower lines of the channel, which define resistance and support levels, assist traders in pinpointing entry and exit points, ultimately aiding better trading decisions.
When prices approach these channel lines, the likelihood of interaction with support or resistance levels increases, and breaking through these lines may signal a price reversal or continuation.
Due to its precision in identifying price trends, analyzing trend reversals, and determining key price levels, the Linear Regression Channel indicator is widely regarded as a reliable tool across financial markets such as Forex, stocks, and cryptocurrencies.
🔵 How to Use
🟣 Identifying Entry Signals
One of the primary uses of this indicator is recognizing buy signals. The lower channel line acts as a support level, and when the price nears this line, the likelihood of an upward reversal increases.
In an uptrend : When the price approaches the lower channel line and signs of upward reversal (e.g., reversal candlesticks or high trading volume) are observed, it is considered a buy signal.
In a downtrend : If the price breaks the lower channel line and subsequently re-enters the channel, it may signal a trend change, offering a buying opportunity.
🟣 Identifying Exit Signals
The Linear Regression Channel is also used to identify sell signals. The upper channel line generally acts as a resistance level, and when the price approaches this line, the likelihood of a price decrease increases.
In an uptrend : Approaching the upper channel line and observing weakness in the uptrend (e.g., declining volume or reversal patterns) indicates a sell signal.
In a downtrend : When the price reaches the upper channel line and reverses downward, this is considered a signal to exit trades.
🟣 Analyzing Channel Breakouts
The Linear Regression Channel allows traders to identify price breakouts as strong signals of potential trend changes.
Breaking the upper channel line : Indicates buyer strength and the likelihood of a continued uptrend, often accompanied by increased trading volume.
Breaking the lower channel line : Suggests seller dominance and the possibility of a continued downtrend, providing a strong sell signal.
🟣 Mean Reversion Analysis
A key concept in using the Linear Regression Channel is the tendency for prices to revert to the midline of the channel, which acts as a dynamic moving average, reflecting the price's equilibrium over time.
In uptrends : Significant deviations from the midline increase the likelihood of a price retracement toward the midline.
In downtrends : When prices deviate considerably from the midline, a return toward the midline can be used to identify potential reversal points.
🔵 Settings
🟣 Time Frame
The time frame setting enables users to view higher time frame data on a lower time frame chart. This feature is especially useful for traders employing multi-time frame analysis.
🟣 Regression Type
Standard : Utilizes classical linear regression to draw the midline and channel lines.
Advanced : Produces similar results to the standard method but may provide slightly different alignment on the chart.
🟣 Scaling Type
Standard Deviation : Suitable for markets with stable volatility.
ATR (Average True Range) : Ideal for markets with higher volatility.
🟣 Scaling Coefficients
Larger coefficients create broader channels for broader trend analysis.
Smaller coefficients produce tighter channels for precision analysis.
🟣 Channel Extension
None : No extension.
Left: Extends lines to the left to analyze historical trends.
Right : Extends lines to the right for future predictions.
Both : Extends lines in both directions.
🔵 Conclusion
The Linear Regression Channel indicator is a versatile and powerful tool in technical analysis, providing traders with support, resistance, and midline insights to better understand price behavior. Its advanced settings, including time frame selection, regression type, scaling options, and customizable coefficients, allow for tailored and precise analysis.
One of its standout advantages is its ability to support multi-time frame analysis, enabling traders to view higher time frame data within a lower time frame context. The option to use scaling methods like ATR or standard deviation further enhances its adaptability to markets with varying volatility.
Designed to identify entry and exit signals, analyze mean reversion, and assess channel breakouts, this indicator is suitable for a wide range of markets, including Forex, stocks, and cryptocurrencies. By incorporating this tool into your trading strategy, you can make more informed decisions and improve the accuracy of your market predictions.
MOKI V1The "MOKI V1" script is a trading strategy on the TradingView platform that uses a combination of two key indicators to identify buy and sell signals:
EMA200 (Exponential Moving Average 200): Used to determine the overall market trend. This line helps ensure that trades are made in the direction of the primary market trend.
RSI (Relative Strength Index): Used to measure the strength or weakness of a trend. In this strategy, a reading above 50 for the RSI indicates stronger buy signals.
Engulfing Pattern: This candlestick pattern occurs when a green (bullish) candle completely engulfs the previous red (bearish) candle. It is used as a buy signal when combined with the other indicators.
BIAS PRO - Zones + Liquidity + SP&RS [AlgoRich]This multifunction indicator is used to identify key areas on the chart, liquidity levels, and support/resistance zones (SP&RS). Its design is aimed at highlighting price pivots (swings) by drawing zones (boxes and lines) based on these pivots, while also displaying information about trading sessions and levels of analysis across different timeframes.
1. Configuration and Input Parameters
Swing Parameters (Bars Right-Left):
Two inputs are defined to adjust the number of bars on the right and left used to detect pivots (swings). This allows the determination of high and low pivot points.
Display Options:
You can choose to show or hide boxes, lines, and labels (bubbles). There is also an option to extend the zones until they are “filled” (confirmed), and you can opt to hide those zones once filled.
Appearance:
Visual parameters are defined, such as the option to display high and low pivots, colors for lines, labels, and boxes (for both bullish and bearish conditions), line styles (solid, dotted, dashed), and other aesthetic details (box width, label size, text alignment).
Lookback and Time Range:
The “lookback” and “daysBack” variables determine whether the analysis is limited to data from a certain number of days, helping to filter out older historical information.
2. Calculation of Pivots (Swings) and Zone Detection
Price Pivots:
Using the pivot functions (ta.pivothigh and ta.pivotlow), the script identifies swing high and low points based on the configured swing size (bars left and right).
If a swing high is detected, its bar index is stored and the corresponding signal is activated.
Similarly, a swing low is detected and marked.
Drawing Zones:
When a swing (high or low) is detected and the time range condition is met (inRange), the script draws:
Boxes: These visually represent the area around the pivot level. The configuration (type and width) is adjustable.
Lines: A horizontal line is drawn from the pivot point to the current bar, using the defined style and color.
Boxes and lines are drawn for both high pivots (showhighs) and low pivots (showlows).
Additionally, these zones are updated and extended dynamically as new bars appear, and zones that are “filled” (when the price exceeds the zone level) are removed.
Labels and Markers:
If enabled, the script displays circle markers (using plotshape) at the swing points.
3. Operational Zone (Sessions)
Customizable Sessions:
The script allows defining up to three operational sessions with distinct time ranges and colors.
For example, Session 1, Session 2, and Session 3 have configurable time ranges and colors (with adjustable opacity).
It checks if the current time falls within any of these sessions and, if so, applies a background color (bgcolor) to the chart with the configured session color.
Timezone Adjustment:
You can configure a UTC offset or use the exchange’s timezone to correctly adjust the session times.
4. Additional Levels and Analysis Groups
Groups of Levels (Levels 1, 2, 3, and 4):
Several groups are defined that allow data requests from different timeframes (e.g., 60 minutes, 240 minutes, daily, or weekly) and configure their parameters (length, line style, color).
For each group, the script uses a function that requests non-repainting data and calculates pivot levels based on ta.pivothigh/ta.pivotlow.
These levels are drawn on the chart with lines and “shadow” lines to reinforce the visualization of key pivot points. Labels are added with a slight offset to indicate the pivot value in the corresponding timeframe.
5. Maintenance and Management of Drawn Elements
Dynamic Update and Deletion:
The script maintains arrays to store the drawn boxes and lines. As new elements are added and the array reaches a maximum size (e.g., 500 elements), the oldest elements are deleted to avoid overloading the chart.
Extension and Hiding Conditions:
Conditions are checked to extend or delete zones based on whether the price has “filled” the area (i.e., if the current price has surpassed the zone level). There is also an option to hide zones once they are filled.
6. Session (Operational Zone) and Levels for Multiple Timeframes
Session Settings:
In addition to the pivot zones, the indicator also defines operational sessions with adjustable time ranges and colors, shading the background of the chart during those sessions.
Additional Level Groups:
The indicator allows grouping of analysis levels by timeframe, which can be useful for multi-timeframe analysis. Parameters such as length, style, and color are configurable for each group.
Summary:
The "BIAS PRO - Zones + Liquidity + SP&RS " is an all-in-one indicator that combines the detection of price pivots (swings) with the visual representation of key zones on the chart. With options to customize appearance, manage operational sessions, and group levels across different timeframes, this script is designed to help traders identify areas of high liquidity, potential breakouts, or reversals, thus optimizing decision-making based on market structure.
This explanation covers the main functionalities and workflow of the script, making it easier to understand without needing to examine the code in detail.
Pearson Correlation CoefficientDescription: The Pearson Correlation Coefficient measures the strength and direction of the linear relationship between two data series. Its value ranges from -1 to +1, where:
+1 indicates a perfect positive linear correlation: as one asset increases, the other asset increases proportionally.
0 indicates no linear correlation: variations in one asset have no relation to variations in the other asset.
-1 indicates a perfect negative linear correlation: as one asset increases, the other asset decreases proportionally.
This measure is widely used in technical analysis to assess the degree of correlation between two financial assets. The "Pearson Correlation (Manual Compare)" indicator allows users to manually select two assets and visually display their correlation relationship on a chart.
Features:
Correlation Period: The time period used for calculating the correlation can be adjusted (default: 50).
Comparison Asset: Users can select a secondary asset for comparison.
Visual Plots: The chart includes reference lines for perfect correlations (+1 and -1) and strong correlations (+0.7 and -0.7).
Alerts: Set alerts for when the correlation exceeds certain threshold values (e.g., +0.7 for strong positive correlation).
How to Select the Second Asset:
Primary Asset Selection: The primary asset is the one you select for viewing on the chart. This can be done by simply opening the chart for the desired asset.
Secondary Asset Selection: To select the secondary asset for comparison, use the input field labeled "Comparison Asset" in the script settings. You can manually enter the ticker symbol of the secondary asset you want to compare with the primary asset.
This indicator is ideal for traders looking to identify relationships and correlations between different financial assets to make informed trading decisions.
Statistical Arbitrage Pairs Trading - Long-Side OnlyThis strategy implements a simplified statistical arbitrage (" stat arb ") approach focused on mean reversion between two correlated instruments. It identifies opportunities where the spread between their normalized price series (Z-scores) deviates significantly from historical norms, then executes long-only trades anticipating reversion to the mean.
Key Mechanics:
1. Spread Calculation: The strategy computes Z-scores for both instruments to normalize price movements, then tracks the spread between these Z-scores.
2. Modified Z-Score: Uses a robust measure combining the median and Median Absolute Deviation (MAD) to reduce outlier sensitivity.
3. Entry Signal: A long position is triggered when the spread’s modified Z-score falls below a user-defined threshold (e.g., -1.0), indicating extreme undervaluation of the main instrument relative to its pair.
4. Exit Signal: The position closes automatically when the spread reverts to its historical mean (Z-score ≥ 0).
Risk management:
Trades are sized as a percentage of equity (default: 10%).
Includes commissions and slippage for realistic backtesting.
VFV Correction Levels
This Pine Script, "VFV Correction Levels," identifies significant daily price corrections and calculates corresponding investments based on fixed thresholds (paliers). Key features include:
Six predefined correction levels trigger investments between $150 and $600 based on the percentage drop.
Larger corrections correspond to higher investment amounts.
Graphical Indicators:
Visual labels mark correction levels and display investment amounts directly on the chart.
Investment Tracking:
Calculates total invested and tracks performance (yield percentage) relative to the initial correction price.
Double RSI + MA Signal [AlgoRich]This indicator combines two RSI (Relative Strength Index) indicators with their respective Exponential Moving Averages (EMA) to provide a more detailed view of the market's relative strength.
Its design allows for the identification of overbought and oversold zones, as well as potential trend reversal signals.
How does it work?
1. RSI (Relative Strength Index)
The RSI is an oscillator that measures the speed and change of price movements.
The values range between 0 and 100:
Values above 70 typically indicate overbought conditions (price may be overvalued).
Values below 30 typically indicate oversold conditions (price may be undervalued).
In this indicator, two RSIs are calculated with different periods to capture strength signals in both the short and medium term:
RSI 1: Uses a shorter period (7 by default), making it more sensitive to recent price changes.
RSI 2: Uses a longer period (14 by default), providing a more stable perspective.
2. EMAs (Exponential Moving Averages)
EMAs are calculated for each RSI to smooth their movements:
EMA RSI 1: Smooths RSI 1 (short-term).
EMA RSI 2: Smooths RSI 2 (medium-term).
These EMAs help filter market noise and allow for clearer trend identification in the RSI data.
3. Key Levels
Horizontal reference levels are defined on the chart:
80 (solid red line): Extreme overbought zone.
70 (dotted red line): Initial overbought zone.
50 (dotted gray line): Midline, acting as an equilibrium reference.
30 (dotted green line): Initial oversold zone.
20 (solid green line): Extreme oversold zone.
These levels help interpret market strength:
Above 70: The market is in a strong bullish phase (or overbought).
Below 30: The market is in a strong bearish phase (or oversold).
4. Visualization
The indicator plots:
RSI 1 and its EMA:
RSI 1: Thick green line.
EMA RSI 1: Thin white line that follows RSI 1.
RSI 2 and its EMA:
RSI 2: Thick red line.
EMA RSI 2: Transparent line (not visible in this case but can be enabled if desired).
What is this indicator used for?
1. Identifying Overbought and Oversold Conditions
Levels 70 and 30 indicate zones where the market might be near a trend reversal.
Levels 80 and 20 identify extreme conditions, often accompanied by strong price reversals.
2. Confirming Trends
If the RSI and its EMA are above 50, it indicates a bullish trend.
If the RSI and its EMA are below 50, it indicates a bearish trend.
3. Filtering False Signals
By combining two RSIs with different periods, you can confirm signals more reliably:
If both RSIs are moving in the same direction (above or below 50), the signal is stronger.
EMAs smooth out oscillations, helping to ignore irrelevant short-term movements.
Benefits for Traders
This indicator is useful for:
Scalpers and Day Traders: By using a shorter RSI (RSI 1), you can capture quick movements in the market.
Swing Traders: With the longer RSI (RSI 2), you can identify broader trends.
Risk Management: Avoid trading in extreme overbought/oversold zones (levels 80 and 20).
In summary, this indicator provides a powerful tool to evaluate the market's relative strength, combining multiple analysis timeframes and helping traders make more informed decisions.
-----------------
TRADUCCIÓN AL ESPAÑOL:
Explicación del Indicador: Double RSI + MA Signal
Este indicador combina dos RSI (Relative Strength Index) con sus respectivas medias móviles exponenciales (EMA) para proporcionar una visión más detallada de la fuerza relativa del mercado.
Su diseño permite identificar zonas de sobrecompra, sobreventa y posibles señales de cambio de tendencia.
¿Cómo funciona?
1. RSI (Relative Strength Index)
El RSI es un oscilador que mide la velocidad y el cambio en los movimientos de precios.
Los valores oscilan entre 0 y 100:
Valores por encima de 70 suelen indicar sobrecompra (precio posiblemente sobrevalorado).
Valores por debajo de 30 suelen indicar sobreventa (precio posiblemente infravalorado).
En este indicador, se calculan dos RSI con diferentes períodos para capturar señales de fuerza a corto y mediano plazo:
RSI 1: Usando un período más corto (7, por defecto), lo que lo hace más sensible a cambios recientes en el precio.
RSI 2: Usando un período más largo (14, por defecto), proporcionando una visión más estable.
2. EMAs (Exponential Moving Averages)
Se calculan EMAs de cada RSI para suavizar sus movimientos:
EMA RSI 1: Suaviza el RSI 1 (corto plazo).
EMA RSI 2: Suaviza el RSI 2 (mediano plazo).
Estas EMAs ayudan a filtrar el ruido del mercado y permiten identificar tendencias más claras en los datos del RSI.
3. Niveles Clave
Se definen niveles de referencia horizontales en el gráfico:
80 (línea sólida roja): Zona de sobrecompra extrema.
70 (línea punteada roja): Zona inicial de sobrecompra.
50 (línea gris punteada): Línea media, que actúa como una referencia de equilibrio.
30 (línea punteada verde): Zona inicial de sobreventa.
20 (línea sólida verde): Zona de sobreventa extrema.
Estos niveles ayudan a interpretar la fuerza del mercado:
Por encima de 70: El mercado está en una fase alcista fuerte (o sobrecompra).
Por debajo de 30: El mercado está en una fase bajista fuerte (o sobreventa).
4. Visualización
El indicador grafica:
RSI 1 y su EMA:
RSI 1: Línea verde gruesa.
EMA RSI 1: Línea blanca delgada, que sigue al RSI 1.
RSI 2 y su EMA:
RSI 2: Línea roja gruesa.
EMA RSI 2: Línea transparente (no visible en este caso, pero puede activarse si se desea).
¿Para qué sirve este indicador?
1. Identificar sobrecompra y sobreventa
Los niveles de 70 y 30 marcan zonas donde el mercado podría estar cerca de un cambio de tendencia.
Los niveles de 80 y 20 identifican extremos, que suelen estar acompañados de fuertes reversiones de precio.
2. Confirmar tendencias
Si el RSI y su EMA están por encima de 50, indica una tendencia alcista.
Si el RSI y su EMA están por debajo de 50, indica una tendencia bajista.
3. Filtrar señales falsas
Al combinar dos RSI con diferentes períodos, puedes confirmar señales de una forma más confiable:
Si ambos RSI están en la misma dirección (por encima o por debajo de 50), la señal es más fuerte.
Las EMAs suavizan las oscilaciones, ayudando a ignorar movimientos temporales irrelevantes.
Beneficio para los Traders
Este indicador es útil para:
Scalpers y Day Traders: Al usar un RSI más corto (RSI 1), puedes capturar movimientos rápidos en el mercado.
Swing Traders: Con el RSI más largo (RSI 2), puedes identificar tendencias más amplias.
Gestión de riesgos: Evitar operaciones en zonas de sobrecompra/sobreventa extremas (niveles 80 y 20).
En resumen, este indicador proporciona una herramienta poderosa para evaluar la fuerza relativa del mercado, combinando diferentes horizontes de análisis y ayudando a los traders a tomar decisiones informadas.
Liquidity + SP y RS + Zones [AlgoRich]This indicator is designed to identify key areas in the market, such as support and resistance levels, liquidity zones, and important price structures.
Additionally, it highlights operational areas based on specific time frames, facilitating technical analysis and decision-making in trading.
How does it work?
1. Identification of Pivot Levels
The indicator identifies local highs and lows on the chart, known as pivot levels, which are zones where the price tends to react, such as:
Support zones: Areas where the price is likely to stop falling.
Resistance zones: Areas where the price might encounter obstacles to keep rising.
These levels are calculated by analyzing a range of bars around the current price and are highlighted with lines, boxes, and labels on the chart.
2. Liquidity Zones
Liquidity zones are defined as areas where there has been an accumulation of orders, either for buying or selling. These zones are significant because they often signal future price movements.
The indicator creates visual boxes around these levels, allowing traders to quickly identify areas where the price might react.
3. Support and Resistance Lines
Horizontal lines are drawn at the identified highs and lows, representing support and resistance levels on the chart.
These lines can be extended forward until the price touches them, showing whether the level has been respected or "broken."
4. Visual Labels
The indicator can also display labels at key levels to provide additional information, such as whether the level corresponds to a high or low.
5. Operational Zones
In addition to support and resistance levels, the indicator allows users to mark specific time periods, referred to as operational sessions.
These zones highlight user-defined periods, such as:
New York session
London session
Daily session
This helps focus analysis on the most active market periods.
6. Customization
The user can customize the following:
Pivot sizes (how many bars to consider to the left and right).
Colors and styles of the lines, boxes, and labels.
Visibility of elements such as boxes, lines, and labels.
Whether to extend the levels forward until the price reaches them.
What is this indicator used for?
Identifying key areas in the market: Support, resistance levels, and liquidity zones are essential for understanding where the price is most likely to react.
Defining entry and exit points: Highlighted zones help determine when to open or close trades.
Highlighting key market moments: With operational sessions, you can focus on the most relevant periods for your strategy.
Simplifying technical analysis: By visualizing levels and zones directly on the chart, it reduces the time needed to identify critical areas.
Benefits for Traders
This indicator is ideal for traders who:
Want to analyze key market levels quickly and efficiently.
Are looking for high-probability zones to trade, based on support, resistance, and liquidity areas.
Need a visual approach to highlight operational levels and important time frames on their charts.
In summary, this indicator serves as a comprehensive tool that combines advanced technical analysis with a user-friendly visual interface, allowing traders to make more informed and precise decisions.
-----------------
TRADUCCIÓN AL ESPAÑOL:
Este indicador está diseñado para identificar zonas clave en el mercado, como niveles de soporte y resistencia, zonas de liquidez, y estructuras importantes de precios. Además, resalta las áreas operativas de acuerdo con horarios específicos, facilitando el análisis técnico y la toma de decisiones en el trading.
¿Cómo funciona?
1. Identificación de Niveles Pivot
El indicador busca máximos y mínimos locales en el gráfico, conocidos como niveles pivote, los cuales son zonas donde el precio suele reaccionar, como en:
Zonas de soporte: Donde el precio tiene probabilidades de detener su caída.
Zonas de resistencia: Donde el precio podría encontrar obstáculos para seguir subiendo.
Estos niveles son calculados analizando un rango de barras alrededor del precio actual, y se destacan con líneas, cajas y etiquetas en el gráfico.
2. Zonas de Liquidez
Las zonas de liquidez se definen como áreas donde ha habido una acumulación de órdenes, ya sea de compra o venta. Estas zonas son importantes porque suelen marcar movimientos futuros significativos en el precio.
El indicador crea cajas visuales alrededor de estos niveles, permitiendo identificar rápidamente las áreas donde el precio puede reaccionar.
3. Líneas de Soporte y Resistencia
Se trazan líneas horizontales en los máximos y mínimos identificados, representando los niveles de soporte y resistencia en el gráfico.
Estas líneas se pueden extender hacia adelante hasta que el precio las toque, mostrando si el nivel ha sido respetado o "roto".
4. Etiquetas Visuales
El indicador también puede mostrar etiquetas en los niveles clave para proporcionar información adicional, como si el nivel corresponde a un máximo o un mínimo.
5. Zonas Operativas
Además de los niveles de soporte y resistencia, el indicador permite marcar zonas de tiempo específicas, llamadas sesiones operativas.
Estas zonas resaltan períodos definidos por el usuario, como:
Sesión de Nueva York.
Sesión de Londres.
Diario.
Esto ayuda a enfocar el análisis en los momentos más activos del mercado.
6. Personalización
El usuario puede personalizar:
Tamaños de pivote (cuántas barras a la izquierda y derecha considerar).
Colores y estilos de las líneas, cajas y etiquetas.
La visibilidad de elementos como cajas, líneas y etiquetas.
Extender o no los niveles hacia adelante hasta que el precio los alcance.
¿Para qué sirve este indicador?
Identificar zonas importantes del mercado: Los niveles de soporte, resistencia y las zonas de liquidez son esenciales para entender dónde es más probable que el precio reaccione.
Definir puntos de entrada y salida: Las zonas destacadas ayudan a determinar cuándo abrir o cerrar operaciones.
Resaltar momentos clave del mercado: Con las sesiones operativas, puedes enfocarte en los períodos más relevantes para tu estrategia.
Simplificar el análisis técnico: Visualizando niveles y zonas directamente en el gráfico, se reduce el tiempo necesario para identificar áreas críticas.
Beneficio para los Traders
Este indicador es ideal para traders que:
Quieren analizar niveles clave del mercado de forma rápida y eficiente.
Buscan zonas de alta probabilidad para operar, basándose en soportes, resistencias y zonas de liquidez.
Necesitan un enfoque visual para destacar niveles operativos y horarios importantes en sus gráficos.
En resumen, este indicador actúa como una herramienta integral para combinar análisis técnico avanzado con una interfaz visual amigable, lo que permite a los traders tomar decisiones más informadas y precisas.
Smoothed Gaussian Trend Filter [AlgoAlpha]Experience seamless trend detection and market analysis with the Smoothed Gaussian Trend Filter by AlgoAlpha! This cutting-edge indicator combines advanced Gaussian filtering with linear regression smoothing to identify and enhance market trends, making it an essential tool for traders seeking precise and actionable signals.
Key Features :
🔍 Gaussian Trend Filtering: Utilizes a customizable Gaussian filter with adjustable length and pole settings for tailored smoothing and trend identification.
📊 Linear Regression Smoothing: Reduces noise and further refines the Gaussian output with user-defined smoothing length and offset, ensuring clarity in trend representation.
✨ Dynamic Visual Highlights: Highlights trends and signals based on volume intensity, allowing for real-time insights into market behavior.
📉 Choppy Market Detection: Identifies ranging or choppy markets, helping traders avoid false signals.
🔔 Custom Alerts: Set alerts for bullish and bearish signals, trend reversals, or choppy market conditions to stay on top of trading opportunities.
🎨 Color-Coded Visuals: Fully customizable colors for bullish and bearish signals, ensuring clear and intuitive chart analysis.
How to Use :
Add the Indicator: Add it to your favorites and apply it to your TradingView chart.
Interpret the Chart: Observe the trend line for directional changes and use the accompanying buy/sell signals for entry and exit opportunities. Choppy market conditions are flagged for additional caution.
Set Alerts: Enable alerts for trend signals or choppy market detections to act promptly without constant chart monitoring.
How It Works :
The Smoothed Gaussian Trend Filter uses a combination of advanced smoothing techniques to identify trends and enhance market clarity. First, a Gaussian filter is applied to price data, using a user-defined length (Gaussian length) and poles (smoothness level) to calculate an alpha value that determines the degree of smoothing. This creates a refined trend line that minimizes noise while preserving key market movements. The output is then further processed using linear regression smoothing, allowing traders to adjust the length and offset to flatten minor oscillations and emphasize the dominant trend. To incorporate market activity, volume intensity is analyzed through a normalized Hull Moving Average (HMA), dynamically adjusting the trend line's color transparency based on trading activity. The indicator also identifies trend direction by comparing the smoothed trend line with a calculated SuperTrend-style level, generating clear trend regimes and highlighting ranging or choppy conditions where trends are less reliable and avoiding false signals. This seamless integration of Gaussian smoothing, regression analysis, and volume dynamics provides traders with a powerful and intuitive tool for market analysis.
Price Projection by Linear RegressionPurpose:
This is a TradingView Pine Script indicator that performs a linear regression on historical price data to project potential future price levels. It's designed to help traders visualize long-term price trends and potential future price targets.
Key Components:
User Inputs:
Historical Data Points (default 1000 bars) - The amount of historical data used to calculate the trend
Years to Project (default 10 years) - How far into the future to project the price
Technical Implementation:
Uses linear regression (ta.linreg) to calculate the trend slope
Converts years to trading days using 252 trading days per year
Limits visible projection to 500 bars due to TradingView's drawing limitations
Projects prices using the formula: current_price + (slope × number_of_bars)
Visual Elements:
Blue line showing actual historical prices
Red projection line showing the expected price path
Label showing the projected price at the visible end of the line
Information table in the top-right corner showing:
Current price
Final projected price after the full time period
Limitations:
Can only display projections up to 500 bars into the future (about 2 years) due to TradingView limitations
The full projection value is still calculated and shown in the table
Past performance doesn't guarantee future results - this is a mathematical projection based on historical trends
Usage:
Traders can use this to:
Visualize potential long-term price trends
Set long-term price targets
Understand the historical trend's trajectory
Compare current prices with projected future values
Previous Candle Sweep IndicatorThis script identifies candlesticks where the current candle's high is higher than the previous candle's high, and the current candle's low is lower than the previous candle's low. If both conditions are met, the candle's body is highlighted in blue on the chart, allowing traders to quickly spot these patterns.
Features:
Highlights candles with both higher highs and lower lows.
Uses clear visual cues (blue body) for easy identification.
Ideal for traders looking to identify specific volatility patterns or reversals.
RM - Hull Moving RegressionRM - Hull Moving Regression (RM - HMR)
This indicator integrates the Enhanced Hull Moving Average (EHMA) with linear regression and RSI to provide a comprehensive view of market trends and momentum. By combining advanced smoothing techniques with dynamic visual cues, it delivers actionable insights for traders seeking clarity in price movements.
Key Features
- Enhanced Hull Moving Average (EHMA):
The indicator computes EHMA values using the open, high, low, and close prices. These are averaged to create a smooth, responsive representation of market trends.
- Linear Regression Smoothing:
The EHMA output is further refined with a linear regression model, reducing noise and highlighting directional trends.
- RSI-Tracking:
RSI is calculated on the smoothed regression output.
- Dynamic Bar Coloring:
Bars change color to reflect shifts in momentum:
- Green for increasing momentum.
- Orange for decreasing momentum.
- Customizable Parameters:
Users can adjust the RSI length, regression length, and EHMA period to suit their trading strategy.
How It Works
1. The indicator calculates EHMA values for four price sources (open, high, low, close).
2. These EHMA values are averaged to generate a smoother price action metric.
3. The averaged EHMA is processed through a linear regression model to further smooth the data.
4. RSI is then applied to the regression output.
How to Use
- Identify Market Trends:
Use the color-coded bars and moving averages to confirm overall market direction.
- Monitor Momentum Changes:
Look for shifts in bar color (e.g., green to orange) to identify potential weakening or strengthening trends.
- Combine with Other Indicators:
Integrate the RM-HMR with other trend-following or momentum tools for robust analysis and confirmation.
Example Use Cases
- Trend Following:
Utilize the smooth moving averages and bar colors to follow dominant market trends.
Disclaimer
This indicator is designed for educational and analytical purposes. It should not be used in isolation and must be paired with sound risk management practices and additional tools for comprehensive market analysis.
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.
Algo Bands [ProjeAdam]OVERVIEW:
The Algo Bands indicator is a technical analysis tool that calculates the highest, lowest, and average price levels over a user-defined number of bars. It generates buy and sell signals based on price interactions with these levels, visualizing them as bands on the chart. Additionally, the indicator provides multi-timeframe analysis and integrates alerts for timely trading decisions.
ALGORITHM:
1. Initialization and Function Definition
The Algo Bands indicator starts by defining functions to calculate critical price levels:
- High Band : A smoothed average of recent high price levels.
- Low Band : A smoothed average of recent low price levels.
- Average Band : The midpoint between the High Band and Low Band.
The smoothing process utilizes a Smoothed Moving Average (SMMA) to reduce noise and ensure accurate signal generation.
2. Inputs and Band Calculation
The indicator accepts customizable inputs for flexibility in trading strategies:
- Backward Length : The number of bars to consider for calculating high and low values.
- Number of Lines : Specifies how many recent high or low values are averaged.
- Smoothing Period : The length of the SMMA to smooth price data.
Using these inputs:
- The High Band is calculated as the smoothed average of the highest price values.
- The Low Band is calculated as the smoothed average of the lowest price values.
- The Average Band is the midpoint of the High and Low Bands.
3. Plotting the Bands
The Algo Bands indicator plots three main lines on the price chart:
- High Band : Plotted as a red step line, representing resistance levels.
- Low Band : Plotted as a green step line, indicating support levels.
- Average Band : Plotted as an orange line, showing the midpoint or equilibrium price.
4. Buy and Sell Conditions
Sell Condition:
The indicator triggers a sell signal when either of the following conditions is met:
A. Crossunder Condition :
- The closing price crosses below the High Band.
- The candle closes below its open price, confirming bearish sentiment.
- The closing price remains below both the High Band and the previous bar's open price.
B. Rejection Condition :
- The high price exceeds the High Band during the bar.
- However, the closing price fails to hold above the High Band and closes lower than both the High Band and the open price.
Buy Condition:
The indicator triggers a buy signal when either of the following conditions is met:
A. Crossover Condition :
- The closing price crosses above the Low Band.
- The candle closes above its open price, indicating bullish momentum.
- The closing price remains above both the Low Band and the previous bar's open price.
B. Rejection Condition :
- The low price dips below the Low Band during the bar.
- However, the closing price recovers and closes higher than both the Low Band and the open price.
5. Signal Visualization
The indicator visually represents buy and sell signals as follows:
- Sell Signals : Displayed as a red downward label (🔴) above the bar.
- Buy Signals : Displayed as a green upward label (🟢) below the bar.
The background colors between the bands also reflect market direction:
- Red for bearish trends.
- Green for bullish trends.
6. Alerts
The Algo Bands indicator includes customizable alerts to notify traders of trading signals:
- Alerts are triggered when Buy or Sell conditions are met.
- Integration with Telegram allows real-time notifications for immediate action.
7. Multi-Timeframe Analysis
The indicator supports analysis across multiple timeframes, including:
- 1 Hour
- 4 Hours
- Daily
It calculates the High and Low Bands for these timeframes to provide a comprehensive view of the market trend.
HOW DOES THE INDICATOR WORK?
1. Price Band Calculation :
- The highest and lowest price values are dynamically identified for a user-defined range.
- These values are smoothed using SMMA to produce the High Band and Low Band.
2. Signal Generation :
- Sell signals occur when the price crosses below or rejects the High Band.
- Buy signals occur when the price crosses above or rejects the Low Band.
3. Visualization :
- The bands are plotted on the chart to display resistance, support, and price equilibrium.
- Buy and Sell signals are marked with labels and color-coded backgrounds.
4. Alerts :
- Custom alerts notify traders in real time when signals are triggered.
BENEFITS OF THE ALGO BANDS INDICATOR:
- Trend Identification : Identifies support, resistance, and price equilibrium levels.
- Clear Buy/Sell Signals : Helps traders make timely entry and exit decisions.
- Noise Reduction : SMMA smoothing minimizes false signals.
- Multi-Timeframe Analysis : Provides insights across 1-hour, 4-hour, and daily timeframes.
- Customizable Parameters : Users can adjust settings for their trading style.
- Real-Time Alerts : Immediate notifications ensure timely actions.
- Visual Clarity : Labels and background colors enhance signal visibility.
- Ease of Use : Suitable for traders of all levels, from beginners to experts.
If you have any ideas what to add to my work to add more sources or make calculations cooler, suggest in DM .
Mean Reversion IndicatorSMA with Deviation and Z-Score Indicator
Overview:
This indicator combines the Simple Moving Average (SMA) with statistical measures of price deviation to identify potential buy and sell signals based on mean reversion principles. It calculates the Z-Score, which quantifies how far the current price is from its moving average in terms of standard deviations, helping traders spot when an asset might be overbought or oversold.
Key Features:
SMA Calculation: Uses a user-defined period to compute a Simple Moving Average, providing a baseline for price movement.
Z-Score: Measures the number of standard deviations the current price is from the SMA. This is crucial for identifying extreme price movements.
Formula: Z-Score = (Current Price - SMA) / Standard Deviation
Signal Generation:
Buy Signal: Generated when the Z-Score falls below a predefined threshold, suggesting the price is significantly below its mean and potentially undervalued.
Sell Signal: Triggered when the Z-Score exceeds another threshold, indicating the price is significantly above its mean and possibly overvalued.
Visual Indicators:
SMA Line: Plotted in blue on the chart for easy reference.
Z-Score Line: Available but hidden by default, can be shown if needed for deeper analysis.
Buy/Sell Signals: Represented by green up-arrows for buy signals and red down-arrows for sell signals.
Background Color: Changes to green or red subtly to indicate buy or sell zones based on Z-Score thresholds.
Z-Score Label: Provides the numerical Z-Score for each bar, aiding in precise decision-making.
Customizable Parameters:
SMA Length: Adjust the period over which the SMA is calculated.
Lookback Period: Set the number of periods for calculating the standard deviation and Z-Score.
Buy/Sell Z-Scores: Thresholds for generating buy and sell signals can be tailored to your strategy or market conditions. FX:EURUSD FX:EURUSD
Usage Tips:
This indicator is best used in conjunction with other forms of analysis for confirmation. Mean reversion does not always hold in trending markets.
Adjust the Z-Score thresholds based on asset volatility for more or less frequent signals.
Backtest with historical data to optimize settings for your specific trading approach.
Note: While this indicator can help identify potential trading opportunities based on statistical anomalies, it does not guarantee success and should be part of a broader trading strategy that includes risk management and market context understanding.
ETH - 12HR Double Kernel Regression Strategy ETH Double Kernel Regression Strategy
This ETH -focused, 12-hour Double Kernel Regression strategy is designed to cut through market noise and guide you toward data-backed, higher-probability trades. By utilizing two kernel regression models—Fast and Slow—this approach gauges momentum shifts and confirms trends. The strategy intelligently switches between these kernels based on identifying FOMO patterns, allowing it to adapt to changing market conditions. This ensures you enter trades when the trend is genuinely gaining strength, rather than blindly "buying the dip."
Key Concepts
Fine-Tuned Since Inception:
The strategy’s logic and filters—including price thresholds, trend moving averages (MAs), and kernel confirmations—are meticulously fine-tuned to perform consistently across all market conditions. This proactive planning enables confident entries during bullish recoveries, eliminating the need to second-guess every signal.
“Buy the Rise, Sell the Dip” Logic:
Unlike the traditional mantra, this strategy waits for slow kernel confirmation before entering uptrends. When market conditions shift, it identifies optimal entry points and holds steady if the trade isn’t losing money. This reduces guesswork and helps prevent buying into false rallies.
Sell the Hype:
The crypto market is often cluttered with noise—meme coins, last-minute hype, and social media influencers. The Double Kernel Regression approach distinguishes genuine trends from hype-driven movements. When the price exceeds simple moving averages (SMAs), the fast kernel generates a sell signal. This carefully crafted strategy helps you navigate the chaotic landscape, especially during hype-driven rallies, and ensures you sell at the top.
Try It Out
Import this strategy into your TradingView platform and observe how it reacts in real-time as market conditions change. Evaluate the signals, adjust parameters if necessary, and experience firsthand how combining sound trading philosophy with a data-driven backbone can transform your trading journey.
Moving Average Cross; Linear RegressionThis Pine Script is designed to display smoothed linear regression lines on a chart, with an option to adjust the regression period lengths and smoothing factor. The script calculates short-term and long-term linear regression lines based on the selected timeframe. These regression lines act as a regressed moving average cross , visually representing the interaction between the two smoothed linear regressions.
Short Regression Line: A linear regression line based on a short lookback period, colored blue for an uptrend and orange for a downtrend .
Long Regression Line: A linear regression line based on a longer lookback period, similarly colored blue for an uptrend and orange for a downtrend .
The script provides input options to adjust:
The length of short and long regression periods.
The smoothing length for the regression lines.
The timeframe for the linear regression calculations.
This tool can help traders observe the crossovers between the two smoothed linear regression lines, which are similar to moving average crossovers, but with the added benefit of regression-based smoothing to reduce noise. The color-coding allows for easy trend identification, with blue indicating an uptrend and orange indicating a downtrend.
Log Regression OscillatorThe Log Regression Oscillator transforms the logarithmic regression curves into an easy-to-interpret oscillator that displays potential cycle tops/bottoms.
🔶 USAGE
Calculating the logarithmic regression of long-term swings can help show future tops/bottoms. The relationship between previous swing points is calculated and projected further. The calculated levels are directly associated with swing points, which means every swing point will change the calculation. Importantly, all levels will be updated through all bars when a new swing is detected.
The "Log Regression Oscillator" transforms the calculated levels, where the top level is regarded as 100 and the bottom level as 0. The price values are displayed in between and calculated as a ratio between the top and bottom, resulting in a clear view of where the price is situated.
The main picture contains the Logarithmic Regression Alternative on the chart to compare with this published script.
Included are the levels 30 and 70. In the example of Bitcoin, previous cycles showed a similar pattern: the bullish parabolic was halfway when the oscillator passed the 30-level, and the top was very near when passing the 70-level.
🔹 Proactive
A "Proactive" option is included, which ensures immediate calculations of tentative unconfirmed swings.
Instead of waiting 300 bars for confirmation, the "Proactive" mode will display a gray-white dot (not confirmed swing) and add the unconfirmed Swing value to the calculation.
The above example shows that the "Calculated Values" of the potential future top and bottom are adjusted, including the provisional swing.
When the swing is confirmed, the calculations are again adjusted, showing a red dot (confirmed top swing) or a green dot (confirmed bottom swing).
🔹 Dashboard
When less than two swings are available (top/bottom), this will be shown in the dashboard.
The user can lower the "Threshold" value or switch to a lower timeframe.
🔹 Notes
Logarithmic regression is typically used to model situations where growth or decay accelerates rapidly at first and then slows over time, meaning some symbols/tickers will fit better than others.
Since the logarithmic regression depends on swing values, each new value will change the calculation. A well-fitted model could not fit anymore in the future.
Users have to check the validity of swings; for example, if the direction of swings is downwards, then the dataset is not fitted for logarithmic regression.
In the example above, the "Threshold" is lowered. However, the calculated levels are unreliable due to the swings, which do not fit the model well.
Here, the combination of downward bottom swings and price accelerates slower at first and faster recently, resulting in a non-fit for the logarithmic regression model.
Note the price value (white line) is bound to a limit of 150 (upwards) and -150 (down)
In short, logarithmic regression is best used when there are enough tops/bottoms, and all tops are around 100, and all bottoms around 0.
Also, note that this indicator has been developed for a daily (or higher) timeframe chart.
🔶 DETAILS
In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length sequences of numbers (arrays) and returns a single number, the sum of the products of the corresponding entries of the two sequences of numbers.
The usual way is to loop through both arrays and sum the products.
In this case, the two arrays are transformed into a matrix, wherein in one matrix, a single column is filled with the first array values, and in the second matrix, a single row is filled with the second array values.
After this, the function matrix.mult() returns a new matrix resulting from the product between the matrices m1 and m2.
Then, the matrix.eigenvalues() function transforms this matrix into an array, where the array.sum() function finally returns the sum of the array's elements, which is the dot product.
dot(x, y)=>
if x.size() > 1 and y.size() > 1
m1 = matrix.new()
m2 = matrix.new()
m1.add_col(m1.columns(), y)
m2.add_row(m2.rows (), x)
m1.mult (m2)
.eigenvalues()
.sum()
🔶 SETTINGS
Threshold: Period used for the swing detection, with higher values returning longer-term Swing Levels.
Proactive: Tentative Swings are included with this setting enabled.
Style: Color Settings
Dashboard: Toggle, "Location" and "Text Size"
Custom Strategy: ETH Martingale 2.0Strategic characteristics
ETH Little Martin 2.0 is a self-developed trading strategy based on the Martingale strategy, mainly used for trading ETH (Ethereum). The core idea of this strategy is to place orders in the same direction at a fixed price interval, and then use Martin's multiple investment principle to reduce losses, but this is also the main source of losses.
Parameter description:
1 Interval: The minimum spacing for taking profit, stop loss, and opening/closing of orders. Different targets have different spacing. Taking ETH as an example, it is generally recommended to have a spacing of 2% for fluctuations in the target.
2 Base Price: This is the price at which you triggered the first order. Similarly, I am using ETH as an example. If you have other targets, I suggest using the initial value of a price that can be backtesting. The Base Price is only an initial order price and has no impact on subsequent orders.
3 Initial Order Amount: Users can set an initial order amount to control the risk of each transaction. If the stop loss is reached, we will double the amount based on this value. This refers to the value of the position held, not the number of positions held.
4 Loss Multiplier: The strategy will increase the next order amount based on the set multiple after the stop loss, in order to make up for the previous losses through a larger position. Note that after taking profit, it will be reset to 1 times the Initial Order Amount.
5. Long Short Operation: The first order of the strategy is a multiple entry, and in subsequent orders, if the stop loss is reached, a reverse order will be opened. The position value of a one-way order is based on the Loss Multiplier multiple investment, so it is generally recommended that the Loss Multiplier default to 2.
Improvement direction
Although this strategy already has a certain trading logic, there are still some improvement directions that can be considered:
1. Dynamic adjustment of spacing: Currently, the spacing is fixed, and it can be considered to dynamically adjust the spacing based on market volatility to improve the adaptability of the strategy. Try using dynamic spacing, which may be more suitable for the actual market situation.
2. Filtering criteria: Orders and no orders can be optimized separately. The biggest problem with this strategy is that it will result in continuous losses during fluctuations, and eventually increase the investment amount. You can consider filtering out some fluctuations or only focusing on trend trends.
3. Risk management: Add more risk management measures, such as setting a maximum loss limit to avoid huge losses caused by continuous stop loss.
4. Optimize the stop loss multiple: Currently, the stop loss multiple is fixed, and it can be considered to dynamically adjust the multiple according to market conditions to reduce risk.
Engulfing Candle IndicatorThis indicator helps identify Bullish and Bearish Engulfing candle patterns on your chart.
Bullish Engulfing: Occurs when a green candle completely engulfs the prior red candle, signaling potential upward momentum.
Bearish Engulfing: Occurs when a red candle completely engulfs the prior green candle, signaling potential downward momentum.
The script highlights these patterns with green triangles below the bars for Bullish Engulfing and red triangles above the bars for Bearish Engulfing.
This tool is helpful for traders who use candlestick patterns as part of their technical analysis strategy.
Salience Theory Crypto Returns (AiBitcoinTrend)The Salience Theory Crypto Returns Indicator is a sophisticated tool rooted in behavioral finance, designed to identify trading opportunities in the cryptocurrency market. Based on research by Bordalo et al. (2012) and extended by Cai and Zhao (2022), it leverages salience theory—the tendency of investors, particularly retail traders, to overemphasize standout returns.
In the crypto market, dominated by sentiment-driven retail investors, salience effects are amplified. Attention disproportionately focused on certain cryptocurrencies often leads to temporary price surges, followed by reversals as the market stabilizes. This indicator quantifies these effects using a relative return salience measure, enabling traders to capitalize on price reversals and trends, offering a clear edge in navigating the volatile crypto landscape.
👽 How the Indicator Works
Salience Measure Calculation :
👾 The indicator calculates how much each cryptocurrency's return deviates from the average return of all cryptos over the selected ranking period (e.g., 21 days).
👾 This deviation is the salience measure.
👾 The more a return stands out (salient outcome), the higher the salience measure.
Ranking:
👾 Cryptos are ranked in ascending order based on their salience measures.
👾 Rank 1 (lowest salience) means the crypto is closer to the average return and is more predictable.
👾 Higher ranks indicate greater deviation and unpredictability.
Color Interpretation:
👾 Green: Low salience (closer to average) – Trending or Predictable.
👾 Red/Orange: High salience (far from average) – Overpriced/Unpredictable.
👾 Text Gradient (Teal to Light Blue): Helps visualize potential opportunities for mean reversion trades (i.e., cryptos that may return to equilibrium).
👽 Core Features
Salience Measure Calculation
The indicator calculates the salience measure for each cryptocurrency by evaluating how much its return deviates from the average market return over a user-defined ranking period. This measure helps identify which assets are trending predictably and which are likely to experience a reversal.
Dynamic Ranking System
Cryptocurrencies are dynamically ranked based on their salience measures. The ranking helps differentiate between:
Low Salience Cryptos (Green): These are trending or predictable assets.
High Salience Cryptos (Red): These are overpriced or deviating significantly from the average, signaling potential reversals.
👽 Deep Dive into the Core Mathematics
Salience Theory in Action
Salience theory explains how investors, particularly in the crypto market, tend to prefer assets with standout returns (salient outcomes). This behavior often leads to overpricing of assets with high positive returns and underpricing of those with standout negative returns. The indicator captures these deviations to anticipate mean reversions or trend continuations.
Salience Measure Calculation
// Calculate the average return
avgReturn = array.avg(returns)
// Calculate salience measure for each symbol
salienceMeasures = array.new_float()
for i = 0 to array.size(returns) - 1
ret = array.get(returns, i)
salienceMeasure = math.abs(ret - avgReturn) / (math.abs(ret) + math.abs(avgReturn) + 0.1)
array.push(salienceMeasures, salienceMeasure)
Dynamic Ranking
Cryptos are ranked in ascending order based on their salience measures:
Low Ranks: Cryptos with low salience (predictable, trending).
High Ranks: Cryptos with high salience (unpredictable, likely to revert).
👽 Applications
👾 Trend Identification
Identify cryptocurrencies that are currently trending with low salience measures (green). These assets are likely to continue their current direction, making them good candidates for trend-following strategies.
👾 Mean Reversion Trading
Cryptos with high salience measures (red to light blue) may be poised for a mean reversion. These assets are likely to correct back towards the market average.
👾 Reversal Signals
Anticipate potential reversals by focusing on high-ranked cryptos (red). These assets exhibit significant deviation and are prone to price corrections.
👽 Why It Works in Crypto
The cryptocurrency market is dominated by retail investors prone to sentiment-driven behavior. This leads to exaggerated price movements, making the salience effect a powerful predictor of reversals.
👽 Indicator Settings
👾 Ranking Period : Number of bars used to calculate the average return and salience measure.
Higher Values: Smooth out short-term volatility.
Lower Values: Make the ranking more sensitive to recent price movements.
👾 Number of Quantiles : Divide ranked assets into quantile groups (e.g., quintiles).
Higher Values: More detailed segmentation (deciles, percentiles).
Lower Values: Broader grouping (quintiles, quartiles).
👾 Portfolio Percentage : Percentage of the portfolio allocated to each selected asset.
Enter a percentage (e.g., 20 for 20%), automatically converted to a decimal (e.g., 0.20).
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.