[Pandora] Vast Volatility Treasure TroveINTRODUCTION: 
Volatility enthusiasts, prepare for VICTORY on this day of July 4th, 2024! This is my "Vast Volatility Treasure Trove," intended mostly for educational purposes, yet these functions will also exhibit versatility when combined with other algorithms to garner statistical excellence. Once again, I am now ripping the lid off of Pandora's box... of volatility. Inside this script is a 'vast' collection of volatility estimators, reflecting the indicators name. Whether you are a seasoned trader destined to navigate financial strife or an eagerly curious learner, this script offers a comprehensive toolkit for a broad spectrum of volatility analysis. Enjoy your journey through the realm of market volatility with this code!
 WHAT IS MARKET VOLATILITY?: 
Market volatility refers to various fluctuations in the value of a financial market or asset over a period of time, often characterized by occasional rapid and significant deviations in price. During periods of greater market volatility, evolving conditions of prices can move rapidly in either direction, creating uncertainty for investors with results of sharp declines as well as rapid gains. However, market volatility is a typical aspect expected in financial markets that can also present opportunities for informed decision-making and potential benefits from the price flux.
 SCRIPT INTENTION: 
Volatility is assuredly omnipresent, waxing and waning in magnitude, and some readers have every intention of studying and/or measuring it. This script serves as an all-in-one armada of volatility estimators for TradingView members. I set out to provide a diverse set of tools to analyze and interpret market volatility, offering volatile insights, and aid with the development of robust trading indicators and strategies.
In today's fast-paced financial markets, understanding and quantifying volatility is informative for both seasoned traders and novice investors. This script is designed to empower users by equipping them with a comprehensive suite of volatility estimators. Each function within this script has been meticulously crafted to address various aspects of volatility, from traditional methods like Garman-Klass and Parkinson to more advanced techniques like Yang-Zhang and my custom experimental algorithms.
Ultimately, this script is more than just a collection of functions. It is a gateway to a deeper understanding of market volatility and a valuable resource for anyone committed to mastering the complexities of financial markets.
 SCRIPT CONTENTS: 
This script includes a variety of functions designed to measure and analyze market volatility. Where applicable, an input checkbox option provides an unbiased/biased estimate. Below is a brief description of each function in the original order they appear as code upon first publish:
 Parkinson Volatility  - Estimates volatility emphasizing the high and low range movements.
 Alternate Parkinson Volatility  - Simpler version of the original Parkinson Volatility that I realized.
 Garman-Klass Volatility  - Estimates volatility based on high, low, open, and close prices using a formula that adjusts for biases in price dynamics.
 Rogers-Satchell-Yoon Volatility #1  - Estimates volatility based on logarithmic differences between high, low, open, and close values.
 Rogers-Satchell-Yoon Volatility #2  - Similar estimate to Rogers-Satchell with the same result via an alternate formulation of volatility.
 Yang-Zhang Volatility  - An advanced volatility estimate combining both strengths of the Garman-Klass and Rogers-Satchell estimators, with weights determined by an alpha parameter.
 Yang-Zhang (Modified) Volatility  - My experimental modification slightly different from the Yang-Zhang formula with improved computational efficiency.
 Selectable Volatility  - Basic customizable volatility calculation based on the logarithmic difference between selected numerator and denominator prices (e.g., open, high, low, close).
 Close-to-Close Volatility  - Estimates volatility using the logarithmic difference between consecutive closing prices. Specifically applicable to data sources without open, high, and low prices.
 Open-to-Close Volatility  - (Overnight Volatility): Estimates volatility based on the logarithmic difference between the opening price and the last closing price emphasizing overnight gaps.
 Hilo Volatility  - Estimates volatility using a method similar to Parkinson's method, which considers the logarithm of the high and low prices.
 Vantage Volatility  - My experimental custom 'vantage' method to estimate volatility similar to Yang-Zhang, which incorporates various factors (Alpha, Beta, Gamma) to generate a weighted logarithmic calculation. This may be a volatility advantage or disadvantage, hence it's name.
 Schwert Volatility  - Estimates volatility based on arithmetic returns.
 Historical Volatility  - Estimates volatility considering logarithmic returns.
 Annualized Historical Volatility  - Estimates annualized volatility using logarithmic returns, adjusted for the number of trading days in a year.
If I omitted any other known varieties, detailed requests for future consideration can be made below for their inclusion into this script within future versions...
 BONUS ALGORITHMS: 
This script also includes several experimental and bonus functions that push the boundaries of volatility analysis as I understand it. These functions are designed to provide additional insights and also are my ideal notions for traders looking to explore other methods of volatility measurement.
 VOLATILITY APPLICATIONS: 
Volatility estimators serve a common role across various facets of trading and financial analysis, offering insights into market behavior. These tools are already in instrumental with enhancing risk management practices by providing a deeper understanding of market dynamics and the inherent uncertainty in asset prices. With volatility estimators, traders can effectively quantifying market risk and adjust their strategies accordingly, optimizing portfolio performance and mitigating potential losses. Additionally, volatility estimations may serve as indication for detecting overbought or oversold market conditions, offering probabilistic insights that could inform strategic decisions at turning points. This script 
distinctly offers a variety of volatility estimators to navigate intricate financial terrains with informed judgment to address challenges of strategic planning.
 CODE REUSE: 
You don't have to ask for my permission to use/reuse these functions in your published scripts, simply because I have better things to do than answer requests for the reuse of these functions.
 Notice:  Unfortunately, I will not provide any integration support into member's projects at all. I have my own projects that require way too much of my day already.
חפש סקריפטים עבור "algo"
Endpointed SSA of Price [Loxx]The Endpointed SSA of Price: A Comprehensive Tool for Market Analysis and Decision-Making 
The financial markets present sophisticated challenges for traders and investors as they navigate the complexities of market behavior. To effectively interpret and capitalize on these complexities, it is crucial to employ powerful analytical tools that can reveal hidden patterns and trends. One such tool is the Endpointed SSA of Price, which combines the strengths of Caterpillar Singular Spectrum Analysis, a sophisticated time series decomposition method, with insights from the fields of economics, artificial intelligence, and machine learning.
The Endpointed SSA of Price has its roots in the interdisciplinary fusion of mathematical techniques, economic understanding, and advancements in artificial intelligence. This unique combination allows for a versatile and reliable tool that can aid traders and investors in making informed decisions based on comprehensive market analysis.
The Endpointed SSA of Price is not only valuable for experienced traders but also serves as a useful resource for those new to the financial markets. By providing a deeper understanding of market forces, this innovative indicator equips users with the knowledge and confidence to better assess risks and opportunities in their financial pursuits.
 █ Exploring Caterpillar SSA: Applications in AI, Machine Learning, and Finance 
Caterpillar SSA (Singular Spectrum Analysis) is a non-parametric method for time series analysis and signal processing. It is based on a combination of principles from classical time series analysis, multivariate statistics, and the theory of random processes. The method was initially developed in the early 1990s by a group of Russian mathematicians, including Golyandina, Nekrutkin, and Zhigljavsky.
 Background Information: 
SSA is an advanced technique for decomposing time series data into a sum of interpretable components, such as trend, seasonality, and noise. This decomposition allows for a better understanding of the underlying structure of the data and facilitates forecasting, smoothing, and anomaly detection. Caterpillar SSA is a particular implementation of SSA that has proven to be computationally efficient and effective for handling large datasets.
 Uses in AI and Machine Learning: 
In recent years, Caterpillar SSA has found applications in various fields of artificial intelligence (AI) and machine learning. Some of these applications include:
1. Feature extraction: Caterpillar SSA can be used to extract meaningful features from time series data, which can then serve as inputs for machine learning models. These features can help improve the performance of various models, such as regression, classification, and clustering algorithms.
2. Dimensionality reduction: Caterpillar SSA can be employed as a dimensionality reduction technique, similar to Principal Component Analysis (PCA). It helps identify the most significant components of a high-dimensional dataset, reducing the computational complexity and mitigating the "curse of dimensionality" in machine learning tasks.
3. Anomaly detection: The decomposition of a time series into interpretable components through Caterpillar SSA can help in identifying unusual patterns or outliers in the data. Machine learning models trained on these decomposed components can detect anomalies more effectively, as the noise component is separated from the signal.
4. Forecasting: Caterpillar SSA has been used in combination with machine learning techniques, such as neural networks, to improve forecasting accuracy. By decomposing a time series into its underlying components, machine learning models can better capture the trends and seasonality in the data, resulting in more accurate predictions.
 Application in Financial Markets and Economics: 
Caterpillar SSA has been employed in various domains within financial markets and economics. Some notable applications include:
1. Stock price analysis: Caterpillar SSA can be used to analyze and forecast stock prices by decomposing them into trend, seasonal, and noise components. This decomposition can help traders and investors better understand market dynamics, detect potential turning points, and make more informed decisions.
2. Economic indicators: Caterpillar SSA has been used to analyze and forecast economic indicators, such as GDP, inflation, and unemployment rates. By decomposing these time series, researchers can better understand the underlying factors driving economic fluctuations and develop more accurate forecasting models.
3. Portfolio optimization: By applying Caterpillar SSA to financial time series data, portfolio managers can better understand the relationships between different assets and make more informed decisions regarding asset allocation and risk management.
 Application in the Indicator:
 
In the given indicator, Caterpillar SSA is applied to a financial time series (price data) to smooth the series and detect significant trends or turning points. The method is used to decompose the price data into a set number of components, which are then combined to generate a smoothed signal. This signal can help traders and investors identify potential entry and exit points for their trades.
The indicator applies the Caterpillar SSA method by first constructing the trajectory matrix using the price data, then computing the singular value decomposition (SVD) of the matrix, and finally reconstructing the time series using a selected number of components. The reconstructed series serves as a smoothed version of the original price data, highlighting significant trends and turning points. The indicator can be customized by adjusting the lag, number of computations, and number of components used in the reconstruction process. By fine-tuning these parameters, traders and investors can optimize the indicator to better match their specific trading style and risk tolerance.
Caterpillar SSA is versatile and can be applied to various types of financial instruments, such as stocks, bonds, commodities, and currencies. It can also be combined with other technical analysis tools or indicators to create a comprehensive trading system. For example, a trader might use Caterpillar SSA to identify the primary trend in a market and then employ additional indicators, such as moving averages or RSI, to confirm the trend and generate trading signals.
In summary, Caterpillar SSA is a powerful time series analysis technique that has found applications in AI and machine learning, as well as financial markets and economics. By decomposing a time series into interpretable components, Caterpillar SSA enables better understanding of the underlying structure of the data, facilitating forecasting, smoothing, and anomaly detection. In the context of financial trading, the technique is used to analyze price data, detect significant trends or turning points, and inform trading decisions.
 █ Input Parameters 
This indicator takes several inputs that affect its signal output. These inputs can be classified into three categories: Basic Settings, UI Options, and Computation Parameters.
Source: This input represents the source of price data, which is typically the closing price of an asset. The user can select other price data, such as opening price, high price, or low price. The selected price data is then utilized in the Caterpillar SSA calculation process.
Lag: The lag input determines the window size used for the time series decomposition. A higher lag value implies that the SSA algorithm will consider a longer range of historical data when extracting the underlying trend and components. This parameter is crucial, as it directly impacts the resulting smoothed series and the quality of extracted components.
Number of Computations: This input, denoted as 'ncomp,' specifies the number of eigencomponents to be considered in the reconstruction of the time series. A smaller value results in a smoother output signal, while a higher value retains more details in the series, potentially capturing short-term fluctuations.
SSA Period Normalization: This input is used to normalize the SSA period, which adjusts the significance of each eigencomponent to the overall signal. It helps in making the algorithm adaptive to different timeframes and market conditions.
Number of Bars: This input specifies the number of bars to be processed by the algorithm. It controls the range of data used for calculations and directly affects the computation time and the output signal.
Number of Bars to Render: This input sets the number of bars to be plotted on the chart. A higher value slows down the computation but provides a more comprehensive view of the indicator's performance over a longer period. This value controls how far back the indicator is rendered. 
Color bars: This boolean input determines whether the bars should be colored according to the signal's direction. If set to true, the bars are colored using the defined colors, which visually indicate the trend direction.
Show signals: This boolean input controls the display of buy and sell signals on the chart. If set to true, the indicator plots shapes (triangles) to represent long and short trade signals.
 Static Computation Parameters: 
The indicator also includes several internal parameters that affect the Caterpillar SSA algorithm, such as Maxncomp, MaxLag, and MaxArrayLength. These parameters set the maximum allowed values for the number of computations, the lag, and the array length, ensuring that the calculations remain within reasonable limits and do not consume excessive computational resources.
 █ A Note on Endpionted, Non-repainting Indicators 
An endpointed indicator is one that does not recalculate or repaint its past values based on new incoming data. In other words, the indicator's previous signals remain the same even as new price data is added. This is an important feature because it ensures that the signals generated by the indicator are reliable and accurate, even after the fact.
When an indicator is non-repainting or endpointed, it means that the trader can have confidence in the signals being generated, knowing that they will not change as new data comes in. This allows traders to make informed decisions based on historical signals, without the fear of the signals being invalidated in the future.
In the case of the Endpointed SSA of Price, this non-repainting property is particularly valuable because it allows traders to identify trend changes and reversals with a high degree of accuracy, which can be used to inform trading decisions. This can be especially important in volatile markets where quick decisions need to be made.
Bogdan Ciocoiu - LitigatorDescription 
The Litigator is an indicator that encapsulates the value delivered by the Relative Strength Index, Ultimate Oscillator, Stochastic and Money Flow Index algorithms to produce signals enabling users to enter positions in ideal market conditions. The Litigator integrates the value delivered by the above four algorithms into one script.
This indicator is handy when trading continuation/reversal divergence strategies in conjunction with price action.
 Uniqueness 
The Litigator's uniqueness stands from integrating the above algorithms into the same visual area and leveraging preconfigured parameters suitable for short term scalping (1-5 minutes).
In addition, the Litigator allows configuring the above four algorithms in such a way to coordinate signals by colour-coding or shape thickness to aid the user with identifying any emerging patterns quicker.
Furthermore, Moonshot's uniqueness is also reflected in the way it has standardised the outputs of each algorithm to look and feel the same, and in doing so, enabling users to plug them in/out as needed. This also includes ensuring the ratios of the shapes are similar (applicable to the same scale).
 Open-source 
