TASC 2024.04 The Ultimate Smoother█ OVERVIEW
This script presents an implementation of the digital smoothing filter introduced by John Ehlers in his article "The Ultimate Smoother" from the  April 2024 edition of TASC's Traders' Tips . 
█ CONCEPTS
The UltimateSmoother preserves low-frequency swings in the input time series while attenuating high-frequency variations and noise. The defining input parameter of the UltimateSmoother is the  critical period , which represents the minimum wavelength (highest frequency) in the filter's pass band. In other words, the filter attenuates or removes the amplitudes of oscillations at shorter periods than the critical period. 
According to Ehlers, one primary advantage of the UltimateSmoother is that it maintains zero  lag  in its pass band and minimal lag in its transition band, distinguishing it from other conventional digital filters (e.g.,  moving averages ). One can apply this smoother to various input data series, including other indicators.
█ CALCULATIONS
Ehlers derived the UltimateSmoother using inspiration from the design principles he learned from his experience with  analog filters , as described in the original publication. On a technical level, the UltimateSmoother's unique response involves subtracting a  high-pass response  from an  all-pass response . At very low frequencies (lengthy periods), where the high-pass filter response has virtually no amplitude, the subtraction yields a frequency and phase response practically equivalent to the input data. At other frequencies, the subtraction achieves filtration through  cancellation  due to the close similarities in response between the high-pass filter and the input data. 
חפש סקריפטים עבור "《中国区域创新能力评价报告2024》"
TASC 2024.03 Rate of Directional Change█ OVERVIEW
This script implements the Rate of Directional Change (RODC) indicator introduced by Richard Poster in the "Taming The Effects Of Whipsaw" article featured in the  March 2024 edition of TASC's Traders' Tips . 
█ CONCEPTS
In his article, Richard Poster discusses an approach to potentially reduce false trend-following strategy entry signals due to  whipsaws  in forex data. The RODC indicator is central to this approach. The idea behind RODC is that one can characterize market whipsaw as alternating up and down ZigZag segments. By counting the number of up and down segments within a lookback window, the RODC indicator aims to identify if the window contains a significant whipsaw pattern:
RODC = 100 * Segments / Window Size (bars)
Larger RODC values suggest elevated whipsaw in the calculation window, while smaller values signify trending price activity.
█ CALCULATIONS
• For each price bar, the script iterates through the  lookback window  to identify up and down segments.
• If the price change between subsequent bars within the window is in the direction opposite to the current segment and exceeds the specified  threshold , the calculation interprets the condition as a reversal point and the start of a new segment.
• The script uses the number of segments within the window to calculate RODC according to the above formula.
• Finally, the script applies a  simple moving average  to  smoothen  the RODC data.
Users can change the length of the  lookback window , the  threshold  value, and the  smoothing  length in the "Inputs" tab of the script's settings.
TASC 2024.02 Price-Time Filtering█ OVERVIEW
This script implements a price-time trend filter proposed by Alfred François Tagher in the “Trend Identification By Price And Time Filtering” article from the  February 2024 edition of TASC's Traders' Tips . 
█ CONCEPTS
In his article, Alfred François Tagher proposed a rule set designed to minimize the impact of stochastic price movements, facilitating the identification of larger-scale trends. The rules are:
• If the most recent week's close exceeds the previous week's high, the trend is up.
• If the most recent week's close is below the previous week's low, the trend is down.
• The trend remains unchanged until one of the above conditions occurs.
Similar rules can also apply to monthly bars. 
The author argues that this approach integrates characteristics of conventional  price  action and  time  dynamics filters, so he refers to it as  price-time filtering . 
█ CALCULATIONS
This script applies the above price-time filtering rules and offers multiple ways to view the results on a chart:
• In the "Oscillator" view mode, the script counts and displays the number of bars in the uptrend and downtrend.
• In the "Linebreak" view mode, the trend filter is presented in a format resembling a  point-and-figure (P&F) chart , with the length of each bar corresponding to the high-low range of the respective trend.
• In both view modes, the script offers bar coloring of the main chart based on the identified trend.
TASC 2024.01 Gap Momentum System█ OVERVIEW
 TASC's January 2024 edition of Traders' Tips  features an article titled “Gap Momentum” by Perry J. Kaufman. The article discusses how a trader might create a momentum strategy based on  opening gap  data. This script implements the Gap Momentum system presented therein.
█ CONCEPTS
In the article, Perry J. Kaufman introduces  Gap Momentum  as a cumulative series constructed in the same way as  On-Balance Volume (OBV) , but using gap openings (today’s open minus yesterday’s close).
To smoothen the resulting time series (i.e., obtain the " signal line "), the author applies a  simple moving average . Subsequently, he proposes the following two trading rules for a long-only trading system:
• Enter a long position when the signal line is moving higher.
• Exit when the signal line is moving lower.
█ CALCULATIONS
The calculation of Gap Momentum involves the following steps:
1. Calculate the ratio of the sum of positive gaps over the past N days to the sum of negative gaps (absolute values) over the same time period.
2. Add the resulting gap ratio to the cumulative time series. This time series is the Gap Momentum.
3. Keep moving forward, as in an N-day moving average.
#1 Vishal Toora Buy Sell Tablecopyright Vishal Toora
**“© 2025 Vishal Toora — counting volumes so you don’t have to. Buy, sell, or just stare at the screen.”**
Or a few more playful options:
1. **“© Vishal Toora — making deltas speak louder than your ex.”**
2. **“© Vishal Toora — one signal to rule them all (Buy/Sell/Neutral).”**
3. **“© Vishal Toora — because guessing markets is so 2024.”**
Disclaimer: This indicator is for educational and informational purposes only. I do not claim 100% accuracy, and you are responsible for your own trading decisions.
Fed Rate Change Impact📊  Fed Rate Change Impact — Macro Event-Driven Indicator 
Fed Rate Change Impact is an advanced indicator designed to analyze the impact of Federal Reserve interest rate changes on financial markets. It integrates event-driven logic with dynamic visualization, percentage diagnostics, and multi-asset selection, offering a clear and customizable view of post-event effects.
🔍 Key Features 📅  Preloaded Fed Events : Includes over 30 historical rate cut (↓) and hike (↑) dates from 2008 to 2024.
📈  Post-Event Analysis : Calculates the percentage change of the selected asset 5, 10, and 30 days after each event.
📌  Vertical Chart Lines : Visually highlights each event directly on the chart, with dynamic coloring (red for hikes, green for cuts).
📋  Diagnostic Table : Displays real-time impact for each event, with color-coded values and a compact layout.
🧠 Interactive Filter: Choose to display only hikes, only cuts, or both.
🧭  Flexible Asset Selection : Analyze the current chart asset, pick from a predefined list, or manually input any ticker via input.symbol().
🎯  Contextual Highlighting : The table highlights the analyzed asset if it matches the active chart symbol.
⚙️  Customizable Parameters  lookahead5, lookahead10, lookahead30: Define the time horizon for measuring post-event impact.
 eventFilter : Choose which type of events to display.
 presetAsset / customAsset : Select or input the asset to analyze.
🧪 Recommended Use Cases Macroeconomic analysis on indices, commodities, crypto, and forex
Studying delayed effects of rate changes on sensitive assets
Building event-driven strategies or diagnostic overlays
Visual backtesting and cross-asset comparison
🧠 Technical Notes The indicator is compatible with overlay=true and works best on Daily timeframe.
The table automatically adapts to the number of events and includes visual padding for improved readability.
All calculations are performed in real time and require no external data.
Trojan Cycle: Dip & Profit Hunter📉 Crypto is changing. Your signals should too. 
This script doesn’t try to outguess price — it helps you  track capital rotation and flow behavior  in alignment with the evolving macro structure of the digital asset market.
 Trojan Cycle: Dip & Profit Hunter  is a signal engine built to support and  validate the capital rotation models outlined in the Trojan Cycle and Synthetic Rotation theses  — available via RWCS_LTD’s published charts
It is not a classic “buy low, sell high” tool. It is a  structural filter  that uses price/volume statistics to surface accumulation zones, synthetic traps, and macro context shifts — all aligned with the institutionalization of crypto post-2024.
 🧠 Purpose & Value 
Crypto no longer follows the retail-led, halving-driven pattern of 2017 or 2021.
Instead,  institutional infrastructure, regulatory filters, and equity-market Trojan horses  define the new path of capital.
This tool helps you  visualize that path  by interpreting behavior through statistical imbalances and real-time momentum signals.
Use it to:
 Track where capital is accumulating or exiting
Identify signals consistent with true cycle rotation (vs. synthetic traps)
Validate your macro view with real-time statistical context 
 🔍 How It Works 
The engine combines four signal layers:
 1. Z-Score Logic 
- Measures how far price and volume have deviated from their mean
- Detects dips, blowoffs, and exhaustion zones
 2. Percentile Logic 
- Compares current price and volume to historical rank distribution
- Flags statistically rare conditions (e.g. bottom 10% price, top 90% volume)
 3. Combined Context Engine 
- Integrates both models to generate one of  36 unique output states 
- Each state provides a labeled market context (e.g.,  🟢 Confluent Buy, 🔴 Confluent Sell, 🧨 Synthetic Trap )
 4. Momentum Spread & Divergence 
- Measures whether price is leading volume (trap risk) or volume is leading price (accumulation)
- Outputs intuitive momentum context with emoji-coded alerts
 📋 What You See 
 🧠 Contextual Table UI  with key Z-Scores, percentiles, signals, and market commentary
 🎯 Emoji-coded signals  to quickly grasp high-probability setups or risk zones
 🌊 Optional overlays:  price/volume divergence, momentum spread
 🎨 Visual table customization  (size, position) and chart highlights for signal clarity
 🔔 Alert System 
 ✅ Single dynamic alert  using alert() that only fires when signal context changes
Prevents alert fatigue and allows clean webhook/automation integration
 🧭 Use Cases 
 For macro cycle traders:  Track where we are in the Trojan Cycle using statistical context
 For thesis explorers:  Use the 36-output signal map to match against your rotation thesis
 For capital rotation watchers:  Identify structural setups consistent with ETF-driven or compliance-filtered flow
 For narrative skeptics:  Avoid synthetic altseason traps where volume lags or flow dries up
 🧪 Suggested Pairing for Thesis Validation 
To use this tool as part of a  thesis-confirmation framework , pair it with:
BTC.D —  Bitcoin Dominance 
ETH/BTC —  Ethereum strength vs. Bitcoin 
TOTALE100/ETH —  Altcoin strength relative to ETH 
 RWCS_LTD’s published charts and macro cycle models 
 🏁 Final Note 
 Crypto has matured. So should your signals. 
This tool doesn’t try to game the next 2 candles. It helps you understand the  current phase  in a  compliance-filtered, institutionalized  rotation model.
It’s not built for hype — it’s built for conviction.
Explore the thesis → Validate the structure → Trade with clarity.
 🚨 Disclaimer 
