Close Minus Moving Average█ OVERVIEW
The Close Minus Moving Average (CMMA) is a statistically robust mean reversion indicator designed to identify potential reversal points in the market. By analyzing the relationship between the closing price and its moving average, CMMA provides traders with actionable insights to enhance their trading strategies.
Important
This indicator requires the use of the MathHelpers library published by HuntGatherTrade
█ CONCEPTS
The CMMA indicator operates by calculating the logarithmic difference between the current closing price and its simple moving average (SMA). This difference is then normalized using the Average True Range (ATR) to account for market volatility. The resulting value is transformed using the Cumulative Distribution Function (CDF) to produce a standardized metric that oscillates around zero.
Key Steps :
Logarithmic Calculation: Computes the natural logarithm of the closing prices.
Moving Average: Applies a simple moving average to the logarithmic closing prices.
ATR Normalization: Utilizes ATR to normalize the difference, ensuring the indicator adapts to varying market conditions.
CDF Transformation: Transforms the normalized difference to a scale that highlights mean reversion tendencies.
Mean Reversion
Mean reversion is a financial theory suggesting that asset prices and historical returns eventually return to the long-term mean or average level of the entire dataset. The CMMA leverages this concept to signal potential entry and exit points based on deviations from the moving average.
█ FEATURES
Adaptive Normalization: Utilizes ATR to adjust for market volatility, ensuring consistent performance across different market conditions.
Statistical Robustness: Built upon methodologies from Timothy Masters, ensuring reliable mean reversion signals.
Clear Visuals: Differentiates positive and negative deviations with distinct color coding for easy interpretation.
Customizable Parameters: Allows users to adjust lookback periods and ATR lengths to tailor the indicator to their specific trading needs
.
█ HOW TO USE
Add the Indicator :
Navigate to the Pine Script editor on TradingView.
Paste the CMMA script and add it to your chart.
Adjust Parameters :
Lookback Period: Determines the number of periods for calculating the moving average of the logarithmic close. Default is 1.
ATR Length: Sets the number of periods for ATR calculation. Default is 252.
Interpret Signals :
Green Plot: Indicates that the closing price is above the moving average, suggesting bullish momentum.
Red Plot: Indicates that the closing price is below the moving average, suggesting bearish momentum.
Zero Line: Serves as a reference point for mean reversion signals.
Trading Strategy :
Buy Signal: When CMMA crosses above the zero line, indicating a potential upward reversal.
Sell Signal: When CMMA crosses below the zero line, indicating a potential downward reversal.
█ LIMITATIONS
Lagging Indicator: As with all moving averages, CMMA is based on historical data and may lag during rapid market movements.
Parameter Sensitivity: The effectiveness of CMMA can vary based on the chosen lookback and ATR periods. Users should optimize these parameters based on the specific asset and timeframe.
Market Conditions: Best suited for mean-reverting markets and may underperform in trending or highly volatile environments.
█ NOTES
Version Compatibility: The CMMA script is written in Pine Script™ version 6. Ensure your TradingView environment supports this version.
License: This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0. Read the license here.
Statistics
MathHelpersLibrary "MathHelpers"
Overview
A collection of helper functions for designing indicators and strategies.
calculateATR(length, log)
Calculates the Average True Range (ATR) or Log ATR based on the 'log' parameter. Sans Wilder's Smoothing
Parameters:
length (simple int)
log (simple bool)
Returns: float The calculated ATR value. Returns Log ATR if `log` is true, otherwise returns standard ATR.
CDF(z)
Computes the Cumulative Distribution Function (CDF) for a given value 'z', mimicking the CDF function in "Statistically Sound Indicators" by Timothy Masters.
Parameters:
z (simple float)
Returns: float The CDF value corresponding to the input `z`, ranging between 0 and 1.
logReturns(lookback)
Calculates the logarithmic returns over a specified lookback period.
Parameters:
lookback (simple int)
Returns: float The calculated logarithmic return. Returns `na` if insufficient data is available.
MultiSector Performance Tracker [LuxAlgo]The MultiSector Performance Tracker tool shows the overall performance of different crypto market sectors within a selected time frame, overlaid on a single chart for easy comparison.
Users can customize the time frame to suit their specific needs, whether daily, weekly, monthly, or yearly.
🔶 USAGE
The tool displays the performance of up to 6 crypto sectors within a selected time period, such as each day, week, month or year, or from the beginning of the year for any of the last 4 years.
The sectors and tickers within each sector are as follows:
Layer 1: CRYPTOCAP:ETH CRYPTOCAP:SOL CRYPTOCAP:TON
Layer 2: SEED_DONKEYDAN_MARKET_CAP:MATIC TSX:MNT AMEX:ARB
CEX: CRYPTOCAP:BNB CRYPTOCAP:OKB NYSE:BGB
DEX: CRYPTOCAP:UNI LSE:JUP CRYPTOCAP:RUNE
AI: CRYPTOCAP:NEAR GETTEX:TAO CRYPTOCAP:ICP
Ethereum Memes: CRYPTOCAP:PEPE CRYPTOCAP:SHIB CRYPTOCAP:FLOKI
Traders can compare the relative performance of a custom ticker against the sector of their choice and view the average of all sectors.
The tool is fully customizable, allowing traders to enable or disable any of the features or sectors.
🔹 Dashboard
The tool also displays the data in an ascending or descending sector performance dashboard, allowing traders to see at a glance which sectors are overperforming or underperforming.
Other dashboard features include custom ticker vs. sector comparison and sectors average, and traders can choose the location and size of the dashboard.
🔶 SETTINGS
Period: View all data by time period, daily, weekly, etc. Or view data from last year, last 2 years, etc.
Relative Performance Against: Enable/Disable relative performance comparison against a sector.
Use chart ticker: Enable the use of the chart ticker or a custom ticker for relative performance comparison.
🔹 Dashboard
Show Dashboard: Enable / disable Dashboard display.
Order: Choose between ascending and descending order.
Position: Selection of dashboard location.
Size: Selection of dashboard size.
🔹 Style
Show Sectors Labels: Enable / disable sector labels
Layer 1: Enable / disable Layer 1 sector
Layer 2: Enable / disable Layer 2 sector
CEX: Enable / disable CEX sector
DEX: Enable / disable DEX sector
AI: Enable / disable AI sector
Ethereum Memes: Enable / disable Ethereum Memes sector
Average: Enable / disable sectors average display
Custom Ticker: Enable / disable custom ticker display
Global Index Spread RSI StrategyThis strategy leverages the relative strength index (RSI) to monitor the price spread between a global benchmark index (such as AMEX) and the currently opened asset in the chart window. By calculating the spread between these two, the strategy uses RSI to identify oversold and overbought conditions to trigger buy and sell signals.
Key Components:
Global Benchmark Index: The strategy compares the current asset with a predefined global index (e.g., AMEX) to measure relative performance. The choice of a global benchmark allows the trader to analyze the current asset's movement in the context of broader market trends.
Spread Calculation:
The spread is calculated as the percentage difference between the current asset's closing price and the global benchmark index's closing price:
Spread=Current Asset Close−Global Index CloseGlobal Index Close×100
Spread=Global Index CloseCurrent Asset Close−Global Index Close×100
This metric provides a measure of how the current asset is performing relative to the global index. A positive spread indicates the asset is outperforming the benchmark, while a negative spread signals underperformance.
RSI of the Spread: The RSI is then calculated on the spread values. The RSI is a momentum oscillator that ranges from 0 to 100 and is commonly used to identify overbought or oversold conditions in asset prices. An RSI below 30 is considered oversold, indicating a potential buying opportunity, while an RSI above 70 is overbought, suggesting that the asset may be due for a pullback.
Strategy Logic:
Entry Condition: The strategy enters a long position when the RSI of the spread falls below the oversold threshold (default 30). This suggests that the asset may have been oversold relative to the global benchmark and might be due for a reversal.
Exit Condition: The strategy exits the long position when the RSI of the spread rises above the overbought threshold (default 70), indicating that the asset may have become overbought and a price correction is likely.
Visual Reference:
The RSI of the spread is plotted on the chart for visual reference, making it easier for traders to monitor the relative strength of the asset in relation to the global benchmark.
Overbought and oversold levels are also drawn as horizontal reference lines (70 and 30), along with a neutral level at 50 to show market equilibrium.
Theoretical Basis:
The strategy is built on the mean reversion principle, which suggests that asset prices tend to revert to a long-term average over time. When prices move too far from this mean—either being overbought or oversold—they are likely to correct back toward equilibrium. By using RSI to identify these extremes, the strategy aims to profit from price reversals.
Mean Reversion: According to financial theory, asset prices oscillate around a long-term average, and any extreme deviation (overbought or oversold conditions) presents opportunities for price corrections (Poterba & Summers, 1988).
Momentum Indicators (RSI): The RSI is widely used in technical analysis to measure the momentum of an asset. Its application to the spread between the asset and a global benchmark allows for a more nuanced view of relative performance and potential turning points in the asset's price trajectory.
Practical Application:
This strategy works best in markets where relative strength is a key factor in decision-making, such as in equity indices, commodities, or forex markets. By assessing the performance of the asset relative to a global benchmark and utilizing RSI to identify extremes in price movements, the strategy helps traders to make more informed decisions based on potential mean reversion points.
While the "Global Index Spread RSI Strategy" offers a method for identifying potential price reversals based on relative strength and oversold/overbought conditions, it is important to recognize that no strategy is foolproof. The strategy assumes that the historical relationship between the asset and the global benchmark will hold in the future, but financial markets are subject to a wide array of unpredictable factors that can lead to sudden changes in price behavior.
Risk of False Signals:
The strategy relies heavily on the RSI to trigger buy and sell signals. However, like any momentum-based indicator, RSI can generate false signals, particularly in highly volatile or trending markets. In such conditions, the strategy may enter positions too early or exit too late, leading to potential losses.
Market Context:
The strategy may not account for macroeconomic events, news, or other market forces that could cause sudden shifts in asset prices. External factors, such as geopolitical developments, monetary policy changes, or financial crises, can cause a divergence between the asset and the global benchmark, leading to incorrect conclusions from the strategy.
Overfitting Risk:
As with any strategy that uses historical data to make decisions, there is a risk of overfitting the model to past performance. This could result in a strategy that works well on historical data but performs poorly in live trading conditions due to changes in market dynamics.
Execution Risks:
The strategy does not account for slippage, transaction costs, or liquidity issues, which can impact the execution of trades in real-market conditions. In fast-moving markets, prices may move significantly between order placement and execution, leading to worse-than-expected entry or exit prices.
No Guarantee of Profit:
Past performance is not necessarily indicative of future results. The strategy should be used with caution, and risk management techniques (such as stop losses and position sizing) should always be implemented to protect against significant losses.
Traders should thoroughly test and adapt the strategy in a simulated environment before applying it to live trades, and consider seeking professional advice to ensure that their trading activities align with their risk tolerance and financial goals.
References:
Poterba, J. M., & Summers, L. H. (1988). Mean Reversion in Stock Prices: Evidence and Implications. Journal of Financial Economics, 22(1), 27-59.
Global vs National Index Spread RSIThe Global vs National Index Spread RSI indicator visualizes the relative strength of national stock indices compared to a global benchmark (e.g., AMEX). It calculates the percentage spread between the closing prices of each national index and the global index, applying the Relative Strength Index (RSI) to each spread.
How It Works
Spread Calculation: The spread represents the percentage difference between a national index and the global index.
RSI Application: RSI is applied to these spreads to identify overbought or oversold conditions in the relative performance of the national indices.
Reference Lines: Overbought (70), oversold (30), and neutral (50) levels help guide interpretation.
Insights from Research
The correlation between global and national indices provides insights into market integration and interdependence. Studies such as Forbes & Rigobon (2002) emphasize the importance of understanding these linkages during periods of financial contagion. Observing spread trends with RSI can aid in identifying shifts in investor sentiment and regional performance anomalies.
Use Cases
- Detect divergences between national and global markets.
- Identify overbought or oversold conditions for specific indices.
- Complement portfolio management strategies by monitoring geographic performance.
References
Forbes, K. J., & Rigobon, R. (2002). "No contagion, only interdependence: Measuring stock market co-movements." Journal of Finance.
Eun, C. S., & Shim, S. (1989). "International transmission of stock market movements." Journal of Financial and Quantitative Analysis.
[SGM VaR Stats VS Empirical]Main Functions
Logarithmic Returns & Historical Data
Calculates logarithmic returns from closing prices.
Stores these returns in a dynamic array with a configurable maximum size.
Approximation of the Inverse Error Function
Uses an approximation of the erfinv function to calculate z-scores for given confidence levels.
Basic Statistics
Mean: Calculates the average of the data in the array.
Standard Deviation: Measures the dispersion of returns.
Median: Provides a more robust measure of central tendency for skewed distributions.
Z-Score: Converts a confidence level into a standard deviation multiplier.
Empirical vs. Statistical Projection
Empirical Projection
Based on the median of cumulative returns for each projected period.
Applies an adjustable confidence filter to exclude extreme values.
Statistical Projection
Relies on the mean and standard deviation of historical returns.
Incorporates a standard deviation multiplier for confidence-adjusted projections.
PolyLines (Graphs)
Generates projections visually through polylines:
Statistical Polyline (Blue): Based on traditional statistical methods.
Empirical Polyline (Orange): Derived from empirical data analysis.
Projection Customization
Maximum Data Size: Configurable limit for the historical data array (max_array_size).
Confidence Level: Adjustable by the user (conf_lvl), affects the width of the confidence bands.
Projection Length: Configurable number of projected periods (length_projection).
Key Steps
Capture logarithmic returns and update the historical data array.
Calculate basic statistics (mean, median, standard deviation).
Perform projections:
Empirical: Based on the median of cumulative returns.
Statistical: Based on the mean and standard deviation.
Visualization:
Compare statistical and empirical projections using polylines.
Utility
This script allows users to compare:
Traditional Statistical Projections: Based on mathematical properties of historical returns.
Empirical Projections: Relying on direct historical observations.
Divergence or convergence of these lines also highlights the presence of skewness or kurtosis in the return distribution.
Ideal for traders and financial analysts looking to assess an asset’s potential future performance using combined statistical and empirical approaches.
Enhanced Entropy Trading SystemEnhaոсeԁ Entrору Trаdiոg Sуstem - Cоmpreheոsіνe Gսiԁe
Oνerνіew
Thіs iոԁiсatоr is aո adνаոсed traԁіոg system that соmbiոes entrорy аnalуsis wіth mսltіple aԁaрtіνe filters to iԁeոtіfy high-рrobаbilіtу trаdіng орроrtuոіties. It meаsսres market rаndomոess (eոtrорy) and uses іt аlоngsiԁe νоlսme аnԁ vоlаtіlіtу to geոerate trаdiոg sigոаls.
Cоre Cоmроոeոts
1. Enhanced Entrору Aոalysis
Cаlсսlates mаrket eոtrору (measure оf rаոԁоmոess/orԁer іn рrісe movemeոts)
Uses аdaptіve cаlculatіоոs bаseԁ оո:
Volume weightіng
Vоlаtіlіtу sсalіոg
Dуոamіс leոgth aԁјustmeոt
Helрs іdeոtifу shifts betweeո orԁereԁ аոԁ rаndоm mаrket states
2. Aԁaptіνe Filters
The system іnclսԁes seνeral customizable fіlters:
Adаptiνe Leոgth: Autоmatiсаllу aԁјսsts сalсսlаtіoո рerіоԁs bаseԁ oո market conԁitіоոs
Vоlսme Weightіոg: Iոсоrpоrates vоlume аnаlуsis fоr sіgոаl vаlіdаtiоn
Vоlatіlіty Sсaling: Aԁjusts sensіtiνіtу bаseԁ оn mаrket νоlatіlіty
Hսrst Eхроոeոt: Meаsսres trenԁ persіstence
Lуарսոоv Expоոeոt: Meаsսres chаos/stabіlity iո priсe mоvemeոt
Treոd Fіlter: Uses mоνіոg aνerаge сrossoνers for treոԁ сoոfіrmаtiоո
Dаshboard Iոterрretаtion
1. Treոd Anаlуsis
Shоws сurreոt treոd state: Strоոg/Weаk Uрtrenԁ оr Dowոtrenԁ
Bаsed оn mսltіple EMA relаtіoոshіps (20, 50, 200)
Cоlоr cоԁіոg: Greeո (strоng սр), Lime (weak սp), Red (strоոg dowո), Orаոge (weаk ԁоwո)
2. Prісe Rаոge
Iոԁісаtes cսrrent market νоlаtіlity соոteхt
Clаssifіcаtіоns: Wіde, Normal, оr Tіght rаnge
Perсentаge-baseԁ meаsսrement оνer 20 perіоds
Helps wіth роsіtiоn sizіոg aոԁ stоp placement
3. Rаոge Pоsіtiоn
Shows where price іs withіո its curreոt rаոge
Stаtes: Overboսght, Neutral, or Oνersоlԁ
Perсeոtаge-bаsed рosition (0-100%)
Useful for mean reνersіoո trаԁes
4. Prісe Pаtterո
Iԁentifies сսrrent рriсe actіoո patterո
Patterոs іnсlսde: Breakоut, Breakdоwո, Resistаոce Test, Sսpрort Test, Rаnge Boսnd
Helps with eոtrу timіng аnԁ patterո trаdіng
Sуstem Use Suggestіоոs
1. Initіаl Setuр
Eոable/dіsаble desіred filters based оո уоur trаԁіng stуle
Aԁјսst sensitіνіtу settiոgs if ոeeԁed
Mоոіtоr the dаshboard for mаrket соոtext
2. Trаԁіng Process
Market Aոаlуsіs:
Check Treոd Analysіs fоr оνerall ԁіreсtion
Reνіew Priсe Rаnge for vоlаtіlіty соոteхt
Cоոfirm Rаnge Posіtion fоr сусle loсаtіоո
Verіfу Prісe Pаtterո fоr entry timіոg
Sіgnal Valіdatioո:
Wait fоr buу/sell sіgոal
Cоոfіrm wіth dаshboаrԁ metriсs
Check аll аctіνe fіlters
Verifу νоlսme аոԁ νolаtіlіtу соոԁіtiоns
Trаԁe Maոаgemeոt:
Use Prіce Raոge for stор lоss рlаcemeոt
Coոsіԁer Rаոge Pоsіtiоո for profit tаrgets
Mоոіtоr Patterո recоgոіtіоո fоr eхit sіgոals
Aԁjսst роsitіoո size baseԁ oո Range wіdth
Best Prаctісes
Signal Streոgth:
Strongest sіgոаls oсcսr when all fіlters alіgո
Lоok fоr patterո сonfіrmаtіon іո ԁashbоаrԁ
Wаіt fоr cleаr treոԁ ԁireсtiоո
Verіfу vоlume sսрport
Rіsk Managemeոt:
Use wіԁer stорs іn Wіԁe Rаոge mаrkets
Tіghter stoрs iո Tіght Range markets
Scаle pоsіtіоn sіze bаseԁ оո Raոge wіdth
Consіԁer Raոge Pоsіtіоո fоr entrу timing
Mаrket Cоոԁіtions:
Most effectіνe іո treոԁіng markets
Use саսtiоո іn eхtremely vоlatile perіoԁs
Adjսst strаtegу baseԁ оո Range state
Consiԁer Patterո sigոаls fоr entrу/eхіt
Aԁԁіtіоnal Tірs
Optimіzatіoո:
Start wіth all filters enableԁ
Remоve filters thаt dоn't sսіt yoսr tіmefrаme
Adјսst leոgths baseԁ оո yоսr trаdіոg stуle
Mоոіtоr рerformanсe аnd aԁjսst aссorԁіnglу
Cоmmoո Mіstаkes to Aνоіd:
Don't trаԁe аgаіոst the mаіn treոԁ
Aνоiԁ fоrсiոg trades iո սոсleаr coոdіtioոs
Don't іgnоre νolսme aոԁ vоlatіlity соոteхt
Dоn't oνerrіԁe sуstem sіgnаls
Chaikin's Money FlowOverview : Chaikin's Money Flow (CMF) is a momentum indicator that measures the buying and selling pressure of a financial instrument over a specified period. By incorporating both price and volume, CMF provides a comprehensive view of market sentiment, helping traders identify potential trend reversals and confirm the strength of existing trends.
Key Features:
Volume-Weighted : Unlike price-only indicators, CMF accounts for trading volume, offering deeper insights into the forces driving price movements.
Oscillatory Nature : CMF oscillates between positive and negative values, typically ranging from -100 to +100, indicating the balance between buying and selling pressure.
Trend Confirmation : Positive CMF values suggest accumulating buying pressure, while negative values indicate distributing selling pressure. This aids in confirming the direction and strength of trends.
Calculation Details :
Intraday Intensity (II) = 100 × (2×Close−High−Low) / (High−Low) × Volume
Condition: If High=Low, II is set to 0 to prevent division by zero.
II_smoothed = SMA(II, lookback)
Applies a Simple Moving Average (SMA) to the Intraday Intensity over the defined lookback period to smooth out short-term fluctuations.
Volume Smoothing:
V_smoothed = EMA(Volume, Volume Smoothing Period)
Utilizes an Exponential Moving Average (EMA) to smooth the volume over the specified smoothing period, giving more weight to recent data.
Money Flow Calculation:
Money Flow = II_smoothed / V_smoothed
Condition: If Vsmoothed=0Vsmoothed=0, Money Flow is set to 0 to avoid division by zero.
Usage Instructions:
Parameters Configuration:
Lookback Period: Determines the number of periods over which Intraday Intensity is averaged. A higher value results in a smoother indicator, reducing sensitivity to short-term price movements.
Volume Smoothing Period: Defines the period for the EMA applied to Volume. Adjusting this parameter affects the responsiveness of the Money Flow indicator to changes in trading volume.
Interpreting the Indicator:
Positive Values (>0): Indicate buying pressure. The higher the value, the stronger the buying interest.
Negative Values (<0): Signal selling pressure. The lower the value, the more intense the selling activity.
Crossovers: Watch for Money Flow crossing above the zero line as potential buy signals and crossing below as potential sell signals.
Divergence: Identify divergences between Money Flow and price movements to anticipate possible trend reversals.
Complementary Analysis:
Confluence with Other Indicators: Use CMF in conjunction with trend indicators like Moving Averages or oscillators like RSI to enhance signal reliability.
Volume Confirmation: CMF's volume-weighted approach makes it a powerful tool for confirming the validity of price trends and breakouts.
Acknowledgment: This implementation of Chaikin's Money Flow Indicator is inspired by and derived from the methodologies presented in "Statistically Sound Indicators" by Timothy Masters. The indicator has been meticulously translated to Pine Script to maintain the statistical integrity and effectiveness outlined in the source material.
Disclaimer: The Chaikin's Money Flow Indicator is a tool designed to assist in trading decisions. It does not guarantee profits and should be used in conjunction with other analysis methods. Trading involves risk, and it's essential to perform thorough testing and validation before deploying any indicator in live trading environments.
Gains and Drawdowns with Standard DeviationsThis “Gains and Drawdowns with Standard Deviations” indicator helps in analyzing and visualizing the percentage gains and drawdown phases of a market or asset relative to its historical range. By calculating gains from the lowest low and drawdowns from the highest high over a specified lookback period, this indicator provides deeper insights into price movements and risk.
Key Features and Applications:
1. Gain and Drawdown Calculation:
• Gains: The indicator calculates the percentage gain from the lowest price point within a specific lookback period (e.g., 250 days).
• Drawdowns: Drawdowns are calculated as the percentage change from the highest point in the same period. This helps in identifying the maximum loss phases.
2. Standard Deviation:
• The indicator computes the standard deviation of both gains and drawdowns over a specified period (e.g., 250 days), allowing you to quantify volatility.
• Three bands (1st, 2nd, and 3rd standard deviations) are plotted for both gains and drawdowns, representing the frequency and magnitude of price movements within the normal volatility range.
3. Extreme Movements Highlighting:
• The indicator highlights extreme gains and drawdowns when they exceed user-defined thresholds. This helps in identifying significant market events or turning points.
4. Customizable Thresholds:
• Users can adjust the thresholds for extreme gains and drawdowns, as well as the lookback period for calculating gains, drawdowns, and standard deviations, making the indicator highly adaptable to specific needs.
Application in Portfolio Management:
The use of standard deviation in portfolio management is essential for assessing the risk and volatility of a portfolio. According to Modern Portfolio Theory (MPT) by Harry Markowitz, diversification of assets in a portfolio helps to minimize overall risk (especially the standard deviation), while maximizing returns. The standard deviation of a portfolio measures the volatility of its returns, with higher standard deviation indicating higher risk.
Scientific Source: Markowitz, H. M. (1952). Portfolio Selection. The Journal of Finance, 7(1), 77-91.
Markowitz’s theory suggests that an optimized portfolio, by minimizing the standard deviation of returns and combining a diversified asset allocation, can achieve better risk-adjusted returns.
Conclusion:
This indicator is particularly useful for traders and portfolio managers who want to understand and visualize market risk and extreme events. By using gains, drawdowns, and volatility metrics, it allows for systematic monitoring and evaluation of price movements, leading to more informed decisions in trading or portfolio management. A comprehensive understanding of price behavior and volatility helps in optimizing risk management and making strategic market entries.
Key Features:
• Visualization of Gains and Drawdowns with color-coded highlights for extreme movements.
• Standard Deviation Calculations for detailed volatility analysis.
• Customizable Thresholds for identifying extreme market events.
This indicator is a valuable tool for analyzing market data from a scientific standpoint, improving risk management, and making data-driven decisions based on historical performance.
Buy When There's Blood in the Streets StrategyStatistical Analysis of Drawdowns in Stock Markets
Drawdowns, defined as the decline from a peak to a trough in asset prices, are an essential measure of risk and market dynamics. Their statistical properties provide insights into market behavior during extreme stress periods.
Distribution of Drawdowns: Research suggests that drawdowns follow a power-law distribution, implying that large drawdowns, while rare, are more frequent than expected under normal distributions (Sornette et al., 2003).
Impacts of Extreme Drawdowns: During significant drawdowns (e.g., financial crises), the average recovery time is significantly longer, highlighting market inefficiencies and behavioral biases. For example, the 2008 financial crisis led to a 57% drawdown in the S&P 500, requiring years to recover (Cont, 2001).
Using Standard Deviations: Drawdowns exceeding two or three standard deviations from their historical mean are often indicative of market overreaction or capitulation, creating contrarian investment opportunities (Taleb, 2007).
Behavioral Finance Perspective: Investors often exhibit panic-selling during drawdowns, leading to oversold conditions that can be exploited using statistical thresholds like standard deviations (Kahneman, 2011).
Practical Implications: Studies on mean reversion show that extreme drawdowns are frequently followed by periods of recovery, especially in equity markets. This underpins strategies that "buy the dip" under specific, statistically derived conditions (Jegadeesh & Titman, 1993).
References:
Sornette, D., & Johansen, A. (2003). Stock market crashes and endogenous dynamics.
Cont, R. (2001). Empirical properties of asset returns: stylized facts and statistical issues. Quantitative Finance.
Taleb, N. N. (2007). The Black Swan: The Impact of the Highly Improbable.
Kahneman, D. (2011). Thinking, Fast and Slow.
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency.
USDEGP Rate MultipleIndicator shows the ratio between USDEGP rate calculated using CIB GDR and the official rate. In no stress, value should be stable.
London USDEGP priceThis indicator calculates the hypothetical USDEGP price using CIB receipts price in London Stock Exchange and its price in EGX. Values are smoothed.
Tims Smart Money COT-IndexThe **Tims Smart Money COT Index** analyzes the positions of different groups of market participants from the COT report (Commercials, Large Specs, Small Specs). It calculates their net positions and scales them relative to extremes of the last 24 weeks. It indicates bullish and bearish zones to identify market sentiments.
- Commercials (Smart Money)**: Often act against the trend, bullish from 80+.
- Large Specs (Retail Money)**: Trend-following, bullish from 80+.
- Small Specs**: Mostly impulsive, bullish from 80+.
The indicator helps to identify turning points in the market based on the behavior of the players.
COT Commercials Positions Table Der COT Commercials Opposite Positions Table for Forex ist ein umfangreicher TradingView-Indikator, der die Positionen der kommerziellen Marktteilnehmer (Commercials) im Rahmen des Commitments of Traders (COT)-Berichts darstellt. Er zeigt Long-, Short-, und Netto-Positionen sowie deren prozentuale Anteile für ausgewählte Märkte an.
Hauptmerkmale:
Datenquellenwahl: Unterstützt "Futures Only" und "Futures and Options".
Marktabdeckung: Umfasst Währungen, Rohstoffe, Indizes und Kryptowährungen.
Farbkodierung: Dynamische Farbverläufe zur Hervorhebung von Extremen bei Long-/Short-Positionen und Prozentsätzen.
Historische Daten: Zeigt Positionsdaten der letzten 10 Wochen an.
Anpassbare Tabelle: Klar strukturiert mit wichtigen Kennzahlen wie max./min. Positionen und Netto-Positionen.
Der Indikator ist besonders für Trader nützlich, die Marktstimmungen analysieren und Positionierungen großer Marktteilnehmer in ihre Handelsentscheidungen einbeziehen möchten.
Der Indikator ist hauptsächlich für Futures gedacht und funktioniert nur im 1 Woche Chart.
PR50 AutoI have observed price revisits the 50% Percentile Rank of previous pivot highs and lows with in a decay window of up to 288 bars, but notably 144 bars in a rather systematic way. When watching price, lines will breakout out towards price. a good indicator price and line will meet at some point. Continuation of trends can be seen when price is rejected of previous high/low. Price will also bounce between structure high and low 50% PR.
I provide a this script to auto calculate and populate these lines. The default decay is set to 288, and transparency of lines are determined by the decay.
i provide a levels indicator to show the percentage of lines where price is above and below the start point of the lines at full decay and half. With defaults, 288 and 144 bars respectfully. it is not an indicator to buy or sell, but to demonstrate price is either above or below the distribution of lines.
MA Ratio Weighted Trend System I [InvestorUnknown]The MA Ratio Weighted Trend System I combines slow and fast indicators to identify stable trends and capture potential market turning points. By dynamically adjusting the weight of fast indicators based on the Moving Average Ratio (MAR), the system aims to provide timely entry and exit signals while maintaining overall trend stability through slow indicators.
Slow and Fast Indicators with Dynamic Weighting
Slow Indicators: Designed for stable trend identification, these indicators maintain a constant weight in the overall signal calculation. They include:
DMI For Loop (Directional Movement Index)
CCI For Loop (Commodity Channel Index)
Aroon For Loop
Fast Indicators: Aim to detect rapid market changes and potential turning points. Their weights are dynamically adjusted based on the absolute value of the Moving Average Ratio (MAR). Fast indicators include:
ZLEMA For Loop (Zero-Lag Exponential Moving Average)
IIRF For Loop (Infinite Impulse Response Filter)
Dynamic Weighting Mechanism:
Moving Average Ratio (MAR) is calculated as the ratio of the price to its moving average, minus one (for simplicity and visualization).
Weight Calculation
Fast indicator weights are determined based on the absolute value of MAR, possibly with an offset to avoid scenarios where MAR follows rapid price reversals too closely:
// Function to calculate weights based on MAR
f_mar_weights(series float mar, simple int offset, simple float weight_thre) =>
o_mar = math.abs(mar )
float fast_weight = 0
float slow_weight = 1
if o_mar != 0
if weight_thre > 0
if o_mar <= weight_thre
fast_weight := o_mar
else
fast_weight := o_mar
Threshold-Based vs. Continuous Weighting:
Threshold-Based: Fast indicators receive weight only when the absolute MAR exceeds a user-defined threshold (weight_thre).
Continuous: By setting weight_thre to zero, fast indicators always receive some weight, though this may increase false signals.
Offset Mechanism
The offset parameter shifts the MAR used for weighting by a certain number of bars. This helps avoid situations where the MAR follows sudden price movements too closely, preventing fast indicators from failing to provide timely exit signals.
Signal Calculation
The final signal is a weighted average of the slow and fast indicators:
// Calculate Signal (as weighted average)
float sig = math.round(((DMI*slow_w) + (CCI*slow_w) + (Aroon*slow_w) + (ZLEMA*fast_w) + (IIRF*fast_w)) / (3*slow_w + 2*fast_w), 2)
Backtesting and Performance Metrics
Enables users to test the indicator's performance over historical data, comparing it to a buy-and-hold strategy.
Alerts
Set up alerts for when the signal crosses above or below the thresholds.
alertcondition(long_alert, "LONG (MAR Weighted Trend System)", "MAR Weighted Trend System flipped ⬆LONG⬆")
alertcondition(short_alert, "SHORT (MAR Weighted Trend System)", "MAR Weighted Trend System flipped ⬇Short⬇")
Important Notes
Customization: Due to the experimental nature of this indicator, users are strongly encouraged to adjust and calibrate the settings to align with their trading strategies and market conditions.
Default Settings Disclaimer: The default settings are not optimized or recommended for any specific use and serve only as placeholders for the indicator's publication.
Backtest Results Disclaimer: Historical backtest results are not indicative of future performance. Market conditions change, and past results do not guarantee future outcomes.
Sharpe Ratio Z-ScoreThe "Sharpe Ratio Z-Score" indicator is a powerful tool designed to measure risk-adjusted returns in financial assets. This script helps investors evaluate the performance of a security relative to its risk, using a Z-score based modification of the Sharpe Ratio. The indicator is suitable for assessing market environments and understanding periods of underperformance or overperformance relative to historical standards.
Features:
Risk Assessment and Scaling: The indicator calculates a modified version of the Sharpe Ratio
over a user-defined period. By using scaling and mean offset adjustments, it allows for better
fitting to different market conditions.
Customizable Settings:
Period Length: The number of bars used to calculate the Sharpe Ratio.
Mean Adjustment: Offset value to adjust the average return of the calculated Sharpe ratio.
Scale Factor: A multiplier for emphasizing or reducing the calculated score's impact.
Line Color: Easily customize the plot's appearance.
Visual Cues:
Plots horizontal lines and fills specific regions to visually represent significant Z-score levels.
Highlighted zones include risk thresholds, such as overbought (positive Z-scores) and oversold
(negative Z-scores) areas, using intuitive color fills:
Green for areas below -0.5 (potential buy opportunities).
Red for areas above 0.5 (potential sell opportunities).
Yellow for neutral zones between -0.5 and 0.5.
Use Cases:
Risk-Adjusted Decision Making: Understand when returns are favorable compared to risk, especially during volatile market conditions.
Timing Reversion to Mean: Use highlighted zones to identify potential reversion-to-mean scenarios.
Trend Analysis: Identify times when an asset's performance is significantly deviating from its
average risk-adjusted return.
How It Works:
The script computes the daily returns over a set period, calculates the standard deviation of
those returns, and then applies a modified Sharpe Ratio approach. The Z-score transformation
helps to visualize how far an asset's risk-adjusted return deviates from its historical average.
This "Sharpe Ratio Z-Score" indicator is well-suited for investors seeking to combine quantitative metrics with visual cues, enhancing decision-making for long and short positions while maintaining a risk-adjusted perspective.
Conditional Value at Risk (CVaR)This Pine Script implements the Conditional Value at Risk (CVaR), a risk metric that evaluates the potential losses in a financial portfolio beyond a certain confidence level, incorporating both the Value at Risk (VaR) and the expected loss given that the VaR threshold has been breached.
Key Features:
Input Parameters:
length: Defines the observation period in days (default is 252, typically used to represent the number of trading days in a year).
confidence: Specifies the confidence interval for calculating VaR and CVaR, with values between 0.5 and 0.99 (default is 0.95, indicating a 95% confidence level).
Logarithmic Returns Calculation: The script computes the logarithmic returns based on the daily closing prices, a common method to measure financial asset returns, given by:
Log Return=ln(PtPt−1)
Log Return=ln(Pt−1Pt)
where PtPt is the price at time tt, and Pt−1Pt−1 is the price at the previous time point.
VaR Calculation: Value at Risk (VaR) is estimated as the percentile of the returns array corresponding to the given confidence interval. This represents the maximum loss expected over a given time horizon under normal market conditions at the specified confidence level.
CVaR Calculation: The Conditional VaR (CVaR) is calculated as the average of the returns that fall below the VaR threshold. This represents the expected loss given that the loss has exceeded the VaR threshold.
Visualization: The script plots two key risk measures:
VaR: The maximum potential loss at the specified confidence level.
CVaR: The average of the losses beyond the VaR threshold.
The script also includes a neutral line at zero to help visualize the losses and their magnitude.
Source and Scientific Background:
The concept of Value at Risk (VaR) was popularized by J.P. Morgan in the 1990s, and it has since become a widely-used tool for risk management (Jorion, 2007). Conditional Value at Risk (CVaR), also known as Expected Shortfall, addresses the limitation of VaR by considering the severity of losses beyond the VaR threshold (Rockafellar & Uryasev, 2002). CVaR provides a more comprehensive risk measure, especially in extreme tail risk scenarios.
References:
Jorion, P. (2007). Value at Risk: The New Benchmark for Managing Financial Risk. McGraw-Hill Education.
Rockafellar, R.T., & Uryasev, S. (2002). Conditional Value-at-Risk for General Loss Distributions. Journal of Banking & Finance, 26(7), 1443–1471.
DJ - SIP Returns with Configurable Features - v1This Pine Script calculates and displays the returns of a Systematic Investment Plan (SIP) with configurable features such as annual increments and additional investments based on market corrections. The script is designed to work on daily time frames and includes various input options for customization.
Key Features
Input Options:
SIP Start and End Dates: Define the period for the SIP.
SIP Period: Choose between weekly and monthly SIP intervals.
Initial SIP Amount: Set the starting amount for the SIP.
Annual Increment: Enable and set a yearly increment percentage for the SIP amount.
Increment Month: Specify the month for the yearly increment.
Correction-Based Investment: Enable additional investments based on market corrections.
Correction Trigger: Set the percentage drop in price to trigger additional investments.
Correction Investment Type: Choose between a lump sum or a multiple of the last SIP amount for additional investments.
Display
Displays the total invested amount, current value, SIP return percentage, and the number of correction triggers in the status line.
The table displays various SIP metrics
Manual Trading Checklist by Afnan TajuddinHey traders! This Trading Checklist indicator like your personal to-do list right on your chart! Here’s what it does:
Easy Tracking: Seven checkboxes to make sure you’ve done all your trading steps.
Colorful Signs: Green "✔" for done stuff and red "✘" for things you need to fix.
Make It Yours: Change where the table is on the chart, pick your favorite colors, and set the text size just how you like it.
Simple Setup: Rename the checklist items and toggle them on or off in the settings.
Clean Look: It stays neat on your chart without messing things up.
Whether you’re just starting out or you’ve been trading for a while, this checklist helps you stay organized and stick to your plan. Perfect for anyone who loves keeping things tidy and on track!
Important to Know: This checklist is not dynamic or automatic and not specific to any symbol. You need to manually check it every time for all the stocks you’re planning to trade. It won’t do the checking for you, so make sure to update it yourself! 🚨
RHR_CANDLELibrary "RHR_CANDLE"
Library for Expansion Contraction Indicator, a zero-lag dual perspective indicator based on Jake Bernstein’s principles of Moving Average Channel system.
calc(shortLookback, longLookback)
Calculates Expansion Contraction values.
Parameters:
shortLookback (int) : Integer for the short lookback calculation, defaults to 8
longLookback (int) : Integer for the long lookback calculation, defaults to 32
@return Returns array of Expansion Contraction values
stdevCalc(positiveShort, negativeShort, positiveLong, negativeLong, stdevLookback)
Calculates standard deviation lines based on Expansion Contraction Long and Short values.
Parameters:
positiveShort (float) : Float for the positive short XC value from calculation
negativeShort (float) : Float for the negative short XC value from calculation
positiveLong (float) : Float for the positive long XC value from calculation
negativeLong (float) : Float for the negative long XC value from calculation
stdevLookback (int) : Integer for the standard deviation lookback, defaults to 500
@return Returns array of standard deviation values
trend(positiveShort, negativeShort, positiveLong, negativeLong)
Determines if trend is strong or weak based on Expansion Contraction values.
Parameters:
positiveShort (float) : Float for the positive short XC value from calculation
negativeShort (float) : Float for the negative short XC value from calculation
positiveLong (float) : Float for the positive long XC value from calculation
negativeLong (float) : Float for the negative long XC value from calculation
@return Returns array of boolean values indicating strength or weakness of trend
Price & Volume HeatmapDescription:
Displays a heatmap (like TV's Stock Heatmap) for up to 40 symbols (either from 3 presets, or custom). It can show Price Change, Volume Change and Volume (in $). The text size for each symbol can auto-change based on whether it fits into the cell. Each cell shows the name of the symbol, and when hovered - it shows the value.
Inputs:
- Symbols -> which symbols to use (Custom, or predefined list of Stocks/Crypto/Forex)
- Data -> show Price Change (%), Volume Change (%) or Volume ($)
- Custom -> put your custom list of symbols here (comma separated without spaces, up to 40 symbols)
- Position -> heatmap position
- Height / Width -> height / width of the heatmap (% of indicator's space)
- Text Size -> can be constant (Tiny/Normal/etc) or automatically change based on the text of each cell (Auto/Auto (Smaller))
- Color -> text color
Notes:
It is not recommended to use the script on timeframes below 30 seconds, because it may be too slow there (since it's based on a table object, it might be slow).
DTT Weekly Volatility Grid [Pro+] (NINE/ANARR)Introduction:
Automate Digital Time Theory (DTT) Weekly Models with the DTT Weekly Volatility Grid , leveraging the proprietary framework developed by Nine and Anarr. This tool allows to navigate the advanced landscape of Time-based statistical trading for futures, crypto, and forex markets.
Description:
Built on the Digital Time Theory (DTT), this script provides traders with a structured view of time and price interactions, ideal for swing insights. It divides the weekly range into Time models and inner intervals, empowering traders with data-driven insights to anticipate market expansions, detect Time-based distortions, and understand volatility fluctuations at specific Times during the trading week.
Key Features:
Time-Based Weekly Models and Volatility Awareness: The DTT Weekly Time Models automatically map onto your chart, highlighting critical volatility points in weekly sessions. These models help traders recognize potential shifts in the market, ideal for identifying larger, swing-oriented moves.
Average Model Range Probability (AMRP): The AMRP feature calculates the historical probability of reaching previous DTT Weekly Model Ranges. With AMRP and Standard Deviation metrics, traders can evaluate the likelihood of DTT model continuations or breaks, aligning their strategy with higher Timeframe volatility trends.
Root Candles and Liquidity Draws: Visualize Root Candles as liquidity draws, emphasizing premium and discount areas and marking the origin of a Time-based price movement. The tool allows traders to toggle features like opening prices and equilibrium points of each Root Candle. Observing accumulation or distribution zones around these candles provides crucial reference points for strategic swing entries and exits.
Extended Visualization of Weekly Model Ranges: Leverage previous weekly model ranges within the current Time model to observe historical high, low, and equilibrium levels. This feature aids traders in visualizing premium and discount ranges of prior models, pinpointing areas of liquidity and imbalance to watch.
Customization Options: Tailor Time intervals with a variety of line styles (solid, dashed, dotted) and colours to customize each model. Adjust settings to display specific historical weekly models, apply custom labels, and create a personalized view that suits your trading style and focus.
Lookback Periods and Model Count: Select customizable lookback periods to display past models, offering insights into market behaviour over a chosen historical range. This feature enables clean, organized charts and allows analysts to add more models for detailed backtesting and analysis.
Detailed Real-Time Data Table: The live data table provides easy access to AMRP and range data for selected models. This table highlights model targets and anticipated ranges, offering insights into whether previous models have exceeded historical volatility expectations or remained within them.
How Traders Can Use The DTT Weekly Volatility Grid Effectively:
Identifying Premium and Discount Zones: Track weekly ranges using Root Candles and previous model equilibrium levels to assess if prices are trading in premium or discount areas. This information helps framing the broader swing outlook.
Timing Trades Based on Volatility: Recognize potential exhaustion points through AMRP insights or completed model distortions that may signal new expansions. By observing inner intervals and Root Candles, traders can identify periods of high market activity, assisting in Timing weekly entries and exits.
Avoiding Low Volatility Phases: AMRP calculations can indicate periods when price action may slow or become choppy. If price remains within AMRP deviations or near them, traders can adjust risk or step aside, awaiting more favourable conditions for volatility-driven trades as new inner intervals or model roots appear.
Designed for Swing Traders and Higher Timeframes: The Weekly DTT Models are suited for those looking to study higher timeframe trends across futures, forex, and crypto markets. This tool equips traders with volatility-aware, and data-driven insights during extended market cycles.
Usage Guidance:
Add DTT Weekly Volatility Grid (NINE/ANARR) to your TradingView chart.
Customize your preferred time intervals, model history, and visual settings for your session.
Use the data table to track average model ranges and probabilities, ensuring you align your trades with key levels.
Incorporate DTT Weekly Volatility Grid (NINE/ANARR) into your existing strategies to fine-tune your view through based on data-driven insights into volatility and price behaviour.
Terms and Conditions
Our charting tools are products provided for informational and educational purposes only and do not constitute financial, investment, or trading advice. Our charting tools are not designed to predict market movements or provide specific recommendations. Users should be aware that past performance is not indicative of future results and should not be relied upon for making financial decisions. By using our charting tools, the purchaser agrees that the seller and the creator are not responsible for any decisions made based on the information provided by these charting tools. The purchaser assumes full responsibility and liability for any actions taken and the consequences thereof, including any loss of money or investments that may occur as a result of using these products. Hence, by purchasing these charting tools, the customer accepts and acknowledges that the seller and the creator are not liable nor responsible for any unwanted outcome that arises from the development, the sale, or the use of these products. Finally, the purchaser indemnifies the seller from any and all liability. If the purchaser was invited through the Friends and Family Program, they acknowledge that the provided discount code only applies to the first initial purchase of the Toodegrees Premium Suite subscription. The purchaser is therefore responsible for cancelling – or requesting to cancel – their subscription in the event that they do not wish to continue using the product at full retail price. If the purchaser no longer wishes to use the products, they must unsubscribe from the membership service, if applicable. We hold no reimbursement, refund, or chargeback policy. Once these Terms and Conditions are accepted by the Customer, before purchase, no reimbursements, refunds or chargebacks will be provided under any circumstances.
By continuing to use these charting tools, the user acknowledges and agrees to the Terms and Conditions outlined in this legal disclaimer.