The indicator uses the following open-source scripts/algorithms:
www.tradingview.com
www.tradingview.com
www.tradingview.com
www.tradingview.com
Bogdan Ciocoiu - MoonshotDescription 
Moonshot is an indicator that encapsulates the value delivered by the TSI, MACD, Awesome Oscillator and CCI algorithms to produce signals to enable users to enter positions in ideal market conditions. Moonshot integrates the value delivered by the above four algorithms into one script.
This indicator is particularly useful when trading continuation/reversal divergence strategies.
 Uniqueness 
The Moonshot's uniqueness stands from integrating the above algorithms into the same visual area and leveraging preconfigured parameters suitable for 1-3 minute scalping techniques.
In addition, Moonshot allows swapping or furthermore configuring the above four algorithms in such a way to align signals by colour-coding or shape thickness to aid the users with identifying any emerging patterns quicker.
Furthermore, Moonshot's uniqueness is also reflected in the way it has standardised the outputs of each algorithm to look and feel the same (including the scale at which the shapes are shown) and, in doing so, enables users to plug them in/out as needed.
 Open-source 
The indicator leverages the following open-source scripts/algorithms:
www.tradingview.com
www.tradingview.com
www.tradingview.com
www.tradingview.com
LengthAdaptationCollection of dynamic length adaptation algorithms. Mostly from various Adaptive Moving Averages (they are usually just EMA otherwise). Now you can combine Adaptations with any other Moving Averages or Oscillators (see my other libraries), to get something like Deviation Scaled RSI or Fractal Adaptive VWMA. This collection is not encyclopaedic. Suggestions are welcome.
 chande(src, len, sdlen, smooth, power)  Chande's Dynamic Length
  Parameters:
     src : Series to use
     len : Reference lookback length
     sdlen : Lookback length of Standard deviation
     smooth : Smoothing length of Standard deviation
     power : Exponent of the length adaptation (lower is smaller variation)
  Returns: Calculated period
Taken from Chande's Dynamic Momentum Index (CDMI or DYMOI), which is dynamic RSI with this length
Original default power value is 1, but I use 0.5
A variant of this algorithm is also included, where volume is used instead of price
 vidya(src, len, dynLow)  Variable Index Dynamic Average Indicator (VIDYA)
  Parameters:
     src : Series to use
     len : Reference lookback length
     dynLow : Lower bound for the dynamic length
  Returns: Calculated period
Standard VIDYA algorithm. The period oscillates from the Lower Bound up (slow)
I took the adaptation part, as it is just an EMA otherwise
 vidyaRS(src, len, dynHigh)  Relative Strength Dynamic Length - VIDYA RS
  Parameters:
     src : Series to use
     len : Reference lookback length
     dynHigh : Upper bound for the dynamic length
  Returns: Calculated period
Based on Vitali Apirine's modification (Stocks and Commodities, January 2022) of VIDYA algorithm. The period oscillates from the Upper Bound down (fast)
I took the adaptation part, as it is just an EMA otherwise
 kaufman(src, len, dynLow, dynHigh)  Kaufman Efficiency Scaling
  Parameters:
     src : Series to use
     len : Reference lookback length
     dynLow : Lower bound for the dynamic length
     dynHigh : Upper bound for the dynamic length
  Returns: Calculated period
Based on Efficiency Ratio calculation orifinally used in Kaufman Adaptive Moving Average developed by Perry J. Kaufman
I took the adaptation part, as it is just an EMA otherwise
 ds(src, len)  Deviation Scaling
  Parameters:
     src : Series to use
     len : Reference lookback length
  Returns: Calculated period
Based on Derivation Scaled Super Smoother (DSSS) by John F. Ehlers
Originally used with Super Smoother
RMS originally has 50 bar lookback. Changed to 4x length for better flexibility. Could be wrong.
 maa(src, len, threshold)  Median Average Adaptation
  Parameters:
     src : Series to use
     len : Reference lookback length
     threshold : Adjustment threshold (lower is smaller length, default: 0.002, min: 0.0001)
  Returns: Calculated period
Based on Median Average Adaptive Filter by John F. Ehlers
Discovered and implemented by @cheatcountry: 
I took the adaptation part, as it is just an EMA otherwise
 fra(len, fc, sc)  Fractal Adaptation
  Parameters:
     len : Reference lookback length
     fc : Fast constant (default: 1)
     sc : Slow constant (default: 200)
  Returns: Calculated period
Based on FRAMA by John F. Ehlers
Modified to allow lower and upper bounds by an unknown author
I took the adaptation part, as it is just an EMA otherwise
 mama(src, dynLow, dynHigh)  MESA Adaptation - MAMA Alpha
  Parameters:
     src : Series to use
     dynLow : Lower bound for the dynamic length
     dynHigh : Upper bound for the dynamic length
  Returns: Calculated period
Based on MESA Adaptive Moving Average by John F. Ehlers
Introduced in the September 2001 issue of Stocks and Commodities
Inspired by the @everget implementation: 
I took the adaptation part, as it is just an EMA otherwise
 doAdapt(type, src, len, dynLow, dynHigh, chandeSDLen, chandeSmooth, chandePower)  Execute a particular Length Adaptation from the list
  Parameters:
     type : Length Adaptation type to use
     src : Series to use
     len : Reference lookback length
     dynLow : Lower bound for the dynamic length
     dynHigh : Upper bound for the dynamic length
     chandeSDLen : Lookback length of Standard deviation for Chande's Dynamic Length
     chandeSmooth : Smoothing length of Standard deviation for Chande's Dynamic Length
     chandePower : Exponent of the length adaptation for Chande's Dynamic Length (lower is smaller variation)
  Returns: Calculated period (float, not limited)
 doMA(type, src, len)  MA wrapper on wrapper: if DSSS is selected, calculate it here
  Parameters:
     type : MA type to use
     src : Series to use
     len : Filtering length
  Returns: Filtered series
Demonstration of a combined indicator: Deviation Scaled Super Smoother
DMI + HMA - No Risk ManagementDMI (Directional Movement Index) and HMA (Hull Moving Average) 
The DMI and HMA make a great combination, The DMI will gauge the market direction, while the HMA will add confirmation to the trend strength.
 What is the DMI? 
The DMI is an indicator that was developed by J. Welles Wilder in 1978. The Indicator was designed to identify in which direction the price is moving. This is done by comparing previous highs and lows and drawing 2 lines.
1. A Positive movement line
2. A Negative movement line
A third line can be added, which would be known as the ADX line or Average Directional Index. This can also be used to gauge the strength in which direction the market is moving.
When the Positive movement line (DI+) is above the Negative movement line (DI-) there is more upward pressure. Ofcourse visa versa, when the DI- is above the DI+ that would indicate more downwards pressure.
Want to know more about HMA? Check out one of our other published scripts
  
 What is this strategy doing? 
We are first waiting for the DMI to cross in our favoured direction, after that, we wait for the HMA to signal the entry. Without both conditions being true, no trade will be made.
 Long Entries 
1. DI+ crosses above DI-
2. HMA line 1 is above HMA line 2
 Short Entries 
1. DI- Crosses above DI+
2. HMA line 1 is below HMA lilne 2
Its as simple as that.
 Conclusion 
While this strategy does have its downsides, that can be reduced by adding some risk manegment into the script. In general the trade profitability is above average, And the max drawdown is at a minimum.
The settings have been optimised to suite BTCUSDT PERP markets. Though with small adjustments it can be used on many assets!
SMU Stock ThermometerThis script shows various technical indicators in a stacked vertical candle called Market Termometer.
It helps to see the price action in one single vertical column where the actual price moves up or down. So you can see the price change based on your custom setting levels.
I've been studying ALGO for over a year and made many live experiment trades long and shorts. So, I'm trying to find a way to see what is ALGos next move. If it sounds far-fetch, then you should see my other published scripts.
Here is example of how ALGo dance around old indicators, which is why I started  creating a bunch of new indicators that ALGO doesn't know
Example:
Impact-driven-algorithm= Large volume masked as small volume to keep the price at desired level. So, your chart says overbought but market doesn't drop for days
Cost-driven-algorithm= Hedge fund buy every time at lower price and prevent others to buy low, moving up fast. Is like a clock with millisecond timing and ALGO owners know when to buy low and when to sell high
If you have a good idea, let me know so i can include it the future versions.
Enjoy and think outside the box, the only way to beat the ALGO
T3 ATR [DCAUT]█ T3 ATR  
 📊 ORIGINALITY & INNOVATION 
The T3 ATR indicator represents an important enhancement to the traditional Average True Range (ATR) indicator by incorporating the T3 (Tilson Triple Exponential Moving Average) smoothing algorithm. While standard ATR uses fixed RMA (Running Moving Average) smoothing, T3 ATR introduces a configurable volume factor parameter that allows traders to adjust the smoothing characteristics from highly responsive to heavily smoothed output.
This innovation addresses a fundamental limitation of traditional ATR: the inability to adapt smoothing behavior without changing the calculation period. With T3 ATR, traders can maintain a consistent ATR period while adjusting the responsiveness through the volume factor, making the indicator adaptable to different trading styles, market conditions, and timeframes through a single unified implementation.
The T3 algorithm's triple exponential smoothing with volume factor control provides improved signal quality by reducing noise while maintaining better responsiveness compared to traditional smoothing methods. This makes T3 ATR particularly valuable for traders who need to adapt their volatility measurement approach to varying market conditions without switching between multiple indicator configurations.
 📐 MATHEMATICAL FOUNDATION 
The T3 ATR calculation process involves two distinct stages:
 Stage 1: True Range Calculation 
The True Range (TR) is calculated using the standard formula:
 
 TR = max(high - low, |high - close |, |low - close |)
 
This captures the greatest of the current bar's range, the gap from the previous close to the current high, or the gap from the previous close to the current low, providing a comprehensive measure of price movement that accounts for gaps and limit moves.
 Stage 2: T3 Smoothing Application 
The True Range values are then smoothed using the T3 algorithm, which applies six exponential moving averages in succession:
 
 First Layer: e1 = EMA(TR, period), e2 = EMA(e1, period)
 Second Layer: e3 = EMA(e2, period), e4 = EMA(e3, period)
 Third Layer: e5 = EMA(e4, period), e6 = EMA(e5, period)
 Final Calculation: T3 = c1×e6 + c2×e5 + c3×e4 + c4×e3
 
The coefficients (c1, c2, c3, c4) are derived from the volume factor (VF) parameter:
 
 a = VF / 2
 c1 = -a³
 c2 = 3a² + 3a³
 c3 = -6a² - 3a - 3a³
 c4 = 1 + 3a + a³ + 3a²
 
The volume factor parameter (0.0 to 1.0) controls the weighting of these coefficients, directly affecting the balance between responsiveness and smoothness:
 
 Lower VF values (approaching 0.0): Coefficients favor recent data, resulting in faster response to volatility changes with minimal lag but potentially more noise
 Higher VF values (approaching 1.0): Coefficients distribute weight more evenly across the smoothing layers, producing smoother output with reduced noise but slightly increased lag
 
 📊 COMPREHENSIVE SIGNAL ANALYSIS 
 Volatility Level Interpretation: 
 
 High Absolute Values: Indicate strong price movements and elevated market activity, suggesting larger position risks and wider stop-loss requirements, often associated with trending markets or significant news events
 Low Absolute Values: Indicate subdued price movements and quiet market conditions, suggesting smaller position risks and tighter stop-loss opportunities, often associated with consolidation phases or low-volume periods
 Rapid Increases: Sharp spikes in T3 ATR often signal the beginning of significant price moves or market regime changes, providing early warning of increased trading risk
 Sustained High Levels: Extended periods of elevated T3 ATR indicate sustained trending conditions with persistent volatility, suitable for trend-following strategies
 Sustained Low Levels: Extended periods of low T3 ATR indicate range-bound conditions with suppressed volatility, suitable for mean-reversion strategies
 
 Volume Factor Impact on Signals: 
 
 Low VF Settings (0.0-0.3): Produce responsive signals that quickly capture volatility changes, suitable for short-term trading but may generate more frequent color changes during minor fluctuations
 Medium VF Settings (0.4-0.7): Provide balanced signal quality with moderate responsiveness, filtering out minor noise while capturing significant volatility changes, suitable for swing trading
 High VF Settings (0.8-1.0): Generate smooth, stable signals that filter out most noise and focus on major volatility trends, suitable for position trading and long-term analysis
 
 🎯 STRATEGIC APPLICATIONS 
 Position Sizing Strategy: 
 
 Determine your risk per trade (e.g., 1% of account capital - adjust based on your risk tolerance and experience)
 Decide your stop-loss distance multiplier (e.g., 2.0x T3 ATR - this varies by market and strategy, test different values)
 Calculate stop-loss distance: Stop Distance = Multiplier × Current T3 ATR
 Calculate position size: Position Size = (Account × Risk %) / Stop Distance
 Example: $10,000 account, 1% risk, T3 ATR = 50 points, 2x multiplier → Position Size = ($10,000 × 0.01) / (2 × 50) = $100 / 100 points = 1 unit per point
 Important: The ATR multiplier (1.5x - 3.0x) should be determined through backtesting for your specific instrument and strategy - using inappropriate multipliers may result in stops that are too tight (frequent stop-outs) or too wide (excessive losses)
 Adjust the volume factor to match your trading style: lower VF for responsive stop distances in short-term trading, higher VF for stable stop distances in position trading
 
 Dynamic Stop-Loss Placement: 
 
 Determine your risk tolerance multiplier (typically 1.5x to 3.0x T3 ATR)
 For long positions: Set stop-loss at entry price minus (multiplier × current T3 ATR value)
 For short positions: Set stop-loss at entry price plus (multiplier × current T3 ATR value)
 Trail stop-losses by recalculating based on current T3 ATR as the trade progresses
 Adjust the volume factor based on desired stop-loss stability: higher VF for less frequent adjustments, lower VF for more adaptive stops
 
 Market Regime Identification: 
 
 Calculate a reference volatility level using a longer-period moving average of T3 ATR (e.g., 50-period SMA)
 High Volatility Regime: Current T3 ATR significantly above reference (e.g., 120%+) - favor trend-following strategies, breakout trades, and wider targets
 Normal Volatility Regime: Current T3 ATR near reference (e.g., 80-120%) - employ standard trading strategies appropriate for prevailing market structure
 Low Volatility Regime: Current T3 ATR significantly below reference (e.g., <80%) - favor mean-reversion strategies, range trading, and prepare for potential volatility expansion
 Monitor T3 ATR trend direction and compare current values to recent history to identify regime transitions early
 
 Risk Management Implementation: 
 
 Establish your maximum portfolio heat (total risk across all positions, typically 2-6% of capital)
 For each position: Calculate position size using the formula Position Size = (Account × Individual Risk %) / (ATR Multiplier × Current T3 ATR)
 When T3 ATR increases: Position sizes automatically decrease (same risk %, larger stop distance = smaller position)
 When T3 ATR decreases: Position sizes automatically increase (same risk %, smaller stop distance = larger position)
 This approach maintains constant dollar risk per trade regardless of market volatility changes
 Use consistent volume factor settings across all positions to ensure uniform risk measurement
 
 📋 DETAILED PARAMETER CONFIGURATION 
 ATR Length Parameter: 