This script is not financial advice. It is an analytical tool designed to support market structure research and rotation thesis validation. Use this as part of a broader framework including technical structure, dominance charts, and macro data.
Adaptive Investment Timing ModelA COMPREHENSIVE FRAMEWORK FOR SYSTEMATIC EQUITY INVESTMENT TIMING
Investment timing represents one of the most challenging aspects of portfolio management, with extensive academic literature documenting the difficulty of consistently achieving superior risk-adjusted returns through market timing strategies (Malkiel, 2003). 
Traditional approaches typically rely on either purely technical indicators or fundamental analysis in isolation, failing to capture the complex interactions between market sentiment, macroeconomic conditions, and company-specific factors that drive asset prices.
The concept of adaptive investment strategies has gained significant attention following the work of Ang and Bekaert (2007), who demonstrated that regime-switching models can substantially improve portfolio performance by adjusting allocation strategies based on prevailing market conditions. Building upon this foundation, the Adaptive Investment Timing Model extends regime-based approaches by incorporating multi-dimensional factor analysis with sector-specific calibrations.
Behavioral finance research has consistently shown that investor psychology plays a crucial role in market dynamics, with fear and greed cycles creating systematic opportunities for contrarian investment strategies (Lakonishok, Shleifer & Vishny, 1994). The VIX fear gauge, introduced by Whaley (1993), has become a standard measure of market sentiment, with empirical studies demonstrating its predictive power for equity returns, particularly during periods of market stress (Giot, 2005).
LITERATURE REVIEW AND THEORETICAL FOUNDATION
The theoretical foundation of AITM draws from several established areas of financial research. Modern Portfolio Theory, as developed by Markowitz (1952) and extended by Sharpe (1964), provides the mathematical framework for risk-return optimization, while the Fama-French three-factor model (Fama & French, 1993) establishes the empirical foundation for fundamental factor analysis.
Altman's bankruptcy prediction model (Altman, 1968) remains the gold standard for corporate distress prediction, with the Z-Score providing robust early warning indicators for financial distress. Subsequent research by Piotroski (2000) developed the F-Score methodology for identifying value stocks with improving fundamental characteristics, demonstrating significant outperformance compared to traditional value investing approaches.
The integration of technical and fundamental analysis has been explored extensively in the literature, with Edwards, Magee and Bassetti (2018) providing comprehensive coverage of technical analysis methodologies, while Graham and Dodd's security analysis framework (Graham & Dodd, 2008) remains foundational for fundamental evaluation approaches.
Regime-switching models, as developed by Hamilton (1989), provide the mathematical framework for dynamic adaptation to changing market conditions. Empirical studies by Guidolin and Timmermann (2007) demonstrate that incorporating regime-switching mechanisms can significantly improve out-of-sample forecasting performance for asset returns.
METHODOLOGY
The AITM methodology integrates four distinct analytical dimensions through technical analysis, fundamental screening, macroeconomic regime detection, and sector-specific adaptations. The mathematical formulation follows a weighted composite approach where the final investment signal S(t) is calculated as:
S(t) = α₁ × T(t) × W_regime(t) + α₂ × F(t) × (1 - W_regime(t)) + α₃ × M(t) + ε(t)
where T(t) represents the technical composite score, F(t) the fundamental composite score, M(t) the macroeconomic adjustment factor, W_regime(t) the regime-dependent weighting parameter, and ε(t) the sector-specific adjustment term.
Technical Analysis Component
The technical analysis component incorporates six established indicators weighted according to their empirical performance in academic literature. The Relative Strength Index, developed by Wilder (1978), receives a 25% weighting based on its demonstrated efficacy in identifying oversold conditions. Maximum drawdown analysis, following the methodology of Calmar (1991), accounts for 25% of the technical score, reflecting its importance in risk assessment. Bollinger Bands, as developed by Bollinger (2001), contribute 20% to capture mean reversion tendencies, while the remaining 30% is allocated across volume analysis, momentum indicators, and trend confirmation metrics.
Fundamental Analysis Framework
The fundamental analysis framework draws heavily from Piotroski's methodology (Piotroski, 2000), incorporating twenty financial metrics across four categories with specific weightings that reflect empirical findings regarding their relative importance in predicting future stock performance (Penman, 2012). Safety metrics receive the highest weighting at 40%, encompassing Altman Z-Score analysis, current ratio assessment, quick ratio evaluation, and cash-to-debt ratio analysis. Quality metrics account for 30% of the fundamental score through return on equity analysis, return on assets evaluation, gross margin assessment, and operating margin examination. Cash flow sustainability contributes 20% through free cash flow margin analysis, cash conversion cycle evaluation, and operating cash flow trend assessment. Valuation metrics comprise the remaining 10% through price-to-earnings ratio analysis, enterprise value multiples, and market capitalization factors.
Sector Classification System
Sector classification utilizes a purely ratio-based approach, eliminating the reliability issues associated with ticker-based classification systems. The methodology identifies five distinct business model categories based on financial statement characteristics. Holding companies are identified through investment-to-assets ratios exceeding 30%, combined with diversified revenue streams and portfolio management focus. Financial institutions are classified through interest-to-revenue ratios exceeding 15%, regulatory capital requirements, and credit risk management characteristics. Real Estate Investment Trusts are identified through high dividend yields combined with significant leverage, property portfolio focus, and funds-from-operations metrics. Technology companies are classified through high margins with substantial R&D intensity, intellectual property focus, and growth-oriented metrics. Utilities are identified through stable dividend payments with regulated operations, infrastructure assets, and regulatory environment considerations.
Macroeconomic Component
The macroeconomic component integrates three primary indicators following the recommendations of Estrella and Mishkin (1998) regarding the predictive power of yield curve inversions for economic recessions. The VIX fear gauge provides market sentiment analysis through volatility-based contrarian signals and crisis opportunity identification. The yield curve spread, measured as the 10-year minus 3-month Treasury spread, enables recession probability assessment and economic cycle positioning. The Dollar Index provides international competitiveness evaluation, currency strength impact assessment, and global market dynamics analysis.
Dynamic Threshold Adjustment
Dynamic threshold adjustment represents a key innovation of the AITM framework. Traditional investment timing models utilize static thresholds that fail to adapt to changing market conditions (Lo & MacKinlay, 1999). 
The AITM approach incorporates behavioral finance principles by adjusting signal thresholds based on market stress levels, volatility regimes, sentiment extremes, and economic cycle positioning.
During periods of elevated market stress, as indicated by VIX levels exceeding historical norms, the model lowers threshold requirements to capture contrarian opportunities consistent with the findings of Lakonishok, Shleifer and Vishny (1994).
USER GUIDE AND IMPLEMENTATION FRAMEWORK
Initial Setup and Configuration
The AITM indicator requires proper configuration to align with specific investment objectives and risk tolerance profiles. Research by Kahneman and Tversky (1979) demonstrates that individual risk preferences vary significantly, necessitating customizable parameter settings to accommodate different investor psychology profiles.
Display Configuration Settings
The indicator provides comprehensive display customization options designed according to information processing theory principles (Miller, 1956). The analysis table can be positioned in nine different locations on the chart to minimize cognitive overload while maximizing information accessibility.
Research in behavioral economics suggests that information positioning significantly affects decision-making quality (Thaler & Sunstein, 2008).
Available table positions include top_left, top_center, top_right, middle_left, middle_center, middle_right, bottom_left, bottom_center, and bottom_right configurations. Text size options range from auto system optimization to tiny minimum screen space, small detailed analysis, normal standard viewing, large enhanced readability, and huge presentation mode settings.
Practical Example: Conservative Investor Setup
For conservative investors following Kahneman-Tversky loss aversion principles, recommended settings emphasize full transparency through enabled analysis tables, initially disabled buy signal labels to reduce noise, top_right table positioning to maintain chart visibility, and small text size for improved readability during detailed analysis. Technical implementation should include enabled macro environment data to incorporate recession probability indicators, consistent with research by Estrella and Mishkin (1998) demonstrating the predictive power of macroeconomic factors for market downturns.
Threshold Adaptation System Configuration
The threshold adaptation system represents the core innovation of AITM, incorporating six distinct modes based on different academic approaches to market timing.
Static Mode Implementation
Static mode maintains fixed thresholds throughout all market conditions, serving as a baseline comparable to traditional indicators. Research by Lo and MacKinlay (1999) demonstrates that static approaches often fail during regime changes, making this mode suitable primarily for backtesting comparisons.
Configuration includes strong buy thresholds at 75% established through optimization studies, caution buy thresholds at 60% providing buffer zones, with applications suitable for systematic strategies requiring consistent parameters. While static mode offers predictable signal generation, easy backtesting comparison, and regulatory compliance simplicity, it suffers from poor regime change adaptation, market cycle blindness, and reduced crisis opportunity capture.
Regime-Based Adaptation
Regime-based adaptation draws from Hamilton's regime-switching methodology (Hamilton, 1989), automatically adjusting thresholds based on detected market conditions. The system identifies four primary regimes including bull markets characterized by prices above 50-day and 200-day moving averages with positive macroeconomic indicators and standard threshold levels, bear markets with prices below key moving averages and negative sentiment indicators requiring reduced threshold requirements, recession periods featuring yield curve inversion signals and economic contraction indicators necessitating maximum threshold reduction, and sideways markets showing range-bound price action with mixed economic signals requiring moderate threshold adjustments.
Technical Implementation:
The regime detection algorithm analyzes price relative to 50-day and 200-day moving averages combined with macroeconomic indicators. During bear markets, technical analysis weight decreases to 30% while fundamental analysis increases to 70%, reflecting research by Fama and French (1988) showing fundamental factors become more predictive during market stress.
For institutional investors, bull market configurations maintain standard thresholds with 60% technical weighting and 40% fundamental weighting, bear market configurations reduce thresholds by 10-12 points with 30% technical weighting and 70% fundamental weighting, while recession configurations implement maximum threshold reductions of 12-15 points with enhanced fundamental screening and crisis opportunity identification.
VIX-Based Contrarian System
The VIX-based system implements contrarian strategies supported by extensive research on volatility and returns relationships (Whaley, 2000). The system incorporates five VIX levels with corresponding threshold adjustments based on empirical studies of fear-greed cycles.
Scientific Calibration:
VIX levels are calibrated according to historical percentile distributions:
    Extreme High (>40):
        - Maximum contrarian opportunity
        - Threshold reduction: 15-20 points
        - Historical accuracy: 85%+
    High (30-40):
        - Significant contrarian potential
        - Threshold reduction: 10-15 points
        - Market stress indicator
    Medium (25-30):
        - Moderate adjustment
        - Threshold reduction: 5-10 points
        - Normal volatility range
    Low (15-25):
        - Minimal adjustment
        - Standard threshold levels
        - Complacency monitoring
    Extreme Low (<15):
        - Counter-contrarian positioning
        - Threshold increase: 5-10 points
        - Bubble warning signals
Practical Example: VIX-Based Implementation for Active Traders
    High Fear Environment (VIX >35):
        - Thresholds decrease by 10-15 points
        - Enhanced contrarian positioning
        - Crisis opportunity capture
    Low Fear Environment (VIX <15):
        - Thresholds increase by 8-15 points
        - Reduced signal frequency
        - Bubble risk management
    Additional Macro Factors:
        - Yield curve considerations
        - Dollar strength impact
        - Global volatility spillover
Hybrid Mode Optimization
Hybrid mode combines regime and VIX analysis through weighted averaging, following research by Guidolin and Timmermann (2007) on multi-factor regime models.
Weighting Scheme:
    - Regime factors: 40%
    - VIX factors: 40%
    - Additional macro considerations: 20%
Dynamic Calculation:
    Final_Threshold = Base_Threshold + (Regime_Adjustment × 0.4) + (VIX_Adjustment × 0.4) + (Macro_Adjustment × 0.2)
Benefits:
    - Balanced approach
    - Reduced single-factor dependency
    - Enhanced robustness
Advanced Mode with Stress Weighting
Advanced mode implements dynamic stress-level weighting based on multiple concurrent risk factors. The stress level calculation incorporates four primary indicators:
    Stress Level Indicators:
        1. Yield curve inversion (recession predictor)
        2. Volatility spikes (market disruption)
        3. Severe drawdowns (momentum breaks)
        4. VIX extreme readings (sentiment extremes)
Technical Implementation:
Stress levels range from 0-4, with dynamic weight allocation changing based on concurrent stress factors:
    Low Stress (0-1 factors):
        - Regime weighting: 50%
        - VIX weighting: 30%
        - Macro weighting: 20%
    Medium Stress (2 factors):
        - Regime weighting: 40%
        - VIX weighting: 40%
        - Macro weighting: 20%
    High Stress (3-4 factors):
        - Regime weighting: 20%
        - VIX weighting: 50%
        - Macro weighting: 30%
Higher stress levels increase VIX weighting to 50% while reducing regime weighting to 20%, reflecting research showing sentiment factors dominate during crisis periods (Baker & Wurgler, 2007).
Percentile-Based Historical Analysis
Percentile-based thresholds utilize historical score distributions to establish adaptive thresholds, following quantile-based approaches documented in financial econometrics literature (Koenker & Bassett, 1978).
Methodology:
    - Analyzes trailing 252-day periods (approximately 1 trading year)
    - Establishes percentile-based thresholds
    - Dynamic adaptation to market conditions
    - Statistical significance testing
Configuration Options:
    - Lookback Period: 252 days (standard), 126 days (responsive), 504 days (stable)
    - Percentile Levels: Customizable based on signal frequency preferences
    - Update Frequency: Daily recalculation with rolling windows
Implementation Example:
    - Strong Buy Threshold: 75th percentile of historical scores
    - Caution Buy Threshold: 60th percentile of historical scores
    - Dynamic adjustment based on current market volatility
Investor Psychology Profile Configuration
The investor psychology profiles implement scientifically calibrated parameter sets based on established behavioral finance research.
Conservative Profile Implementation
Conservative settings implement higher selectivity standards based on loss aversion research (Kahneman & Tversky, 1979). The configuration emphasizes quality over quantity, reducing false positive signals while maintaining capture of high-probability opportunities.
Technical Calibration:
    VIX Parameters:
        - Extreme High Threshold: 32.0 (lower sensitivity to fear spikes)
        - High Threshold: 28.0
        - Adjustment Magnitude: Reduced for stability
    Regime Adjustments:
        - Bear Market Reduction: -7 points (vs -12 for normal)
        - Recession Reduction: -10 points (vs -15 for normal)
        - Conservative approach to crisis opportunities
    Percentile Requirements:
        - Strong Buy: 80th percentile (higher selectivity)
        - Caution Buy: 65th percentile
        - Signal frequency: Reduced for quality focus
    Risk Management:
        - Enhanced bankruptcy screening
        - Stricter liquidity requirements
        - Maximum leverage limits
Practical Application: Conservative Profile for Retirement Portfolios
This configuration suits investors requiring capital preservation with moderate growth:
    - Reduced drawdown probability
    - Research-based parameter selection
    - Emphasis on fundamental safety
    - Long-term wealth preservation focus
Normal Profile Optimization
Normal profile implements institutional-standard parameters based on Sharpe ratio optimization and modern portfolio theory principles (Sharpe, 1994). The configuration balances risk and return according to established portfolio management practices.
Calibration Parameters:
    VIX Thresholds:
        - Extreme High: 35.0 (institutional standard)
        - High: 30.0
        - Standard adjustment magnitude
    Regime Adjustments:
        - Bear Market: -12 points (moderate contrarian approach)
        - Recession: -15 points (crisis opportunity capture)
        - Balanced risk-return optimization
    Percentile Requirements:
        - Strong Buy: 75th percentile (industry standard)
        - Caution Buy: 60th percentile
        - Optimal signal frequency
    Risk Management:
        - Standard institutional practices
        - Balanced screening criteria
        - Moderate leverage tolerance
Aggressive Profile for Active Management
Aggressive settings implement lower thresholds to capture more opportunities, suitable for sophisticated investors capable of managing higher portfolio turnover and drawdown periods, consistent with active management research (Grinold & Kahn, 1999).
Technical Configuration:
    VIX Parameters:
        - Extreme High: 40.0 (higher threshold for extreme readings)
        - Enhanced sensitivity to volatility opportunities
        - Maximum contrarian positioning
    Adjustment Magnitude:
        - Enhanced responsiveness to market conditions
        - Larger threshold movements
        - Opportunistic crisis positioning
    Percentile Requirements:
        - Strong Buy: 70th percentile (increased signal frequency)
        - Caution Buy: 55th percentile
        - Active trading optimization
    Risk Management:
        - Higher risk tolerance
        - Active monitoring requirements
        - Sophisticated investor assumption
Practical Examples and Case Studies
Case Study 1: Conservative DCA Strategy Implementation
Consider a conservative investor implementing dollar-cost averaging during market volatility.
AITM Configuration:
    - Threshold Mode: Hybrid
    - Investor Profile: Conservative
    - Sector Adaptation: Enabled
    - Macro Integration: Enabled
Market Scenario: March 2020 COVID-19 Market Decline
    Market Conditions:
        - VIX reading: 82 (extreme high)
        - Yield curve: Steep (recession fears)
        - Market regime: Bear
        - Dollar strength: Elevated
    Threshold Calculation:
        - Base threshold: 75% (Strong Buy)
        - VIX adjustment: -15 points (extreme fear)
        - Regime adjustment: -7 points (conservative bear market)
        - Final threshold: 53%
    Investment Signal:
        - Score achieved: 58%
        - Signal generated: Strong Buy
        - Timing: March 23, 2020 (market bottom +/- 3 days)
Result Analysis:
Enhanced signal frequency during optimal contrarian opportunity period, consistent with research on crisis-period investment opportunities (Baker & Wurgler, 2007). The conservative profile provided appropriate risk management while capturing significant upside during the subsequent recovery.
Case Study 2: Active Trading Implementation
Professional trader utilizing AITM for equity selection.
Configuration:
    - Threshold Mode: Advanced
    - Investor Profile: Aggressive
    - Signal Labels: Enabled
    - Macro Data: Full integration
Analysis Process:
    Step 1: Sector Classification
        - Company identified as technology sector
        - Enhanced growth weighting applied
        - R&D intensity adjustment: +5%
    Step 2: Macro Environment Assessment
        - Stress level calculation: 2 (moderate)
        - VIX level: 28 (moderate high)
        - Yield curve: Normal
        - Dollar strength: Neutral
    Step 3: Dynamic Weighting Calculation
        - VIX weighting: 40%
        - Regime weighting: 40%
        - Macro weighting: 20%
    Step 4: Threshold Calculation
        - Base threshold: 75%
        - Stress adjustment: -12 points
        - Final threshold: 63%
    Step 5: Score Analysis
        - Technical score: 78% (oversold RSI, volume spike)
        - Fundamental score: 52% (growth premium but high valuation)
        - Macro adjustment: +8% (contrarian VIX opportunity)
        - Overall score: 65%