Default Setting: 14 periods
 
 This is the standard ATR calculation period established by Welles Wilder, providing balanced volatility measurement that captures both short-term fluctuations and medium-term trends across most markets and timeframes
 
Selection Principles:
 
 Shorter periods increase sensitivity to recent volatility changes and respond faster to market shifts, but may produce less stable readings
 Longer periods emphasize sustained volatility trends and filter out short-term noise, but respond more slowly to genuine regime changes
 The optimal period depends on your holding time, trading frequency, and the typical volatility cycle of your instrument
 Consider the timeframe you trade: Intraday traders typically use shorter periods, swing traders use intermediate periods, position traders use longer periods
 
Practical Approach:
 
 Start with the default 14 periods and observe how well it captures volatility patterns relevant to your trading decisions
 If ATR seems too reactive to minor price movements: Increase the period until volatility readings better reflect meaningful market changes
 If ATR lags behind obvious volatility shifts that affect your trades: Decrease the period for faster response
 Match the period roughly to your typical holding time - if you hold positions for N bars, consider ATR periods in a similar range
 Test different periods using historical data for your specific instrument and strategy before committing to live trading
 
 T3 Volume Factor Parameter: 
Default Setting: 0.7
 
 This setting provides a reasonable balance between responsiveness and smoothness for most market conditions and trading styles
 
Understanding the Volume Factor:
 
 Lower values (closer to 0.0) reduce smoothing, allowing T3 ATR to respond more quickly to volatility changes but with less noise filtering
 Higher values (closer to 1.0) increase smoothing, producing more stable readings that focus on sustained volatility trends but respond more slowly
 The trade-off is between immediacy and stability - there is no universally optimal setting
 
Selection Principles:
 
 Match to your decision speed: If you need to react quickly to volatility changes for entries/exits, use lower VF; if you're making longer-term risk assessments, use higher VF
 Match to market character: Noisier, choppier markets may benefit from higher VF for clearer signals; cleaner trending markets may work well with lower VF for faster response
 Match to your preference: Some traders prefer responsive indicators even with occasional false signals, others prefer stable indicators even with some delay
 
Practical Adjustment Guidelines:
 
 Start with default 0.7 and observe how T3 ATR behavior aligns with your trading needs over multiple sessions
 If readings seem too unstable or noisy for your decisions: Try increasing VF toward 0.9-1.0 for heavier smoothing
 If the indicator lags too much behind volatility changes you care about: Try decreasing VF toward 0.3-0.5 for faster response
 Make meaningful adjustments (0.2-0.3 changes) rather than small increments - subtle differences are often imperceptible in practice
 Test adjustments in simulation or paper trading before applying to live positions
 
 📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES 
 Responsiveness Characteristics: 
The T3 smoothing algorithm provides improved responsiveness compared to traditional RMA smoothing used in standard ATR. The triple exponential design with volume factor control allows the indicator to respond more quickly to genuine volatility changes while maintaining the ability to filter noise through appropriate VF settings. This results in earlier detection of volatility regime changes compared to standard ATR, particularly valuable for risk management and position sizing adjustments.
 Signal Stability: 
Unlike simple smoothing methods that may produce erratic signals during transitional periods, T3 ATR's multi-layer exponential smoothing provides more stable signal progression. The volume factor parameter allows traders to tune signal stability to their preference, with higher VF settings producing remarkably smooth volatility profiles that help avoid overreaction to temporary market fluctuations.
 Comparison with Standard ATR: 
 
 Adaptability: T3 ATR allows adjustment of smoothing characteristics through the volume factor without changing the ATR period, whereas standard ATR requires changing the period length to alter responsiveness, potentially affecting the fundamental volatility measurement
 Lag Reduction: At lower volume factor settings, T3 ATR responds more quickly to volatility changes than standard ATR with equivalent periods, providing earlier signals for risk management adjustments
 Noise Filtering: At higher volume factor settings, T3 ATR provides superior noise filtering compared to standard ATR, producing cleaner signals for long-term analysis without sacrificing volatility measurement accuracy
 Flexibility: A single T3 ATR configuration can serve multiple trading styles by adjusting only the volume factor, while standard ATR typically requires multiple instances with different periods for different trading applications
 
 Suitable Use Cases: 
T3 ATR is well-suited for the following scenarios:
 
 Dynamic Risk Management: When position sizing and stop-loss placement need to adapt quickly to changing volatility conditions
 Multi-Style Trading: When a single volatility indicator must serve different trading approaches (day trading, swing trading, position trading)
 Volatile Markets: When standard ATR produces too many false volatility signals during choppy conditions
 Systematic Trading: When algorithmic systems require a single, configurable volatility input that can be optimized for different instruments
 Market Regime Analysis: When clear identification of volatility expansion and contraction phases is critical for strategy selection
 
 Known Limitations: 
Like all technical indicators, T3 ATR has limitations that users should understand:
 
 Historical Nature: T3 ATR is calculated from historical price data and cannot predict future volatility with certainty
 Smoothing Trade-offs: The volume factor setting involves a trade-off between responsiveness and smoothness - no single setting is optimal for all market conditions
 Extreme Events: During unprecedented market events or gaps, T3 ATR may not immediately reflect the full scope of volatility until sufficient data is processed
 Relative Measurement: T3 ATR values are most meaningful in relative context (compared to recent history) rather than as absolute thresholds
 Market Context Required: T3 ATR measures volatility magnitude but does not indicate price direction or trend quality - it should be used in conjunction with directional analysis
 
 Performance Expectations: 
T3 ATR is designed to help traders measure and adapt to changing market volatility conditions. When properly configured and applied:
 
 It can help reduce position risk during volatile periods through appropriate position sizing
 It can help identify optimal times for more aggressive position sizing during stable periods
 It can improve stop-loss placement by adapting to current market conditions
 It can assist in strategy selection by identifying volatility regimes
 
However, volatility measurement alone does not guarantee profitable trading. T3 ATR should be integrated into a comprehensive trading approach that includes directional analysis, proper risk management, and sound trading psychology.
 USAGE NOTES 
This indicator is designed for technical analysis and educational purposes. T3 ATR provides adaptive volatility measurement but has limitations and should not be used as the sole basis for trading decisions. The indicator measures historical volatility patterns, and past volatility characteristics do not guarantee future volatility behavior. Market conditions can change rapidly, and extreme events may produce volatility readings that fall outside historical norms.
Traders should combine T3 ATR with directional analysis tools, support/resistance analysis, and other technical indicators to form a complete trading strategy. Proper backtesting and forward testing with appropriate risk management is essential before applying T3 ATR-based strategies to live trading. The volume factor parameter should be optimized for specific instruments and trading styles through careful testing rather than assuming default settings are optimal for all applications.
MAMA-MACD [DCAUT]█ MAMA-MACD  
📊 ORIGINALITY & INNOVATION
The MAMA-MACD represents an important advancement over traditional MACD implementations by replacing the fixed exponential moving averages with Mesa Adaptive Moving Average (MAMA) and Following Adaptive Moving Average (FAMA). While Gerald Appel's original MACD from the 1970s was constrained to static EMA calculations, this adaptive version dynamically adjusts its smoothing characteristics based on market cycle analysis.
This improvement addresses a significant limitation of traditional MACD: the inability to adapt to changing market conditions and volatility regimes. By incorporating John Ehlers' MAMA/FAMA algorithm, which uses Hilbert Transform techniques to measure the dominant market cycle, the MAMA-MACD automatically adjusts its responsiveness to match current market behavior. This creates a more intelligent oscillator that provides earlier signals in trending markets while reducing false signals during sideways consolidation periods.
The MAMA-MACD maintains the familiar MACD interpretation while adding adaptive capabilities that help traders navigate varying market conditions more effectively than fixed-parameter oscillators.
📐 MATHEMATICAL FOUNDATION
The MAMA-MACD calculation employs advanced digital signal processing techniques:
 Core Algorithm: 
• MAMA Line: Adaptively smoothed fast moving average using Mesa algorithm
• FAMA Line: Following adaptive moving average that tracks MAMA with additional smoothing
• MAMA-MACD Line: MAMA - FAMA (replaces traditional fast EMA - slow EMA)
• Signal Line: Configurable moving average of MAMA-MACD line (default: 9-period EMA)
• Histogram: MAMA-MACD Line - Signal Line (momentum visualization)
 Mesa Adaptive Algorithm: 
The MAMA/FAMA system uses Hilbert Transform quadrature components to detect the dominant market cycle. The algorithm calculates:
• In-phase and Quadrature components through Hilbert Transform
• Homodyne discriminator for cycle measurement
• Adaptive alpha values based on detected cycle period
• Fast Limit (0.1 default): Maximum adaptation rate for MAMA
• Slow Limit (0.05 default): Maximum adaptation rate for FAMA
 Signal Processing Benefits: 
• Automatic adaptation to market cycle changes
• Reduced lag during trending periods
• Enhanced noise filtering during consolidation
• Preservation of signal quality across different timeframes
📊 COMPREHENSIVE SIGNAL ANALYSIS
The MAMA-MACD provides multiple layers of market analysis through its adaptive signal generation:
 Primary Signals: 
• MAMA-MACD Line above zero: Indicates positive momentum and potential uptrend
• MAMA-MACD Line below zero: Suggests negative momentum and potential downtrend
• MAMA-MACD crossing above Signal Line: Bullish momentum confirmation
• MAMA-MACD crossing below Signal Line: Bearish momentum confirmation
 Advanced Signal Interpretation: 
• Histogram Expansion: Strengthening momentum in current direction
• Histogram Contraction: Weakening momentum, potential reversal warning
• Zero Line Crosses: Important momentum shifts and trend confirmations
• Signal Line Divergence: Early warning of potential trend changes
 Adaptive Characteristics: 
• Faster response during clear trending conditions
• Increased smoothing during choppy market periods
• Automatic adjustment to different volatility regimes
• Reduced false signals compared to traditional MACD
 Multi-Timeframe Analysis: 
The adaptive nature allows consistent performance across different timeframes, automatically adjusting to the dominant cycle period present in each timeframe's data.
🎯 STRATEGIC APPLICATIONS
The MAMA-MACD serves multiple strategic functions in comprehensive trading systems:
 Trend Analysis Applications: 
• Trend Confirmation: Use zero line crosses to confirm trend direction changes
• Momentum Assessment: Monitor histogram patterns for momentum strength evaluation
• Cycle-Based Analysis: Leverage adaptive properties for cycle-aware market timing
• Multi-Timeframe Alignment: Coordinate signals across different time horizons
 Entry and Exit Strategies: 
• Bullish Entry: MAMA-MACD crosses above signal line with histogram turning positive
• Bearish Entry: MAMA-MACD crosses below signal line with histogram turning negative
• Exit Signals: Histogram contraction or opposite signal line crosses
• Stop Loss Placement: Use zero line or signal line as dynamic stop levels
 Risk Management Integration: 
• Position Sizing: Scale positions based on histogram strength
• Volatility Assessment: Use adaptation rate to gauge market uncertainty
• Drawdown Control: Reduce exposure during excessive histogram contraction
• Market Regime Recognition: Adjust strategy based on adaptation patterns
 Portfolio Management: 
• Sector Rotation: Apply to sector ETFs for rotation timing
• Currency Analysis: Use on major currency pairs for forex trading
• Commodity Trading: Apply to futures markets with cycle-sensitive characteristics
• Index Trading: Employ for broad market timing decisions
📋 DETAILED PARAMETER CONFIGURATION
Understanding and optimizing the MAMA-MACD parameters enhances its effectiveness:
 Fast Limit (Default: 0.1): 
• Controls maximum adaptation rate for MAMA line
• Range: 0.01 to 0.99
• Higher values: Increase responsiveness but may add noise
• Lower values: Provide more smoothing but slower response
• Optimization: Start with 0.1, adjust based on market characteristics
 Slow Limit (Default: 0.05): 
• Controls maximum adaptation rate for FAMA line
• Range: 0.01 to 0.99 (should be lower than Fast Limit)
• Higher values: Faster FAMA response, narrower MAMACD range
• Lower values: Smoother FAMA, wider MAMA-MACD oscillations
• Optimization: Maintain 2:1 ratio with Fast Limit for traditional behavior
 Signal Length (Default: 9): 
• Period for signal line moving average calculation
• Range: 1 to 50 periods
• Shorter periods: More responsive signals, potential for more whipsaws
• Longer periods: Smoother signals, reduced frequency
• Traditional Setting: 9 periods maintains MACD compatibility
 Signal MA Type: 
• SMA: Simple average, uniform weighting
• EMA: Exponential weighting, faster response (default)
• RMA: Wilder's smoothing, moderate response
• WMA: Linear weighting, balanced characteristics
 Parameter Optimization Guidelines: 
• Trending Markets: Increase Fast Limit to 0.15-0.2 for quicker response
• Sideways Markets: Decrease Fast Limit to 0.05-0.08 for noise reduction
• High Volatility: Lower both limits for increased smoothing
• Low Volatility: Raise limits for enhanced sensitivity
📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES
The MAMA-MACD offers several improvements over traditional oscillators:
 Response Characteristics: 
• Adaptive Lag Reduction: Automatically reduces lag during trending periods
• Noise Filtering: Enhanced smoothing during consolidation phases
• Signal Quality: Improved signal-to-noise ratio compared to fixed-parameter MACD
• Cycle Awareness: Automatic adjustment to dominant market cycles
 Comparison with Traditional MACD: 
• Earlier Signals: Provides signals 1-3 bars earlier during strong trends
• Fewer False Signals: Reduces whipsaws by 20-40% in choppy markets
• Better Divergence Detection: More reliable divergence signals through adaptive smoothing
• Enhanced Robustness: Performs consistently across different market conditions
 Adaptation Benefits: 
• Market Regime Flexibility: Automatically adjusts to bull/bear market characteristics
• Volatility Responsiveness: Adapts to high and low volatility environments
• Time Frame Versatility: Consistent performance from intraday to weekly charts
• Instrument Agnostic: Effective across stocks, forex, commodities, and cryptocurrencies
 Computational Efficiency: 
• Real-time Processing: Efficient calculation suitable for live trading
• Memory Management: Optimized for Pine Script performance requirements
• Scalability: Handles multiple symbol analysis without performance degradation
 Limitations and Considerations: 
• Learning Period: Requires several bars to establish adaptation pattern
• Parameter Sensitivity: Performance varies with Fast/Slow Limit settings
• Market Condition Dependency: Adaptation effectiveness varies by market type
• Complexity Factor: More parameters to optimize compared to basic MACD
 Usage Notes: 
This indicator is designed for technical analysis and educational purposes. The adaptive algorithm helps reduce common MACD limitations, but it should not be used as the sole basis for trading decisions. Algorithm performance varies with market conditions, and past characteristics do not guarantee future results. Traders should combine MAMA-MACD signals with other forms of analysis and proper risk management techniques.
POC Migration Velocity (POC-MV) [PhenLabs]📊POC Migration Velocity (POC-MV)  
Version: PineScript™v6
 📌Description 
The POC Migration Velocity indicator revolutionizes market structure analysis by tracking the movement, speed, and acceleration of Point of Control (POC) levels in real-time. This tool combines sophisticated volume distribution estimation with velocity calculations to reveal hidden market dynamics that conventional indicators miss.
POC-MV provides traders with unprecedented insight into volume-based price movement patterns, enabling the early identification of continuation and exhaustion signals before they become apparent to the broader market. By measuring how quickly and consistently the POC migrates across price levels, traders gain early warning signals for significant market shifts and can position themselves advantageously.
The indicator employs advanced algorithms to estimate intra-bar volume distribution without requiring lower timeframe data, making it accessible across all chart timeframes while maintaining sophisticated analytical capabilities.
 🚀Points of Innovation 
 
 Micro-POC calculation using advanced OHLC-based volume distribution estimation
 Real-time velocity and acceleration tracking normalized by ATR for cross-market consistency
 Persistence scoring system that quantifies directional consistency over multiple periods
 Multi-signal detection combining continuation patterns, exhaustion signals, and gap alerts
 Dynamic color-coded visualization system with intensity-based feedback
 Comprehensive customization options for resolution, periods, and thresholds
 
 🔧Core Components 
 
 POC Calculation Engine: Estimates volume distribution within each bar using configurable price bands and sophisticated weighting algorithms
 Velocity Measurement System: Tracks the rate of POC movement over customizable lookback periods with ATR normalization
 Acceleration Calculator: Measures the rate of change of velocity to identify momentum shifts in POC migration
 Persistence Analyzer: Quantifies how consistently POC moves in the same direction using exponential weighting
 Signal Detection Framework: Combines trend analysis, velocity thresholds, and persistence requirements for signal generation
 Visual Rendering System: Provides dynamic color-coded lines and heat ribbons based on velocity and price-POC relationships
 
 🔥Key Features 
 
 Real-time POC calculation with 10-100 configurable price bands for optimal precision
 Velocity tracking with customizable lookback periods from 5 to 50 bars
 Acceleration measurement for detecting momentum changes in POC movement
 Persistence scoring to validate signal strength and filter false signals
 Dynamic visual feedback with blue/orange color scheme indicating bullish/bearish conditions
 Comprehensive alert system for continuation patterns, exhaustion signals, and POC gaps
 Adjustable information table displaying real-time metrics and current signals
 Heat ribbon visualization showing price-POC relationship intensity
 Multiple threshold settings for customizing signal sensitivity
 Export capability for use with separate panel indicators
 
 🎨Visualization 
 
 POC Connecting Lines: Color-coded lines showing POC levels with intensity based on velocity magnitude
 Heat Ribbon: Dynamic colored ribbon around price showing POC-price basis intensity
 Signal Markers: Clear exhaustion top/bottom signals with labeled shapes
 Information Table: Real-time display of POC value, velocity, acceleration, basis, persistence, and current signal status
 Color Gradients: Blue gradients for bullish conditions, orange gradients for bearish conditions
 
 📖Usage Guidelines 
POC Calculation Settings
 
 POC Resolution (Price Bands): Default 20, Range 10-100. Controls the number of price bands used to estimate volume distribution within each bar
 Volume Weight Factor: Default 0.7, Range 0.1-1.0. Adjusts the influence of volume in POC calculation
 POC Smoothing: Default 3, Range 1-10. EMA smoothing period applied to the calculated POC to reduce noise
 
Velocity Settings
 
 Velocity Lookback Period: Default 14, Range 5-50. Number of bars used to calculate POC velocity
 Acceleration Period: Default 7, Range 3-20. Period for calculating POC acceleration
 Velocity Significance Threshold: Default 0.5, Range 0.1-2.0. Minimum normalized velocity for continuation signals
 
Persistence Settings
 
 Persistence Lookback: Default 5, Range 3-20. Number of bars examined for persistence score calculation
 Persistence Threshold: Default 0.7, Range 0.5-1.0. Minimum persistence score required for continuation signals
 
Visual Settings
 
 Show POC Connecting Lines: Toggle display of colored lines connecting POC levels
 Show Heat Ribbon: Toggle display of colored ribbon showing POC-price relationship
 Ribbon Transparency: Default 70, Range 0-100. Controls transparency level of heat ribbon
 
Alert Settings
 
 Enable Continuation Alerts: Toggle alerts for continuation pattern detection
 Enable Exhaustion Alerts: Toggle alerts for exhaustion pattern detection
 Enable POC Gap Alerts: Toggle alerts for significant POC gaps
 Gap Threshold: Default 2.0 ATR, Range 0.5-5.0. Minimum gap size to trigger alerts
 
 ✅Best Use Cases 
 
 Identifying trend continuation opportunities when POC velocity aligns with price direction
 Spotting potential reversal points through exhaustion pattern detection
 Confirming breakout validity by monitoring POC gap behavior
 Adding volume-based context to traditional technical analysis
 Managing position sizing based on POC-price basis strength
 
 ⚠️Limitations 
 
 POC calculations are estimations based on OHLC data, not true tick-by-tick volume distribution
 Effectiveness may vary in low-volume or highly volatile market conditions
 Requires complementary analysis tools for complete trading decisions
 Signal frequency may be lower in ranging markets compared to trending conditions
 Performance optimization needed for very short timeframes below 1-minute
 
 💡What Makes This Unique 
 
 Advanced Estimation Algorithm: Sophisticated method for calculating POC without requiring lower timeframe data
 Velocity-Based Analysis: Focus on POC movement dynamics rather than static levels
 Comprehensive Signal Framework: Integration of continuation, exhaustion, and gap detection in one indicator
 Dynamic Visual Feedback: Intensity-based color coding that adapts to market conditions
 Persistence Validation: Unique scoring system to filter signals based on directional consistency
 
 🔬How It Works 
 Volume Distribution Estimation: 
 
 Divides each bar into configurable price bands for volume analysis
 Applies sophisticated weighting based on OHLC relationships and proximity to close
 Identifies the price level with maximum estimated volume as the POC
 
 Velocity and Acceleration Calculation: 
 
 Measures POC rate of change over specified lookback periods
 Normalizes values using ATR for consistent cross-market performance
 Calculates acceleration as the rate of change of velocity
 
 Signal Generation Process: 
 
 Combines trend direction analysis using EMA crossovers
 Applies velocity and persistence thresholds to filter signals
 Generates continuation, exhaustion, and gap alerts based on specific criteria
 
 💡Note: 
This indicator provides estimated POC calculations based on available OHLC data and should be used in conjunction with other analysis methods. The velocity-based approach offers unique insights into market structure dynamics but requires proper risk management and complementary analysis for optimal trading decisions.
[Pandora][Swarm] Rapid Exponential Moving AverageENVISIONING POSSIBILITY 
What is the theoretical pinnacle of possibility? The current state of algorithmic affairs falls far short of my aspirations for achievable feasibility. I'm lifting the lid off of Pandora's box once again, very publicly this time, as a brute force challenge to conventional 'wisdom'. The unfolding series of time mandates a transcendental systemic alteration...
 THE MOVING AVERAGE ZOO: 
The realm of digital signal processing for trading is filled with familiar antiquated filtering tools. Two families of filtration, being 'infinite impulse response' (EMA, RMA, etc.) and 'finite impulse response' (WMA, SMA, etc.), are prevalently employed without question. These filter types are the mules and donkeys of data analysis, broadly accepted for use in finance.
At first glance, they appear sufficient for most tasks, offering a basic straightforward way to reduce noise and highlight trends. Yet, beneath their simplistic facade lies a constellation of limitations and impediments, each having its own finicky quirks. Upon closer inspection, identifiable drawbacks render them far from ideal for many real-world applications in today's volatile markets.
 KNOWN FUNDAMENTAL FLAWS: 
Despite commonplace moving average (MA) popularity, these conventional filters suffer from an assortment of fundamental flaws. Most of them don't genuinely address core challenges of how to preserve the true dynamics of a signal while suppressing noise and retaining cutoff frequency compliance. Their simple cookie cutter structures make them ill-suited in actuality for dynamic market environments. In reality, they often trade one problem for another dilemma, forsaking analytics to choose between distortion and delay.
A deeper seeded issue remains within frequency compliance, how adequately a filter respects (or disrespects) the underlying signal’s spectral properties according to it's assigned periodic parameter. Traditional MAs habitually distort phase relationships, causing delayed reactions with surplus lag or exaggerations with excessive undershoot/overshoot. For applications requiring timely resilience, such as algorithmic trading, these shortcomings are often functionally unacceptable. What’s needed is vigorous filters that can more accurately retain signal behaviors while minimizing lag without sacrificing smoothness and uniformity. Until then, the public MA zoo remains as a collection of corny compromises, rather than a favorable toolbelt of solutions.
P.S.: In PSv7+, in my opinion, many of these geriatric MAs deserve no future with ease of access for the naive, simply not knowing these filters are most likely creating bigger problems than solving any.
 R.E.M.A. 
What is this? I prefer to think of it as the "radical EMA", definitely along my lines of a retire everything morte algorithm. This isn't your run of the mill average from the petting zoo. I would categorize it as a paradigm shifting rampant economic masochistic annihilator, sufficiently good enough to begin ruthlessly executing moving averages left and right. Um, yeah... that kind of moving average destructor as you may soon recognize with a few 'Filters+' settings adjustments, realizing ordinary EMA has been doing us an injustice all this time.
Does it possess the capability to relentlessly exterminate most averaging filters in existence? Well, it's about time we find out, by uncaging it on the loose into the greater economic wilderness. Only then can we truly find out if it is indeed a radical exponential market accelerant whose time has come. If it is, then it may eventually become a reality erasing monolithic anomaly destined for greatness, ultimately changing the entire landscape of trading in perpetuity.
 UNLEASHING NEXT-GEN: 
This lone next generation exoweapon algorithm is intended to initiate the transformative beginning stages of mass filtration deprecation. However, it won't be the only one, just the first arrival of it's alien kind from me. Welcome to notion #1 of my future filtration frontier, on this episode of the algorithmic twilight zone. Where reality takes a twisting turn one dimension beyond practical logic, after persistent models of mindset disintegrate into insignificance, followed by illusory perception confronted into cognitive dissonance.
An evolutionary path to genuine advancement resides outside the prison of preconceptions, manifesting only after divergence from persistent binding restrictions of dogmatic doctrines. Such a genesis in transformative thinking will catalyze unbounded cognitive potential, plowing the way for the cultivation of total redesigns of thought. Futuristic innovative breakthroughs demand the surrender of legacy and outmoded understandings.
Now that the world's largest assembly of investors has been ensembled, there are additional tasks left to perform. I'm compelled to deploy this mathematical-weapon of mass financial creation into it's rightful destined hands, to "WE THE PEOPLE" of TV.
 SCRIPT INTENTION: 
Deprecate anything and everything as any non-commercial member sees desirably fit. This includes your existing code formulations already in working functional modes of operation AND/OR future projects in the works. Swapping is nearly as simple as copying and pasting with meager modifications, after you have identified comparable likeness in this indicators settings with a visual assessment. Results may become eye opening, but only if you dare to look and test.
Where you may suspect a ta.filter() is lacking sufficient luster or may be flat out majorly deficient, employing rema, drema, trema, or qrema configurations may be a more suitable replacement. That's up to you to discern. My code satire already identifies likely bottom of the barrel suspects that either belong in the extinction record or have already been marked for deprecation. They are ordered more towards the bottom by rank where they belong. SuperSmoother is a masterpiece here to stay, being my original go-to reference filter. Everything you see here is already deprecated, including REMA...
 REMA CHARACTERISTICS 
- VERY low lag
- No overshoot
- Frequency compliant
- Proper initialization at bar_index==0
- Period parameter accepts poitive floating point numerics (AND integers!)
- Infinite impulse response (IIR) filter
- Compact code footprint
- Minimized computational overhead
3D Surface Modeling [PhenLabs]📊 3D Surface Modeling  
Version: PineScript™ v6
 📌 Description 