Signal Generation:
Strong Buy triggered at 65% overall score, exceeding the dynamic threshold of 63%. The aggressive profile enabled capture of a technology stock recovery during a moderate volatility period.
Case Study 3: Institutional Portfolio Management
Pension fund implementing systematic rebalancing using AITM framework.
Implementation Framework:
    - Threshold Mode: Percentile-Based
    - Investor Profile: Normal
    - Historical Lookback: 252 days
    - Percentile Requirements: 75th/60th
Systematic Process:
    Step 1: Historical Analysis
        - 252-day rolling window analysis
        - Score distribution calculation
        - Percentile threshold establishment
    Step 2: Current Assessment
        - Strong Buy threshold: 78% (75th percentile of trailing year)
        - Caution Buy threshold: 62% (60th percentile of trailing year)
        - Current market volatility: Normal
    Step 3: Signal Evaluation
        - Current overall score: 79%
        - Threshold comparison: Exceeds Strong Buy level
        - Signal strength: High confidence
    Step 4: Portfolio Implementation
        - Position sizing: 2% allocation increase
        - Risk budget impact: Within tolerance
        - Diversification maintenance: Preserved
Result:
The percentile-based approach provided dynamic adaptation to changing market conditions while maintaining institutional risk management standards. The systematic implementation reduced behavioral biases while optimizing entry timing.
Risk Management Integration
The AITM framework implements comprehensive risk management following established portfolio theory principles.
Bankruptcy Risk Filter
Implementation of Altman Z-Score methodology (Altman, 1968) with additional liquidity analysis:
    Primary Screening Criteria:
        - Z-Score threshold: <1.8 (high distress probability)
        - Current Ratio threshold: <1.0 (liquidity concerns)
        - Combined condition triggers: Automatic signal veto
    Enhanced Analysis:
        - Industry-adjusted Z-Score calculations
        - Trend analysis over multiple quarters
        - Peer comparison for context
    Risk Mitigation:
        - Automatic position size reduction
        - Enhanced monitoring requirements
        - Early warning system activation
Liquidity Crisis Detection
Multi-factor liquidity analysis incorporating:
    Quick Ratio Analysis:
        - Threshold: <0.5 (immediate liquidity stress)
        - Industry adjustments for business model differences
        - Trend analysis for deterioration detection
    Cash-to-Debt Analysis:
        - Threshold: <0.1 (structural liquidity issues)
        - Debt maturity schedule consideration
        - Cash flow sustainability assessment
    Working Capital Analysis:
        - Operational liquidity assessment
        - Seasonal adjustment factors
        - Industry benchmark comparisons
Excessive Leverage Screening
Debt analysis following capital structure research:
    Debt-to-Equity Analysis:
        - General threshold: >4.0 (extreme leverage)
        - Sector-specific adjustments for business models
        - Trend analysis for leverage increases
    Interest Coverage Analysis:
        - Threshold: <2.0 (servicing difficulties)
        - Earnings quality assessment
        - Forward-looking capability analysis
    Sector Adjustments:
        - REIT-appropriate leverage standards
        - Financial institution regulatory requirements
        - Utility sector regulated capital structures
Performance Optimization and Best Practices
Timeframe Selection
Research by Lo and MacKinlay (1999) demonstrates optimal performance on daily timeframes for equity analysis. Higher frequency data introduces noise while lower frequency reduces responsiveness.
Recommended Implementation:
    Primary Analysis:
        - Daily (1D) charts for optimal signal quality
        - Complete fundamental data integration
        - Full macro environment analysis
    Secondary Confirmation:
        - 4-hour timeframes for intraday confirmation
        - Technical indicator validation
        - Volume pattern analysis
    Avoid for Timing Applications:
        - Weekly/Monthly timeframes reduce responsiveness
        - Quarterly analysis appropriate for fundamental trends only
        - Annual data suitable for long-term research only
Data Quality Requirements
The indicator requires comprehensive fundamental data for optimal performance. Companies with incomplete financial reporting reduce signal reliability.
Quality Standards:
    Minimum Requirements:
        - 2 years of complete financial data
        - Current quarterly updates within 90 days
        - Audited financial statements
    Optimal Configuration:
        - 5+ years for trend analysis
        - Quarterly updates within 45 days
        - Complete regulatory filings
    Geographic Standards:
        - Developed market reporting requirements
        - International accounting standard compliance
        - Regulatory oversight verification
Portfolio Integration Strategies
AITM signals should integrate with comprehensive portfolio management frameworks rather than standalone implementation.
Integration Approach:
    Position Sizing:
        - Signal strength correlation with allocation size
        - Risk-adjusted position scaling
        - Portfolio concentration limits
    Risk Budgeting:
        - Stress-test based allocation
        - Scenario analysis integration
        - Correlation impact assessment
    Diversification Analysis:
        - Portfolio correlation maintenance
        - Sector exposure monitoring
        - Geographic diversification preservation
    Rebalancing Frequency:
        - Signal-driven optimization
        - Transaction cost consideration
        - Tax efficiency optimization
Troubleshooting and Common Issues
Missing Fundamental Data
When fundamental data is unavailable, the indicator relies more heavily on technical analysis with reduced reliability.
Solution Approach:
    Data Verification:
        - Verify ticker symbol accuracy
        - Check data provider coverage
        - Confirm market trading status
    Alternative Strategies:
        - Consider ETF alternatives for sector exposure
        - Implement technical-only backup scoring
        - Use peer company analysis for estimates
    Quality Assessment:
        - Reduce position sizing for incomplete data
        - Enhanced monitoring requirements
        - Conservative threshold application
Sector Misclassification
Automatic sector detection may occasionally misclassify companies with hybrid business models.
Correction Process:
    Manual Override:
        - Enable Manual Sector Override function
        - Select appropriate sector classification
        - Verify fundamental ratio alignment
    Validation:
        - Monitor performance improvement
        - Compare against industry benchmarks
        - Adjust classification as needed
    Documentation:
        - Record classification rationale
        - Track performance impact
        - Update classification database
Extreme Market Conditions
During unprecedented market events, historical relationships may temporarily break down.
Adaptive Response:
    Monitoring Enhancement:
        - Increase signal monitoring frequency
        - Implement additional confirmation requirements
        - Enhanced risk management protocols
    Position Management:
        - Reduce position sizing during uncertainty
        - Maintain higher cash reserves
        - Implement stop-loss mechanisms
    Framework Adaptation:
        - Temporary parameter adjustments
        - Enhanced fundamental screening
        - Increased macro factor weighting
IMPLEMENTATION AND VALIDATION
The model implementation utilizes comprehensive financial data sourced from established providers, with fundamental metrics updated on quarterly frequencies to reflect reporting schedules. Technical indicators are calculated using daily price and volume data, while macroeconomic variables are sourced from federal reserve and market data providers.
Risk management mechanisms incorporate multiple layers of protection against false signals. The bankruptcy risk filter utilizes Altman Z-Scores below 1.8 combined with current ratios below 1.0 to identify companies facing potential financial distress. Liquidity crisis detection employs quick ratios below 0.5 combined with cash-to-debt ratios below 0.1. Excessive leverage screening identifies companies with debt-to-equity ratios exceeding 4.0 and interest coverage ratios below 2.0.
Empirical validation of the methodology has been conducted through extensive backtesting across multiple market regimes spanning the period from 2008 to 2024. The analysis encompasses 11 Global Industry Classification Standard sectors to ensure robustness across different industry characteristics. Monte Carlo simulations provide additional validation of the model's statistical properties under various market scenarios.
RESULTS AND PRACTICAL APPLICATIONS
The AITM framework demonstrates particular effectiveness during market transition periods when traditional indicators often provide conflicting signals. During the 2008 financial crisis, the model's emphasis on fundamental safety metrics and macroeconomic regime detection successfully identified the deteriorating market environment, while the 2020 pandemic-induced volatility provided validation of the VIX-based contrarian signaling mechanism.
Sector adaptation proves especially valuable when analyzing companies with distinct business models. Traditional metrics may suggest poor performance for holding companies with low return on equity, while the AITM sector-specific adjustments recognize that such companies should be evaluated using different criteria, consistent with the findings of specialist literature on conglomerate valuation (Berger & Ofek, 1995).
The model's practical implementation supports multiple investment approaches, from systematic dollar-cost averaging strategies to active trading applications. Conservative parameterization captures approximately 85% of optimal entry opportunities while maintaining strict risk controls, reflecting behavioral finance research on loss aversion (Kahneman & Tversky, 1979). Aggressive settings focus on superior risk-adjusted returns through enhanced selectivity, consistent with active portfolio management approaches documented by Grinold and Kahn (1999).
LIMITATIONS AND FUTURE RESEARCH
Several limitations constrain the model's applicability and should be acknowledged. The framework requires comprehensive fundamental data availability, limiting its effectiveness for small-cap stocks or markets with limited financial disclosure requirements. Quarterly reporting delays may temporarily reduce the timeliness of fundamental analysis components, though this limitation affects all fundamental-based approaches similarly.
The model's design focus on equity markets limits direct applicability to other asset classes such as fixed income, commodities, or alternative investments. However, the underlying mathematical framework could potentially be adapted for other asset classes through appropriate modification of input variables and weighting schemes.
Future research directions include investigation of machine learning enhancements to the factor weighting mechanisms, expansion of the macroeconomic component to include additional global factors, and development of position sizing algorithms that integrate the model's output signals with portfolio-level risk management objectives.
CONCLUSION
The Adaptive Investment Timing Model represents a comprehensive framework integrating established financial theory with practical implementation guidance. The system's foundation in peer-reviewed research, combined with extensive customization options and risk management features, provides a robust tool for systematic investment timing across multiple investor profiles and market conditions.
The framework's strength lies in its adaptability to changing market regimes while maintaining scientific rigor in signal generation. Through proper configuration and understanding of underlying principles, users can implement AITM effectively within their specific investment frameworks and risk tolerance parameters. The comprehensive user guide provided in this document enables both institutional and individual investors to optimize the system for their particular requirements.
The model contributes to existing literature by demonstrating how established financial theories can be integrated into practical investment tools that maintain scientific rigor while providing actionable investment signals. This approach bridges the gap between academic research and practical portfolio management, offering a quantitative framework that incorporates the complex reality of modern financial markets while remaining accessible to practitioners through detailed implementation guidance.
REFERENCES
Altman, E. I. (1968). Financial ratios, discriminant analysis and the prediction of corporate bankruptcy. Journal of Finance, 23(4), 589-609.
Ang, A., & Bekaert, G. (2007). Stock return predictability: Is it there? Review of Financial Studies, 20(3), 651-707.
Baker, M., & Wurgler, J. (2007). Investor sentiment in the stock market. Journal of Economic Perspectives, 21(2), 129-152.
Berger, P. G., & Ofek, E. (1995). Diversification's effect on firm value. Journal of Financial Economics, 37(1), 39-65.
Bollinger, J. (2001). Bollinger on Bollinger Bands. New York: McGraw-Hill.
Calmar, T. (1991). The Calmar ratio: A smoother tool. Futures, 20(1), 40.
Edwards, R. D., Magee, J., & Bassetti, W. H. C. (2018). Technical Analysis of Stock Trends. 11th ed. Boca Raton: CRC Press.
Estrella, A., & Mishkin, F. S. (1998). Predicting US recessions: Financial variables as leading indicators. Review of Economics and Statistics, 80(1), 45-61.
Fama, E. F., & French, K. R. (1988). Dividend yields and expected stock returns. Journal of Financial Economics, 22(1), 3-25.
Fama, E. F., & French, K. R. (1993). Common risk factors in the returns on stocks and bonds. Journal of Financial Economics, 33(1), 3-56.
Giot, P. (2005). Relationships between implied volatility indexes and stock index returns. Journal of Portfolio Management, 31(3), 92-100.
Graham, B., & Dodd, D. L. (2008). Security Analysis. 6th ed. New York: McGraw-Hill Education.
Grinold, R. C., & Kahn, R. N. (1999). Active Portfolio Management. 2nd ed. New York: McGraw-Hill.
Guidolin, M., & Timmermann, A. (2007). Asset allocation under multivariate regime switching. Journal of Economic Dynamics and Control, 31(11), 3503-3544.
Hamilton, J. D. (1989). A new approach to the economic analysis of nonstationary time series and the business cycle. Econometrica, 57(2), 357-384.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. Econometrica, 47(2), 263-291.
Koenker, R., & Bassett Jr, G. (1978). Regression quantiles. Econometrica, 46(1), 33-50.
Lakonishok, J., Shleifer, A., & Vishny, R. W. (1994). Contrarian investment, extrapolation, and risk. Journal of Finance, 49(5), 1541-1578.
Lo, A. W., & MacKinlay, A. C. (1999). A Non-Random Walk Down Wall Street. Princeton: Princeton University Press.
Malkiel, B. G. (2003). The efficient market hypothesis and its critics. Journal of Economic Perspectives, 17(1), 59-82.
Markowitz, H. (1952). Portfolio selection. Journal of Finance, 7(1), 77-91.
Miller, G. A. (1956). The magical number seven, plus or minus two: Some limits on our capacity for processing information. Psychological Review, 63(2), 81-97.
Penman, S. H. (2012). Financial Statement Analysis and Security Valuation. 5th ed. New York: McGraw-Hill Education.
Piotroski, J. D. (2000). Value investing: The use of historical financial statement information to separate winners from losers. Journal of Accounting Research, 38, 1-41.
Sharpe, W. F. (1964). Capital asset prices: A theory of market equilibrium under conditions of risk. Journal of Finance, 19(3), 425-442.
Sharpe, W. F. (1994). The Sharpe ratio. Journal of Portfolio Management, 21(1), 49-58.
Thaler, R. H., & Sunstein, C. R. (2008). Nudge: Improving Decisions About Health, Wealth, and Happiness. New Haven: Yale University Press.
Whaley, R. E. (1993). Derivatives on market volatility: Hedging tools long overdue. Journal of Derivatives, 1(1), 71-84.
Whaley, R. E. (2000). The investor fear gauge. Journal of Portfolio Management, 26(3), 12-17.
Wilder, J. W. (1978). New Concepts in Technical Trading Systems. Greensboro: Trend Research.
MNQ EMA StrategyThis strategy is not perfected yet. ONE MINUTE TIMEFRAME 
The goal is to take Longs above the 5 ema when price is above all the 200, 30, and 5 ema.
Short side is when candle closes below the 5 ema and price is below the 300, 30, and 5 ema. 
 I use candle range blocks for different time zones to avoid excess orders from being triggered. As well as blocks when stoploss is hit or after a profitable trade of certain ticks. 