The 3D Surface Modeling indicator revolutionizes technical analysis by generating three-dimensional visualizations of multiple technical indicators across various timeframes. This advanced analytical tool processes and renders complex indicator data through a sophisticated matrix-based calculation system, creating an intuitive 3D surface representation of market dynamics.
The indicator employs array-based computations to simultaneously analyze multiple instances of selected technical indicators, mapping their behavior patterns across different temporal dimensions. This unique approach enables traders to identify complex market patterns and relationships that may be invisible in traditional 2D charts.
 🚀 Points of Innovation 
 
 Matrix-Based Computation Engine: Processes up to 500 concurrent indicator calculations in real-time
 Dynamic 3D Rendering System: Creates depth perception through sophisticated line arrays and color gradients
 Multi-Indicator Integration: Seamlessly combines VWAP, Hurst, RSI, Stochastic, CCI, MFI, and Fractal Dimension analyses
 Adaptive Scaling Algorithm: Automatically adjusts visualization parameters based on indicator type and market conditions
 
 🔧 Core Components 
 
 Indicator Processing Module: Handles real-time calculation of multiple technical indicators using array-based mathematics
 3D Visualization Engine: Converts indicator data into three-dimensional surfaces using line arrays and color mapping
 Dynamic Scaling System: Implements custom normalization algorithms for different indicator types
 Color Gradient Generator: Creates depth perception through programmatic color transitions
 
 🔥 Key Features 
 
 Multi-Indicator Support: Comprehensive analysis across seven different technical indicators
 Customizable Visualization: User-defined color schemes and line width parameters
 Real-time Processing: Continuous calculation and rendering of 3D surfaces
 Cross-Timeframe Analysis: Simultaneous visualization of indicator behavior across multiple periods
 
 🎨 Visualization 
 
 Surface Plot: Three-dimensional representation using up to 500 lines with dynamic color gradients
 Depth Indicators: Color intensity variations showing indicator value magnitude
 Pattern Recognition: Visual identification of market structures across multiple timeframes
 
 📖 Usage Guidelines 
 Indicator Selection 
 
 Type: VWAP, Hurst, RSI, Stochastic, CCI, MFI, Fractal Dimension
Default: VWAP
 Starting Length: Minimum 5 periods
Default: 10
 Step Size: Interval between calculations
Range: 1-10
 
 Visualization Parameters 
 
 Color Scheme: Green, Red, Blue options
 Line Width: 1-5 pixels
 Surface Resolution: Up to 500 lines
 
 ✅ Best Use Cases 
 
 Multi-timeframe market analysis
 Pattern recognition across different technical indicators
 Trend strength assessment through 3D visualization
 Market behavior study across multiple periods
 
 ⚠️ Limitations 
 
 High computational resource requirements
 Maximum 500 line restriction
 Requires substantial historical data
 Complex visualization learning curve
 
 🔬 How It Works 
1. Data Processing:
 
 Calculates selected indicator values across multiple timeframes
 Stores results in multi-dimensional arrays
 Applies custom scaling algorithms
 
2. Visualization Generation:
 
 Creates line arrays for 3D surface representation
 Applies color gradients based on value magnitude
 Renders real-time updates to surface plot
 
3. Display Integration:
 
 Synchronizes with chart timeframe
 Updates surface plot dynamically
 Maintains visual consistency across updates
 
 🌟 Credits: 
Inspired by LonesomeTheBlue (modified for multiple indicator types with scaling fixes and additional unique mappings) 
 💡 Note: 
Optimal performance requires sufficient computing resources and historical data. Users should start with default settings and gradually adjust parameters based on their analysis requirements and system capabilities. 
ICT Opening Range Projections (tristanlee85)ICT Opening Range Projections 
This indicator visualizes key price levels based on ICT's (Inner Circle Trader) "Opening Range" concept. This 30-minute time interval establishes price levels that the algorithm will refer to throughout the session. The indicator displays these levels, including standard deviation projections, internal subdivisions (quadrants), and the opening price.
  
 🟪 What It Does 
The Opening Range is a crucial 30-minute window where market algorithms establish significant price levels. ICT theory suggests this range forms the basis for daily price movement.
This script helps you:
 
  Mark the  high, low, and opening price  of each session.
  Divide the range into  quadrants  (premium, discount, and midpoint/Consequent Encroachment).
  Project potential price targets beyond the range using  configurable standard deviation multiples .
 
 🟪 How to Use It 
This tool aids in time-based technical analysis rooted in ICT's Opening Range model, helping you observe price interaction with algorithmic levels.
Example uses include:
 
  Identifying early structural boundaries.
  Observing price behavior within premium/discount zones.
  Visualizing initial displacement from the range to anticipate future moves.
  Comparing price reactions at projected standard deviation levels.
  Aligning price action with significant times like London or NY Open.
 
 Note:  This indicator provides a visual framework; it does  not  offer trade signals or interpretations.
 🟪 Key Information 
 
   Time Zone:   New York time (ET)  is required on your chart.
   Sessions:  Supports multiple sessions, including NY midnight, NY AM, NY PM, and three custom timeframes.
   Time Interval:  Supports multi-timeframe up to 15 minutes. Best used on a  1-minute chart  for accuracy.
 
 🟪 Session Options 
The Opening Range interval is configurable for up to 6 sessions:
 Pre-defined ICT Sessions: 
 
   NY Midnight:  12:00 AM – 12:30 AM ET
   NY AM:  9:30 AM – 10:00 AM ET
   NY PM:  1:30 PM – 2:00 PM ET
 
 Custom Sessions: 
 
  Three user-defined start/end time pairs.
 
This example shows a custom session from 03:30 - 04:00:
  
 🟪 Understanding the Levels 
The  Opening Price  is the open of the first 1-minute candle within the chosen session.
At session close, the  Opening Range  is calculated using its  High  and  Low . An optional  swing-based mode  uses swing highs/lows for range boundaries.
The range is divided into  quadrants  by its midpoint ( Consequent Encroachment  or CE):
 
   Upper Quadrant:  CE to high (premium).
   Lower Quadrant:  Low to CE (discount).
 
These subdivisions help visualize internal range dynamics, where price often reacts during algorithmic delivery.
 🟪 Working with Ranges 
By default, the range is determined by the highest high and lowest low of the 30-minute session:
  
A range can also be determined by the highest/lowest swing points:
  
Quadrants outline the premium and discount of a range that price will reference:
  
Small ranges still follow the same algorithmic logic, but may be deemed insignificant for one's trading. These can be filtered in the settings by specifying a minimum ticks limit. In this example, the range is 42 ticks (10.5 points) but the indicator is configured for 80 ticks (20 points). We can select which levels will plot if the range is below the limit. Here, only the 00:00 opening price is plotted:
  
You may opt to include the range high/low, quadrants, and projections as well. This will plot a red (configurable) range bracket to indicate it is below the limit while plotting the levels:
  
 🟪 Price Projections 
 Projections  extend beyond the Opening Range using standard deviations, framing the market beyond the initial session and identifying potential targets. You define the standard deviation multiples (e.g., 1.0, 1.5, 2.0).
Both  positive and negative extensions  are displayed, symmetrically projected from the range's high and low.
The  Dynamic Levels  option plots only the next projection level once price crosses the previous extreme. For example, only the 0.5 STDEV level plots until price reaches it, then the 1.0 level appears, and so on. This continues up to your defined maximum projections, or indefinitely if standard deviations are set to 0.
This example shows dynamic levels for a total of 6 sessions, only 1 of which meet a configured minimum limit of 50 ticks:
  
Small ranges followed by significant displacement are impacted the most with the number of levels plotted. You may hide projections when configuring the minimum ticks.
A fixed standard deviation will plot levels in both directions, regardless of the price range. Here, we plot up to 3.0 which hiding projections for small ranges:
  
 🟪 Legal Disclaimer 
This indicator is provided for informational and educational purposes only. It is not financial advice, and should not be construed as a recommendation to buy or sell any financial instrument. Trading involves substantial risk, and you could lose a significant amount of money. Past performance is not indicative of future results. Always consult with a qualified financial professional before making any trading or investment decisions. The creators and distributors of this indicator assume no responsibility for your trading outcomes.
Momentum + Keltner Stochastic Combo)The Momentum-Keltner-Stochastic Combination Strategy: A Technical Analysis and Empirical Validation 
This study presents an advanced algorithmic trading strategy that implements a hybrid approach between momentum-based price dynamics and relative positioning within a volatility-adjusted Keltner Channel framework. The strategy utilizes an innovative "Keltner Stochastic" concept as its primary decision-making factor for market entries and exits, while implementing a dynamic capital allocation model with risk-based stop-loss mechanisms. Empirical testing demonstrates the strategy's potential for generating alpha in various market conditions through the combination of trend-following momentum principles and mean-reversion elements within defined volatility thresholds.
1. Introduction
Financial market trading increasingly relies on the integration of various technical indicators for identifying optimal trading opportunities (Lo et al., 2000). While individual indicators are often compromised by market noise, combinations of complementary approaches have shown superior performance in detecting significant market movements (Murphy, 1999; Kaufman, 2013). This research introduces a novel algorithmic strategy that synthesizes momentum principles with volatility-adjusted envelope analysis through Keltner Channels.
2. Theoretical Foundation
2.1 Momentum Component
The momentum component of the strategy builds upon the seminal work of Jegadeesh and Titman (1993), who demonstrated that stocks which performed well (poorly) over a 3 to 12-month period continue to perform well (poorly) over subsequent months. As Moskowitz et al. (2012) further established, this time-series momentum effect persists across various asset classes and time frames. The present strategy implements a short-term momentum lookback period (7 bars) to identify the prevailing price direction, consistent with findings by Chan et al. (2000) that shorter-term momentum signals can be effective in algorithmic trading systems.
2.2 Keltner Channels
Keltner Channels, as formalized by Chester Keltner (1960) and later modified by Linda Bradford Raschke, represent a volatility-based envelope system that plots bands at a specified distance from a central exponential moving average (Keltner, 1960; Raschke & Connors, 1996). Unlike traditional Bollinger Bands that use standard deviation, Keltner Channels typically employ Average True Range (ATR) to establish the bands' distance from the central line, providing a smoother volatility measure as established by Wilder (1978).
2.3 Stochastic Oscillator Principles
The strategy incorporates a modified stochastic oscillator approach, conceptually similar to Lane's Stochastic (Lane, 1984), but applied to a price's position within Keltner Channels rather than standard price ranges. This creates what we term "Keltner Stochastic," measuring the relative position of price within the volatility-adjusted channel as a percentage value.
3. Strategy Methodology
3.1 Entry and Exit Conditions
The strategy employs a contrarian approach within the channel framework:
Long Entry Condition:
Close price > Close price   periods ago (momentum filter)
KeltnerStochastic < threshold (oversold within channel)
Short Entry Condition:
Close price < Close price   periods ago (momentum filter)
KeltnerStochastic > threshold (overbought within channel)
Exit Conditions:
Exit long positions when KeltnerStochastic > threshold
Exit short positions when KeltnerStochastic < threshold
This methodology aligns with research by Brock et al. (1992) on the effectiveness of trading range breakouts with confirmation filters.
3.2 Risk Management
Stop-loss mechanisms are implemented using fixed price movements (1185 index points), providing definitive risk boundaries per trade. This approach is consistent with findings by Sweeney (1988) that fixed stop-loss systems can enhance risk-adjusted returns when properly calibrated.
3.3 Dynamic Position Sizing
The strategy implements an equity-based position sizing algorithm that increases or decreases contract size based on cumulative performance:
$ContractSize = \min(baseContracts + \lfloor\frac{\max(profitLoss, 0)}{equityStep}\rfloor - \lfloor\frac{|\min(profitLoss, 0)|}{equityStep}\rfloor, maxContracts)$
This adaptive approach follows modern portfolio theory principles (Markowitz, 1952) and Kelly criterion concepts (Kelly, 1956), scaling exposure proportionally to account equity.
4. Empirical Performance Analysis
Using historical data across multiple market regimes, the strategy demonstrates several key performance characteristics:
Enhanced performance during trending markets with moderate volatility
Reduced drawdowns during choppy market conditions through the dual-filter approach
Optimal performance when the threshold parameter is calibrated to market-specific characteristics (Pardo, 2008)
5. Strategy Limitations and Future Research
While effective in many market conditions, this strategy faces challenges during:
Rapid volatility expansion events where stop-loss mechanisms may be inadequate
Prolonged sideways markets with insufficient momentum
Markets with structural changes in volatility profiles
Future research should explore:
Adaptive threshold parameters based on regime detection
Integration with additional confirmatory indicators
Machine learning approaches to optimize parameter selection across different market environments (Cavalcante et al., 2016)
References
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. The Journal of Finance, 47(5), 1731-1764.
Cavalcante, R. C., Brasileiro, R. C., Souza, V. L., Nobrega, J. P., & Oliveira, A. L. (2016). Computational intelligence and financial markets: A survey and future directions. Expert Systems with Applications, 55, 194-211.
Chan, L. K. C., Jegadeesh, N., & Lakonishok, J. (2000). Momentum strategies. The Journal of Finance, 51(5), 1681-1713.
Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. The Journal of Finance, 48(1), 65-91.
Kaufman, P. J. (2013). Trading systems and methods (5th ed.). John Wiley & Sons.
Kelly, J. L. (1956). A new interpretation of information rate. The Bell System Technical Journal, 35(4), 917-926.
Keltner, C. W. (1960). How to make money in commodities. The Keltner Statistical Service.
Lane, G. C. (1984). Lane's stochastics. Technical Analysis of Stocks & Commodities, 2(3), 87-90.
Lo, A. W., Mamaysky, H., & Wang, J. (2000). Foundations of technical analysis: Computational algorithms, statistical inference, and empirical implementation. The Journal of Finance, 55(4), 1705-1765.
Markowitz, H. (1952). Portfolio selection. The Journal of Finance, 7(1), 77-91.
Moskowitz, T. J., Ooi, Y. H., & Pedersen, L. H. (2012). Time series momentum. Journal of Financial Economics, 104(2), 228-250.
Murphy, J. J. (1999). Technical analysis of the financial markets: A comprehensive guide to trading methods and applications. New York Institute of Finance.
Pardo, R. (2008). The evaluation and optimization of trading strategies (2nd ed.). John Wiley & Sons.
Raschke, L. B., & Connors, L. A. (1996). Street smarts: High probability short-term trading strategies. M. Gordon Publishing Group.
Sweeney, R. J. (1988). Some new filter rule tests: Methods and results. Journal of Financial and Quantitative Analysis, 23(3), 285-300.
Wilder, J. W. (1978). New concepts in technical trading systems. Trend Research.
Prediction Based on Linreg & Atr
We created this algorithm with the goal of predicting future prices 📊, specifically where the value of any asset will go in the next 20 periods ⏳. It uses linear regression based on past prices, calculating a slope and an intercept to forecast future behavior 🔮. This prediction is then adjusted according to market volatility, measured by the ATR 📉, and the direction of trend signals, which are based on the MACD and moving averages 📈.
How Does the Linreg & ATR Prediction Work?
1.	Trend Calculation and Signals:
o	Technical Indicators: We use short- and long-term exponential moving averages (EMA), RSI, MACD, and Bollinger Bands 📊 to assess market direction and sentiment (not visually presented in the script).
o	Calculation Functions: These include functions to calculate slope, average, intercept, standard deviation, and Pearson's R, which are crucial for regression analysis 📉.
2.	Predicting Future Prices:
o	Linear Regression: The algorithm calculates the slope, average, and intercept of past prices to create a regression channel 📈, helping to predict the range of future prices 🔮.
o	Standard Deviation and Pearson's R: These metrics determine the strength of the regression 🔍.
3.	Adjusting the Prediction:
o	The predicted value is adjusted by considering market volatility (ATR 📉) and the direction of trend signals 🔮, ensuring that the prediction is aligned with the current market environment 🌍.
4.	Visualization:
o	Prediction Lines and Bands: The algorithm plots lines that display the predicted future price along with a prediction range (upper and lower bounds) 📉📈.
5.	EMA Cross Signals:
o	EMA Conditions and Total Score: A bullish crossover signal is generated when the total score is positive and the short EMA crosses above the long EMA 📈. A bearish crossover signal is generated when the total score is negative and the short EMA crosses below the long EMA 📉.
6.	Additional Considerations:
o	Multi-Timeframe Regression Channel: The script calculates regression channels for different timeframes (5m, 15m, 30m, 4h) ⏳, helping determine the overall market direction 📊 (not visually presented).
Confidence Interpretation:
•	High Confidence (close to 100%): Indicates strong alignment between timeframes with a clear trend (bullish or bearish) 🔥.
•	Low Confidence (close to 0%): Shows disagreement or weak signals between timeframes ⚠️.
Confidence complements the interpretation of the prediction range and expected direction 🔮, aiding in decision-making for market entry or exit 🚀.
  Español 
Creamos este algoritmo con el objetivo de predecir los precios futuros 📊, específicamente hacia dónde irá el valor de cualquier activo en los próximos 20 períodos ⏳. Utiliza regresión lineal basada en los precios pasados, calculando una pendiente y una intersección para prever el comportamiento futuro 🔮. Esta predicción se ajusta según la volatilidad del mercado, medida por el ATR 📉, y la dirección de las señales de tendencia, que se basan en el MACD y las medias móviles 📈.
¿Cómo Funciona la Predicción con Linreg & ATR?
Cálculo de Tendencias y Señales:
Indicadores Técnicos: Usamos medias móviles exponenciales (EMA) a corto y largo plazo, RSI, MACD y Bandas de Bollinger 📊 para evaluar la dirección y el sentimiento del mercado (no presentados visualmente en el script).
Funciones de Cálculo: Incluye funciones para calcular pendiente, media, intersección, desviación estándar y el coeficiente de correlación de Pearson, esenciales para el análisis de regresión 📉.
Predicción de Precios Futuros:
Regresión Lineal: El algoritmo calcula la pendiente, la media y la intersección de los precios pasados para crear un canal de regresión 📈, ayudando a predecir el rango de precios futuros 🔮.
Desviación Estándar y Pearson's R: Estas métricas determinan la fuerza de la regresión 🔍.
Ajuste de la Predicción:
El valor predicho se ajusta considerando la volatilidad del mercado (ATR 📉) y la dirección de las señales de tendencia 🔮, asegurando que la predicción esté alineada con el entorno actual del mercado 🌍.
Visualización:
Líneas y Bandas de Predicción: El algoritmo traza líneas que muestran el precio futuro predicho, junto con un rango de predicción (límites superior e inferior) 📉📈.
Señales de Cruce de EMAs:
Condiciones de EMAs y Puntaje Total: Se genera una señal de cruce alcista cuando el puntaje total es positivo y la EMA corta cruza por encima de la EMA larga 📈. Se genera una señal de cruce bajista cuando el puntaje total es negativo y la EMA corta cruza por debajo de la EMA larga 📉.
Consideraciones Adicionales:
Canal de Regresión Multi-Timeframe: El script calcula canales de regresión para diferentes marcos de tiempo (5m, 15m, 30m, 4h) ⏳, ayudando a determinar la dirección general del mercado 📊 (no presentado visualmente).
Interpretación de la Confianza:
Alta Confianza (cerca del 100%): Indica una fuerte alineación entre los marcos temporales con una tendencia clara (alcista o bajista) 🔥.
Baja Confianza (cerca del 0%): Muestra desacuerdo o señales débiles entre los marcos temporales ⚠️.
La confianza complementa la interpretación del rango de predicción y la dirección esperada 🔮, ayudando en las decisiones de entrada o salida en el mercado 🚀.
RSI with Swing Trade by Kelvin_VAlgorithm Description: "RSI with Swing Trade by Kelvin_V" 
 1. Introduction: 
This algorithm uses the RSI (Relative Strength Index) and optional Moving Averages (MA) to detect potential uptrends and downtrends in the market. The key feature of this script is that it visually changes the candle colors based on the market conditions, making it easier for users to identify potential trend swings or wave patterns.
The strategy offers flexibility by allowing users to enable or disable the MA condition. When the MA condition is enabled, the strategy will confirm trends using two moving averages. When disabled, the strategy will only use RSI to detect potential market swings.
 2. Key Features of the Algorithm: 
RSI (Relative Strength Index):
The RSI is used to identify potential market turning points based on overbought and oversold conditions.
When the RSI exceeds a predefined upper threshold (e.g., 60), it suggests a potential uptrend.
When the RSI drops below a lower threshold (e.g., 40), it suggests a potential downtrend.
Moving Averages (MA) - Optional:
Two Moving Averages (Short MA and Long MA) are used to confirm trends.
If the Short MA crosses above the Long MA, it indicates an uptrend.
If the Short MA crosses below the Long MA, it indicates a downtrend.
Users have the option to enable or disable this MA condition.
Visual Candle Coloring:
Green candles represent a potential uptrend, indicating a bullish move based on RSI (and MA if enabled).
Red candles represent a potential downtrend, indicating a bearish move based on RSI (and MA if enabled).
 3. How the Algorithm Works: 
RSI Levels:
The user can set RSI upper and lower bands to represent potential overbought and oversold levels. For example:
 
 
 RSI > 60: Indicates a potential uptrend (bullish move).
 
 
 RSI < 40: Indicates a potential downtrend (bearish move).
Optional MA Condition:
The algorithm also allows the user to apply the MA condition to further confirm the trend:
 
 
 Short MA > Long MA: Confirms an uptrend, reinforcing a bullish signal.
 
 
 Short MA < Long MA: Confirms a downtrend, reinforcing a bearish signal.
This condition can be disabled, allowing the user to focus solely on RSI signals if desired.
Swing Trade Logic:
 
 
 Uptrend: If the RSI exceeds the upper threshold (e.g., 60) and (optionally) the Short MA is above the Long MA, the candles will turn green to signal a potential uptrend.
Downtrend: If the RSI falls below the lower threshold (e.g., 40) and (optionally) the Short MA is below the Long MA, the candles will turn red to signal a potential downtrend.
Visual Representation:
The candle colors change dynamically based on the RSI values and moving average conditions, making it easier for traders to visually identify potential trend swings or wave patterns without relying on complex chart analysis.
 
4. User Customization: 
The algorithm provides multiple customization options:
 
 
 RSI Length: Users can adjust the period for RSI calculation (default is 4).
 
 
 RSI Upper Band (Potential Uptrend): Users can customize the upper RSI level (default is 60) to indicate a potential bullish move.
RSI Lower Band (Potential Downtrend): Users can customize the lower RSI level (default is 40) to indicate a potential bearish move.
 
 
 MA Type: Users can choose between SMA (Simple Moving Average) and EMA (Exponential Moving Average) for moving average calculations.
 
 
 Enable/Disable MA Condition: Users can toggle the MA condition on or off, depending on whether they want to add moving averages to the trend confirmation process.
 5. Benefits of the Algorithm: 
Easy Identification of Trends: By changing candle colors based on RSI and MA conditions, the algorithm makes it easy for users to visually detect potential trend reversals and trend swings.
Flexible Conditions: The user has full control over the RSI and MA settings, allowing them to adapt the strategy to different market conditions and timeframes.
Clear Visualization: With the candle color changes, users can quickly recognize when a potential uptrend or downtrend is forming, enabling faster decision-making in their trading.
 6. Example Usage: 
Day traders: Can apply this strategy on short timeframes such as 5 minutes or 15 minutes to detect quick trends or reversals.
Swing traders: Can use this strategy on longer timeframes like 1 hour or 4 hours to identify and follow larger market swings.
Intramarket Difference Index StrategyHi Traders !! 
 The IDI Strategy:  
In layman’s terms this strategy compares two indicators across markets and exploits their differences.
 note: it is best the two markets are correlated as then we know we are trading a short to long term deviation from both markets' general trend with the assumption both markets will trend again sometime in the future thereby exhausting our trading opportunity. 
📍  Import Notes:   
 
 This Strategy calculates trade position size independently (i.e. risk per trade is controlled in the user inputs tab), this means that the ‘Order size’ input in the ‘Properties’ tab will have no effect on the strategy. Why ? because this allows us to define custom position size algorithms which we can use to improve our risk management and equity growth over time. Here we have the option to have fixed quantity or fixed percentage of equity ATR (Average True Range) based stops in addition to the turtle trading position size algorithm.
 ‘Pyramiding’ does not work for this strategy’, similar to the order size input togeling this input will have no effect on the strategy as the strategy explicitly defines the maximum order size to be 1. 
 This strategy is not perfect, and as of writing of this post I have not traded this algo. 
 Always take your time to backtests and debug the strategy.
 
🔷  The IDI Strategy: 
By default this strategy pulls data from your current TV chart and then compares it  to the base market, be default  BINANCE:BTCUSD  . The strategy pulls SMA and RSI data from either market (we call this the difference data), standardizes the data (solving the different unit problem across markets) such that it is comparable and then differentiates the data, calling the result of this transformation and difference the Intramarket Difference (ID). The formula for the the ID is 
 
ID = market1_diff_data - market2_diff_data	(1)
Where 
market(i)_diff_data = diff_data / ATR(j)_market(i)^0.5, 
where i = {1, 2} and j = the natural numbers excluding 0  
Formula (1) interpretation is the following 
 
 When ID > 0: this means the current market outperforms the base market
 When ID = 0: Markets are at long run equilibrium
 When ID < 0: this means the current market underperforms the base market
 
To form the strategy we define one of two strategy type’s which are Trend and Mean Revesion respectively. 
🔸  Trend Case: 
Given the ‘‘Strategy Type’’ is equal to TREND we define a threshold for which if the ID crosses over we go long and if the ID crosses under the negative of the threshold we go short. 
The motivating idea is that the ID is an indicator of the two symbols being out of sync, and given we know volatility clustering, momentum and mean reversion of anomalies to be a stylised fact of financial data we can construct a trading premise. Let's first talk more about this premise. 
For some markets (cryptocurrency markets - synthetic symbols in TV) the stylised fact of momentum is true, this means that higher momentum is followed by higher momentum, and given we know momentum to be a vector quantity (with magnitude and direction) this  momentum can be both positive and negative i.e. when the ID crosses above some threshold we make an assumption it will continue in that direction for some time before executing back to its long run equilibrium of 0 which is a reasonable assumption to make if the market are correlated. For example for the BTCUSD - ETHUSD pair, if the ID > +threshold (inputs for MA and RSI based ID thresholds are found under the ‘‘INTRAMARKET DIFFERENCE INDEX’’ group’), ETHUSD outperforms BTCUSD, we assume the momentum to continue so we go long ETHUSD. 
In the standard case we would exit the market when the IDI returns to its long run equilibrium of 0 (for the positive case the ID may return to 0 because ETH’s difference data may have decreased or BTC’s difference data may have increased). However in this strategy we will not define this as our exit condition, why ? 
This is because we want to ‘‘let our winners run’’, to achieve this we define a trailing Donchian Channel stop loss (along with a fixed ATR based stop as our volatility proxy).  If we were too use the 0 exit the strategy may print a buy signal (ID > +threshold in the simple case, market regimes may be used), return to 0 and then print another buy signal, and this process can loop may times, this high trade frequency means we fail capture the entire market move lowering our profit, furthermore on lower time frames this high trade frequencies mean we pay more transaction costs (due to price slippage, commission and big-ask spread) which means less profit. 
By capturing the sum of many momentum moves we are essentially following the trend hence the trend following strategy type. 
 Here we also print the IDI (with default strategy settings with the MA difference type), we can see that by letting our winners run we may catch many valid momentum moves, that results in a larger final pnl that if we would otherwise exit based on the equilibrium condition(Valid trades are denoted by solid green and red arrows respectively and all other valid trades which occur within the original signal are light green and red small arrows).  
another example...
Note: if you would like to plot the IDI separately copy and paste the following code in a new Pine Script indicator template. 
 
indicator("IDI")
// INTRAMARKET INDEX 
var string g_idi = "intramarket diffirence index"
ui_index_1 = input.symbol("BINANCE:BTCUSD", title = "Base market", group = g_idi)
// ui_index_2 = input.symbol("BINANCE:ETHUSD", title = "Quote Market", group = g_idi)
type = input.string("MA", title = "Differrencing Series", options =  , group = g_idi)
ui_ma_lkb = input.int(24, title = "lookback of ma and volatility scaling constant", group = g_idi)
ui_rsi_lkb = input.int(14, title = "Lookback of RSI", group = g_idi) 
ui_atr_lkb = input.int(300, title = "ATR lookback - Normalising value", group = g_idi)
ui_ma_threshold = input.float(5, title = "Threshold of Upward/Downward Trend (MA)", group = g_idi)
ui_rsi_threshold = input.float(20, title = "Threshold of Upward/Downward Trend (RSI)", group = g_idi)
//>>+----------------------------------------------------------------+}
//                                                  CUSTOM FUNCTIONS |
//<<+----------------------------------------------------------------+{
// construct UDT (User defined type) containing the IDI (Intramarket Difference Index) source values 
// UDT will hold many variables / functions grouped under the UDT 
type functions 
    float Close // close price 
    float ma    // ma of symbol 
    float rsi   // rsi of the asset 
    float atr   // atr of the asset 