There is an RSI to avoid trades when there isn't too much movement. 
My goal is to get an entry when price trades above the 5 ema and then next candle passes it by .25 instead of entering immediately. The stoploss as the low of candle before entry and TP as 3 times the stoploss. I've tried a million times to make it like this but I don't know how to use pine script or Code. 
The sell side is basically the same, enter at candle close below 5 ema wait for low to get swept to enter and stoploss above previous  high, with TP 3 times the stoploss. 
Publishing in hopes anyone knows how to adjust this 
 
CAUTION THIS STRATEGY WORKS WITH CURRENT PRICE ACTION DUE TO ME USING RECENT TICK COUNT RATHER THAN BASED ON CANDLES OR PERCENTAGES. THIS WILL ONLY WORK AS LONG AS MARKET MOVES AS IT HAS BEEN SINCE 2024.   CME_MINI:MNQ1!  
Monthly DividerThis Trading View indicator visually marks the beginning of each month starting from January 2024. It draws vertical lines on the chart at the start of each month and labels them with the corresponding month abbreviation (e.g., "Jan", "Feb"). Users can customize the color and thickness of the lines through the indicator settings, allowing for personalized chart aesthetics. This tool is ideal for traders and analysts who want to easily identify month transitions and enhance their technical analysis.
TASC 2025.02 Autocorrelation Indicator█ OVERVIEW 
This script implements the Autocorrelation Indicator introduced by John Ehlers in the "Drunkard's Walk: Theory And Measurement By Autocorrelation" article from the  February 2025 edition of TASC's Traders' Tips . The indicator calculates the  autocorrelation  of a price series across several  lags  to construct a  periodogram , which traders can use to identify market cycles, trends, and potential reversal patterns. 
 █ CONCEPTS 
 Drunkard's walk 
A  drunkard's walk , formally known as a  random walk , is a type of  stochastic process  that models the evolution of a system or variable through successive random steps. 
In his article, John Ehlers relates this model to market data. He discusses two first- and second-order partial differential equations, modified for discrete (non-continuous) data, that can represent solutions to the discrete random walk problem: the diffusion equation and the wave equation. According to Ehlers, market data takes on a mixture of two "modes" described by these equations. He theorizes that when "diffusion mode" is dominant, trading success is almost a matter of luck, and when "wave mode" is dominant, indicators may have improved performance. 
 Pink spectrum 
John Ehlers explains that many recent academic studies affirm that market data has a  pink spectrum , meaning the power spectral density of the data is proportional to the wavelengths it contains, like  pink noise . A random walk with a pink spectrum suggests that the states of the random variable are  correlated  and not independent. In other words, the random variable exhibits  long-range dependence  with respect to previous states. 
 Autocorrelation function (ACF) 
 Autocorrelation  measures the correlation of a time series with a delayed copy, or  lag , of itself. The autocorrelation function (ACF) is a method that evaluates autocorrelation across a  range of lags , which can help to identify patterns, trends, and cycles in stochastic market data. Analysts often use ACF to detect and characterize long-range dependence in a time series. 
The Autocorrelation Indicator evaluates the ACF of market prices over a fixed range of lags, expressing the results as a color-coded heatmap representing a dynamic periodogram. Ehlers suggests the information from the periodogram can help traders identify different market behaviors, including:  
 Cycles : Distinguishable as  repeated patterns  in the periodogram.
 Reversals : Indicated by sharp vertical changes in the periodogram when the indicator uses a  short data length . 
 Trends : Indicated by increasing correlation across lags, starting with the shortest, over time. 
 
 █ USAGE 
This script calculates the Autocorrelation Indicator on an input "Source" series, smoothed by Ehlers'  UltimateSmoother  filter, and plots several color-coded lines to represent the periodogram's information. Each line corresponds to an analyzed lag, with the shortest lag's line at the bottom of the pane. Green hues in the line indicate a positive correlation for the lag, red hues indicate a negative correlation (anticorrelation), and orange or yellow hues mean the correlation is near zero. 
Because Pine has a limit on the number of plots for a single indicator, this script divides the periodogram display into  three  distinct ranges that cover different lags. To see the full periodogram, add three instances of this script to the chart and set the "Lag range" input for each to a different value, as demonstrated in the chart above. 
With a modest autocorrelation length, such as 20 on a "1D" chart, traders can identify seasonal patterns in the price series, which can help to pinpoint cycles and moderate trends. For instance, on the daily ES1! chart above, the indicator shows repetitive, similar patterns through fall 2023 and winter 2023-2024. The green "triangular" shape rising from the zero lag baseline over different time ranges corresponds to seasonal trends in the data.
To identify turning points in the price series, Ehlers recommends using a short autocorrelation length, such as 2. With this length, users can observe sharp, sudden shifts along the vertical axis, which suggest potential turning points from upward to downward or vice versa.
Session Bar/Candle ColoringChange the color of candles within a user-defined trading session.  Borders and wicks can be changed as well, not just the body color.
 PREFACE 
This script can be used an educational resource for those who are interested in learning Pine Script.  Therefore, the script is published open source and is organized in a manner that follows the recommended  Style Guide .
While the main premise of the indicator is rather simple, the script showcases various things that can be achieved such as conditional plotting, alignment of indicator settings, user input validation, script optimization, and more.  The script also has examples of taking into consideration the chart timeframe and/or different chart types (Heikin Ashi, Renko, etc.) that a user might be running it on.  Note: for complete beginners, I strongly suggest going through the  Pine Script User Manual  (possibly more than once).
 FEATURES 
Besides being able to select a specific time window, the indicator also provides additional color settings for changing the background color or changing the colors of neutral/indecisive candles, as shown in the image below.
  
This allows for a higher level of customization beyond the TradingView chart settings or other similar scripts that are currently available.
 HOW TO USE 
 
  First, define the intraday trading session that will contain the candles to modify.  The session can be limited to specific days of the week.
  Next, select the parts of the candles that should be modified: Body, Borders, Wick, and/or Background.
  For each of the candle parts that were enabled, you can select the colors that will be used depending on whether a candle is bullish (⇧), bearish (⇩), or neutral (⇆).
 
All other indicator settings will have a detailed tooltip to describe its usage and/or effect.
 LIMITATIONS 
 
  The indicator is not intended to function on Daily or higher timeframes due to the intraday nature of session time windows.
  The indicator cannot always automatically detect the chart type being used, therefore the user is requested to manually input the chart type via the " Chart Style " setting.
  Depending on the available historical data and the selected choice for the " Portion of bar in session " setting, the indicator may not be able to update very old candles on the chart.
 
 EXAMPLE USAGE 
This section will show examples of different scenarios that the indicator can be used for.
  
Emphasizing a main trading session.
  
Defining a "Pre/post market hours background" like is available for some symbols (e.g.,  NASDAQ:AAPL ).
  
Highlighting in which bar the midnight candle occurs.
  
Hiding indecision bars (neutral candles).
  
Showing only "Regular Trading Hours" for a chart that does not have the option to toggle ETH/RTH.  To achieve this, the actual chart data is hidden, and only the indicator is visible; alternatively, a 2nd instance of the indicator could change colors to match the chart background.
  
Using a combination of Bars and Japanese Candlesticks.  Alternatively, this could be done by hiding the main chart data and using 2 instances of the indicator (one with " Chart Style " setting as  Bars , and the other set to  Candles ).
  
Using a combination of thin and thick bars on  Range  charts.  Note: requires disabling the "Thin Bars" setting for  Bar  charts in the TradingView chart settings.
 NOTES 
 
  If using more than one instance of this indicator on the same chart, you can use the TradingView "Save Indicator Template" feature to avoid having to re-configure the multiple indicators at a later time.
  This indicator is intended to work "out-of-the-box" thanks to the  behind_chart  option introduced to Pine Script in October 2024.  But you can always manually bring the indicator to the front just in case the color changes are not being seen (using the "More" option in the indicator status line:  More  >  Visual Order  >  Bring to front ).
  Many thanks to  fikira  for their help and inspiring me to create open source scripts.
  Any feedback including bug reports or suggestions for improving the indicator (or source code itself) are always welcome in the comments section.
Portfolio SnapShot v0.3Here is a Tradingview Pinescript that I call "Portfolio Snapshot".  It is based on two other separate scripts that I combined, modified and simplified - shoutout to RedKTrader (Portfolio Tracker - Table Version) and FriendOfTheTrend (Portfolio Tracker For Stocks & Crypto) for their inspiration and code. I was using both of these scripts, and decided to combine the two and increase the number of stocks to 20. I was looking for an easy way to track my entire portfolio (scattered across 5 accounts) PnL on a total and stock basis. PnL - that's it, very simple by design. The features are:
1) Track PnL across multiple accounts, from inception and current day.
2) PnL is reported in two tables, at the portfolio level and individual stock level
3) Both tables can be turned on/off and placed anywhere on the chart.
4) Input up to 20 assets (stocks, crypto, ETFs)
The user has to manually calculate total shares and average basis for stocks in multiple accounts, and then inputs this in the user input dialog. I update mine as each trade is made, or you can just update once a week or so.
I've pre-loaded it with the major indices and sector ETFs, plus URA, GLD, SLV.  100 shares of each, and prices are based on the close Jan 2 2024.  So if you don't want to track your portfolio, you can use it to track other things you find interesting, such as annual performance of each sector.
[ALGOA+] Markov Chains Library by @metacamaleoLibrary   "MarkovChains" 
    Markov Chains library by @metacamaleo. Created in 09/08/2024. 
This library provides tools to calculate and visualize Markov Chain-based transition matrices and probabilities. This library supports two primary algorithms: a rolling window Markov Chain and a conditional Markov Chain (which operates based on specified conditions). The key concepts used include Markov Chain states, transition matrices, and future state probabilities based on past market conditions or indicators.
Key functions:
- `mc_rw()`: Builds a transition matrix using a rolling window Markov Chain, calculating probabilities based on a fixed length of historical data.
- `mc_cond()`: Builds a conditional Markov Chain transition matrix, calculating probabilities based on the current market condition or indicator state.
Basically, you will just need to use the above functions on your script to default outputs and displays.
Exported UDTs include:
- s_map: An UDT variable used to store a map with dummy states, i.e., if possible states are bullish, bearish, and neutral, and current is bullish, it will be stored
  in a map with following keys and values: "bullish", 1; "bearish", 0; and "neutral", 0. You will only use it to customize your own script, otherwise, it´s only for internal use.
- mc_states: This UDT variable stores user inputs, calculations and MC outputs. As the above, you don´t need to use it, but you may get features to customize your own script.
For example, you may use mc.tm to get the transition matrix, or the prob map to customize the display. As you see, functions are all based on mc_states UDT. The s_map UDT is used within mc_states´s s array.
Optional exported functions include:
- `mc_table()`: Displays the transition matrix in a table format on the chart for easy visualization of the probabilities.
- `display_list()`: Displays a map (or array) of string and float/int values in a table format, used for showing transition counts or probabilities.
- `mc_prob()`: Calculates and displays probabilities for a given number of future bars based on the current state in the Markov Chain.
- `mc_all_states_prob()`: Calculates probabilities for all states for future bars, considering all possible transitions.
The above functions may be used to customize your outputs. Use the returned variable mc_states from mc_rw() and mc_cond() to display each of its matrix, maps or arrays using mc_table() (for matrices) and display_list() (for maps and arrays) if you desire to debug or track the calculation process.
See the examples in the end of this script.
Have good trading days! 
Best regards,
@metacamaleo
-----------------------------
  KEY FUNCTIONS  
 mc_rw(state, length, states, pred_length, show_table, show_prob, table_position, prob_position, font_size) 
  Builds the transition matrix for a rolling window Markov Chain.
  Parameters:
     state (string) : The current state of the market or system.
     length (int) : The rolling window size.
     states (array) : Array of strings representing the possible states in the Markov Chain.
     pred_length (int) : The number of bars to predict into the future.
     show_table (bool) : Boolean to show or hide the transition matrix table.
     show_prob (bool) : Boolean to show or hide the probability table.
     table_position (string) : Position of the transition matrix table on the chart.
     prob_position (string) : Position of the probability list on the chart.
     font_size (string) : Size of the table font.
  Returns: The transition matrix and probabilities for future states.
 mc_cond(state, condition, states, pred_length, show_table, show_prob, table_position, prob_position, font_size) 
  Builds the transition matrix for conditional Markov Chains.
  Parameters:
     state (string) : The current state of the market or system.
     condition (string) : A string representing the condition.
     states (array) : Array of strings representing the possible states in the Markov Chain.
     pred_length (int) : The number of bars to predict into the future.
     show_table (bool) : Boolean to show or hide the transition matrix table.
     show_prob (bool) : Boolean to show or hide the probability table.
     table_position (string) : Position of the transition matrix table on the chart.
     prob_position (string) : Position of the probability list on the chart.
     font_size (string) : Size of the table font.
  Returns: The transition matrix and probabilities for future states based on the HMM.
Black-Scholes option price model & delta hedge strategyBlack-Scholes Option Pricing Model Strategy 
The strategy is based on the Black-Scholes option pricing model and allows the calculation of option prices, various option metrics (the Greeks), and the creation of synthetic positions through delta hedging.
 ATTENTION! 
 Trading derivative financial instruments involves high risks. The author of the strategy is not responsible for your financial results! The strategy is not self-sufficient for generating profit! It is created exclusively for constructing a synthetic derivative financial instrument. Also, there might be errors in the script, so use it at your own risk! I would appreciate it if you point out any mistakes in the comments! I would be even more grateful if you send the corrected code! 
 Application Scope 
This strategy can be used for delta hedging short positions in sold options. For example, suppose you sold a call option on Bitcoin on the Deribit exchange with a strike price of $60,000 and an expiration date of September 27, 2024. Using this script, you can create a delta hedge to protect against the risk of loss in the option position if the price of Bitcoin rises.
Another example: Suppose you use staking of altcoins in your strategies, for which options are not available. By using this strategy, you can hedge the risk of a price drop (Put option). In this case, you won't lose money if the underlying asset price increases, unlike with a short futures position.
Another example: You received an airdrop, but your tokens will not be fully unlocked soon. Using this script, you can fully hedge your position and preserve their dollar value by the time the tokens are fully unlocked. And you won't fear the underlying asset price increasing, as the loss in the event of a price rise is limited to the option premium you will pay if you rebalance the portfolio.
Of course, this script can also be used for simple directional trading of momentum and mean reversion strategies!
 Key Features and Input Parameters 