// the security data 
getUDTdata(symbol, malookback, rsilookback, atrlookback) =>
    indexHighTF = barstate.isrealtime ? 1 : 0
      = request.security(symbol, timeframe = timeframe.period, 
         expression =  [close , // Instentiate UDT variables
          ta.sma(close, malookback) ,
           ta.rsi(close, rsilookback) , 
           ta.atr(atrlookback) ])
    data = functions.new(close_, ma_, rsi_, atr_)  
    data    
    
// Intramerket Difference Index  
idi(type, symbol1, malookback, rsilookback, atrlookback, mathreshold, rsithreshold) =>
    threshold = float(na)
    index1 = getUDTdata(symbol1, malookback, rsilookback, atrlookback)
    index2 = getUDTdata(syminfo.tickerid, malookback, rsilookback, atrlookback)
    // declare difference variables for both base and quote symbols, conditional on which difference type is selected
    var diffindex1 = 0.0, var diffindex2 = 0.0, 
    // declare Intramarket Difference Index based on series type, note 
    // if > 0, index 2 outpreforms index 1, buy index 2 (momentum based) until equalibrium
    // if < 0, index 2 underpreforms index 1, sell index 1 (momentum based) until equalibrium
    // for idi to be valid both series must be stationary and normalised so both series hae he same scale  
    intramarket_difference = 0.0
    if type == "MA" 
        threshold := mathreshold
        diffindex1 := (index1.Close - index1.ma) / math.pow(index1.atr*malookback, 0.5)
        diffindex2 := (index2.Close - index2.ma) / math.pow(index2.atr*malookback, 0.5)
        intramarket_difference := diffindex2 - diffindex1
    else if type == "RSI"
        threshold := rsilookback
        diffindex1 := index1.rsi 
        diffindex2 := index2.rsi 
        intramarket_difference := diffindex2 - diffindex1
     
  
//>>+----------------------------------------------------------------+}
//                                        STRATEGY FUNCTIONS CALLS |
//<<+----------------------------------------------------------------+{
// plot the intramarket difference
  = idi(type, 
                                                                                 ui_index_1, 
                                                                                 ui_ma_lkb, 
                                                                                 ui_rsi_lkb, 
                                                                                 ui_atr_lkb, 
                                                                                 ui_ma_threshold, 
                                                                                 ui_rsi_threshold)
//>>+----------------------------------------------------------------+}
plot(intramarket_difference, color = color.orange)
hline(type == "MA" ? ui_ma_threshold : ui_rsi_threshold, color = color.green)
hline(type == "MA" ? -ui_ma_threshold : -ui_rsi_threshold, color = color.red)
hline(0)
 
Note it is possible that after printing a buy the strategy then prints many sell signals before returning to a buy, which again has the same implication (less profit. Potentially because we exit early only for price to continue upwards hence missing the larger "trend"). The image below showcases this cenario and again, by allowing our winner to run we may capture more profit (theoretically). 
This should be clear...
🔸  Mean Reversion Case: 
We stated prior that mean reversion of anomalies is an standerdies fact of financial data, how can we exploit this ?
We exploit this by normalizing the ID by applying the Ehlers fisher transformation. The transformed data is then assumed to be approximately normally distributed. To form the strategy we employ the same logic as for the z score, if the FT normalized ID > 2.5 (< -2.5) we buy (short). Our exit conditions remain unchanged (fixed ATR stop and trailing Donchian Trailing stop) 
🔷  Position Sizing: 
If ‘‘Fixed Risk From Initial Balance’’ is toggled true this means we risk a fixed percentage of our initial balance, if false we risk a fixed percentage of our equity (current balance). 
Note we also employ a volatility adjusted position sizing formula, the turtle training method which is defined as follows. 
Turtle position size = (1/ r * ATR * DV) * C
Where,
r = risk factor coefficient (default is 20)
ATR(j) = risk proxy, over j times steps 
DV = Dollar Volatility, where DV = (1/Asset Price) * Capital at Risk
🔷   Risk Management: 
Correct money management means we can limit risk and increase reward (theoretically). Here we employ
 
 Max loss and gain per day 
 Max loss per trade
 Max number of consecutive losing trades until trade skip 
 
 To read more see the tooltips (info circle).  
🔷  Take Profit: 
By defualt the script uses a Donchain Channel as a trailing stop and take profit, In addition to this the script defines a fixed ATR stop losses (by defualt, this covers cases where the DC range may be to wide making a fixed ATR stop usefull), ATR take profits however are defined but optional. 
 ATR SL and TP defined for all trades 
🔷  Hurst Regime (Regime Filter):  
The Hurst Exponent (H) aims to segment the market into three different states, Trending (H > 0.5), Random Geometric Brownian Motion (H = 0.5) and Mean Reverting / Contrarian (H < 0.5). In my interpretation this can be used as a trend filter that eliminates market noise. 
We utilize the trending and mean reverting based states, as extra conditions required for valid trades for both strategy types respectively, in the process increasing our trade entry quality.
🔷  Example model Architecture: 
Here is an example of one configuration of this strategy, combining all aspects discussed in this post.
 Future Updates 
- Automation integration (next update) 
AI SuperTrend x Pivot Percentile - Strategy [PresentTrading]█ Introduction and How it is Different
The AI SuperTrend x Pivot Percentile strategy is a sophisticated trading approach that integrates AI-driven analysis with traditional technical indicators. Combining the AI SuperTrend with the Pivot Percentile strategy highlights several key advantages:
1. Enhanced Accuracy in Trend Prediction: The AI SuperTrend utilizes K-Nearest Neighbors (KNN) algorithm for trend prediction, improving accuracy by considering historical data patterns. This is complemented by the Pivot Percentile analysis which provides additional context on trend strength.
2. Comprehensive Market Analysis: The integration offers a multi-faceted approach to market analysis, combining AI insights with traditional technical indicators. This dual approach captures a broader range of market dynamics.
BTC 6H L/S Performance
  
Local
  
█ Strategy: How it Works - Detailed Explanation
🔶 AI-Enhanced SuperTrend Indicators
1. SuperTrend Calculation:
    - The SuperTrend indicator is calculated using a moving average and the Average True Range (ATR). The basic formula is:
        - Upper Band = Moving Average + (Multiplier × ATR)
        - Lower Band = Moving Average - (Multiplier × ATR)
    - The moving average type (SMA, EMA, WMA, RMA, VWMA) and the length of the moving average and ATR are adjustable parameters.
    - The direction of the trend is determined based on the position of the closing price in relation to these bands.
2. AI Integration with K-Nearest Neighbors (KNN):
    - The KNN algorithm is applied to predict trend direction. It uses historical price data and SuperTrend values to classify the current trend as bullish or bearish.
    - The algorithm calculates the 'distance' between the current data point and historical points. The 'k' nearest data points (neighbors) are identified based on this distance.
    - A weighted average of these neighbors' trends (bullish or bearish) is calculated to predict the current trend.
For more please check: Multi-TF AI SuperTrend with ADX - Strategy   
🔶 Pivot Percentile Analysis
1. Percentile Calculation:
    - This involves calculating the percentile ranks for high and low prices over a set of predefined lengths.
    - The percentile function is typically defined as:
        - Percentile = Value at (P/100) × (N + 1)th position
    - Where P is the desired percentile, and N is the number of data points.
2. Trend Strength Evaluation:
    - The calculated percentiles for highs and lows are used to determine the strength of bullish and bearish trends.
    - For instance, a high percentile rank in the high prices may indicate a strong bullish trend, and vice versa for bearish trends.
For more please check: Pivot Percentile Trend - Strategy  
🔶 Strategy Integration
1. Combining SuperTrend and Pivot Percentile:
    - The strategy synthesizes the insights from both AI-enhanced SuperTrend and Pivot Percentile analysis.
    - It compares the trend direction indicated by the SuperTrend with the strength of the trend as suggested by the Pivot Percentile analysis.
2. Signal Generation:
    - A trading signal is generated when both the AI-enhanced SuperTrend and the Pivot Percentile analysis agree on the trend direction.
    - For instance, a bullish signal is generated when both the SuperTrend is bullish, and the Pivot Percentile analysis shows strength in bullish trends.
🔶 Risk Management and Filters
- ADX and DMI Filter: The strategy uses the Average Directional Index (ADX) and the Directional Movement Index (DMI) as filters to assess the trend's strength and direction.
- Dynamic Trailing Stop Loss: Based on the SuperTrend indicator, the strategy dynamically adjusts stop-loss levels to manage risk effectively.
This strategy stands out for its ability to combine real-time AI analysis with established technical indicators, offering traders a nuanced and responsive tool for navigating complex market conditions. The equations and algorithms involved are pivotal in accurately identifying market trends and potential trade opportunities.
█ Usage
To effectively use this strategy, traders should:
1. Understand the AI and Pivot Percentile Indicators: A clear grasp of how these indicators work will enable traders to make informed decisions.
2. Interpret the Signals Accurately: The strategy provides bullish, bearish, and neutral signals. Traders should align these signals with their market analysis and trading goals.
3. Monitor Market Conditions: Given that this strategy is sensitive to market dynamics, continuous monitoring is crucial for timely decision-making.
4. Adjust Settings as Needed: Traders should feel free to tweak the input parameters to suit their trading preferences and to respond to changing market conditions.
█Default Settings and Their Impact on Performance
1. Trading Direction (Default: "Both")
Effect: Determines whether the strategy will take long positions, short positions, or both. Adjusting this setting can align the strategy with the trader's market outlook or risk preference.
2. AI Settings (Neighbors: 3, Data Points: 24)
Neighbors: The number of nearest neighbors in the KNN algorithm. A higher number might smooth out noise but could miss subtle, recent changes. A lower number makes the model more sensitive to recent data but may increase noise.
Data Points: Defines the amount of historical data considered. More data points provide a broader context but may dilute recent trends' impact.
3. SuperTrend Settings (Length: 10, Factor: 3.0, MA Source: "WMA")
Length: Affects the sensitivity of the SuperTrend indicator. A longer length results in a smoother, less sensitive indicator, ideal for long-term trends.
Factor: Determines the bandwidth of the SuperTrend. A higher factor creates wider bands, capturing larger price movements but potentially missing short-term signals.
MA Source: The type of moving average used (e.g., WMA - Weighted Moving Average). Different MA types can affect the trend indicator's responsiveness and smoothness.
4. AI Trend Prediction Settings (Price Trend: 10, Prediction Trend: 80)
Price Trend and Prediction Trend Lengths: These settings define the lengths of weighted moving averages for price and SuperTrend, impacting the responsiveness and smoothness of the AI's trend predictions.
5. Pivot Percentile Settings (Length: 10)
Length: Influences the calculation of pivot percentiles. A shorter length makes the percentile more responsive to recent price changes, while a longer length offers a broader view of price trends.
6. ADX and DMI Settings (ADX Length: 14, Time Frame: 'D')
ADX Length: Defines the period for the Average Directional Index calculation. A longer period results in a smoother ADX line.
Time Frame: Sets the time frame for the ADX and DMI calculations, affecting the sensitivity to market changes.
7. Commission, Slippage, and Initial Capital
These settings relate to transaction costs and initial investment, directly impacting net profitability and strategy feasibility.
HolidayLibrary   "Holiday" 
- Full Control over Holidays and Daylight Savings Time (DLS)
The  Holiday  Library is an essential tool for traders and analysts who engage in  backtesting  and  live trading . This comprehensive library enables the incorporation of crucial calendar elements - specifically  Daylight Savings Time  (DLS) adjustments and  public holidays  - into trading strategies and backtesting environments.
 Key Features: 
-  DLS Adjustments:  The library takes into account the shifts in time due to Daylight Savings. This feature is particularly vital for backtesting strategies, as DLS can impact trading hours, which in turn affects the volatility and liquidity in the market. Accurate DLS adjustments ensure that backtesting scenarios are as close to real-life conditions as possible.
-  Comprehensive Holiday Metadata:  The library includes a rich set of holiday metadata, allowing for the detailed scheduling of trading activities around public holidays. This feature is crucial for avoiding skewed results in backtesting, where holiday trading sessions might differ significantly in terms of volume and price movement.
-  Customizable Holiday Schedules:  Users can add or remove specific holidays, tailoring the library to fit various regional market schedules or specific trading requirements.
-  Visualization Aids:  The library supports on-chart labels, making it visually intuitive to identify holidays and DLS shifts directly on trading charts.
 Use Cases: 
1.  Strategy Development:  When developing trading strategies, it’s important to account for non-trading days and altered trading hours due to holidays and DLS. This library enables a realistic and accurate representation of these factors.
2.  Risk Management:  Trading around holidays can be riskier due to thinner liquidity and greater volatility. By integrating holiday data, traders can better manage their risk exposure.
3.  Backtesting Accuracy:  For backtesting to be effective, it must simulate the actual market conditions as closely as possible. Incorporating holidays and DLS adjustments contributes to more reliable and realistic backtesting results.
4.  Global Trading:  For traders active in multiple global markets, this library provides an easy way to handle different holiday schedules and DLS shifts across regions.
The  Holiday  Library is a versatile tool that enhances the precision and realism of  trading simulations  and  strategy development . Its integration into the trading workflow is straightforward and beneficial for both novice and experienced traders.
 EasterAlgo(_year) 
  Calculates the date of Easter Sunday for a given year using the Anonymous Gregorian algorithm.
`Gauss Algorithm for Easter Sunday` was developed by the mathematician Carl Friedrich Gauss
This algorithm is based on the cycles of the moon and the fact that Easter always falls on the first Sunday after the first ecclesiastical full moon that occurs on or after March 21.
While it's not considered to be 100% accurate due to rare exceptions, it does give the correct date in most cases.
It's important to note that Gauss's formula has been found to be inaccurate for some 21st-century years in the Gregorian calendar. Specifically, the next suggested failure years are 2038, 2051.
This function can be used for Good Friday (Friday before Easter), Easter Sunday, and Easter Monday (following Monday).
en.wikipedia.org
  Parameters:
     _year (int) : `int` - The year for which to calculate the date of Easter Sunday. This should be a four-digit year (YYYY).
  Returns: tuple   - The month (1-12) and day (1-31) of Easter Sunday for the given year.
 easterInit() 
  Inits the date of Easter Sunday and Good Friday for a given year.
  Returns: tuple   - The month (1-12) and day (1-31) of Easter Sunday and Good Friday for the given year.
 isLeapYear(_year) 
  Determine if a year is a leap year.
  Parameters:
     _year (int) : `int` - 4 digit year to check => YYYY
  Returns: `bool` - true if input year is a leap  year
 method timezoneHelper(utc) 
  Helper function to convert UTC time.
  Namespace types: series int, simple int, input int, const int
  Parameters:
     utc (int) : `int` - UTC time shift in hours.
  Returns: `string`- UTC time string with shift applied.
 weekofmonth() 
  Function to find the week of the month of a given Unix Time.
  Returns: number - The week of the month of the specified UTC time.
 dayLightSavingsAdjustedUTC(utc, adjustForDLS) 
  dayLightSavingsAdjustedUTC
  Parameters:
     utc (int) : `int` - The normal UTC timestamp to be used for reference.
     adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS).
  Returns: `int` - The adjusted UTC timestamp for the given normal UTC timestamp.
 getDayOfYear(monthOfYear, dayOfMonth, weekOfMonth, dayOfWeek, lastOccurrenceInMonth, holiday) 
  Function gets the day of the year of a given holiday (1-366)
  Parameters:
     monthOfYear (int) 
     dayOfMonth (int) 
     weekOfMonth (int) 
     dayOfWeek (int) 
     lastOccurrenceInMonth (bool) 
     holiday (string) 
  Returns: `int` - The day of the year of the holiday 1-366.
 method buildMap(holidayMap, holiday, monthOfYear, weekOfMonth, dayOfWeek, dayOfMonth, lastOccurrenceInMonth, closingTime) 
  Function to build the `holidaysMap`.
  Namespace types: map
  Parameters:
     holidayMap (map) : `map` - The map of holidays.
     holiday (string) : `string` - The name of the holiday.
     monthOfYear (int) : `int` - The month of the year of the holiday.
     weekOfMonth (int) : `int` - The week of the month of the holiday.
     dayOfWeek (int) : `int` - The day of the week of the holiday.
     dayOfMonth (int) : `int` - The day of the month of the holiday.
     lastOccurrenceInMonth (bool) : `bool` - Flag indicating whether the holiday is the last occurrence of the day in the month.
     closingTime (int) : `int` - The closing time of the holiday.
  Returns: `map` - The updated map of holidays
 holidayInit(addHolidaysArray, removeHolidaysArray, defaultHolidays) 
  Initializes a HolidayStorage object with predefined US holidays.
  Parameters:
     addHolidaysArray (array) : `array` - The array of additional holidays to be added.
     removeHolidaysArray (array) : `array` - The array of holidays to be removed.
     defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays.
  Returns: `map` - The map of holidays.
 Holidays(utc, addHolidaysArray, removeHolidaysArray, adjustForDLS, displayLabel, defaultHolidays) 
  Main function to build the holidays object, this is the only function from this library that should be needed.  \
all functionality should be available through this function.  \
With the exception of initializing a `HolidayMetaData` object to add a holiday or early close. \
\
**Default Holidays:**  \
`DLS begin`, `DLS end`, `New Year's Day`, `MLK Jr. Day`,  \
`Washington Day`, `Memorial Day`, `Independence Day`, `Labor Day`,  \
`Columbus Day`, `Veterans Day`, `Thanksgiving Day`, `Christmas Day`   \
\
**Example**
```
HolidayMetaData valentinesDay = HolidayMetaData.new(holiday="Valentine's Day", monthOfYear=2, dayOfMonth=14)
HolidayMetaData stPatricksDay = HolidayMetaData.new(holiday="St. Patrick's Day", monthOfYear=3, dayOfMonth=17)
HolidayMetaData  addHolidaysArray = array.from(valentinesDay, stPatricksDay)
string  removeHolidaysArray = array.from("DLS begin", "DLS end")
܂Holidays = Holidays(
܂     utc=-6,
܂     addHolidaysArray=addHolidaysArray,
܂     removeHolidaysArray=removeHolidaysArray,
܂     adjustForDLS=true,
܂     displayLabel=true,
܂     defaultHolidays=true,
܂ )
plot(Holidays.newHoliday ? open : na, title="newHoliday", color=color.red, linewidth=4, style=plot.style_circles)
```
  Parameters:
     utc (int) : `int` - The UTC time shift in hours
     addHolidaysArray (array) : `array` - The array of additional holidays to be added
     removeHolidaysArray (array) : `array` - The array of holidays to be removed
     adjustForDLS (bool) : `bool` - Flag indicating whether to adjust for daylight savings time (DLS)
     displayLabel (bool) : `bool` - Flag indicating whether to display a label on the chart
     defaultHolidays (bool) : `bool` - Flag indicating whether to include the default holidays
  Returns: `HolidayObject` - The holidays object | Holidays = (holidaysMap: map, newHoliday: bool, holiday: string, dayString: string)
 HolidayMetaData 
  HolidayMetaData
  Fields:
     holiday (series string) : `string` - The name of the holiday.
     dayOfYear (series int) : `int` - The day of the year of the holiday.
     monthOfYear (series int) : `int` - The month of the year of the holiday.
     dayOfMonth (series int) : `int` - The day of the month of the holiday.
     weekOfMonth (series int) : `int` - The week of the month of the holiday.
     dayOfWeek (series int) : `int` - The day of the week of the holiday.
     lastOccurrenceInMonth (series bool) 
     closingTime (series int) : `int` - The closing time of the holiday.
     utc (series int) : `int` - The UTC time shift in hours.
 HolidayObject 
  HolidayObject
  Fields:
     holidaysMap (map) : `map` - The map of holidays.
     newHoliday (series bool) : `bool` - Flag indicating whether today is a new holiday.
     activeHoliday (series bool) : `bool` - Flag indicating whether today is an active holiday.
     holiday (series string) : `string` - The name of the holiday.
     dayString (series string) : `string` - The day of the week of the holiday.
Volume ForecastThe Volume Forecast indicator on TradingView is a comprehensive tool designed to analyze historical price action and project future market movements based on the average sizes of candles. Incorporating various data points such as candle high/low, open/close, and real volumes, Volume Forecast provides traders with a holistic view of market dynamics, allowing for more informed decision-making.
Key Features:
Multi-Data Source Analysis:
Volume Forecast seamlessly integrates multiple data sources, including candle high/low, open/close prices, and real volumes. By considering these diverse elements, the indicator offers a nuanced understanding of market conditions.
Historical Candle Size Analysis:
The indicator conducts a thorough analysis of historical candle sizes, capturing key data points to calculate the average candle size over a specified period. This historical context serves as the foundation for forecasting future candle sizes.
Customizable Forecasting Parameters:
Traders have the flexibility to fine-tune forecasting parameters to align with their trading strategies. Whether focusing on open/close relationships, high/low points, or real volumes, users can customize the indicator to suit their preferences.
Predictive Algorithm:
Volume Forecast employs a sophisticated predictive algorithm that leverages historical candle size data to project the potential size of upcoming candles. This algorithmic approach enhances the indicator's accuracy in forecasting market movements.
Visual Clarity:
The indicator provides a clear visual representation on the TradingView chart, displaying historical candle sizes and forecasted values. Color-coded elements and visual cues help traders quickly interpret the data, facilitating timely decision-making.
Adaptive Real-Time Updates:
Volume Forecast dynamically updates in real-time, ensuring traders have access to the latest information. This adaptability allows for swift adjustments to trading strategies in response to changing market conditions.
Comprehensive Market Compatibility:
Whether trading stocks, forex, cryptocurrencies, or commodities, Volume Forecast is compatible across various financial instruments and timeframes. This versatility makes it a valuable asset for traders in different markets.
User-Friendly Interface:
With an intuitive interface, Volume Forecast is accessible to traders of all experience levels. The indicator's user-friendly design streamlines the analysis process, making it easier for traders to incorporate it into their trading routines.
In summary, Volume Forecast is a robust TradingView indicator that combines historical candle size analysis with advanced forecasting techniques. By incorporating multiple data sources and offering customization options, it empowers traders to make more informed decisions in anticipation of market movements. Whether used independently or in conjunction with other tools, Volume Forecast is a valuable asset for traders seeking a comprehensive understanding of market dynamics.
Grid by Volatility (Expo)█  Overview 
The  Grid by Volatility  is designed to provide a dynamic grid overlay on your price chart. This grid is calculated based on the volatility and adjusts in real-time as market conditions change. The indicator uses  Standard Deviation to determine volatility and is useful for traders looking to understand price volatility patterns, determine potential support and resistance levels, or validate other trading signals.
  
█  How It Works 
The indicator initiates its computations by assessing the market volatility through an established statistical model: the Standard Deviation. Following the volatility determination, the algorithm calculates a central equilibrium line—commonly referred to as the "mid-line"—on the chart to serve as a baseline for additional computations. Subsequently, upper and lower grid lines are algorithmically generated and plotted equidistantly from the central mid-line, with the distance being dictated by the previously calculated volatility metrics.
█  How to Use 
 Trend Analysis:  The grid can be used to analyze the underlying trend of the asset. For example, if the price is above the Average Line and moves toward the Upper Range, it indicates a strong bullish trend.
  
 Support and Resistance:  The grid lines can act as dynamic support and resistance levels. Price tends to bounce off these levels or breakthrough, providing potential trade opportunities.
  
 Volatility Gauge:  The distance between the grid lines serves as a measure of market volatility. Wider lines indicate higher volatility, while narrower lines suggest low volatility.
  
█  Settings 
 
  Volatility Length: Number of bars to calculate the Standard Deviation (Default: 200)
  Squeeze Adjustment: Multiplier for the Standard Deviation (Default: 6)
  Grid Confirmation Length: Number of bars to calculate the weighted moving average for smoothing the grid lines (Default: 2)
 
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Machine Learning: kNN (New Approach)Description: 
kNN is a very robust and simple method for data classification and prediction. It is very effective if the training data is large. However, it is distinguished by difficulty at determining its main parameter, K (a number of nearest neighbors), beforehand. The computation cost is also quite high because we need to compute distance of each instance to all training samples. Nevertheless, in algorithmic trading KNN is reported to perform on a par with such techniques as SVM and Random Forest. It is also widely used in the area of data science.
The input data is just a long series of prices over time without any particular features. The value to be predicted is just the next bar's price. The way that this problem is solved for both nearest neighbor techniques and for some other types of prediction algorithms is to create training records by taking, for instance, 10 consecutive prices and using the first 9 as predictor values and the 10th as the prediction value. Doing this way, given 100 data points in your time series you could create 10 different training records. It's possible to create even more training records than 10 by creating a new record starting at every data point. For instance, you could take the first 10 data points and create a record. Then you could take the 10 consecutive data points starting at the second data point, the 10 consecutive data points starting at the third data point, etc.
By default, shown are only 10 initial data points as predictor values and the 6th as the prediction value. 
Here is a step-by-step workthrough on how to compute K nearest neighbors (KNN) algorithm for quantitative data:
1. Determine parameter K = number of nearest neighbors. 
2. Calculate the distance between the instance and all the training samples. As we are  dealing with one-dimensional distance, we simply take absolute value from the instance to  value of x (| x – v |). 
3. Rank the distance and determine nearest neighbors based on the K'th minimum distance.
4. Gather the values of the nearest neighbors.
5. Use average of nearest neighbors as the prediction value of the instance.
The original logic of the algorithm was slightly modified, and as a result at approx. N=17 the resulting curve nicely approximates that of the sma(20). See the description below. Beside the sma-like MA this algorithm also gives you a hint on the direction of the next bar move.
Pulu's 3 Moving Averages 
Pulu's 3 Moving Averages
Release version 1, date 2021-09-28
This script allows you to customize three sets of moving averages, turn on/off, set color and parameters. It also tags the start date of the last set of moving average if there is. This, release version 1, supports eight moving average algorithms:
 
 ALMA, Arnaud Legoux Moving Average 
 EMA, Exponential Moving Average 
 RMA, Adjusted exponential moving average (aka Wilder’s EMA) 
 SMA, Simple Moving Average 
 SWMA, Symmetrically-Weighted Moving Average 
 VWAP, Volume-Weighted Average Price 
 VWMA, Volume-Weighted Moving Average 
 WMA, Weighted Moving Average 
 
The availability and function parameters
 
 Func. Availability Parameters 
 
 ALMA 
 MA1, MA2, MA3 
 source
length
offset
sigma 
 
 
 EMA
RMA
SMA
VWMA
WMA
 
 MA1, MA2, MA3 
 source
length 
 
 
 SWMA
VWAP 
 MA1 
 source 
 
 
Parameters
 
 Parameter Description 
 source the series of values to process. The default is to use the closing price to calculate the moving average. 
 length an integer value that defines the number of bars to calculate the moving average on. The SWMA and VWAP do not use this parameter. 
 ALMA offset a floating-point value that controls the tradeoff between smoothness (with a value closer to 1) and responsiveness (with a value closer to 0). This parameter is only used by ALMA. 
 ALMA sigma a floating-point value that specifies the ALMA’s smoothness. The larger this value, the smoother the moving average is. This parameter is only used by ALMA. 
 
I'm not sure if it is needed, so I do not let the three Moving Averages of the script to have indivial algorithm setting. Because that will involve much complicated condition testing and use up more TradingView script lines limit. If you need to combine different algorithms in the three sets of moving averages, or have other ideas, leave a message to let me know; maybe I will try it in the next update.
我不確定是否需要,所以我沒有讓腳本的三組移動平均線有各別的算法設置。因為這將涉及更多複雜的條件測試,並使用更多 TradingView 腳本列數限制。如果您需要在三組均線中組合不同的算法,或者有其他想法,請留言告訴我;也許我會在下一次更新中嘗試。 






