1. Option settings:
   - Style of option: "European vanilla", "Binary", "Asian geometric".
   - Type of option: "Call" (bet on the rise) or "Put" (bet on the fall).
   - Strike price: the option contract price.
   - Expiration: the expiry date and time of the option contract.
2. Market statistic settings:
   - Type of price source: open, high, low, close, hl2, hlc3, ohlc4, hlcc4 (using hl2, hlc3, ohlc4, hlcc4 allows smoothing the price in more volatile series).
   - Risk-free return symbol: the risk-free rate for the market where the underlying asset is traded. For the cryptocurrency market, the return on the funding rate arbitrage strategy is accepted (a special function is written for its calculation based on the Premium Price).
   - Volatility calculation model: realized (standard deviation over a moving period), implied (e.g., DVOL or VIX), or custom (you can specify a specific number in the field below). For the cryptocurrency market, the calculation of implied volatility is implemented based on the product of the realized volatility ratio of the considered asset and Bitcoin to the Bitcoin implied volatility index.
   - User implied volatility: fixed implied volatility (used if "Custom" is selected in the "Volatility Calculation Method").
3. Display settings:
   - Choose metric: what to display on the indicator scale – the price of the underlying asset, the option price, volatility, or Greeks (all are available).
   - Measure: bps (basis points), percent. This parameter allows choosing the unit of measurement for the displayed metric (for all except the Greeks).
4. Trading settings:
   - Hedge model: None (do not trade, default), Simple (just open a position for the full volume when the strike price is crossed), Synthetic option (creating a synthetic option based on the Black-Scholes model).
   - Position side: Long, Short.
   - Position size: the number of units of the underlying asset needed to create the option.
   - Strategy start time: the moment in time after which the strategy will start working to create a synthetic option.
   - Delta hedge interval: the interval in minutes for rebalancing the portfolio. For example, a value of 5 corresponds to rebalancing the portfolio every 5 minutes.
 Post scriptum 
My strategy based on the SegaRKO model. Many thanks to the author! Unfortunately, I don't have enough reputation points to include a link to the author in the description. You can find the original model via the link in the code, as well as through the search indicators on the charts by entering the name: "Black-Scholes Option Pricing Model". I have significantly improved the model: the calculation of volatility, risk-free rate and time value of the option have been reworked. The code performance has also been significantly optimized. And the most significant change is the execution, with which you can now trade using this script.
Concretum BandsDefinition
 
The Concretum Bands indicator recreates the Upper and Lower Bound of the Noise Area described in the paper "Beat the Market: An Effective Intraday Momentum Strategy for S&P500 ETF (SPY)" published by Concretum founder Zarattini, along with Barbon and Aziz, in May 2024. 
Below we provide all the information required to understand how the indicator is calculated, the rationale behind it and how people can use it.  
 Idea Behind
 
The indicator aims to outline an intraday price region where the stock is expected to move without indicating any demand/supply imbalance. When the price crosses the boundaries of the Noise Area, it suggests a significant imbalance that may trigger an intraday trend.
 How the Indicator is Calculated 
The bands at time  HH:MM  are computed by taking the open price of day  t  and then adding/subtracting the average absolute move over the last n days from market open to minute  HH:MM . The bands are also adjusted to account for overnight gaps. A volatility multiplier can be used to increase/decrease the width of the bands, similar to other well-known technical bands. The bands described in the paper were computed using a lookback period (length) of 14 days and a Volatility Multiplier of 1. Users can easily adjust these settings.
 How to use the indicator 
A trader may use this indicator to identify intraday moves that exceed the average move over the most recent period. A break outside the bands could be used as a signal of significant demand/supply imbalance.
NCI - Timeframe + WatermarkDeveloped by Jayce in June 2022 and later updated by Light in January 2024.
 Key Features: 
 Customizable Watermark:   Enhance your chart with a personalized watermark. Enter any text, like your trading mantra or brand name, to keep your focus aligned with your trading strategy.
 Adjustable Font Size:  Tailor the appearance of your watermark and notes with adjustable font sizes, ranging from "Tiny" to "Huge," ensuring optimal visibility and integration with your chart setup.
 Timeframe Display:  Stay informed of the current chart's timeframe, neatly displayed alongside your chosen watermark. Whether you're analyzing trends in minutes, hours, or days, this feature keeps you oriented without cluttering your workspace.
 Inspirational Note:   Complement your watermark with an inspirational note or a quick reminder of your trading discipline and risk management strategies, keeping your principles front and center.
3 Important Value CompositesCalculated on February 17, 2024. USDT 378 items, BTC 282 items, BINANCE 
This is a watchlist, along with the most accurate computed values that I could achieve. It may be beneficial for those who want to change values from the "120x ticker screener (composite tickers)" indicator, which is one of the excellent indicators to bypass the limitation of the request. security() function that limits to only 40 requests. I've thought about this before but couldn't succeed, but someone finally did it.  :)
-->  120x ticker screener (composite tickers) 
Thank you once again for this idea.
 You must look for this and change it. 
  t1 = 'symbol', n1 = Multiply  , r1 = Pricescale(decimal)  
 Example of grouping: Group 1 
 BINANCE:ETHUSDT    , BINANCE:FDUSDUSDT    , BINANCE:BTCUSDT
       2,                  4,                      2
      13,                  10 
 █ Note
   • Tickers: For your watchlist, arrange them from left to right, pairing them in groups of 3.
   • Pricescale: This represents the decimal length, arrange them from left to right, pairing them in groups of 3.
   • Multiply: This involves multiplying the first 2 items in each pair of watchlists. Arrange them from left to right, pairing them in groups of 2.
   * If you group items incorrectly, it may lead to inaccurate results.
   * Please be advised that if one of the values in the "Pricescale"(decimal) trio changes, there may be a need to adjust those values accordingly to ensure correct digit separation. Otherwise, within the group, the numbers might appear peculiar.
Multi-TF Gates (Labels + Alerts)//@version=6
indicator("PO9 – Multi-TF Gates (Labels + Alerts)", overlay=true, max_lines_count=500)
iYear=input.int(2024,"Anchor Year",minval=1970)
iMonth=input.int(11,"Anchor Month",minval=1,maxval=12)
iDay=input.int(6,"Anchor Day",minval=1,maxval=31)
useSymbolTZ=input.bool(true,"Use symbol's exchange timezone (syminfo.timezone)")
tzChoice=input.string("Etc/UTC","Custom timezone (if not using symbol TZ)",options= )
anchorType=input.string("FX NY 17:00","Anchor at",options= )
showEvery=input.int(9,"Mark every Nth candle",minval=1)
showD=input.bool(true,"Show Daily")
show3H=input.bool(true,"Show 3H")
show1H=input.bool(true,"Show 1H")
show15=input.bool(true,"Show 15M")
show5=input.bool(false,"Show 5M (optional)")
colD=input.color(color.new(color.red,0),"Daily color")
col3H=input.color(color.new(color.orange,0),"3H color")
col1H=input.color(color.new(color.yellow,0),"1H color")
col15=input.color(color.new(color.teal,0),"15M color")
col5=input.color(color.new(color.gray,0),"5M color")
styStr=input.string("dashed","Line style",options= )
lnW=input.int(2,"Line width",minval=1,maxval=4)
extendTop=input.float(1.5,"ATR multiples above high",minval=0.1)
extendBottom=input.float(1.5,"ATR multiples below low",minval=0.1)
showLabels=input.bool(true,"Show labels")
enableAlerts=input.bool(true,"Enable alerts")
f_style(s)=>s=="solid"?line.style_solid:s=="dashed"?line.style_dashed:line.style_dotted
var lines=array.new_line()
f_prune(maxKeep)=>
    if array.size(lines)>maxKeep
        old=array.shift(lines)
        line.delete(old)
tzEff=useSymbolTZ?syminfo.timezone:tzChoice
anchorTs=anchorType=="FX NY 17:00"?timestamp("America/New_York",iYear,iMonth,iDay,17,0):timestamp(tzEff,iYear,iMonth,iDay,0,0)
atr=ta.atr(14)
f_vline(_color,_tf,_idx)=>
    y1=low-atr*extendBottom
    y2=high+atr*extendTop
    lid=line.new(x1=bar_index,y1=y1,x2=bar_index,y2=y2,xloc=xloc.bar_index,extend=extend.none,color=_color,style=f_style(styStr),width=lnW)
    if showLabels
        label.new(x=bar_index,y=high+(atr*2),text=_tf+" #"+str.tostring(_idx),xloc=xloc.bar_index,style=label.style_label_down,color=_color,textcolor=color.black)
    array.push(lines,lid)
is_tf_open(tf)=> time==request.security(syminfo.tickerid,tf,time,barmerge.gaps_off,barmerge.lookahead_off)
f_tf(_tf,_show,_color,_name)=>
    var bool started=false
    var int idx=0
    isOpen=_show and is_tf_open(_tf)
    firstBar=isOpen and (time>=anchorTs) and (nz(time ,time)
Luxy BIG beautiful Dynamic ORBThis is an advanced Opening Range Breakout (ORB) indicator that tracks price breakouts from the first 5, 15, 30, and 60 minutes of the trading session. It provides complete trade management including entry signals, stop-loss placement, take-profit targets, and position sizing calculations.
The ORB strategy is based on the concept that the opening range of a trading session often acts as support/resistance, and breakouts from this range tend to lead to significant moves.
  
 What Makes This Different? 
Most ORB indicators simply draw horizontal lines and leave you to figure out the rest. This indicator goes several steps further:
 Multi-Stage Tracking 
Instead of just one ORB timeframe, this tracks FOUR simultaneously (5min, 15min, 30min, 60min). Each stage builds on the previous one, giving you multiple trading opportunities throughout the session.
 Active Trade Management 
When a breakout occurs, the indicator automatically calculates and displays entry price, stop-loss, and multiple take-profit targets. These lines extend forward and update in real-time until the trade completes.
 Cycle Detection 
Unlike indicators that only show the first breakout, this tracks the complete cycle: Breakout → Retest → Re-breakout. You can see when price returns to test the ORB level after breaking out (potential re-entry).
 Failed Breakout Warning 
If price breaks out but quickly returns inside the range (within a few bars), the label changes to "FAILED BREAK" - warning you to exit or avoid the trade.
 Position Sizing Calculator 
Built-in risk management that tells you exactly how many shares to buy based on your account size and risk tolerance. No more guessing or manual calculations.
 Advanced Filtering 
Optional filters for volume confirmation, trend alignment, and Fair Value Gaps (FVG) to reduce false signals and improve win rate.
  
 Core Features Explained
 
### 1. Multi-Stage ORB Levels
The indicator builds four separate Opening Range levels:
 
 ORB 5  - First 5 minutes (fastest signals, most volatile)
 ORB 15  - First 15 minutes (balanced, most popular)
 ORB 30  - First 30 minutes (slower, more reliable)
 ORB 60  - First 60 minutes (slowest, most confirmed)
 
Each level is drawn as a horizontal range on your chart. As time progresses, the ranges expand to include more price action. You can enable or disable any stage and assign custom colors to each.
 How it works:  During the opening minutes, the indicator tracks the highest high and lowest low. Once the time period completes, those levels become your ORB high and low for that stage.
### 2. Breakout Detection
When price closes outside the ORB range, a label appears:
 
 BREAK UP  (green label above price) - Price closed above ORB High
 BREAK DOWN  (red label below price) - Price closed below ORB Low
 
The label shows which ORB stage triggered (ORB5, ORB15, etc.) and the cycle number if tracking multiple breakouts.
 Important:  Signals appear on bar close only - no repainting. What you see is what you get.
### 3. Retest Detection
After price breaks out and moves away, if it returns to test the ORB level, a "RETEST" label appears (orange). This indicates:
 
 The original breakout level is now acting as support/resistance
 Potential re-entry opportunity if you missed the first breakout
 Confirmation that the level is significant
 
The indicator requires price to move a minimum distance away before considering it a valid retest (configurable in settings).
### 4. Failed Breakout Detection
If price breaks out but returns inside the ORB range within a few bars (before the breakout is "committed"), the original label changes to "FAILED BREAK" in orange.
This warns you:
 
 The breakout lacked conviction
 Consider exiting if already in the trade
 Wait for better setup
 
 Committed Breakout:  The indicator tracks how many bars price stays outside the range. Only after staying outside for the minimum number of bars does it become a committed breakout that can be retested.
  
### 5. TP/SL Lines (Trade Management)
When a breakout occurs, colored horizontal lines appear showing:
 
 Entry Line  (cyan for long, orange for short) - Your entry price (the ORB level)
 Stop Loss Line  (red) - Where to exit if trade goes against you
 TP1, TP2, TP3 Lines  (same color as entry) - Profit targets at 1R, 2R, 3R
 
These lines extend forward as new bars form, making it easy to track your trade. When a target is hit, the line turns green and the label shows a checkmark.
 Lines freeze (stop updating) when: 
 
 Stop loss is hit
 The final enabled take-profit is hit
 End of trading session (optional setting)
 
### 6. Position Sizing Dashboard
The dashboard (bottom-left corner by default) shows real-time information:
 
 Current ORB stage and range size
 Breakout status (Inside Range / Break Up / Break Down)
 Volume confirmation (if filter enabled)
 Trend alignment (if filter enabled)
 Entry and Stop Loss prices
 All enabled Take Profit levels with percentages
 Risk/Reward ratio
 Position sizing: Max shares to buy and total risk amount
 
 Position Sizing Example: 
If your account is $25,000 and you risk 1% per trade ($250), and the distance from entry to stop loss is $0.50, the calculator shows you can buy 500 shares (250 / 0.50 = 500).
  
### 7. FVG Filter (Fair Value Gap)
Fair Value Gaps are price inefficiencies - gaps left by strong momentum where one candle's high doesn't overlap with a previous candle's low (or vice versa).
When enabled, this filter:
 
 Detects bullish and bearish FVGs
 Draws semi-transparent boxes around these gaps
 Only allows breakout signals if there's an FVG near the breakout level
 
 Why this helps:  FVGs indicate institutional activity. Breakouts through FVGs tend to be stronger and more reliable.
 Proximity setting:  Controls how close the FVG must be to the ORB level. 2.0x means the breakout can be within 2 times the FVG size - a reasonable default.
### 8. Volume & Trend Filters
 Volume Filter: 
Requires current volume to be above average (customizable multiplier). High volume breakouts are more likely to sustain.
 
 Set minimum multiplier (e.g., 1.5x = 50% above average)
 Set "strong volume" multiplier (e.g., 2.5x) that bypasses other filters
 Dashboard shows current volume ratio
 
 Trend Filter: 
Only shows breakouts aligned with a higher timeframe trend. Choose from:
 
 VWAP - Price above/below volume-weighted average
 EMA - Price above/below exponential moving average
 SuperTrend - ATR-based trend indicator
 Combined modes (VWAP+EMA, VWAP+SuperTrend) for stricter filtering
 
### 9. Pullback Filter (Advanced)
 Purpose: 
Waits for price to pull back slightly after initial breakout before confirming the signal. 
This reduces false breakouts from immediate reversals.
 How it works: 
- After breakout is detected, indicator waits for a small pullback (default 2%)
- Once pullback occurs AND price breaks out again, signal is confirmed
- If no pullback within timeout period (5 bars), signal is issued anyway
 Settings: 
 
 Enable Pullback Filter:  Turn this filter on/off
 Pullback %:  How much price must pull back (2% is balanced)
 Timeout (bars):  Max bars to wait for pullback (5 is standard)
 
 When to use: 
- Choppy markets with many fake breakouts
- When you want higher quality signals
- Combine with Volume filter for maximum confirmation
 Trade-off: 
- Better signal quality
- May miss some valid fast moves
- Slight entry delay
  
 How to Use This Indicator 
### For Beginners - Simple Setup
 
 Add the indicator to your chart (5-minute or 15-minute timeframe recommended)
 Leave all default settings - they work well for most stocks
 Watch for BREAK UP or BREAK DOWN labels to appear
 Check the dashboard for entry, stop loss, and targets
 Use the position sizing to determine how many shares to buy
 
 Basic Trading Plan: 
 
 Wait for a clear breakout label
 Enter at the ORB level (or next candle open if you're late)
 Place stop loss where the red line indicates
 Take profit at TP1 (50% of position) and TP2 (remaining 50%)
 
### For Advanced Traders - Customized Setup
 
 Choose which ORB stages to track (you might only want ORB15 and ORB30)
 Enable filters: Volume (stocks) or Trend (trending markets)
 Enable FVG filter for institutional confirmation
 Set "Track Cycles" mode to catch retests and re-breakouts
 Customize stop loss method (ATR for volatile stocks, ORB% for stable ones)
 Adjust risk per trade and account size for accurate position sizing
 
 Advanced Strategy Example: 
 
 Enable ORB15 only (disable others for cleaner chart)
 Turn on Volume filter at 1.5x with Strong at 2.5x
 Enable Trend filter using VWAP
 Set Signal Mode to "Track Cycles" with Max 3 cycles
 Wait for aligned breakouts (Volume + Trend + Direction)
 Enter on retest if you missed the initial break
 
### Timeframe Recommendations
 
 5-minute chart:  Scalping, very active trading, crypto
 15-minute chart:  Day trading, balanced approach (most popular)
 30-minute chart:  Swing entries, less screen time
 60-minute chart:  Position trading, longer holds
 
The indicator works on any intraday timeframe, but ORB is fundamentally a day trading strategy. Daily charts don't make sense for ORB.
 
 DEFAULT CONFIGURATION  
ON by Default:
• All 4 ORB stages (5/15/30/60)
• Breakout Detection
• Retest Labels
• All TP levels (1/1.5/2/3)
• TP/SL Lines (Detailed mode)
• Dashboard (Bottom Left, Dark theme)
• Position Size Calculator
OFF by Default (Optional Filters):
• FVG Filter
• Pullback Filter
• Volume Filter
• Trend Filter
• HTF Bias Check
• Alerts
Recommended for Beginners:
• Leave all defaults
• Session Mode: Auto-Detect
• Signal Mode: Track Cycles
• Stop Method: ATR
• Add Volume Filter if trading stocks
 Recommended for Advanced: 
• Enable ORB15 + ORB30 only (disable 5 & 60)
• Enable: Volume + Trend + FVG 
• Signal Mode: Track Cycles, Max 3 
• Stop Method: ATR or Safer 
• Enable HTF Daily bias check 
 
## Settings Guide
The settings are organized into logical groups. Here's what each section controls:
### ORB COLORS Section
 
 Show Edge Labels:  Display "ORB 5", "ORB 15" labels at the right edge of the levels
 Background:  Fill the area between ORB high/low with color
 Transparency:  How see-through the background is (95% is nearly invisible)
 Enable ORB 5/15/30/60:  Turn each stage on or off individually
 Colors:  Assign colors to each ORB stage for easy identification
 
### SESSION SETTINGS Section
 
 Session Mode:  Choose trading session (Auto-Detect works for most instruments)
 Custom Session Hours:  Define your own hours if needed (format: HHMM-HHMM)
 
Auto-Detect uses the instrument's natural hours (stocks use exchange hours, crypto uses 24/7).
### BREAKOUT DETECTION Section
 
 Enable Breakout Detection:  Master switch for signals
 Show Retest Labels:  Display retest signals
 Label Size:  Visual size for all labels (Small recommended)
 Enable FVG Filter:  Require Fair Value Gap confirmation
 Show FVG Boxes:  Display the gap boxes on chart
 Signal Mode:  "First Only" = one signal per direction per day, "Track Cycles" = multiple signals
 Max Cycles:  How many breakout-retest cycles to track (6 is balanced)
 Breakout Buffer:  Extra distance required beyond ORB level (0.1-0.2% recommended)
 Min Distance for Retest:  How far price must move away before retest is valid (2% recommended)
 Min Bars Outside ORB:  Bars price must stay outside for committed breakout (2 is balanced)
 
### TARGETS & RISK Section
 
 Enable Targets & Stop-Loss:  Calculate and show trade management
 TP1/TP2/TP3 checkboxes:  Select which profit targets to display
 Stop Method:  How to calculate stop loss placement
  - ATR: Based on volatility (best for most cases)
  - ORB %: Fixed % of ORB range
  - Swing: Recent swing high/low
  - Safer: Widest of all methods
 ATR Length & Multiplier:  Controls ATR stop distance (14 period, 1.5x is standard)
 ORB Stop %:  Percentage beyond ORB for stop (20% is balanced)
 Swing Bars:  Lookback period for swing high/low (3 is recent)
 
### TP/SL LINES Section
 
 Show TP/SL Lines:  Display horizontal lines on chart
 Label Format:  "Short" = minimal text, "Detailed" = shows prices
 Freeze Lines at EOD:  Stop extending lines at session close
 
### DASHBOARD Section
 
 Show Info Panel:  Display the metrics dashboard
 Theme:  Dark or Light colors
 Position:  Where to place dashboard on chart
 Toggle rows:  Show/hide specific information rows
 Calculate Position Size:  Enable the position sizing calculator
 Risk Mode:  Risk fixed $ amount or % of account
 Account Size:  Your total trading capital
 Risk %:  Percentage to risk per trade (0.5-1% recommended)
 
### VOLUME FILTER Section
 
 Enable Volume Filter:  Require volume confirmation
 MA Length:  Average period (20 is standard)
 Min Volume:  Required multiplier (1.5x = 50% above average)
 Strong Volume:  Multiplier that bypasses other filters (2.5x)
 
### TREND FILTER Section
 
 Enable Trend Filter:  Require trend alignment
 Trend Mode:  Method to determine trend (VWAP is simple and effective)
 Custom EMA Length:  If using EMA mode (50 for swing, 20 for day trading)
 SuperTrend settings:  Period and Multiplier if using SuperTrend mode
 
### HIGHER TIMEFRAME Section
 
 Check Daily Trend:  Display higher timeframe bias in dashboard
 Timeframe:  What TF to check (D = daily, recommended)
 Method:  Price vs MA (stable) or Candle Direction (reactive)
 MA Period:  EMA length for Price vs MA method (20 is balanced)
 Min Strength %:  Minimum strength threshold for HTF bias to be considered
  - For "Price vs MA": Minimum distance (%) from moving average
  - For "Candle Direction": Minimum candle body size (%)
  - 0.5% is balanced - increase for stricter filtering
  - Lower values = more signals, higher values = only strong trends
 
### ALERTS Section
 
 Enable Alerts:  Master switch (must be ON to use any alerts)
 Breakout Alerts:  Notify on ORB breakouts
 Retest Alerts:  Notify when price retests after breakout
 Failed Break Alerts:  Notify on failed breakouts
 Stage Complete Alerts:  Notify when each ORB stage finishes forming
 
After enabling desired alert types, click "Create Alert" button, select this indicator, choose "Any alert() function call".
## Tips & Best Practices
### General Trading Tips
 
 ORB works best on liquid instruments (stocks with good volume, major crypto pairs)
 First hour of the session is most important - that's when ORB is forming
 Breakouts WITH the trend have higher success rates - use the trend filter
 Failed breakouts are common - use the "Min Bars Outside" setting to filter weak moves
 Not every day produces good ORB setups - be patient and selective
 
### Position Sizing Best Practices
 
 Never risk more than 1-2% of your account on a single trade
 Use the built-in calculator - don't guess your position size
 Update your account size monthly as it grows
 Smaller accounts: use $ Amount mode for simplicity
 Larger accounts: use % of Account mode for scaling
 
### Take Profit Strategy
 
 Most traders use: 50% at TP1, 50% at TP2
 Aggressive: Hold through TP1 for TP2 or TP3
 Conservative: Full exit at TP1 (1:1 risk/reward)
 After TP1 hits, consider moving stop to breakeven
 TP3 rarely hits - only on strong trending days
 
### Filter Combinations
 
 Maximum Quality:  Volume + Trend + FVG (fewest signals, highest quality)
 Balanced:  Volume + Trend (good quality, reasonable frequency)
 Active Trading:  No filters or Volume only (many signals, lower quality)
 Trending Markets:  Trend filter essential (indices, crypto)
 Range-Bound:  Volume + FVG (avoid trend filter)
 
### Common Mistakes to Avoid
 
 Chasing breakouts - wait for the bar to close, don't FOMO into wicks
 Ignoring the stop loss - always use it, move it manually if needed
 Over-leveraging - the calculator shows MAX shares, you can buy less
 Trading every signal - quality > quantity, use filters
 Not tracking results - keep a journal to see what works for YOU
 
## Pros and Cons
### Advantages
 
 Complete all-in-one solution - from signal to position sizing
 Multiple timeframes tracked simultaneously
 Visual clarity - easy to see what's happening
 Cycle tracking catches opportunities others miss
 Built-in risk management eliminates guesswork
 Customizable filters for different trading styles
 No repainting - what you see is locked in
 Works across multiple markets (stocks, forex, crypto)
 
### Limitations
 
 Intraday strategy only - doesn't work on daily charts
 Requires active monitoring during first 1-2 hours of session
 Not suitable for after-hours or extended sessions by default
 Can produce many signals in choppy markets (use filters)
 Dashboard can be overwhelming for complete beginners
 Performance depends on market conditions (trends vs ranges)
 Requires understanding of risk management concepts
 
### Best For
 
 Day traders who can watch the first 1-2 hours of market open
 Traders who want systematic entry/exit rules
 Those learning proper position sizing and risk management
 Active traders comfortable with multiple signals per day
 Anyone trading liquid instruments with clear sessions
 
### Not Ideal For
 
 Swing traders holding multi-day positions
 Set-and-forget / passive investors
 Traders who can't watch market open
 Complete beginners unfamiliar with trading concepts
 Low volume / illiquid instruments
 
## Frequently Asked Questions
 Q: Why are no signals appearing? 
A: Check that you're on an intraday timeframe (5min, 15min, etc.) and that the current time is within your session hours. Also verify that "Enable Breakout Detection" is ON and at least one ORB stage is enabled. If using filters, they might be blocking signals - try disabling them temporarily.
 Q: What's the best ORB stage to use? 
A: ORB15 (15 minutes) is most popular and balanced. ORB5 gives faster signals but more noise. ORB30 and ORB60 are slower but more reliable. Many traders use ORB15 + ORB30 together.
 Q: Should I enable all the filters? 
A: Start with no filters to see all signals. If too many false signals, add Volume filter first (stocks) or Trend filter (trending markets). FVG filter is most restrictive - use for maximum quality but fewer signals.
 Q: How do I know which stop loss method to use? 
A: ATR works for most cases - it adapts to volatility. Use ORB% if you want predictable stop placement. Swing is for respecting chart structure. Safer gives you the most room but largest risk.
 Q: Can I use this for swing trading? 
A: Not really - ORB is fundamentally an intraday strategy. The ranges reset each day. For swing trading, look at weekly support/resistance or moving averages instead.
 Q: Why do TP/SL lines disappear sometimes? 
A: Lines freeze (stop extending) when: stop loss is hit, the last enabled take-profit is hit, or end of session arrives (if "Freeze at EOD" is enabled). This is intentional - the trade is complete.
 Q: What's the difference between "First Only" and "Track Cycles"? 
A: "First Only" shows one breakout UP and one DOWN per day maximum - clean but might miss opportunities. "Track Cycles" shows breakout-retest-rebreak sequences - more signals but busier chart.
 Q: Is position sizing accurate for options/forex? 
A: The calculator is designed for shares (stocks). For options, ignore the share count and use the risk amount. For forex, you'll need to adapt the lot size calculation manually.
 Q: How much capital do I need to use this? 
A: The indicator works for any account size, but practical day trading typically requires $25,000 in the US due to Pattern Day Trader rules. Adjust the "Account Size" setting to match your capital.
 Q: Can I backtest this strategy? 
A: This is an indicator, not a strategy script, so it doesn't have built-in backtesting. You can visually review historical signals or code a strategy script using similar logic.
 Q: Why does the dashboard show different entry price than the breakout label? 
A: If you're looking at an old breakout, the ORB levels may have changed when the next stage completed. The dashboard always shows the CURRENT active range and trade setup.
 Q: What's a good win rate to expect? 
A: ORB strategies typically see 40-60% win rate depending on market conditions and filters used. The strategy relies on positive risk/reward ratios (2:1 or better) to be profitable even with moderate win rates.
 Q: Does this work on crypto? 
A: Yes, but crypto trades 24/7 so you need to define what "session start" means. Use Session Mode = Custom and set your preferred daily reset time (e.g., 0000-2359 UTC).
## Credits & Transparency
### Development
This indicator was developed with the assistance of AI technology to implement complex ORB trading logic.
The strategy concept, feature specifications, and trading logic were designed by the publisher. The implementation leverages modern development tools to ensure:
 
 Clean, efficient, and maintainable code
 Comprehensive error handling and input validation
 Detailed documentation and user guidance
 Performance optimization
 
### Trading Concepts
This indicator implements several public domain trading concepts:
 
 Opening Range Breakout (ORB):  Trading strategy popularized by Toby Crabel, Mark Fisher and many more talanted traders.
 Fair Value Gap (FVG):  Price imbalance concept from ICT methodology
 SuperTrend:  ATR-based trend indicator using public formula
 Risk/Reward Ratio:  Standard risk management principle
 
All mathematical formulas and technical concepts used are in the public domain.
### Pine Script
Uses standard TradingView built-in functions:
 ta.ema(), ta.atr(), ta.vwap(), ta.highest(), ta.lowest(), request.security() 
No external libraries or proprietary code from other authors.
## Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice.
Trading involves substantial risk of loss and is not suitable for every investor. Past performance shown in examples is not indicative of future results.
The indicator provides signals and calculations, but trading decisions are solely your responsibility. Always:
 
 Test strategies on paper before using real money
 Never risk more than you can afford to lose
 Understand that all trading involves risk
 Consider seeking advice from a licensed financial advisor
 
The publisher makes no guarantees regarding accuracy, profitability, or performance. Use at your own risk.
---
 Version:  3.0
 Pine Script Version:  v6
 Last Updated:  October 2024
For support, questions, or suggestions, please comment below or send a private message.
---
 Happy trading, and remember: consistent risk management beats perfect entry timing every time.
Advanced Multi-Timeframe Trend & Signal System═══════════════════════════════════════════════════════════════
ADVANCED MULTI-TIMEFRAME TREND & SIGNAL SYSTEM v1.0
═══════════════════════════════════════════════════════════════
Created by: Zakaria Safri
License: Mozilla Public License 2.0
A comprehensive technical analysis tool designed for traders seeking 
multi-dimensional market insights. This indicator combines proven 
technical analysis methods with modern visualization techniques.
═══════════════════════════════════════════════════════════════
KEY FEATURES
═══════════════════════════════════════════════════════════════
✓ SUPERTREND SIGNAL GENERATION
  - Customizable sensitivity settings
  - Clear long/short entry signals
  - Automatic trend direction detection
  - ATR-based dynamic calculations
✓ MULTI-TIMEFRAME DASHBOARD
  - Real-time trend analysis across 6 timeframes
  - Synchronized trend confirmation
  - Customizable table position and size
  - Current: 1M, 5M, 15M, 1H, 1D coverage
✓ QQE REVERSAL DETECTION
  - Quantitative Qualitative Estimation algorithm
  - Early reversal signal identification
  - Adjustable RSI and smoothing parameters
  - Confirmation-based plotting
✓ DYNAMIC SUPPORT & RESISTANCE
  - Pivot-based level calculation
  - Quick and standard pivot detection
  - Color-coded zones (8 levels)
  - Automatic level updates
✓ MOMENTUM BREAKOUT SIGNALS
  - Ichimoku-inspired calculations
  - Bullish and bearish breakout detection
  - Visual zone highlighting
  - Trend confirmation filters
✓ RISK MANAGEMENT SYSTEM
  - ATR-based stop loss calculation
  - Multiple take profit targets (TP1, TP2, TP3)
  - Customizable risk-to-reward ratios
  - Dynamic price level tracking
  - Hit detection markers
✓ VOLATILITY BANDS
  - Keltner Channel implementation
  - Multiple band layers (3 levels)
  - EMA-based calculations
  - Adaptive to market conditions
✓ TREND CLOUD VISUALIZATION
  - Dual moving average cloud
  - Clear trend direction indication
  - Customizable color scheme
  - Trend bar coloring
═══════════════════════════════════════════════════════════════
HOW TO USE
═══════════════════════════════════════════════════════════════
SETUP:
1. Add indicator to your chart
2. Configure sensitivity in Core Signals section
3. Enable desired features (signals, reversals, breakouts)
4. Set up risk management levels if trading
5. Position MTF dashboard to preference
SIGNAL INTERPRETATION:
• LONG Signal: Price crosses above Supertrend
• SHORT Signal: Price crosses below Supertrend
• REV (Reversal): QQE indicates potential trend change
• Diamond Breakouts: Momentum shift confirmation
• T1/T2/T3: Take profit level hits
MULTI-TIMEFRAME ANALYSIS:
• Green (BULL): Higher timeframe supports uptrend
• Red (BEAR): Higher timeframe supports downtrend
• Use for trend alignment and confirmation
• Best results when multiple timeframes align
RISK MANAGEMENT:
• Enable Stop Loss for automatic SL calculation
• Activate TP levels based on trading style
• Adjust Risk-to-Reward ratio (1:1 to 1:10)
• Monitor hit detection circles for exits
═══════════════════════════════════════════════════════════════
TECHNICAL SPECIFICATIONS
═══════════════════════════════════════════════════════════════
CALCULATIONS:
• Supertrend: ATR-based with customizable multiplier
• QQE: Modified RSI with Wilders smoothing
• Keltner Channels: EMA basis with ATR bands
• Pivots: Standard left/right bar methodology
• Support/Resistance: Multi-level pivot analysis
PARAMETERS:
• Supertrend Sensitivity: 0.5 to 10.0 (default: 2.0)
• RSI Period: 5 to 50 (default: 14)
• QQE Multiplier: 1.0 to 10.0 (default: 4.238)
• Risk-to-Reward: 1 to 10 (default: 4)
TIMEFRAMES:
Compatible with all timeframes. MTF dashboard displays:
• 1 Minute (1M)
• 5 Minutes (5M)
• 15 Minutes (15M)
• 1 Hour (1H)
• 1 Day (1D)
• Current chart timeframe
═══════════════════════════════════════════════════════════════
CUSTOMIZATION OPTIONS
═══════════════════════════════════════════════════════════════
VISUAL:
• Professional color scheme (Cyan/Orange)
• Adjustable table position (9 positions)
• Table size options (tiny/small/normal/large)
• Transparent zone highlighting
• Clean, modern label design
TOGGLES:
• Enable/disable any feature independently
• Show/hide signals, reversals, breakouts
• Toggle S/R levels and zones
• Control trend cloud and bands
• Master trend line optional
ALERTS:
The indicator provides visual signals that can be used with 
TradingView's alert system by setting alerts on the indicator.
═══════════════════════════════════════════════════════════════
BEST PRACTICES
═══════════════════════════════════════════════════════════════
✓ Combine signals for higher probability setups
✓ Use MTF dashboard for trend confirmation
✓ Respect S/R levels for entry/exit planning
✓ Monitor QQE reversals at key price levels
✓ Adjust sensitivity based on asset volatility
✓ Test on demo/paper trading first
✓ Use proper risk management always
═══════════════════════════════════════════════════════════════
IMPORTANT DISCLAIMER
═══════════════════════════════════════════════════════════════
This indicator is a technical analysis tool and does NOT:
• Guarantee profitable trades
• Provide financial advice
• Predict future price movements with certainty
• Replace proper risk management
• Substitute for personal due diligence
Past performance does not indicate future results. All trading 
involves risk. Users should:
- Understand the indicator's logic
- Test thoroughly before live trading
- Use appropriate position sizing
- Never risk more than they can afford to lose
- Consult financial advisors if needed
═══════════════════════════════════════════════════════════════
CODING STANDARDS
═══════════════════════════════════════════════════════════════
This indicator follows PineCoders Coding Conventions:
✓ Proper variable naming (prefixes: i_, f_, c_)
✓ Clear function documentation
✓ Organized code structure
✓ Type declarations
✓ Efficient calculations
✓ No repainting (confirmed signals)
✓ Proper use of request.security
═══════════════════════════════════════════════════════════════
SUPPORT & UPDATES
═══════════════════════════════════════════════════════════════
Version: 1.0
Author: Zakaria Safri
License: MPL 2.0
Last Updated: 2024
For questions, feedback, or suggestions, please comment below.
═══════════════════════════════════════════════════════════════
#trading #signals #supertrend #multiTimeframe #QQE #reversals
#supportResistance #riskManagement #trendAnalysis #momentum
Multi-Timeframe EMA Trend Dashboard with Volume and RSI Filters═══════════════════════════════════════════════════════════
MULTI-TIMEFRAME EMA TREND DASHBOARD
═══════════════════════════════════════════════════════════
OVERVIEW
This indicator provides a comprehensive view of trend direction across multiple timeframes using the classic EMA 20/50 crossover methodology, enhanced with volume confirmation and RSI filtering. It aggregates trend information from six timeframes into a single dashboard for efficient market analysis.
The indicator is designed for educational purposes and to assist traders in identifying potential trend alignments across different time horizons.
═══════════════════════════════════════════════════════════
FEATURES
═══════════════════════════════════════════════════════════
MULTI-TIMEFRAME ANALYSIS
• Monitors 6 timeframes simultaneously: 1m, 5m, 15m, 1H, 4H, 1D
• Each timeframe analyzed independently using request.security()
• Non-repainting implementation with proper lookahead settings
• Calculates overall trend strength as percentage of bullish timeframes
EMA CROSSOVER SYSTEM
• Fast EMA (default: 20) and Slow EMA (default: 50)
• Bullish: Fast EMA > Slow EMA
• Bearish: Fast EMA < Slow EMA  
• Neutral: Fast EMA = Slow EMA (rare condition)
• Visual EMA plots with optional fill area
VOLUME CONFIRMATION
• Optional volume filter for crossover signals
• Compares current volume against moving average (default: 20-period SMA)
• Categorizes volume as: High (>1.5x average), Normal (>average), Low (70), oversold (<30), and neutral zones
• Used in quality score calculation
• Optional display toggle
SUPPORT & RESISTANCE DETECTION
• Automatic detection using highest/lowest over lookback period (default: 50 bars)
• Plots resistance (red), support (green), and mid-level (gray)
• Step-line style for clear visualization
• Optional display toggle
QUALITY SCORING SYSTEM
• Rates trade setups from 1-5 stars
• Considers: MTF alignment, volume confirmation, RSI positioning
• 5 stars: 4+ timeframes aligned + volume confirmed + RSI 50-70
• 4 stars: 4+ timeframes aligned + volume confirmed
• 3 stars: 3+ timeframes aligned
• 2 stars: Exactly 3 timeframes aligned
• 1 star: Other conditions
VISUAL DASHBOARD
• Clean table display (position customizable)
• Color-coded trend indicators (green/red/yellow)
• Extended statistics panel (toggleable)
• Shows: Trends, Strength, Quality, RSI, Volume, Price Distance
═══════════════════════════════════════════════════════════
TECHNICAL SPECIFICATIONS
═══════════════════════════════════════════════════════════
CALCULATIONS
Trend Determination per Timeframe:
• request.security() fetches EMA values with gaps=off, lookahead=off
• Compares Fast EMA vs Slow EMA
• Returns: 1 (bullish), -1 (bearish), 0 (neutral)
Trend Strength:
• Counts number of bullish timeframes
• Formula: (bullish_count / 6) × 100
• Range: 0% (all bearish) to 100% (all bullish)
Price Distance from EMA:
• Formula: ((close - EMA) / EMA) × 100
• Positive: Price above EMA
• Negative: Price below EMA
• Warning when absolute distance > 5%
ANTI-REPAINTING MEASURES
• All request.security() calls use lookahead=barmerge.lookahead_off
• Dashboard updates only on barstate.islast
• Historical bars remain unchanged
• Crossover signals finalize on bar close
═══════════════════════════════════════════════════════════
USAGE GUIDE
═══════════════════════════════════════════════════════════
INTERPRETING THE DASHBOARD
Timeframe Rows:
• Each row shows individual timeframe trend status
• Look for alignment (multiple timeframes same direction)
• Higher timeframes generally more significant
Strength Indicator:
• >66.67%: Strong bullish (4+ timeframes bullish)
• 33.33-66.67%: Mixed/choppy conditions
• <33.33%: Strong bearish (4+ timeframes bearish)
Quality Score:
• Higher stars = better confluence of factors
• 5-star setups have strongest multi-factor confirmation
• Lower scores may indicate weaker or conflicting signals
SUGGESTED APPLICATIONS
Trend Confirmation:
• Check if multiple timeframes confirm current chart trend
• Higher agreement = stronger trend confidence
• Use for position sizing decisions
Entry Timing:
• Wait for EMA crossover on chart timeframe
• Confirm with higher timeframe alignment
• Volume above average preferred
• RSI not in extreme zones
Divergence Detection:
• When lower timeframes diverge from higher
• May indicate trend exhaustion or reversal
• Requires additional confirmation
CUSTOMIZATION
EMA Settings:
• Adjust Fast/Slow lengths for different sensitivities
• Shorter periods = more responsive, more signals
• Longer periods = smoother, fewer signals
• Common alternatives: 10/30, 12/26, 50/200
Volume Filter:
• Enable for higher-quality signals (fewer false positives)
• Disable in always-liquid markets or for more signals
• Adjust MA length based on typical volume patterns
Display Options:
• Toggle EMAs, S/R levels, extended stats as needed
• Choose dashboard position to avoid chart overlap
• Adjust colors for visibility preferences
═══════════════════════════════════════════════════════════
ALERTS
═══════════════════════════════════════════════════════════
AVAILABLE ALERT CONDITIONS
1. Bullish EMA Cross (Volume Confirmed)
2. Bearish EMA Cross (Volume Confirmed)
3. Strong Bullish Alignment (4+ timeframes)
4. Strong Bearish Alignment (4+ timeframes)
5. Trend Strength Increasing (>16.67% jump)
6. Trend Strength Decreasing (>16.67% drop)
7. Excellent Trade Setup (5-star rating)
Alert messages use standard placeholders:
• {{ticker}} - Symbol name
• {{close}} - Current close price
• {{time}} - Bar timestamp
═══════════════════════════════════════════════════════════
LIMITATIONS & CONSIDERATIONS
═══════════════════════════════════════════════════════════
KNOWN LIMITATIONS
• Lower timeframe data may not be available on all symbols
• 1-minute data typically limited to recent history
• request.security() subject to TradingView data limits
• Dashboard requires screen space (may overlap on small screens)
• More complex calculations may affect load time on slower devices
NOT SUITABLE FOR
• Highly volatile/illiquid instruments (many false signals)
• News-driven markets during announcements
• Automated trading without additional filters
• Markets where EMA strategies don't perform well
DOES NOT PROVIDE
• Exact entry/exit prices
• Stop-loss or take-profit levels
• Position sizing recommendations
• Guaranteed profit signals
• Market predictions
═══════════════════════════════════════════════════════════
BEST PRACTICES
═══════════════════════════════════════════════════════════
RECOMMENDED USAGE
✓ Combine with price action analysis
✓ Use appropriate risk management
✓ Backtest on historical data before live use
✓ Adjust settings for specific market characteristics
✓ Wait for higher-quality setups in important trades
✓ Consider overall market context and fundamentals
NOT RECOMMENDED
✗ Using as standalone trading system without confirmation
✗ Trading every signal without discretion
✗ Ignoring risk management principles
✗ Trading without understanding the methodology
✗ Applying to unsuitable markets/timeframes
═══════════════════════════════════════════════════════════
EDUCATIONAL BACKGROUND
═══════════════════════════════════════════════════════════
EMA CROSSOVER STRATEGY
The Exponential Moving Average crossover is a classical trend-following technique:
• Golden Cross: Fast EMA crosses above Slow EMA (bullish signal)
• Death Cross: Fast EMA crosses below Slow EMA (bearish signal)
• Widely used since the 1970s in various markets
• More responsive than SMA due to exponential weighting
MULTI-TIMEFRAME ANALYSIS
Analyzing multiple timeframes helps traders:
• Identify alignment between short and long-term trends
• Reduce false signals from single-timeframe noise
• Understand market context across different horizons
• Make informed decisions about trade duration
VOLUME ANALYSIS
Volume confirmation adds reliability:
• High volume suggests institutional participation
• Low volume signals may indicate false breakouts
• Volume precedes price in many market theories
• Helps distinguish genuine moves from noise
═══════════════════════════════════════════════════════════
TECHNICAL IMPLEMENTATION
═══════════════════════════════════════════════════════════
CODE STRUCTURE
• Organized in clear sections with proper commenting
• Uses explicit type declarations (int, float, bool, color, string)
• Constants defined at top (BULLISH=1, BEARISH=-1, etc.)
• Functions documented with @function, @param, @returns
• Follows PineCoders naming conventions (camelCase variables)
PERFORMANCE OPTIMIZATION
• var keyword for table (created once, not every bar)
• Calculations cached where possible
• Dashboard updates only on last bar
• Minimal redundant security() calls
SECURITY IMPLEMENTATION
• Proper gaps and lookahead parameters
• No future data leakage
• Signals finalize on bar close
• Historical bars remain static
═══════════════════════════════════════════════════════════
VERSION INFORMATION
═══════════════════════════════════════════════════════════
Current Version: 2.0
Pine Script Version: 5
Last Updated: 2024
Developed by: Zakaria Safri
═══════════════════════════════════════════════════════════
SETTINGS REFERENCE
═══════════════════════════════════════════════════════════
EMA SETTINGS
• Fast EMA Length: 1-500 (default: 20)
• Slow EMA Length: 1-500 (default: 50)
VOLUME & MOMENTUM
• Use Volume Confirmation: true/false (default: true)
• Volume MA Length: 1-500 (default: 20)
• Show RSI Levels: true/false (default: true)
• RSI Length: 1-500 (default: 14)
PRICE ACTION FEATURES
• Show Price Distance: true/false (default: true)
• Show Key Levels: true/false (default: true)
• S/R Lookback Period: 10-500 (default: 50)
DISPLAY SETTINGS
• Show EMAs on Chart: true/false (default: true)
• Fast EMA Color: customizable (default: cyan)
• Slow EMA Color: customizable (default: orange)
• EMA Line Width: 1-5 (default: 2)
• Show Fill Between EMAs: true/false (default: true)
• Show Crossover Signals: true/false (default: true)
DASHBOARD SETTINGS
• Position: Top Left/Right, Bottom Left/Right
• Show Extended Statistics: true/false (default: true)
ALERT SETTINGS
• Alert on Multi-TF Alignment: true/false (default: true)
• Alert on Trend Strength Change: true/false (default: true)
═══════════════════════════════════════════════════════════
RISK DISCLAIMER
═══════════════════════════════════════════════════════════
This indicator is provided for educational and informational purposes only. It should not be considered financial advice or a recommendation to buy or sell any security.
IMPORTANT NOTICES:
• Past performance does not indicate future results
• All trading involves risk of capital loss
• No indicator guarantees profitable trades
• Always conduct independent research and analysis
• Use proper risk management and position sizing
• Consult a qualified financial advisor before trading
• The developer assumes no liability for trading losses
By using this indicator, you acknowledge that you understand these risks and accept full responsibility for your trading decisions.
═══════════════════════════════════════════════════════════
SUPPORT & CONTRIBUTIONS
═══════════════════════════════════════════════════════════
FEEDBACK WELCOME
• Constructive comments appreciated
• Bug reports help improve the indicator
• Feature suggestions considered for future versions
• Share your experience to help other users
OPEN SOURCE
This code is published as open source for the TradingView community to:
• Learn from the implementation
• Modify for personal use
• Understand multi-timeframe analysis techniques
If you find this indicator useful, please consider:
• Leaving a thoughtful review
• Sharing with other traders who might benefit
• Following for future updates and releases
═══════════════════════════════════════════════════════════
ADDITIONAL RESOURCES
═══════════════════════════════════════════════════════════
RECOMMENDED READING
• TradingView Pine Script documentation
• PineCoders community resources
• Technical analysis textbooks on moving averages
• Multi-timeframe trading strategy guides
• Risk management principles
RELATED CONCEPTS
• Trend following strategies
• Moving average convergence/divergence
• Multiple timeframe analysis
• Volume-price relationships
• Momentum indicators
═══════════════════════════════════════════════════════════
Thank you for using this indicator. Trade responsibly and continue learning!
═══════════════════════════════════════════════════════════
TradeVision Pro - Multi-Factor Analysis System═══════════════════════════════════════════════════════════════════
TRADEVISION PRO - MULTI-FACTOR ANALYSIS SYSTEM
Created by Zakaria Safri
═══════════════════════════════════════════════════════════════════
A comprehensive technical analysis tool combining multiple factors for 
signal generation, trend analysis, and dynamic risk management visualization. 
Designed for educational purposes to study multi-factor convergence trading 
strategies across all markets and timeframes.
⚠️ IMPORTANT DISCLAIMER:
This indicator is provided for EDUCATIONAL and INFORMATIONAL purposes only.
It does NOT constitute financial advice, investment advice, or trading advice.
Past performance does not guarantee future results. Trading involves 
substantial risk of loss. Always do your own research and consult a 
financial advisor before making trading decisions.
🎯 KEY FEATURES
═══════════════════════════════════════════════════════════════════
✅ MULTI-FACTOR SIGNAL GENERATION
   • Price Volume Trend (PVT) analysis
   • Rate of Change (ROC) momentum confirmation
   • Volume-Weighted Moving Average (VWMA) trend filter
   • Simple Moving Average (SMA) price smoothing
   • Signals only when all factors align
✅ DYNAMIC RISK VISUALIZATION (Educational Only)
   • ATR-based stop loss calculation
   • Risk-reward based take profit levels (1-5 targets)
   • Visual lines and labels showing entry, SL, and TPs
   • Automatically adapts to market volatility
   • ⚠️ VISUAL REFERENCE ONLY - Does not execute trades
✅ SUPPORT & RESISTANCE DETECTION
   • Automatic pivot-based level identification
   • Red dashed lines for resistance zones
   • Green dashed lines for support areas
   • Helps identify key price levels
✅ VWMA TREND BANDS
   • Volume-weighted moving average with standard deviation
   • Color-changing bands (Green = Uptrend, Red = Downtrend)
   • Filled band area for easy visualization
   • Volume-confirmed trend strength
✅ TREND DETECTION SYSTEM
   • Counting-based trend confirmation
   • Three states: Up Trend, Down Trend, Ranging
   • Requires threshold of consecutive bars
   • Independent trend validation
✅ PRICE RANGE VISUALIZATION
   • High/Low range lines showing market structure
   • Filled area highlighting price volatility
   • Helps identify breakout zones
✅ COMPREHENSIVE INFO TABLE
   • Real-time trend status
   • Last signal type (BUY/SELL)
   • Entry price display
   • Stop loss level
   • All active take profit levels
   • Clean, professional layout
✅ OPTIONAL FEATURES
   • Bar coloring by trend direction
   • Customizable alert notifications
   • Toggle visibility for all components
   • Fully configurable parameters
📊 HOW IT WORKS
═══════════════════════════════════════════════════════════════════
SIGNAL METHODOLOGY:
BUY SIGNAL generates when ALL conditions are met:
• Smoothed price > Moving Average (upward price trend)
• PVT > PVT Average (volume supporting uptrend)
• ROC > 0 (positive momentum)
• Close > VWMA (above volume-weighted average)
SELL SIGNAL generates when ALL conditions are met:
• Smoothed price < Moving Average (downward price trend)
• PVT < PVT Average (volume supporting downtrend)
• ROC < 0 (negative momentum)
• Close < VWMA (below volume-weighted average)
This multi-factor approach filters out weak signals and waits for
strong convergence before generating alerts.
RISK CALCULATION:
Stop Loss = Entry ± (ATR × SL Multiplier)
• Uses Average True Range for volatility measurement
• Automatically adjusts to market conditions
Take Profit Levels = Entry ± (Risk Distance × TP Multiplier × Level)
• Risk Distance = |Entry - Stop Loss|
• Creates risk-reward based targets
• Example: TP Multiplier 1.0 = 1:1, 2:2, 3:3 risk-reward
⚠️ NOTE: All risk levels are VISUAL REFERENCES for educational study.
They do not execute trades automatically.
⚙️ SETTINGS GUIDE
═══════════════════════════════════════════════════════════════════
SIGNAL SETTINGS:
• Signal Length (14): Main calculation period for averages
• Smooth Length (8): Price data smoothing period
• PVT Length (14): Price Volume Trend calculation period
• ROC Length (9): Rate of Change momentum period
RISK MANAGEMENT (Visual Only):
• ATR Length (14): Volatility measurement lookback
• SL Multiplier (2.2): Stop loss distance (× ATR)
• TP Multiplier (1.0): Risk-reward ratio per TP level
• TP Levels (1-5): Number of take profit targets to display
• Show TP/SL Lines: Toggle visual reference lines
SUPPORT & RESISTANCE:
• Pivot Lookback (10): Sensitivity for S/R detection
• Show SR: Toggle support/resistance lines
VWMA BANDS:
• VWMA Length (20): Volume-weighted average period
• Show Bands: Toggle band visibility
TREND DETECTION:
• Trend Threshold (5): Consecutive bars required for trend
PRICE LINES:
• Period (20): High/low calculation lookback
• Show: Toggle price range visualization
DISPLAY OPTIONS:
• Signals: Show/hide BUY/SELL labels
• Table: Show/hide information panel
• Color Bars: Enable trend-based bar coloring
ALERTS:
• Enable: Activate alert notifications for signals
💡 USAGE INSTRUCTIONS
═══════════════════════════════════════════════════════════════════
RECOMMENDED APPROACH:
• Works on all timeframes (1m to Monthly)
• Suitable for all markets (Stocks, Forex, Crypto, etc.)
• Best used with additional analysis and confirmation
• Always practice proper risk management
ENTRY STRATEGY:
1. Wait for BUY or SELL signal to appear
2. Check trend table for trend confirmation
3. Verify VWMA band color matches signal direction
4. Look for nearby support/resistance confluence
5. Consider entering on next candle open
6. Use visual SL level for risk management
EXIT STRATEGY:
1. Use TP levels as potential exit zones
2. Consider scaling out at multiple TP levels
3. Exit on opposite signal
4. Adjust stops as trade progresses
5. Account for spread and slippage
TREND TRADING:
• "Up Trend" → Focus on BUY signals
• "Down Trend" → Focus on SELL signals
• "Ranging" → Wait for clear trend or use range strategies
🎨 VISUAL ELEMENTS
═══════════════════════════════════════════════════════════════════
• GREEN VWMA BANDS → Bullish trend indication
• RED VWMA BANDS → Bearish trend indication
• ORANGE DASHED LINE → Entry price reference
• RED SOLID LINE → Stop loss level
• GREEN DOTTED LINES → Take profit targets
• RED DASHED LINES → Resistance levels
• GREEN DASHED LINES → Support levels
• GREY FILLED AREA → Price high/low range
• GREEN BUY LABEL → Long signal
• RED SELL LABEL → Short signal
• BLUE INFO TABLE → Current trade details
• GREEN/RED BARS → Trend direction (optional)
⚠️ IMPORTANT NOTES
═══════════════════════════════════════════════════════════════════
RISK WARNING:
• Trading involves substantial risk of loss
• You can lose more than your initial investment
• Past performance does not guarantee future results
• No indicator is 100% accurate
• Always use proper position sizing
• Never risk more than you can afford to lose
EDUCATIONAL PURPOSE:
• This tool is for learning and research
• Not a complete trading system
• Should be combined with other analysis
• Requires interpretation and context
• Test thoroughly before live use
• Consider consulting a financial advisor
TECHNICAL LIMITATIONS:
• Signals lag price action (all indicators lag)
• False signals occur in choppy markets
• Works better in trending conditions
• Support/resistance levels are approximate
• TP/SL levels are suggestions, not guarantees
📚 METHODOLOGY
═══════════════════════════════════════════════════════════════════
This indicator combines established technical analysis concepts:
• Price Volume Trend (PVT): Volume-weighted price momentum
• Rate of Change (ROC): Momentum measurement
• Volume-Weighted Moving Average (VWMA): Trend identification
• Average True Range (ATR): Volatility measurement (J. Welles Wilder)
• Pivot Points: Support/resistance detection
All methods are based on publicly available technical analysis
principles. No proprietary or "secret" algorithms are used.
⚖️ FULL DISCLAIMER
═══════════════════════════════════════════════════════════════════
LIABILITY:
The creator (Zakaria Safri) assumes NO liability for:
• Trading losses or damages of any kind
• Loss of capital or profits
• Incorrect signal interpretation
• Technical issues, bugs, or errors
• Any consequences of using this tool
USER RESPONSIBILITY:
By using this indicator, you acknowledge that:
• You are solely responsible for your trading decisions
• You understand the substantial risks involved
• You will not hold the creator liable for losses
• You will conduct your own research and analysis
• You may consult a licensed financial professional
• You are using this tool entirely at your own risk
AS-IS PROVISION:
This indicator is provided "AS IS" without warranty of any kind,
express or implied, including but not limited to warranties of
merchantability, fitness for a particular purpose, or non-infringement.
The creator is not a registered investment advisor, financial planner,
or broker-dealer. This tool is not approved or endorsed by any
financial authority.
📞 ABOUT THE CREATOR
═══════════════════════════════════════════════════════════════════
Created by: Zakaria Safri
Specialization: Technical analysis indicator development
Focus: Multi-factor analysis, risk visualization, trend detection
This is an educational tool designed to demonstrate technical
analysis concepts and multi-factor signal generation methods.
📋 VERSION INFO
═══════════════════════════════════════════════════════════════════
Version: 1.0
Platform: TradingView Pine Script v5
License: Mozilla Public License 2.0
Creator: Zakaria Safri
Year: 2024
═══════════════════════════════════════════════════════════════════
Study Carefully, Trade Wisely, Manage Risk Properly
TradeVision Pro - Educational Trading Tool
Created by Zakaria Safri
═══════════════════════════════════════════════════════════════════






















