OpenAI Signal Generator - Enhanced Accuracy# AI-Powered Trading Signal Generator Guide
## Overview
This is an advanced trading signal generator that combines multiple technical indicators using AI-enhanced logic to generate high-accuracy trading signals. The indicator uses a sophisticated combination of RSI, MACD, Bollinger Bands, EMAs, ADX, and volume analysis to provide reliable buy/sell signals with comprehensive market analysis.
## Key Features
### 1. Multi-Indicator Analysis
- **RSI (Relative Strength Index)**
  - Length: 14 periods (default)
  - Overbought: 70 (default)
  - Oversold: 30 (default)
  - Used for identifying overbought/oversold conditions
- **MACD (Moving Average Convergence Divergence)**
  - Fast Length: 12 (default)
  - Slow Length: 26 (default)
  - Signal Length: 9 (default)
  - Identifies trend direction and momentum
- **Bollinger Bands**
  - Length: 20 periods (default)
  - Multiplier: 2.0 (default)
  - Measures volatility and potential reversal points
- **EMAs (Exponential Moving Averages)**
  - Fast EMA: 9 periods (default)
  - Slow EMA: 21 periods (default)
  - Used for trend confirmation
- **ADX (Average Directional Index)**
  - Length: 14 periods (default)
  - Threshold: 25 (default)
  - Measures trend strength
- **Volume Analysis**
  - MA Length: 20 periods (default)
  - Threshold: 1.5x average (default)
  - Confirms signal strength
### 2. Advanced Features
- **Customizable Signal Frequency**
  - Daily
  - Weekly
  - 4-Hour
  - Hourly
  - On Every Close
- **Enhanced Filtering**
  - EMA crossover confirmation
  - ADX trend strength filter
  - Volume confirmation
  - ATR-based volatility filter
- **Comprehensive Alert System**
  - JSON-formatted alerts
  - Detailed technical analysis
  - Multiple timeframe analysis
  - Customizable alert frequency
## How to Use
### 1. Initial Setup
1. Open TradingView and create a new chart
2. Select your preferred trading pair
3. Choose an appropriate timeframe
4. Apply the indicator to your chart
### 2. Configuration
#### Basic Settings
- **Signal Frequency**: Choose how often signals are generated
  - Daily: Signals at the start of each day
  - Weekly: Signals at the start of each week
  - 4-Hour: Signals every 4 hours
  - Hourly: Signals every hour
  - On Every Close: Signals on every candle close
- **Enable Signals**: Toggle signal generation on/off
- **Include Volume**: Toggle volume analysis on/off
#### Technical Parameters
##### RSI Settings
- Adjust `rsi_length` (default: 14)
- Modify `rsi_overbought` (default: 70)
- Modify `rsi_oversold` (default: 30)
##### EMA Settings
- Fast EMA Length (default: 9)
- Slow EMA Length (default: 21)
##### MACD Settings
- Fast Length (default: 12)
- Slow Length (default: 26)
- Signal Length (default: 9)
##### Bollinger Bands
- Length (default: 20)
- Multiplier (default: 2.0)
##### Enhanced Filters
- ADX Length (default: 14)
- ADX Threshold (default: 25)
- Volume MA Length (default: 20)
- Volume Threshold (default: 1.5)
- ATR Length (default: 14)
- ATR Multiplier (default: 1.5)
### 3. Signal Interpretation
#### Buy Signal Requirements
1. RSI crosses above oversold level (30)
2. Price below lower Bollinger Band
3. MACD histogram increasing
4. Fast EMA above Slow EMA
5. ADX above threshold (25)
6. Volume above threshold (if enabled)
7. Market volatility check (if enabled)
#### Sell Signal Requirements
1. RSI crosses below overbought level (70)
2. Price above upper Bollinger Band
3. MACD histogram decreasing
4. Fast EMA below Slow EMA
5. ADX above threshold (25)
6. Volume above threshold (if enabled)
7. Market volatility check (if enabled)
### 4. Visual Indicators
#### Chart Elements
- **Moving Averages**
  - SMA (Blue line)
  - Fast EMA (Yellow line)
  - Slow EMA (Purple line)
- **Bollinger Bands**
  - Upper Band (Green line)
  - Middle Band (Orange line)
  - Lower Band (Green line)
- **Signal Markers**
  - Buy Signals: Green triangles below bars
  - Sell Signals: Red triangles above bars
- **Background Colors**
  - Light green: Buy signal period
  - Light red: Sell signal period
### 5. Alert System
#### Alert Types
1. **Signal Alerts**
   - Generated when buy/sell conditions are met
   - Includes comprehensive technical analysis
   - JSON-formatted for easy integration
2. **Frequency-Based Alerts**
   - Daily/Weekly/4-Hour/Hourly/Every Close
   - Includes current market conditions
   - Technical indicator values
#### Alert Message Format
```json
{
  "symbol": "TICKER",
  "side": "BUY/SELL/NONE",
  "rsi": "value",
  "macd": "value",
  "signal": "value",
  "adx": "value",
  "bb_upper": "value",
  "bb_middle": "value",
  "bb_lower": "value",
  "ema_fast": "value",
  "ema_slow": "value",
  "volume": "value",
  "vol_ma": "value",
  "atr": "value",
  "leverage": 10,
  "stop_loss_percent": 2,
  "take_profit_percent": 5
}
```
## Best Practices
### 1. Signal Confirmation
- Wait for multiple confirmations
- Consider market conditions
- Check volume confirmation
- Verify trend strength with ADX
### 2. Risk Management
- Use appropriate position sizing
- Implement stop losses (default 2%)
- Set take profit levels (default 5%)
- Monitor market volatility
### 3. Optimization
- Adjust parameters based on:
  - Trading pair volatility
  - Market conditions
  - Timeframe
  - Trading style
### 4. Common Mistakes to Avoid
1. Trading without volume confirmation
2. Ignoring ADX trend strength
3. Trading against the trend
4. Not considering market volatility
5. Overtrading on weak signals
## Performance Monitoring
Regularly review:
1. Signal accuracy
2. Win rate
3. Average profit per trade
4. False signal frequency
5. Performance in different market conditions
## Disclaimer
This indicator is for educational purposes only. Past performance is not indicative of future results. Always use proper risk management and trade responsibly. Trading involves significant risk of loss and is not suitable for all investors.
Cerca negli script per "美联储9月降息25个基点"
Bear Market Probability Model# Bear Market Probability Model: A Multi-Factor Risk Assessment Framework
The Bear Market Probability Model represents a comprehensive quantitative framework for assessing systemic market risk through the integration of 13 distinct risk factors across four analytical categories: macroeconomic indicators, technical analysis factors, market sentiment measures, and market breadth metrics. This indicator synthesizes established financial research methodologies to provide real-time probabilistic assessments of impending bear market conditions, offering institutional-grade risk management capabilities to retail and professional traders alike.
## Theoretical Foundation
### Historical Context of Bear Market Prediction
Bear market prediction has been a central focus of financial research since the seminal work of Dow (1901) and the subsequent development of technical analysis theory. The challenge of predicting market downturns gained renewed academic attention following the market crashes of 1929, 1987, 2000, and 2008, leading to the development of sophisticated multi-factor models.
Fama and French (1989) demonstrated that certain financial variables possess predictive power for stock returns, particularly during market stress periods. Their three-factor model laid the groundwork for multi-dimensional risk assessment, which this indicator extends through the incorporation of real-time market microstructure data.
### Methodological Framework
The model employs a weighted composite scoring methodology based on the theoretical framework established by Campbell and Shiller (1998) for market valuation assessment, extended through the incorporation of high-frequency sentiment and technical indicators as proposed by Baker and Wurgler (2006) in their seminal work on investor sentiment.
The mathematical foundation follows the general form:
Bear Market Probability = Σ(Wi × Ci) / ΣWi × 100
Where:
- Wi = Category weight (i = 1,2,3,4)
- Ci = Normalized category score
- Categories: Macroeconomic, Technical, Sentiment, Breadth
## Component Analysis
### 1. Macroeconomic Risk Factors
#### Yield Curve Analysis
The inclusion of yield curve inversion as a primary predictor follows extensive research by Estrella and Mishkin (1998), who demonstrated that the term spread between 3-month and 10-year Treasury securities has historically preceded all major recessions since 1969. The model incorporates both the 2Y-10Y and 3M-10Y spreads to capture different aspects of monetary policy expectations.
Implementation:
- 2Y-10Y Spread: Captures market expectations of monetary policy trajectory
- 3M-10Y Spread: Traditional recession predictor with 12-18 month lead time
Scientific Basis: Harvey (1988) and subsequent research by Ang, Piazzesi, and Wei (2006) established the theoretical foundation linking yield curve inversions to economic contractions through the expectations hypothesis of the term structure.
#### Credit Risk Premium Assessment
High-yield credit spreads serve as a real-time gauge of systemic risk, following the methodology established by Gilchrist and Zakrajšek (2012) in their excess bond premium research. The model incorporates the ICE BofA High Yield Master II Option-Adjusted Spread as a proxy for credit market stress.
Threshold Calibration:
- Normal conditions: < 350 basis points
- Elevated risk: 350-500 basis points  
- Severe stress: > 500 basis points
#### Currency and Commodity Stress Indicators
The US Dollar Index (DXY) momentum serves as a risk-off indicator, while the Gold-to-Oil ratio captures commodity market stress dynamics. This approach follows the methodology of Akram (2009) and Beckmann, Berger, and Czudaj (2015) in analyzing commodity-currency relationships during market stress.
### 2. Technical Analysis Factors
#### Multi-Timeframe Moving Average Analysis
The technical component incorporates the well-established moving average convergence methodology, drawing from the work of Brock, Lakonishok, and LeBaron (1992), who provided empirical evidence for the profitability of technical trading rules.
Implementation:
- Price relative to 50-day and 200-day simple moving averages
- Moving average convergence/divergence analysis
- Multi-timeframe MACD assessment (daily and weekly)
#### Momentum and Volatility Analysis
The model integrates Relative Strength Index (RSI) analysis following Wilder's (1978) original methodology, combined with maximum drawdown analysis based on the work of Magdon-Ismail and Atiya (2004) on optimal drawdown measurement.
### 3. Market Sentiment Factors
#### Volatility Index Analysis  
The VIX component follows the established research of Whaley (2009) and subsequent work by Bekaert and Hoerova (2014) on VIX as a predictor of market stress. The model incorporates both absolute VIX levels and relative VIX spikes compared to the 20-day moving average.
Calibration:
- Low volatility: VIX < 20
- Elevated concern: VIX 20-25
- High fear: VIX > 25
- Panic conditions: VIX > 30
#### Put-Call Ratio Analysis
Options flow analysis through put-call ratios provides insight into sophisticated investor positioning, following the methodology established by Pan and Poteshman (2006) in their analysis of informed trading in options markets.
### 4. Market Breadth Factors
#### Advance-Decline Analysis
Market breadth assessment follows the classic work of Fosback (1976) and subsequent research by Brown and Cliff (2004) on market breadth as a predictor of future returns.
Components:
- Daily advance-decline ratio
- Advance-decline line momentum
- McClellan Oscillator (Ema19 - Ema39 of A-D difference)
#### New Highs-New Lows Analysis
The new highs-new lows ratio serves as a market leadership indicator, based on the research of Zweig (1986) and validated in academic literature by Zarowin (1990).
## Dynamic Threshold Methodology
The model incorporates adaptive thresholds based on rolling volatility and trend analysis, following the methodology established by Pagan and Sossounov (2003) for business cycle dating. This approach allows the model to adjust sensitivity based on prevailing market conditions.
Dynamic Threshold Calculation:
- Warning Level: Base threshold ± (Volatility × 1.0)
- Danger Level: Base threshold ± (Volatility × 1.5)
- Bounds: ±10-20 points from base threshold
## Professional Implementation
### Institutional Usage Patterns
Professional risk managers typically employ multi-factor bear market models in several contexts:
#### 1. Portfolio Risk Management
- Tactical Asset Allocation: Reducing equity exposure when probability exceeds 60-70%
- Hedging Strategies: Implementing protective puts or VIX calls when warning thresholds are breached
- Sector Rotation: Shifting from growth to defensive sectors during elevated risk periods
#### 2. Risk Budgeting
- Value-at-Risk Adjustment: Incorporating bear market probability into VaR calculations
- Stress Testing: Using probability levels to calibrate stress test scenarios
- Capital Requirements: Adjusting regulatory capital based on systemic risk assessment
#### 3. Client Communication
- Risk Reporting: Quantifying market risk for client presentations
- Investment Committee Decisions: Providing objective risk metrics for strategic decisions
- Performance Attribution: Explaining defensive positioning during market stress
### Implementation Framework
Professional traders typically implement such models through:
#### Signal Hierarchy:
1. Probability < 30%: Normal risk positioning
2. Probability 30-50%: Increased hedging, reduced leverage
3. Probability 50-70%: Defensive positioning, cash building
4. Probability > 70%: Maximum defensive posture, short exposure consideration
#### Risk Management Integration:
- Position Sizing: Inverse relationship between probability and position size
- Stop-Loss Adjustment: Tighter stops during elevated risk periods
- Correlation Monitoring: Increased attention to cross-asset correlations
## Strengths and Advantages
### 1. Comprehensive Coverage
The model's primary strength lies in its multi-dimensional approach, avoiding the single-factor bias that has historically plagued market timing models. By incorporating macroeconomic, technical, sentiment, and breadth factors, the model provides robust risk assessment across different market regimes.
### 2. Dynamic Adaptability
The adaptive threshold mechanism allows the model to adjust sensitivity based on prevailing volatility conditions, reducing false signals during low-volatility periods and maintaining sensitivity during high-volatility regimes.
### 3. Real-Time Processing
Unlike traditional academic models that rely on monthly or quarterly data, this indicator processes daily market data, providing timely risk assessment for active portfolio management.
### 4. Transparency and Interpretability
The component-based structure allows users to understand which factors are driving risk assessment, enabling informed decision-making about model signals.
### 5. Historical Validation
Each component has been validated in academic literature, providing theoretical foundation for the model's predictive power.
## Limitations and Weaknesses
### 1. Data Dependencies
The model's effectiveness depends heavily on the availability and quality of real-time economic data. Federal Reserve Economic Data (FRED) updates may have lags that could impact model responsiveness during rapidly evolving market conditions.
### 2. Regime Change Sensitivity
Like most quantitative models, the indicator may struggle during unprecedented market conditions or structural regime changes where historical relationships break down (Taleb, 2007).
### 3. False Signal Risk
Multi-factor models inherently face the challenge of balancing sensitivity with specificity. The model may generate false positive signals during normal market volatility periods.
### 4. Currency and Geographic Bias
The model focuses primarily on US market indicators, potentially limiting its effectiveness for global portfolio management or non-USD denominated assets.
### 5. Correlation Breakdown
During extreme market stress, correlations between risk factors may increase dramatically, reducing the model's diversification benefits (Forbes and Rigobon, 2002).
## References
Akram, Q. F. (2009). Commodity prices, interest rates and the dollar. Energy Economics, 31(6), 838-851.
Ang, A., Piazzesi, M., & Wei, M. (2006). What does the yield curve tell us about GDP growth? Journal of Econometrics, 131(1-2), 359-403.
Baker, M., & Wurgler, J. (2006). Investor sentiment and the cross‐section of stock returns. The Journal of Finance, 61(4), 1645-1680.
Baker, S. R., Bloom, N., & Davis, S. J. (2016). Measuring economic policy uncertainty. The Quarterly Journal of Economics, 131(4), 1593-1636.
Barber, B. M., & Odean, T. (2001). Boys will be boys: Gender, overconfidence, and common stock investment. The Quarterly Journal of Economics, 116(1), 261-292.
Beckmann, J., Berger, T., & Czudaj, R. (2015). Does gold act as a hedge or a safe haven for stocks? A smooth transition approach. Economic Modelling, 48, 16-24.
Bekaert, G., & Hoerova, M. (2014). The VIX, the variance premium and stock market volatility. Journal of Econometrics, 183(2), 181-192.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. The Journal of Finance, 47(5), 1731-1764.
Brown, G. W., & Cliff, M. T. (2004). Investor sentiment and the near-term stock market. Journal of Empirical Finance, 11(1), 1-27.
Campbell, J. Y., & Shiller, R. J. (1998). Valuation ratios and the long-run stock market outlook. The Journal of Portfolio Management, 24(2), 11-26.
Dow, C. H. (1901). Scientific stock speculation. The Magazine of Wall Street.
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. (1989). Business conditions and expected returns on stocks and bonds. Journal of Financial Economics, 25(1), 23-49.
Forbes, K. J., & Rigobon, R. (2002). No contagion, only interdependence: measuring stock market comovements. The Journal of Finance, 57(5), 2223-2261.
Fosback, N. G. (1976). Stock market logic: A sophisticated approach to profits on Wall Street. The Institute for Econometric Research.
Gilchrist, S., & Zakrajšek, E. (2012). Credit spreads and business cycle fluctuations. American Economic Review, 102(4), 1692-1720.
Harvey, C. R. (1988). The real term structure and consumption growth. Journal of Financial Economics, 22(2), 305-333.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. Econometrica, 47(2), 263-291.
Magdon-Ismail, M., & Atiya, A. F. (2004). Maximum drawdown. Risk, 17(10), 99-102.
Nickerson, R. S. (1998). Confirmation bias: A ubiquitous phenomenon in many guises. Review of General Psychology, 2(2), 175-220.
Pagan, A. R., & Sossounov, K. A. (2003). A simple framework for analysing bull and bear markets. Journal of Applied Econometrics, 18(1), 23-46.
Pan, J., & Poteshman, A. M. (2006). The information in option volume for future stock prices. The Review of Financial Studies, 19(3), 871-908.
Taleb, N. N. (2007). The black swan: The impact of the highly improbable. Random House.
Whaley, R. E. (2009). Understanding the VIX. The Journal of Portfolio Management, 35(3), 98-105.
Wilder, J. W. (1978). New concepts in technical trading systems. Trend Research.
Zarowin, P. (1990). Size, seasonality, and stock market overreaction. Journal of Financial and Quantitative Analysis, 25(1), 113-125.
Zweig, M. E. (1986). Winning on Wall Street. Warner Books.
Schaff Trend Cycle (STC)The STC (Schaff Trend Cycle) indicator is a momentum oscillator that combines elements of MACD and stochastic indicators to identify market cycles and potential trend reversals.
Key features of the STC indicator:
 
 Oscillates between 0 and 100, similar to a stochastic oscillator
 Values above 75 generally indicate overbought conditions
 Values below 25 generally indicate oversold conditions
 Signal line crossovers (above 75 or below 25) can suggest potential entry/exit points
 Faster and more responsive than traditional MACD
 Designed to filter out market noise and identify cyclical trends
 
Traders typically use the STC indicator to:
 
 Identify potential trend reversals
 Confirm existing trends
 Generate buy/sell signals when combined with other technical indicators
 Filter out false signals in choppy market conditions
 
This STC implementation includes multiple smoothing options that act as filters:
 
 None: Raw STC values without additional smoothing, which provides the most responsive but potentially noisier signals.
 EMA Smoothing: Applies a 3-period Exponential Moving Average to reduce noise while maintaining reasonable responsiveness (default).
 Sigmoid Smoothing: Transforms the STC values using a sigmoid (S-curve) function, creating more gradual transitions between signals and potentially reducing whipsaw trades.
 Digital (Schmitt Trigger) Smoothing: Creates a binary output (0 or 100) with built-in hysteresis to prevent rapid switching.
The STC indicator uses dynamic color coding to visually represent momentum:
 Green: When the STC value is above its 5-period EMA, indicating positive momentum
 Red: When the STC value is below its 5-period EMA, indicating negative momentum
The neutral zone (25-75) is highlighted with a light gray fill to clearly distinguish between normal and extreme readings.
Alerts:
Bullish Signal Alert:
 The STC has been falling
 It bottoms below the 25 level
 It begins to rise again
This pattern helps confirm potential uptrend starts with higher reliability.
Bearish Signal Alert:
 The STC has been rising
 It peaks above the 75 level
 It begins to decline
This pattern helps identify potential downtrend starts.
ADX + DMI (HMA Version)📝 Description (What This Indicator Does)
🚀 ADX + DMI (HMA Version) is a trend strength oscillator that enhances the traditional ADX by using the Hull Moving Average (HMA) instead of EMA.
✅ This results in a much faster and more responsive trend detection while filtering out choppy price action.
🎯 What This Indicator Does:
1️⃣ Measures Trend Strength – ADX shows when a trend is strong or weak.
2️⃣ Identifies Trend Direction – DI+ (Green) shows bullish momentum, DI- (Red) shows bearish momentum.
3️⃣ Uses Hull Moving Average (HMA) for Faster Signals – Removes lag and reacts faster to trend changes.
4️⃣ Reduces False Signals – Traditional ADX lags behind, but this version reacts quickly to reversals.
5️⃣ Good for Scalping & Day Trading – Especially for BTC 5-min and lower timeframes.
⚙ Indicator Inputs (Customization)
Input Name	Example Value	Purpose
ADX Length	14	Defines the smoothing for the ADX value.
DI Length	        14     Defines how DI+ and DI- are calculated.
HMA Length	24	Hull Moving Average smoothing for ADX & DI+.
Trend Threshold	25	The level above which ADX confirms a strong trend.
📌 You can adjust these settings to optimize for different assets and timeframes.
🎯 Trading Rules & How to Use It
✅ How to Identify a Strong Trend:
When ADX (Blue Line) is above 25→ A strong trend is in play.
When ADX is below 25 → The market is choppy or ranging.
✅ How to Use DI+ and DI- for Trend Direction:
If DI+ (Green) is above DI- (Red), the market is in an uptrend.
If DI- (Red) is above DI+ (Green), the market is in a downtrend.
✅ How to Confirm Entries & Exits:
1️⃣ Enter Long when DI+ crosses above DI- while ADX is rising above 25.
2️⃣ Enter Short when DI- crosses above DI+ while ADX is rising above 25.
3️⃣ Avoid trading when ADX is below 25 – the market is in a choppy range.
This should not be used as a stand alone oscillator. Trading takes skill and is risky. Use at your own risk. 
This is not advise on how to trade, these are just examples of how I use the oscillator. Trade at your own risk.
You can put this on your chart versus the tradingview adx and you can adjust the settings to see the difference. This was optimized for btc on the 5 min chart. You can adjust for your trading strategy.
BTCUSD with adjustable sl,tpThis strategy is designed for swing traders who want to enter long positions on pullbacks after a short-term trend shift, while also allowing immediate short entries when conditions favor downside movement. It combines SMA crossovers, a fixed-percentage retracement entry, and adjustable risk management parameters for optimal trade execution.
Key Features:
✅ Trend Confirmation with SMA Crossover
The 10-period SMA crossing above the 25-period SMA signals a bullish trend shift.
The 10-period SMA crossing below the 25-period SMA signals a bearish trend shift.
Short trades are only taken if the price is below the 150 EMA, ensuring alignment with the broader trend.
📉 Long Pullback Entry Using Fixed Percentage Retracement
Instead of entering immediately on the SMA crossover, the strategy waits for a retracement before going long.
The pullback entry is defined as a percentage retracement from the recent high, allowing for an optimized entry price.
The retracement percentage is fully adjustable in the settings (default: 1%).
A dynamic support level is plotted on the chart to visualize the pullback entry zone.
📊 Short Entry Rules
If the SMA(10) crosses below the SMA(25) and price is below the 150 EMA, a short trade is immediately entered.
Risk Management & Exit Strategy:
🚀 Take Profit (TP) – Fully customizable profit target in points. (Default: 1000 points)
🛑 Stop Loss (SL) – Adjustable stop loss level in points. (Default: 250 points)
🔄 Break-Even (BE) – When price moves in favor by a set number of points, the stop loss is moved to break-even.
📌 Extra Exit Condition for Longs:
If the SMA(10) crosses below SMA(25) while the price is still below the EMA150, the strategy force-exits the long position to avoid reversals.
How to Use This Strategy:
Enable the strategy on your TradingView chart (recommended for stocks, forex, or indices).
Customize the settings – Adjust TP, SL, BE, and pullback percentage for your risk tolerance.
Observe the plotted retracement levels – When the price touches and bounces off the level, a long trade is triggered.
Let the strategy manage the trade – Break-even protection and take-profit logic will automatically execute.
Ideal Market Conditions:
✅ Trending Markets – The strategy works best when price follows strong trends.
✅ Stocks, Indices, or Forex – Can be applied across multiple asset classes.
✅ Medium-Term Holding Period – Suitable for swing trades lasting days to weeks.
O'Neil Earnings StabilityO'Neil Earnings Stability Indicator
This indicator implements William O'Neil's earnings stability analysis, a key factor in identifying high-quality growth stocks. It measures both earnings stability (1-99 scale) and growth rate.
Scale Interpretation:
• 1-25: Highly stable earnings (ideal)
• 26-30: Moderately stable
• >30: More cyclical/less dependable
The stability score is calculated by measuring deviations from the earnings trend line, with lower scores indicating more consistent growth. Combined with the annual growth rate (target ≥25%), this helps identify stocks with both steady and strong earnings growth.
Optimal Criteria:
✓ Stability Score < 25
✓ Annual Growth > 25%
This tool helps filter out stocks with erratic earnings patterns and identify those with proven, sustainable growth records. Green label indicates both criteria are met; red indicates one or both criteria failed."
Would you like me to modify any part of this description or add more details about specific aspects of the calculation?
The key concepts in these calculations:
Stability Score (1-99 scale):
Lower score = more stable
Takes average deviation from mean earnings
Uses logarithmic scaling to emphasize smaller deviations
Multiplies by 20 to get into 1-99 range
Score ≤ 25 meets O'Neil's criteria
Growth Rate:
Year-over-year comparison (current quarter vs same quarter last year)
Calculated as percentage change
Growth ≥ 25% meets O'Neil's criteria
O'Neil's Combined Criteria:
Stability Score should be ≤ 25 (indicating stable earnings)
Growth Rate should be ≥ 25% (indicating strong growth)
Both must be met for ideal conditions
MTF RSI CandlesThis Pine Script indicator is designed to provide a visual representation of Relative Strength Index (RSI) values across multiple timeframes. It enhances traditional candlestick charts by color-coding candles based on RSI levels, offering a clearer picture of overbought, oversold, and sideways market conditions. Additionally, it displays a hoverable table with RSI values for multiple predefined timeframes.
 Key Features 
1. Candle Coloring Based on RSI Levels:
 
 Candles are color-coded based on predefined RSI ranges for easy interpretation of market conditions.
 RSI Levels:
 75-100: Strongest Overbought (Green)
 65-75: Stronger Overbought (Dark Green)
 55-65: Overbought (Teal)
 45-55: Sideways (Gray)
 35-45: Oversold (Light Red)
 25-35: Stronger Oversold (Dark Red)
 0-25: Strongest Oversold (Bright Red)
 
2. Multi-Timeframe RSI Table:
 
 Displays RSI values for the following timeframes:
 1 Min, 2 Min, 3 Min, 4 Min, 5 Min
 10 Min, 15 Min, 30 Min, 1 Hour, 1 Day, 1 Week
 Helps traders identify RSI trends across different time horizons.
 
3. Hoverable RSI Values:
 
 
 Displays the RSI value of any candle when hovering over it, providing additional insights for analysis.
 
 Inputs 
1. RSI Length:
 
 Default: 14
 Determines the calculation period for the RSI indicator.
 
2. RSI Levels:
 
 Configurable thresholds for RSI zones:
 75-100: Strongest Overbought
 65-75: Stronger Overbought
 55-65: Overbought
 45-55: Sideways
 35-45: Oversold
 25-35: Stronger Oversold
 0-25: Strongest Oversold
 
 How It Works: 
1. RSI Calculation:
 
 The RSI is calculated for the current timeframe using the input RSI Length.
 It is also computed for 11 additional predefined timeframes using request.security.
 
2. Candle Coloring:
 
 Candles are colored based on their RSI values and the specified RSI levels.
 
3. Hoverable RSI Values:
 
 Each candle displays its RSI value when hovered over, via a dynamically created label.
 Multi-Timeframe Table:
 
 
 
 A table at the bottom-left of the chart displays RSI values for all predefined timeframes, making it easy to compare trends.
 
 
 Usage: 
1. Trend Identification:
 
 Use candle colors to quickly assess market conditions (overbought, oversold, or sideways).
 
2. Timeframe Analysis:
 
 Compare RSI values across different timeframes to determine long-term and short-term momentum.
 
3. Signal Confirmation:
 
 Combine RSI signals with other indicators or patterns for higher-confidence trades.
 
 Best Practices 
 
 Use this indicator in conjunction with volume analysis, support/resistance levels, or trendline strategies for better results.
 Customize RSI levels and timeframes based on your trading strategy or market conditions.
 Limitations 
 RSI is a lagging indicator and may not always predict immediate market reversals.
 Multi-timeframe analysis can lead to conflicting signals; consider your trading horizon.
 
DNSE VN301!, SMA & EMA Cross StrategyDiscover the tailored Pinescript to trade VN30F1M Future Contracts intraday, the strategy focuses on SMA & EMA crosses to identify potential entry/exit points. The script closes all positions by 14:25 to avoid holding any contracts overnight.
 HNX:VN301!  
 www.tradingview.com 
 Setting & Backtest result: 
1-minute chart, initial capital of VND 100 million, entering 4 contracts per time, backtest result from Jan-2024 to Nov-2024 yielded a return over 40%, executed over 1,000 trades (average of 4 trades/day), winning trades rate ~ 30% with a profit factor of 1.10. 
 The default setting of the script:  
A decent optimization is reached when SMA and EMA periods are set to 60 and 15 respectively while the Long/Short stop-loss level is set to 20 ticks (2 points) from the entry price. 
 Entry & Exit conditions:  
Long signals are generated when ema(15) crosses over sma(60) while Short signals happen when ema(15) crosses under sma(60). Long orders are closed when ema(15) crosses under sma(60) while Short orders are closed when ema(15) crosses over sma(60).
Exit conditions happen when (whichever came first):
 
 Another Long/Short signal is generated
 The Stop-loss level is reached 
 The Cut-off time is reached (14:25 every day)
 
 *Disclaimers:  
Futures Contracts Trading are subjected to a high degree of risk and price movements can fluctuate significantly. This script functions as a reference source and should be used after users have clearly understood how futures trading works, accessed their risk tolerance level, and are knowledgeable of the functioning logic behind the script. 
Users are solely responsible for their investment decisions, and DNSE is not responsible for any potential losses from applying such a strategy to real-life trading activities. Past performance is not indicative/guarantee of future results, kindly reach out to us should you have specific questions about this script.
---------------------------------------------------------------------------------------
Khám phá Pinescript được thiết kế riêng để giao dịch Hợp đồng tương lai VN30F1M trong ngày, chiến lược tập trung vào các đường SMA & EMA cắt nhau để xác định các điểm vào/ra tiềm năng. Chiến lược sẽ đóng tất cả các vị thế trước 14:25 để tránh giữ bất kỳ hợp đồng nào qua đêm.
 Thiết lập & Kết quả backtest: 
Chart 1 phút, vốn ban đầu là 100 triệu đồng, vào 4 hợp đồng mỗi lần, kết quả backtest từ tháng 1/2024 tới tháng 11/2024 mang lại lợi nhuận trên 40%, thực hiện hơn 1.000 giao dịch (trung bình 4 giao dịch/ngày), tỷ lệ giao dịch thắng ~ 30% với hệ số lợi nhuận là 1,10.
 Thiết lập mặc định của chiến lược: 
Đạt được một mức tối ưu ổn khi SMA và EMA periods được đặt lần lượt là 60 và 15 trong khi mức cắt lỗ được đặt thành 20 tick (2 điểm) từ giá vào.
 Điều kiện Mở và Đóng vị thế:  
Tín hiệu Long được tạo ra khi ema(15) cắt trên sma(60) trong khi tín hiệu Short xảy ra khi ema(15) cắt dưới sma(60). Lệnh Long được đóng khi ema(15) cắt dưới sma(60) trong khi lệnh Short được đóng khi ema(15) cắt lên sma(60).
Điều kiện đóng vị thể xảy ra khi (tùy điều kiện nào đến trước):
 
 Một tín hiệu Long/Short khác được tạo ra
 Giá chạm mức cắt lỗ
 Lệnh chưa đóng nhưng tới giờ cut-off (14:25 hàng ngày)
 
 *Tuyên bố miễn trừ trách nhiệm: 
Giao dịch hợp đồng tương lai có mức rủi ro cao và giá có thể dao động đáng kể. Chiến lược này hoạt động như một nguồn tham khảo và nên được sử dụng sau khi người dùng đã hiểu rõ cách thức giao dịch hợp đồng tương lai, đã đánh giá mức độ chấp nhận rủi ro của bản thân và hiểu rõ về logic vận hành của chiến lược này.
Người dùng hoàn toàn chịu trách nhiệm về các quyết định đầu tư của mình và DNSE không chịu trách nhiệm về bất kỳ khoản lỗ tiềm ẩn nào khi áp dụng chiến lược này vào các hoạt động giao dịch thực tế. Hiệu suất trong quá khứ không chỉ ra/cam kết kết quả trong tương lai, vui lòng liên hệ với chúng tôi nếu bạn có thắc mắc cụ thể về chiến lược giao dịch này.
RSI 15/60 and ADX PlotIn this script, the buy and sell criteria are based on the Relative Strength Index (RSI) values calculated for two different timeframes: the 15-minute RSI and the hourly RSI. These timeframes are used together to check signals when certain thresholds are crossed, providing confirmation across both short-term and longer-term momentum.
Buy Criteria:
Condition 1:
Hourly RSI > 60: This means the longer-term momentum shows strength.
15-minute RSI crosses above 60: This shows that the shorter-term momentum is catching up and confirms increasing strength.
Condition 2:
15-minute RSI > 60: This indicates that the short-term trend is already strong.
Hourly RSI crosses above 60: This confirms that the longer-term trend is also gaining strength.
Both conditions aim to capture the moments when the market shows increasing strength across both short and long timeframes, signaling a potential buy opportunity.
Sell Criteria:
Condition 1:
Hourly RSI < 40: This indicates that the longer-term trend is weakening.
15-minute RSI crosses below 40: The short-term momentum is also turning down, confirming the weakening trend.
Condition 2:
15-minute RSI < 40: The short-term trend is already weak.
Hourly RSI crosses below 40: The longer-term trend is now confirming the weakness, indicating a potential sell.
These conditions work to identify when the market is showing weakness in both short-term and long-term timeframes, signaling a potential sell opportunity.
ADX Confirmation :
The Average Directional Index (ADX) is a key tool for measuring the strength of a trend. It can be used alongside the RSI to confirm whether a buy or sell signal is occurring in a strong trend or during market consolidation. Here's how ADX can be integrated:
ADX > 25: This indicates a strong trend. Using this threshold, you can confirm buy or sell signals when there is a strong upward or downward movement in the market.
Buy Example: If a buy signal (RSI > 60) is triggered and the ADX is above 25, this confirms that the market is in a strong uptrend, making the buy signal more reliable.
Sell Example: If a sell signal (RSI < 40) is triggered and the ADX is above 25, it confirms a strong downtrend, validating the sell signal.
ADX < 25: This suggests a weak or non-existent trend. In this case, RSI signals might be less reliable since the market could be moving sideways.
Final Approach:
The RSI criteria help identify potential overbought and oversold conditions in both short and long timeframes.
The ADX confirmation ensures that the signals generated are happening during strong trends, increasing the likelihood of successful trades by filtering out weak or choppy market conditions.
This combination of RSI and ADX can help traders make more informed decisions by ensuring both momentum and trend strength align before entering or exiting trades.
Average Directional Index with MACombining the Average Directional Index (ADX) with a 14-period Exponential Moving Average (EMA) can provide traders with a comprehensive approach to identify both the strength of a trend (through ADX) and the trend's direction (using EMA). Let's break down each component and then discuss how they can be combined:
Average Directional Index (ADX):
The ADX is a technical indicator that measures the strength or momentum of a trend, regardless of its direction. The ADX is derived from two other indicators:
    Positive Directional Index (+DI): Measures the strength of upward price movement.
    Negative Directional Index (-DI): Measures the strength of downward price movement.
14-period Exponential Moving Average (EMA):
The 14-period EMA is a trend-following indicator that gives more weight to recent price data compared to simple moving averages (SMAs). The EMA is calculated by taking the average of the last 14 closing prices, giving more importance to the most recent prices.
Combining ADX and EMA:
When combining ADX with a 14-period EMA:
    ADX as a Filter:
        Traders might use the ADX to filter out trades when the trend's strength is weak (e.g., ADX below 25) to avoid trading in sideways or choppy markets.
    EMA for Trend Direction:
        Traders can use the 14-period EMA to determine the trend direction.
        A price above the 14-period EMA might indicate an uptrend, while a price below the EMA might suggest a downtrend.
Example Strategy:
Here's a simplified trading strategy combining ADX and EMA:
    Trend Identification:
        Buy when the price is above the 14-period EMA and the ADX indicates a strong uptrend (e.g., ADX > 25).
        Sell or go short when the price is below the 14-period EMA and the ADX indicates a strong downtrend (e.g., ADX > 25).
    Avoid Choppy Markets:
        Avoid trading when the ADX is below a certain threshold (e.g., ADX < 25) to filter out sideways or range-bound markets.
Combining ADX and a 14-period EMA can provide traders with a balanced approach to identify both the strength and direction of a trend. However, it's essential to remember that no indicator or strategy can guarantee profits, and it's crucial to use risk management techniques and other tools to make informed trading decisions. Consider back testing this strategy on historical data and adjusting the parameters based on their trading style and risk tolerance.
Statistics • Chi Square • P-value • SignificanceThe  Statistics • Chi Square • P-value • Significance  publication aims to provide a tool for combining different conditions and checking whether the outcome is significant using the Chi-Square Test and P-value.
🔶  USAGE 
The basic principle is to compare two or more groups and check the results of a query test, such as asking men and women whether they want to see a romantic or non-romantic movie.
 
–––––––––––––––––––––––––––––––––––––––––––––
|       | ROMANTIC | NON-ROMANTIC | ⬅︎ MOVIE |
–––––––––––––––––––––––––––––––––––––––––––––
|  MEN  |     2    |       8      |    10    |
–––––––––––––––––––––––––––––––––––––––––––––
| WOMEN |     7    |       3      |    10    |
–––––––––––––––––––––––––––––––––––––––––––––
|⬆︎ SEX |    10    |      10      |    20    |
–––––––––––––––––––––––––––––––––––––––––––––
 
We calculate the Chi-Square Formula, which is:
 Χ² = Σ ( (Observed Value − Expected Value)² / Expected Value )
 
In this publication, this is:
 
    chiSquare = 0.
    for i = 0 to rows -1
        for j = 0 to colums -1
            observedValue = aBin.get(i).aFloat.get(j)
            expectedValue = math.max(1e-12, aBin.get(i).aFloat.get(colums) * aBin.get(rows).aFloat.get(j) / sumT) //Division by 0 protection
            chiSquare += math.pow(observedValue - expectedValue, 2) / expectedValue
 
Together with the 'Degree of Freedom', which is  (rows − 1) × (columns − 1) , the P-value can be calculated.
In this case it is  P-value: 0.02462 
A P-value lower than 0.05 is considered to be significant. Statistically, women tend to choose a romantic movie more, while men prefer a non-romantic one.
Users have the option to choose a P-value, calculated from a standard table or through a  math.ucla.edu  - Javascript-based function (see references below).
Note that the population (10 men + 10 women = 20) is small, something to consider.
Either way, this principle is applied in the script, where conditions can be chosen like rsi, close, high, ...
🔹  CONDITION 
Conditions are added to the left column ('CONDITION')
For example, previous rsi values (rsi ) between 0-100, divided in separate groups
  
🔹  CLOSE 
Then, the movement of the last close is evaluated
 
 UP when close is higher then previous close (close )
 DOWN when close is lower then previous close 
 EQUAL when close is equal then previous close 
 
It is also possible to use only 2 columns by adding EQUAL to UP or DOWN
 
 UP 
 DOWN/EQUAL 
 
or
 
 UP/EQUAL
 DOWN 
 
In other words, when previous  rsi  value was between 80 and 90, this resulted in:
 
 19 times a current close higher than previous close
 14 times a current close lower than previous close
  0 times a current close equal than previous close
 
However, the  P-value  tells us it is not statistical significant.
 NOTE:  Always keep in mind that past behaviour gives no certainty about future behaviour.
A vertical line is drawn at the beginning of the chosen population (max 4990)
  
Here, the results seem significant.
🔹  GROUPS 
It is important to ensure that the groups are formed correctly. All possibilities should be present, and conditions should only be part of 1 group.
  
In the example above, the two top situations are acceptable; close  against close  can only be higher, lower or equal.
The two examples at the bottom, however, are very poorly constructed. 
Several conditions can be placed in more than 1 group, and some conditions are not integrated into a group. Even if the results are significant, they are useless because of the group formation.
A population count is added as an aid to spot errors in group formation.
  
In this example, there is a discrepancy between the population and total count due to the absence of a condition. 
  
The results when rsi was between 5-25 are not included, resulting in unreliable results. 
🔹  PRACTICAL EXAMPLES 
In this example, we have specific groups where the condition only applies to that group.
For example, the condition  rsi > 55 and rsi <= 65  isn't true in another group.
Also, every possible rsi value (0 - 100) is present in 1 of the groups. 
 rsi > 15 and rsi <= 25  28 times UP, 19 times DOWN and 2 times EQUAL. P-value: 0.01171
When looking in detail and examining the area 15-25 RSI, we see this:
  
The population is now not representative (only checking for RSI between 15-25; all other RSI values are not included), so we can ignore the P-value in this case. It is merely to check in detail. In this case, the RSI values 23 and 24 seem promising.
 NOTE:  We should check what the close price did without any condition.
If, for example, the close price had risen 100 times out of 100, this would make things very relative.
In this case (at least two conditions need to be present), we set 1 condition at 'always true' and another at 'always false' so we'll get only the close values without any condition:
  
Changing the population or the conditions will change the P-value.
  
  
  
In the following example, the outcome is evaluated when:
 
 close value from 1 bar back is higher than the close value from 2 bars back
 close value from 1 bar back is lower/equal than the close value from 2 bars back
 
  
Or:
 
 close value from 1 bar back is higher than the close value from 2 bars back
 close value from 1 bar back is equal   than the close value from 2 bars back
 close value from 1 bar back is lower   than the close value from 2 bars back
 
  
In both examples, all possibilities of close  against close  are included in the calculations. close  can only by higher, equal or lower than close 
Both examples have the results without a condition included (5 = 5 and 5 < 5) so one can compare the direction of current close.
🔶  NOTES 
• Always keep in mind that:
 
  Past behaviour gives no certainty about future behaviour.
 Everything depends on time, cycles, events, fundamentals, technicals, ...
 
• This test only works for categorical data (data in categories), such as Gender {Men, Women} or color {Red, Yellow, Green, Blue} etc., but not numerical data such as height or weight. One might argue that such tests shouldn't use rsi, close, ... values.
• Consider what you're measuring 
For example rsi of the current bar will always lead to a close higher than the previous close, since this is inherent to the rsi calculations.
  
• Be careful; often, there are  na -values at the beginning of the series, which are not included in the calculations!
  
• Always keep in mind considering what the close price did without any condition
• The numbers must be large enough. Each entry must be five or more. In other words, it is vital to make the 'population' large enough.
• The code can be developed further, for example, by splitting UP, DOWN in close UP 1-2%, close UP 2-3%, close UP 3-4%, ...
• rsi can be supplemented with stochRSI, MFI, sma, ema, ...
🔶  SETTINGS 
🔹  Population 
• Choose the population size; in other words, how many bars you want to go back to. If fewer bars are available than set, this will be automatically adjusted.
🔹  Inputs 
At least two conditions need to be chosen.
  
• Users can add up to 11 conditions, where each condition can contain two different conditions.
🔹  RSI 
• Length
🔹  Levels 
• Set the used levels as desired.
🔹  Levels 
• P-value: P-value retrieved using a standard table method or a function.
• Used function, derived from  Chi-Square Distribution Function; JavaScript 
 
LogGamma(Z) =>
	S = 1 
      + 76.18009173   / Z 
      - 86.50532033   / (Z+1)
      + 24.01409822   / (Z+2)
      - 1.231739516   / (Z+3)
      + 0.00120858003 / (Z+4)
      - 0.00000536382 / (Z+5)
	(Z-.5) * math.log(Z+4.5) - (Z+4.5) + math.log(S * 2.50662827465)
Gcf(float X, A) =>        // Good for X > A +1
	A0=0., B0=1., A1=1., B1=X, AOLD=0., N=0
	while (math.abs((A1-AOLD)/A1) > .00001) 
		AOLD := A1
		N    += 1
		A0   := A1+(N-A)*A0
		B0   := B1+(N-A)*B0
		A1   := X*A0+N*A1
		B1   := X*B0+N*B1
		A0   := A0/B1
		B0   := B0/B1
		A1   := A1/B1
		B1   := 1
	Prob      = math.exp(A * math.log(X) - X - LogGamma(A)) * A1
	1 - Prob
Gser(X, A) =>        // Good for X < A +1
	T9 = 1. / A
	G  = T9
	I  = 1
	while (T9 > G* 0.00001) 
		T9 := T9 * X / (A + I)
		G  := G + T9
		I  += 1
	
	G *= math.exp(A * math.log(X) - X - LogGamma(A))
Gammacdf(x, a) =>
	GI = 0.
	if (x<=0) 
		GI := 0
	else if (x
    Chisqcdf  = Gammacdf(Z/2, DF/2)
	Chisqcdf := math.round(Chisqcdf * 100000) / 100000
    pValue    = 1 - Chisqcdf
 
🔶  REFERENCES 
 
 mathsisfun.com, Chi-Square Test 
 Chi-Square Distribution Function 
 
Incomplete Session Candle - Incomplete Timeframe Candle Marker The "Incomplete Session Candle - Incomplete Timeframe Candle Marker" is an advanced tool tailored for technical analysts who understand the importance of accurate timeframes in their charting. While the indicator is not limited to the Indian market, its genesis is rooted in the nuances of trading sessions like those in India, which span 375 minutes from 9:15 AM to 3:30 PM.
 Key Features: 
 
 Detects if the current timeframe is intraday (minutes or hours).
 Calculates the expected duration of the candle for the chosen timeframe.
 Highlights candles that don't achieve their expected session duration by placing a cross shape above the bar.
 Compatible across various intraday timeframes, aiding traders in spotting discrepancies promptly.
 
 Why We Made This: Not Just for India: 
While we looked at the Indian market, this indicator works everywhere. Regular timeframes like 30 minutes, 1 hour, and 2 hours often end with incomplete candles, especially at the end of the trading day. For example:
 
 A 30-minute timeframe makes 13 candles, but the last one is only 15 minutes long.
 A 1-hour timeframe shows 7 candles, but the last one is just the last 15 minutes.
 
By switching to different timeframes like 25 minutes, 75 minutes, and 125 minutes, you get more complete information for better trading decisions. Learn more about this in our article: "Power of 25, 75, and 125-Minute Timeframes in the Indian Market", recognized by Trading View's Editors' Pick.
  
 Benefits: 
The indicator extends its benefits even to users without access to certain timeframes. It accommodates traders using a 1-hour timeframe (pertaining to Indian traders). By employing this indicator, traders consistently remain mindful of incomplete candles within their chosen timeframe
For those who utilize concepts like RBR, RBD, DBR, and DBD, this indicator is paramount. An incomplete candle can skew analysis, leading to potential misinterpretations of base or leg candles.
 Final thoughts: 
In markets like the Indian stock market, adopting such a tool is not just beneficial, but necessary. Whether you have access to unconventional timeframes or are using traditional ones, recognizing and accounting for the limitations of incomplete candles is critical & it's important to know if your candles fit the timeframe properly. This indicator gives you a better view of the market, which helps you make smarter trades.
Lastly, Thank you for your support! Your likes & comments. If you want to give any feedback then you can give in comment section.
 Let's conquer the markets together!
Any Oscillator Underlay [TTF]We are proud to release a new indicator that has been a while in the making - the  Any Oscillator Underlay (AOU) !
 Note:   There is a lot to discuss regarding this indicator, including its intent and some of how it operates, so please be sure to read this entire description before using this indicator to help ensure you understand both the intent and some limitations with this tool.
Our intent for building this indicator was to accomplish the following:
 
  Combine all of the oscillators that we like to use into a single indicator
  Take up a bit less screen space for the underlay indicators for strategies that utilize multiple oscillators
  Provide a tool for newer traders to be able to leverage multiple oscillators in a single indicator
 
 Features: 
 
  Includes 8 separate, fully-functional indicators combined into one
  Ability to easily enable/disable and configure each included indicator independently
  Clearly named plots to support user customization of color and styling, as well as manual creation of alerts
  Ability to customize sub-indicator title position and color
  Ability to customize sub-indicator divider lines style and color
 
Indicators that are included in this initial release:
 
  TSI
  2x RSIs (dubbed the  Twin RSI )
  Stochastic RSI
  Stochastic
  Ultimate Oscillator
  Awesome Oscillator
  MACD
   Outback RSI  (Color-coding only)
 
 Quick note on OB/OS: 
Before we get into covering each included indicator, we first need to cover a core concept for how we're defining OB and OS levels.  To help illustrate this, we will use the  TSI  as an example.
The TSI by default has a mid-point of 0 and a range of -100 to 100.  As a result, a common practice is to place lines on the -30 and +30 levels to represent OS and OB zones, respectively.  Most people tend to view these levels as distance from the edges/outer bounds or as absolute levels, but we feel a more way to frame the OB/OS concept is to instead define it as distance ("offset") from the mid-line.  In keeping with the -30 and +30 levels in our example, the offset in this case would be "30".  
Taking this a step further, let's say we decided we wanted an offset of 25.  Since the mid-point is 0, we'd then calculate the OB level as 0 + 25 (+25), and the OS level as 0 - 25 (-25).
Now that we've covered the concept of how we approach defining OB and OS levels (based on offset/distance from the mid-line), and since we did apply some transformations, rescaling, and/or repositioning to all of the indicators noted above, we are going to discuss each component indicator to detail both how it was modified from the original to fit the stacked-indicator model, as well as the various major components that the indicator contains.
 TSI: 
  
This indicator contains the following major elements:
 
  TSI and TSI Signal Line
  Color-coded fill for the TSI/TSI Signal lines
  Moving Average for the TSI
  TSI Histogram
  Mid-line and OB/OS lines 
 
Default TSI fill color coding:
 
   Green : TSI is above the signal line
   Red : TSI is below the signal line
 
Note:  The TSI traditionally has a range of -100 to +100 with a mid-point of 0 (range of 200).  To fit into our stacking model, we first shrunk the range to 100 (-50 to +50 - cut it in half), then repositioned it to have a mid-point of 50.  Since this is the "bottom" of our indicator-stack, no additional repositioning is necessary.
 Twin  RSI: 
  
This indicator contains the following major elements:
 
  Fast RSI (useful if you want to leverage 2x RSIs as it makes it easier to see the overlaps and crosses - can be disabled if desired)
  Slow RSI (primary RSI)
  Color-coded fill for the Fast/Slow RSI lines (if Fast RSI is enabled and configured)
  Moving Average for the Slow RSI
  Mid-line and OB/OS lines 
 
Default Twin RSI fill color coding:
 
   Dark Red : Fast RSI below Slow RSI and Slow RSI below Slow RSI MA
   Light Red : Fast RSI below Slow RSI and Slow RSI above Slow RSI MA
   Dark Green : Fast RSI above Slow RSI and Slow RSI below Slow RSI MA
   Light Green : Fast RSI above Slow RSI and Slow RSI above Slow RSI MA
 
Note:  The RSI naturally has a range of 0 to 100 with a mid-point of 50, so no rescaling or transformation is done on this indicator.  The only manipulation done is to properly position it in the indicator-stack based on which other indicators are also enabled.
 Stochastic  and  Stochastic RSI: 
  
  
These indicators contain the following major elements:
 
  Configurable lengths for the RSI (for the Stochastic RSI only), K, and D values
  Configurable base price source
  Mid-line and OB/OS lines 
 
Note:  The Stochastic and Stochastic RSI both have a normal range of 0 to 100 with a mid-point of 50, so no rescaling or transformations are done on either of these indicators.  The only manipulation done is to properly position it in the indicator-stack based on which other indicators are also enabled.
 Ultimate Oscillator (UO): 
  
This indicator contains the following major elements:
 
  Configurable lengths for the Fast, Middle, and Slow BP/TR components
  Mid-line and OB/OS lines
  Moving Average for the UO
  Color-coded fill for the UO/UO MA lines (if UO MA is enabled and configured)
 
Default UO fill color coding:
 
   Green : UO is above the moving average line
   Red : UO is below the moving average line
 
Note:  The UO naturally has a range of 0 to 100 with a mid-point of 50, so no rescaling or transformation is done on this indicator.  The only manipulation done is to properly position it in the indicator-stack based on which other indicators are also enabled.
 Awesome Oscillator (AO): 
  
This indicator contains the following major elements:
 
  Configurable lengths for the Fast and Slow moving averages used in the AO calculation
  Configurable price source for the moving averages used in the AO calculation
  Mid-line
  Option to display the AO as a line or pseudo-histogram
  Moving Average for the AO
  Color-coded fill for the AO/AO MA lines (if AO MA is enabled and configured)
 
Default AO fill color coding (Note: Fill was disabled in the image above to improve clarity):
 
   Green : AO is above the moving average line
   Red : AO is below the moving average line
 
Note: The AO is technically has an infinite (unbound) range - -∞ to ∞ - and the effective range is bound to the underlying security price (e.g. BTC will have a wider range than SP500, and SP500 will have a wider range than EUR/USD).  We employed some special techniques to rescale this indicator into our desired range of 100 (-50 to 50), and then repositioned it to have a midpoint of 50 (range of 0 to 100) to meet the constraints of our stacking model.  We then do one final repositioning to place it in the correct position the indicator-stack based on which other indicators are also enabled.  For more details on how we accomplished this, read our section  "Binding Infinity"  below.
 MACD: 
  
This indicator contains the following major elements:
 
  Configurable lengths for the Fast and Slow moving averages used in the MACD calculation
  Configurable price source for the moving averages used in the MACD calculation
  Configurable length and calculation method for the MACD Signal Line calculation
  Mid-line
 
Note: Like the AO, the MACD also technically has an infinite (unbound) range.  We employed the same principles here as we did with the AO to rescale and reposition this indicator as well.  For more details on how we accomplished this, read our section  "Binding Infinity"  below.
 Outback RSI (ORSI): 
This is a stripped-down version of the Outback RSI indicator (linked above) that only includes the color-coding background (suffice it to say that it was not technically feasible to attempt to rescale the other components in a way that could consistently be clearly seen on-chart).  As this component is a bit of a niche/special-purpose sub-indicator, it is disabled by default, and we suggest it remain disabled unless you have some pre-defined strategy that leverages the color-coding element of the Outback RSI that you wish to use.
 Binding Infinity - How We Incorporated the AO and MACD  (Warning - Math Talk Ahead!) 
Note: This applies only to the AO and MACD at time of original publication.  If any other indicators are added in the future that also fall into the category of "binding an infinite-range oscillator", we will make that clear in the release notes when that new addition is published.
To help set the stage for this discussion, it's important to note that the broader challenge of "equalizing inputs" is nothing new.  In fact, it's a key element in many of the most popular fields of data science, such as AI and Machine Learning.  They need to take a diverse set of inputs with a wide variety of ranges and seemingly-random inputs (referred to as "features"), and build a mathematical or computational model in order to work.  But, when the raw inputs can vary significantly from one another, there is an inherent need to do some pre-processing to those inputs so that one doesn't overwhelm another simply due to the difference in raw values between them.  This is where  feature scaling  comes into play.
With this in mind, we implemented 2 of the most common methods of Feature Scaling - Min-Max Normalization (which we call "Normalization" in our settings), and Z-Score Normalization (which we call "Standardization" in our settings).  Let's take a look at each of those methods as they have been implemented in this script.
 Min-Max Normalization (Normalization) 
This is one of the most common - and most basic - methods of feature scaling.  The basic formula is:   y = (x - min)/(max - min)  - where  x  is the current data sample,  min  is the lowest value in the dataset, and  max  is the highest value in the dataset.  In this transformation, the max would evaluate to 1, and the min would evaluate to 0, and any value in between the min and the max would evaluate somewhere between 0 and 1.
The key benefits of this method are:
 
  It can be used to transform datasets of any range into a new dataset with a consistent and known range (0 to 1).
  It has no dependency on the "shape" of the raw input dataset (i.e. does not assume the input dataset can be approximated to a normal distribution).
 
But there are a couple of "gotchas" with this technique...
 
  First, it assumes the input dataset is complete, or an accurate representation of the population via random sampling.  While in most situations this is a valid assumption, in trading indicators we don't really have that luxury as we're often limited in what sample data we can access (i.e. number of historical bars available).
  Second, this method is highly sensitive to outliers.  Since the crux of this transformation is based on the  max-min  to define the initial range, a single significant outlier can result in skewing the post-transformation dataset (i.e. major price movement as a reaction to a significant news event).
 
You can potentially mitigate those 2 "gotchas" by using a mechanism or technique to find and discard outliers (e.g. calculate the mean and standard deviation of the input dataset and discard any raw values more than 5 standard deviations from the mean), but if your most recent datapoint is an "outlier" as defined by that algorithm, processing it using the "scrubbed" dataset would result in that new datapoint being outside the intended range of 0 to 1 (e.g. if the new datapoint is greater than the "scrubbed" max, it's post-transformation value would be greater than 1).  Even though this is a bit of an edge-case scenario, it is still sure to happen in live markets processing live data, so it's not an ideal solution in our opinion (which is why we chose not to attempt to discard outliers in this manner).
 Z-Score Normalization (Standardization) 
This method of rescaling is a bit more complex than the Min-Max Normalization method noted above, but it is also a widely used process.  The basic formula is:  y = (x – μ) / σ  - where  x  is the current data sample,  μ  is the mean (average) of the input dataset, and  σ  is the standard deviation of the input dataset.  While this transformation still results in a technically-infinite possible range, the output of this transformation has a 2  very  significant properties - the mean (average) of the output dataset has a mean (μ) of 0 and a standard deviation (σ) of 1.
The key benefits of this method are:
 
  As it's based on normalizing the mean and standard deviation of the input dataset instead of a linear range conversion, it is far less susceptible to outliers significantly affecting the result (and in fact has the effect of "squishing" outliers).
  It can be used to accurately transform disparate sets of data into a similar range regardless of the original dataset's raw/actual range.
 
But there are a couple of "gotchas" with this technique as well...
 
  First, it still technically does not do any form of range-binding, so it is still  technically  unbounded (range -∞ to ∞ with a mid-point of 0).
  Second, it implicitly assumes that the raw input dataset to be transformed is normally distributed, which won't always be the case in financial markets.
 
The first "gotcha" is a bit of an annoyance, but isn't a huge issue as we can apply principles of  normal distribution  to conceptually limit the range by defining a fixed number of  standard deviations  from the mean.  While this doesn't  totally  solve the "infinite range" problem (a strong enough sudden move can still break out of our "conceptual range" boundaries), the amount of movement needed to achieve that kind of impact will generally be pretty rare.
The bigger challenge is how to deal with the assumption of the input dataset being normally distributed.  While most financial markets (and indicators) do tend towards a normal distribution, they are almost never going to match that distribution exactly.  So let's dig a bit deeper into distributions are defined and how things like trending markets can affect them.
 Skew (skewness):  This is a measure of asymmetry of the bell curve, or put another way, how and in what way the bell curve is disfigured when comparing the 2 halves.  The easiest way to visualize this is to draw an imaginary vertical line through the apex of the bell curve, then fold the curve in half along that line.  If both halves are exactly the same, the skew is 0 (no skew/perfectly symmetrical) - which is what a normal distribution has (skew = 0).  Most financial markets tend to have short, medium, and long-term trends, and these trends will cause the distribution curve to skew in one direction or another.  Bullish markets tend to skew to the right (positive), and bearish markets to the left (negative).
 Kurtosis:  This is a measure of the "tail size" of the bell curve.  Another way to state this could be how "flat" or "steep" the bell-shape is.  If the bell is steep with a strong drop from the apex (like a steep cliff), it has low kurtosis.  If the bell has a shallow, more sweeping drop from the apex (like a tall hill), is has high kurtosis.  Translating this to financial markets, kurtosis is generally a metric of volatility as the bell shape is largely defined by the strength and frequency of outliers.  This is effectively a measure of volatility - volatile markets tend to have a high level of kurtosis (>3), and stable/consolidating markets tend to have a low level of kurtosis (<3).  A normal distribution (our reference), has a kurtosis value of 3.
So to try and bring all that back together, here's a quick recap of the Standardization rescaling method:
 
  The Standardization method has an assumption of a normal distribution of input data by using the mean (average) and standard deviation to handle the transformation
  Most financial markets do NOT have a normal distribution (as discussed above), and will have varying degrees of skew and kurtosis
 
 Q:  Why are we still favoring the Standardization method over the Normalization method, and how are we accounting for the innate skew and/or kurtosis inherent in most financial markets?  
 A:  Well, since we're only trying to rescale oscillators that by-definition have a midpoint of 0, kurtosis isn't a major concern beyond the affect it has on the post-transformation scaling (specifically, the number of standard deviations from the mean we need to include in our "artificially-bound" range definition).
 Q:  So that answers the question about kurtosis, but what about skew?
 A:  So - for skew, the answer is in the formula - specifically the mean (average) element.  The standard mean calculation assumes a complete dataset and therefore uses a standard (i.e. simple) average, but we're limited by the data history available to us.  So we adapted the transformation formula to leverage a moving average that included a weighting element to it so that it favored recent datapoints more heavily than older ones.  By making the average component more adaptive, we gained the effect of reducing the skew element by having the average itself be more responsive to recent movements, which significantly reduces the effect historical outliers have on the dataset as a whole.  While this is certainly not a perfect solution, we've found that it serves the purpose of rescaling the MACD and AO to a far more well-defined range while still preserving the oscillator behavior and mid-line exceptionally well.  
The most difficult parts to compensate for are periods where markets have low volatility for an extended period of time - to the point where the oscillators are hovering around the 0/midline (in the case of the AO), or when the oscillator and signal lines converge and remain close to each other (in the case of the MACD).  It's during these periods where even our best attempt at ensuring accurate mirrored-behavior when compared to the original can still occasionally lead or lag by a candle.  
 Note: If this is a make-or-break situation for you or your strategy, then we recommend you do not use any of the included indicators that leverage this kind of bounding technique (the AO and MACD at time of publication) and instead use the Trandingview built-in versions! 
We know this is a lot to read and digest, so please take your time and feel free to ask questions - we will do our best to answer!  And as always, constructive feedback is always welcome! 
SUPERTREND MIXED ICHI-DMI-DONCHIAN-VOL-GAP-HLBox@RLSUPERTREND MIXED ICHI-DMI-VOL-GAP-HLBox@RL 
by RegisL76
This script is based on several trend indicators. 
* ICHIMOKU (KINKO HYO) 
* DMI (Directional Movement Index) 
* SUPERTREND ICHIMOKU + SUPERTREND DMI 
* DONCHIAN CANAL Optimized with Colored Bars 
* HMA Hull 
* Fair Value GAP 
* VOLUME/ MA Volume 
* PRICE / MA Price 
* HHLL BOXES 
All these indications are visible simultaneously on a single graph. A data table summarizes all the important information to make a good trade decision.
ICHIMOKU Indicator: 
The ICHIMOKU indicator is visualized in the traditional way.
 ICHIMOKU standard setting values are respected but modifiable. (Traditional defaults =  . 
An oriented visual symbol, near the last value, indicates the progression (Ascending, Descending or neutral) of the TENKAN-SEN and the KIJUN-SEN as well as the period used. 
The CLOUD (KUMO) and the CHIKOU-SPAN are present and are essential for the complete analysis of the ICHIMOKU. 
At the top of the graph are visually represented the crossings of the TENKAN and the KIJUN. 
Vertical lines, accompanied by labels, make it possible to quickly visualize the particularities of the ICHIMOKU. 
A line displays the current bar. 
A line visualizes the end of the CLOUD (KUMO) which is shifted 25 bars into the future. 
A line visualizes the end of the chikou-span, which is shifted 25 bars in the past. 
DIRECTIONAL MOVEMENT INDEX (DMI) :  Treated conventionally : DI+, DI-, ADX and associated with a SUPERTREND DMI. 
A visual symbol at the bottom of the graph indicates DI+ and DI- crossings 
A line of oriented and colored symbols (DMI Line) at the top of the chart indicates the direction and strength of the trend.
SUPERTREND ICHIMOKU + SUPERTREND DMI : 
Trend following by SUPERTREND calculation. 
DONCHIAN CHANNEL: Treated conventionally. (And optimized by colored bars when overshooting either up or down.
The lines, high and low of the last values of the channel are represented to quickly visualize the level of the RANGE. 
SUPERTREND HMA (HULL) Treated conventionally. 
The HMA line visually indicates, according to color and direction, the market trend. 
A visual symbol at the bottom of the chart indicates opportunities to sell and buy. 
VOLUME: 
Calculation of the MOBILE AVERAGE of the volume with comparison of the volume compared to the moving average of the volume. 
The indications are colored and commented according to the comparison. 
PRICE: Calculation of the MOBILE AVERAGE of the price with comparison of the price compared to the moving average of the price. 
The indications are colored and commented according to the comparison. 
HHLL BOXES: 
Visualizes in the form of a box, for a given period, the max high and min low values of the price. 
The configuration allows taking into account the high and low wicks of the price or the opening and closing values. 
FAIR VALUE GAP : 
This indicator displays 'GAP' levels over the current time period and an optional higher time period. 
The script takes into account the high/low values of the current bar and compares with the 2 previous bars. 
The "gap" is generated from the lack of overlap between these bars. Bearish or bullish gaps are determined by whether the gap is above or below HmaPrice, as they tend to fill, and can be used as targets. 
NOTE: FAIR VALUE GAP has no values displayed in the table and/or label. 
Important information (DATA) relating to each indicator is displayed in real time in a table and/or a label.
 Each information is commented and colored according to direction, value, comparison etc. 
Each piece of information indicates the values of the current bar and the previous value (in "FULL" mode). 
The other possible modes for viewing the table and/or the label allow a more synthetic view of the information ("CONDENSED" and "MINIMAL" modes). 
In order not to overload the vision of the chart too much, the visualization box of the RANGE DONCHIAN, the vertical lines of the shifted marks of the ICHIMOKU, as well as the boxes of the HHLL Boxes indicator are only visualized intermittently (managed by an adjustable time delay  ). 
The "HISTORICAL INFO READING" configuration parameter set to zero (by default) makes it possible to read all the information of the current bar in progress (Bar #0). All other values allow to read the information of a historical bar. The value 1 reads the information of the bar preceding the current bar (-1). The value 10 makes it possible to read the information of the tenth bar behind (-10) compared to the current bar, etc. 
At the bottom of the DATAS table and label, lights, red, green or white indicate quickly summarize the trend from the various indicators. 
Each light represents the number of indicators with the same trend at a given time. 
Green for a bullish trend, red for a bearish trend and white for a neutral trend. 
The conditions for determining a trend are for each indicator: 
SUPERTREND  ICHIMOHU + DMI: the 2 Super trends together are either bullish or bearish. 
Otherwise the signal is neutral. 
DMI: 2 main conditions: 
BULLISH if DI+ >= DI- and ADX >25. 
BEARISH if DI+ < DI- and ADX >25. 
NEUTRAL if the 2 conditions are not met.
ICHIMOKU: 3 main conditions: 
BULLISH if PRICE above the cloud and TENKAN > KIJUN and GREEN CLOUD AHEAD. 
BEARISH if PRICE below the cloud and TENKAN < KIJUN and RED CLOUD AHEAD. 
The other additional conditions (Data) complete the analysis and are present for informational purposes of the trend and depend on the context. 
DONCHIAN CHANNEL: 1 main condition: 
BULLISH: the price has crossed above the HIGH DC line. 
BEARISH: the price has gone below the LOW DC line. 
NEUTRAL if the price is between the HIGH DC and LOW DC lines 
The 2 other complementary conditions (Datas) complete the analysis: 
HIGH DC and LOW DC are increasing, falling or stable. 
SUPERTREND HMA HULL: The script determines several trend levels: 
STRONG BUY, BUY, STRONG SELL, SELL AND NEUTRAL. 
VOLUME: 3 trend levels: 
VOLUME > MOVING AVERAGE, 
VOLUME < MOVING AVERAGE, 
VOLUME = MOVING AVERAGE. 
PRICE: 3 trend levels: 
PRICE > MOVING AVERAGE, 
PRICE < MOVING AVERAGE, 
PRICE = MOVING AVERAGE. 
If you are using this indicator/strategy and you are satisfied with the results, you can possibly make a donation (a coffee, a pizza or more...) via paypal to: lebourg.regis@free.fr. 
Thanks in advance !!! 
Have good winning Trades.
**************************************************************************************************************************
SUPERTREND MIXED ICHI-DMI-VOL-GAP-HLBox@RL
by RegisL76
Ce script est basé sur plusieurs indicateurs de tendance.
* ICHIMOKU (KINKO HYO)
* DMI (Directional Movement Index)
* SUPERTREND ICHIMOKU +  SUPERTREND DMI
* DONCHIAN CANAL Optimized with Colored Bars
* HMA Hull
* Fair Value GAP
* VOLUME/ MA Volume
* PRIX / MA Prix
* HHLL BOXES
Toutes ces indications sont visibles simultanément sur un seul et même graphique.
Un tableau de données récapitule toutes les informations importantes pour prendre une bonne décision de Trade.
I- Indicateur ICHIMOKU : 
L’indicateur ICHIMOKU est visualisé de manière traditionnelle
Les valeurs de réglage standard ICHIMOKU sont respectées mais modifiables. (Valeurs traditionnelles par défaut =  
Un symbole visuel orienté, à proximité de la dernière valeur, indique la progression (Montant, Descendant ou neutre) de la TENKAN-SEN et de la KIJUN-SEN ainsi que la période utilisée. 
Le NUAGE (KUMO) et la CHIKOU-SPAN sont bien présents et sont primordiaux pour l'analyse complète de l'ICHIMOKU.
En haut du graphique sont représentés visuellement les croisements de la TENKAN et de la KIJUN.
Des lignes verticales, accompagnées d'étiquettes, permettent de visualiser rapidement les particularités de l'ICHIMOKU.
Une ligne visualise la barre en cours.
Une ligne visualise l'extrémité du NUAGE (KUMO) qui est décalé de 25 barres dans le futur.
Une ligne visualise l'extrémité de la chikou-span, qui est décalée de 25 barres dans le passé.
II-DIRECTIONAL MOVEMENT INDEX (DMI)
Traité de manière conventionnelle : DI+, DI-, ADX et associé à un SUPERTREND DMI
Un symbole visuel en bas du graphique indique les croisements DI+ et DI-
Une ligne de symboles orientés et colorés (DMI Line) en haut du graphique, indique la direction et la puissance de la tendance.
III SUPERTREND ICHIMOKU + SUPERTREND DMI
Suivi de tendance par calcul SUPERTREND
IV- DONCHIAN CANAL : 
Traité de manière conventionnelle.
(Et optimisé par des barres colorées en cas de dépassement soit vers le haut, soit vers le bas.
Les lignes, haute et basse des dernières valeurs du canal sont représentées pour visualiser rapidement la fourchette du RANGE. 
V- SUPERTREND HMA (HULL)
Traité de manière conventionnelle.
La ligne HMA indique visuellement, selon la couleur et l'orientation, la tendance du marché.
Un symbole visuel en bas du graphique indique les opportunités de vente et d'achat.
*VI VOLUME : 
Calcul de la MOYENNE MOBILE du volume avec comparaison du volume par rapport à la moyenne mobile du volume.
Les indications sont colorées et commentées en fonction de la comparaison.
*VII PRIX : 
Calcul de la MOYENNE MOBILE du prix avec comparaison du prix par rapport à la moyenne mobile du prix.
Les indications sont colorées et commentées en fonction de la comparaison.
*VIII HHLL BOXES : 
Visualise sous forme de boite, pour une période donnée, les valeurs max hautes et min basses du prix.
La configuration permet de prendre en compte les mèches hautes et basses du prix ou bien les valeurs d'ouverture et de fermeture.
IX - FAIR VALUE GAP
Cet indicateur affiche les niveaux de 'GAP' sur la période temporelle actuelle ET une période temporelle facultative supérieure.
Le script prend en compte les valeurs haut/bas de la barre actuelle  et compare avec les 2 barres précédentes.
Le "gap" est généré à partir du manque de recouvrement entre ces barres.
Les écarts baissiers ou haussiers sont déterminés selon que l'écart est supérieurs ou inférieur à HmaPrice, car ils ont tendance à être comblés, et peuvent être utilisés comme cibles.
NOTA : FAIR VALUE GAP n'a pas de valeurs affichées dans la table et/ou l'étiquette.
Les informations importantes (DATAS) relatives à chaque indicateur sont visualisées en temps réel dans une table et/ou une étiquette.
Chaque information est commentée et colorée en fonction de la direction, de la valeur, de la comparaison etc.
Chaque information indique la valeurs de la barre en cours et la valeur précédente ( en mode "COMPLET").
Les autres modes possibles pour visualiser la table et/ou l'étiquette, permettent une vue plus synthétique des informations (modes "CONDENSÉ" et "MINIMAL").
Afin de ne pas trop surcharger la vision du graphique, la boite de visualisation du RANGE DONCHIAN, les lignes verticales des marques décalées de l'ICHIMOKU, ainsi que les boites de l'indicateur HHLL Boxes ne sont visualisées que de manière intermittente (géré par une temporisation réglable  ).
Le paramètre de configuration "HISTORICAL INFO READING" réglé sur zéro (par défaut) permet de lire toutes les informations de la barre actuelle en cours (Barre #0).
Toutes autres valeurs permet de lire les informations d'une barre historique. La valeur 1 permet de lire les informations de la barre précédant la barre en cours (-1).
La valeur 10 permet de lire les information de la dixième barre en arrière (-10) par rapport à la barre en cours, etc.
Dans le bas de la table et de l'étiquette de DATAS, des voyants, rouge, vert ou blanc indique de manière rapide la synthèse de la tendance issue des différents indicateurs.
Chaque voyant représente le nombre d'indicateur ayant la même tendance à un instant donné. Vert pour une tendance Bullish, rouge pour une tendance Bearish et blanc pour une tendance neutre.
Les conditions pour déterminer une tendance sont pour chaque indicateur :
SUPERTREND ICHIMOHU + DMI : les 2 Super trends sont ensemble soit bullish soit Bearish. Sinon le signal est neutre.
DMI : 2 conditions principales : 
BULLISH si DI+ >= DI- et ADX >25.
BEARISH si DI+ <  DI- et ADX >25.
NEUTRE si les 2 conditions ne sont pas remplies.
ICHIMOKU : 3 conditions principales :
BULLISH si PRIX au dessus du nuage  et TENKAN > KIJUN et NUAGE VERT DEVANT.
BEARISH si PRIX en dessous du nuage et TENKAN < KIJUN et NUAGE ROUGE DEVANT.
Les autres conditions complémentaires (Datas) complètent l'analyse et sont présents à titre informatif de la tendance et dépendent du contexte.
CANAL DONCHIAN : 1 condition principale : 
BULLISH : le prix est passé au dessus de la ligne HIGH DC.
BEARISH : le prix est passé au dessous de la ligne LOW DC.
NEUTRE si le prix se situe entre les lignes  HIGH DC et LOW DC
Les 2 autres conditions complémentaires (Datas) complètent l'analyse : HIGH DC  et LOW DC sont croissants, descendants ou stables.
SUPERTREND HMA HULL : 
Le script détermine plusieurs niveaux de tendance :
STRONG BUY, BUY, STRONG SELL, SELL ET NEUTRE.
VOLUME : 3 niveaux de tendance : 
VOLUME > MOYENNE MOBILE, VOLUME < MOYENNE MOBILE, VOLUME = MOYENNE MOBILE.
PRIX : 3 niveaux de tendance : 
PRIX > MOYENNE MOBILE, PRIX < MOYENNE MOBILE, PRIX = MOYENNE MOBILE.
Si vous utilisez cet indicateur/ stratégie et que vous êtes satisfait des résultats, 
 vous pouvez éventuellement me faire un don (un café, une pizza ou plus ...) via paypal à : lebourg.regis@free.fr.
 Merci d'avance !!!
Ayez de bons Trades gagnants.
StableF-MainIt is combination of  Built in Super trend  and Adx with take profit 
 uptrend is considered when +dmi is above -dmi and +dmi is above 25 and adx is above 25 and supertrend gives Buy
 downtrend is considered when -dmi is above +dmi and -dmi is above 25 and adx is above 25 and supertrend give sell
use fibo for target by taking as previous swing high and swing low 
-supertrend crossover is referred as  buy plotshape 
-supertrend cross under is referred as  Sell plotshape 
 -keep stoploss at dot line of supertrend  
-adx-dmi crossover (+dmi crossed above -dmi) is shown by Triangle Up symbol 
-adx-dmi crossunder( -dmi crosses below +dmi) is shown by Triangle down symbol
--Cross symbol with blue line with linewidth 2 is referred as  Take profit    
--combine this with adx -dmi setting with 7 and 14 
----disclaimer-----
used free built in supertrend and adx so u can use same setting in other broker or in trading view 
not responsible for any loss or gain 
-only for educational purpose
Market Traffic Light (redesigned)redesigned the market traffic light from funcharts, all honor to him, I just put a new design ;-) and some bugfixes
1. Section (Fear & Greed)
Approximation of the CNN Money Fear & Greed index based on code of user MagicEins. The index shows values between 0 (extreme fear, red) and 100 (extreme greed, green).
2. Section (warning signs)
VIX: Values above 20 are red and below green. The legend shows the value of the current bar including the change from the bar before. The average VIX is about 16. Values over 20 are a sign of stressed market.
Distribution days: A distribution day (loss to the day before > 0,2 % and higher volume ) is marked with a yellow dot. In case there are more than four distributions days within 25 markets days the dot is orange. When big players redistribute their investments distribution days can occur. If this is done often (more than four times within 25 market days) it is possible that the markets changes or that a sector rotation occurs. For calculation distribution days futures of S&P 500 ( ES1! ) and NASDAQ ( NQ1! ) are used because the volume for this calculation is needed. TradingView does not support volumes for S&P 500 or NASDAQ directly.
Markets: A green/red dot signals that the market is above/below its 25-Daily-EMA. A green/red square signals that the market is above/below its 25-Weekly-EMA. Markets can give as a feeling about where investors store their money. E.g. when markets are falling but DUX (Down Jones Utility Average) is rising this means that investors put their money into save haven. This can be a sign that the markets will fall more.
3. Section (panic signs, = signs of reaching a low within a correction of a crash)
VIX-Reversion: A VIX reversion day ( VIX > 20 & VIX high > VIX high of the day before & VIX high – VIX close > 3) is marked as a yellow dot
VVIX: A value equal or above 140 is marked with a yellow dot and shows absolute panic.
PCR Intra max: A value equal or above 1.4 is marked with a yellow dot.
New high/lows: New highs/lows are shown for AMEX, NYSE and NASDAQ. A yellow dot is shown if the ratio is less or equal than 0. 01 .
Down-Day: Down days are shown for AMEX, NYSE and NASDA. A yellow dot is shown if at least 90 % of the whole volume (up and down) is a down volume .
In Addition to the warning signs in the second section a check of the Advance Decline Line (NYSE and NASDAQ) for bullish and bearish divergences is useful. The whole set-up can be seen in the screenshot.
Only one signal normally does not give us a good prediction. Therefore we need to see these indication as a bundle. TradingView gives us the opportunity to check some striking market situations in the past. So feel free to test this indication for building up your own opinion.
Please feel free to comment in case of failures, improvements or experiences (good or bad).
ADX / RSI Strategy by Trade Rush (created by SirPoggy) This is one of many new strategies coming soon which were seen on Trade Rush
 This one is the ADX / RSI Strategy seen here: 
  https:www.youtube.com/watch?v=uSkGE0ujyn4
 While the strategy has been modified slightly to use the DMI instead of the ADX, the core of the strategy is essentially the same
 Long signals are generated when the RSI is above 70, close is above the 200EMA, and the ADX is above 25 (added is the plus DMI over 25 and minus DMI below 20)
    Stop loss is placed below /above the 21 EMA, however, there is a deviation required to ensure price is not too close to where a stop loss would be placed.
 Short signals are generated when the RSI is below 30, close is below the 200EMA, and the ADX is above 25 (added is the minus DMI over 25 and plus DMI below 20)
 
 I do not recommend using this strategy but I have provided this code for educational purposes.  
Thanks!
Let me know which strategy you'd like coded next in the comments below. 
[kai]Futility RatioAn indicator that measures movement inefficiency
Inefficient movement, that is, the range market becomes a high number, the limit is reached at about 60 and a trend occurs
When the range breaks and a trend occurs, the inefficiency drops to about 40 and many trends end.
The full-scale trend goes down further and goes down to about 25, which is evaluated as an efficient movement, the limit is reached and the trend ends.
As for how to use this Inge, the direction of the trend needs to be considered in other ways.
Create a position when you reach 60
Position closed or contrarian at 40 or 25
I assume the usage
動きの非効率性を測定するインジケーターです
非効率な動きをするつまりレンジ相場は高い数字になって、60程度で限界が訪れてトレンドが発生します
レンジがブレイクしトレンドが発生すると40程度まで非効率性は下がりって多くのトレンドは終了します
本格的なトレンドはさらに下がっていって効率的な動きと評価される25程度まで下がって限界が訪れてトレンドが終了します
このインジの使い方はトレンドの方向は他の方法で考える必要がありますが
60まで上がったときにポジション作成
40又は25でポジションクローズ又は逆張り
という使い方を想定しています
Market Traffic LightThis indicator visualizes warning and panic signs, which are shown separately.
 1. Section (Fear & Greed) 
Approximation of the CNN Money Fear & Greed index based on code of user MagicEins. The index shows values between 0 (extreme fear, red) and 100 (extreme greed, green).
 2. Section (warning signs) 
 
 VIX: Values above 20 are red and below green. The legend shows the value of the current bar including the change from the bar before. The average VIX is about 16. Values over 20 are a sign of stressed market.
 Distribution days: A distribution day (loss to the day before > 0,2 % and higher volume) is marked with a yellow dot. In case there are more than four distributions days within 25 markets days the dot is orange. When big players redistribute their investments distribution days can occur. If this is done often (more than four times within 25 market days) it is possible that the markets changes or that a sector rotation occurs. For calculation distribution days futures of S&P 500 (ES1!) and NASDAQ (NQ1!) are used because the volume for this calculation is needed. TradingView does not support volumes for S&P 500 or NASDAQ directly.
 Markets: A green/red dot signals that the market is above/below its 25-Daily-EMA. A green/red square signals that the market is above/below its 25-Weekly-EMA. Markets can give as a feeling about where investors store their money. E.g. when markets are falling but DUX (Down Jones Utility Average) is rising this means that investors put their money into save haven. This can be a sign that the markets will fall more.
 
 3. Section (panic signs, = signs of reaching a low within a correction of a crash) 
 
 VIX-Reversion: A VIX reversion day (VIX > 20 & VIX high > VIX high of the day before & VIX high – VIX close > 3) is marked as a yellow dot
 VVIX: A value equal or above 140 is marked with a yellow dot and shows absolute panic. 
 PCR Intra max: A value equal or above 1.4 is marked with a yellow dot. 
 New high/lows: New highs/lows are shown for AMEX, NYSE and NASDAQ. A yellow dot is shown if the ratio is less or equal than 0.01.
 Down-Day: Down days are shown for AMEX, NYSE and NASDA. A yellow dot is shown if at least 90 % of the whole volume (up and down) is a down volume.
 
In Addition to the warning signs in the second section a check of the Advance Decline Line (NYSE and NASDAQ) for bullish and bearish divergences is useful. The whole set-up can be seen in the screenshot.
Only one signal normally does not give us a good prediction. Therefore we need to see these indication as a bundle. TradingView gives us the opportunity to check some striking market situations in the past. So feel free to test this indication for building up your own opinion.
Please feel free to comment in case of failures, improvements or experiences (good or bad).
ADX Color Change by BehemothI find this tool to be the most valuable and accurate entry point indicator along with moving averages and the VWAP.  
 ADX Color Indicator - Controls & Intraday Trading Benefits
 
 Indicator Controls:
 
 1. ADX Length  (default: 14)
   - Controls the calculation period for ADX
   - Lower values (7-10) = more sensitive, faster signals (better for scalping)
   - Higher values (14-20) = smoother, fewer false signals (better for swing trades)
   - *Intraday tip:* Try 10-14 for most intraday timeframes
 2. Show Threshold Levels  (default: On)
   - Displays the 20 and 25 horizontal lines
   - Helps you quickly identify when ADX crosses key strength levels
 3. Use Custom Timeframe  (default: Off)
   - Allows viewing higher timeframe ADX on lower timeframe charts
   - *Example:* Trade on 5-min chart but see 15-min or 1-hour ADX
 4. Custom Timeframe 
    - Select any timeframe: 1m, 5m, 15m, 30m, 1H, 4H, D, etc.
   - *Intraday tip:* Use 15m or 1H ADX on 5m charts for better trend context
 5. Show +DI and -DI  (default: Off)
   - Shows directional movement indicators
   - Green line (+DI) > Red line (-DI) = bullish trend
   - Red line (-DI) > Green line (+DI) = bearish trend
 6. Show Background Zon es (default: Off)
   - Visual background colors for quick trend strength identification
   - Green = strong trend (ADX > 25)
   - Yellow = moderate trend (ADX 20-25)
 Intraday Trading Benefits:
 
 1. Avoid Choppy Markets
 - When ADX < 20 (no background color), market is ranging
- Reduces false breakout trades and whipsaws
- Save time and capital by stepping aside during low-quality setups
 2. Identify High-Probability Trend Trades
 - **Green line + Green zone** = strong trend building, look for pullback entries
- Yellow line crossing above 20 = early trend formation signal
- Catch trends early when ADX starts rising from below 20
 3. Multi-Timeframe Analysis
 - Use custom timeframe to align with higher timeframe trends
- *Example:* If 1H ADX shows green (strong trend), take breakout trades on 5m chart in same direction
- Increases win rate by trading with the bigger picture
 4. Exit Signals
 - When ADX turns red (falling), trend is weakening
- Consider tightening stops or taking profits
- Avoid entering new positions when ADX is declining
 5. Quick Visual Confirmation
 - Color coding eliminates need to analyze numbers
- Instant recognition: Green = go, Yellow = caution, Red = trend dying
- Faster decision-making during fast market moves
 6. Scalping Strategy
 - Set ADX length to 7-10 for sensitive signals
- Only scalp when ADX is rising (blue, yellow, or green)
- Exit when ADX turns red
 7. Breakout Confirmation
 - Wait for ADX to rise above 20 after a breakout
- Filters false breakouts in ranging markets
- Yellow or green color confirms momentum behind the move
 Optimal Intraday Settings:
 
- Day Trading (5-15 min charts):** ADX Length = 10-14
- Scalping (1-5 min charts):** ADX Length = 7-10, watch custom 15m timeframe
- Swing Intraday (30min-1H charts):** ADX Length = 14-20
 Simple Trading Rules:
 ✅ Trade: ADX rising + above 20 (yellow or green)  
⚠️ Caution: ADX flat or just crossed 20  
❌ Avoid:*ADX falling (red) or below 20
The key advantage is  staying out of low-quality, choppy price action  which is where most intraday traders lose money!
TwistedHWAY Oracle - Intelligent Level Detection System═════════════════════════════════════════════════════════════════════════
 🎯 TwistedHWAY Oracle™ - Intelligent Level Detection System 
═════════════════════════════════════════════════════════════════════════
 OVERVIEW 
TwistedHWAY Oracle™ combines six independent calculation engines to identify high-probability support and resistance levels. The indicator uses adaptive market regime detection and confluence analysis to automatically rank levels by confidence score, helping traders identify key reaction zones where price is likely to find support or resistance.
 KEY FEATURES 
The indicator provides comprehensive level detection through:
 
 Six Detection Engines  — Each engine operates independently with its own alert system
 Confluence Analysis  — Automatically awards bonus confidence when multiple engines identify the same level  
 Adaptive Intelligence  — Market volatility detection adjusts parameters in real-time
 Confidence Scoring  — Every level is ranked and displayed with a numerical confidence score
 Individual Alerts  — Separate alert controls for each detection method
 
 DETECTION ENGINES 
 1 — Pivot Points Engine 
Calculates daily pivot levels including PP, R1-R3, and S1-S3 using previous day's high, low, and close.
 2 — Swing Detector  
Identifies significant swing highs and lows using prominence filtering to eliminate noise.
 3 — Psychological Matrix 
Detects round number levels at three configurable increments (default: 10, 25, 50).
 4 — Fibonacci Engine 
Calculates retracement levels (23.6%, 38.2%, 50%, 61.8%, 78.6%) from major swings.
 5 — VWAP System 
Generates volume-weighted average price levels at three different periods.
 6 — Confluence Analyzer 
Awards bonus confidence points when multiple engines identify the same level.
 HOW TO USE 
 Reading the Levels 
 
 Levels above current price = Resistance (red by default)
 Levels below current price = Support (green by default)  
 Numbers in brackets show confidence score  
 Higher confidence = stronger level
 Levels with score > 2.0 indicate extreme confluences
 
 Trading Strategies 
 
 Bounce Trading  — Enter positions when price approaches high-confidence levels expecting reversal
 Breakout Trading  — Trade breakouts through levels, using broken level as stop-loss
 Confluence Zones  — Focus on areas where multiple engines agree
 
 SETTINGS GUIDE 
 Oracle Settings 
 
 Validation Mode  — Conservative parameters for more reliable signals
 Max Levels  — Number of levels to display (10-50)
 Level Extension  — Line extension direction (None/Left/Right/Both)
 
 Individual Engine Controls 
Each engine can be toggled on/off with separate alert controls:
 
 Pivot Engine (daily pivots)
 Swing Detector (historical swings)
 Psychological Matrix (round numbers)
 Fibonacci Engine (retracements)
 VWAP System (volume-weighted levels)
 
 Visual Settings 
 
 Individual color selection for each level type
 Label display toggle with size options
 Line style preferences (Solid/Dashed/Dotted)
 
 Alert Configuration 
 
 Alert Distance %  — Proximity threshold (default: 0.5%)
 Alert Cooldown  — Minimum bars between alerts (default: 60)
 Individual alert toggles for each engine
 
 ADAPTIVE PARAMETERS 
The indicator automatically adjusts to market conditions:
 
 High Volatility Mode  — Wider swing detection, stricter prominence filters
 Normal Mode  — Balanced parameters for typical market conditions  
 Validation Mode  — Most conservative settings for reliable signals
 
Market regime is detected using 100-period volatility measurement with automatic threshold adjustment.
 ALERTS 
Five alert types plus special confluence alerts:
 
 🎯  Pivot Alerts  — Daily pivot level approaches
 🌊  Swing Alerts  — Historical swing level tests
 🧠  Psychological Alerts  — Round number approaches  
 🌀  Fibonacci Alerts  — Retracement level tests
 📉  VWAP Alerts  — Volume-weighted level approaches
 ⚡  Critical Alerts  — Ultra-high confidence levels (score ≥ 2.0)
 
Alerts include price level, confidence score, and source information.
 BEST PRACTICES 
 Timeframe Selection 
 
 Works on all timeframes (optimized for 5min to Daily)
 Higher timeframes = more reliable levels
 Use multi-timeframe analysis for confirmation
 
 Optimization by Instrument 
 Forex: 
Psychological increments: 0.0010, 0.0050, 0.0100
 Stocks (Low-priced): 
Psychological increments: 1, 5, 10
 Stocks (High-priced): 
Psychological increments: 10, 25, 50
 Crypto: 
Adjust based on price range and volatility
 LIMITATIONS 
 
 Calculation intensive on last bar (may cause slight delays)
 Maximum 50 levels can be displayed simultaneously
 Swing detection requires minimum 25 bars of history
 VWAP calculations use price range as volume proxy when volume unavailable
 
 NOTES 
 
 Levels are recalculated on each bar close
 Confidence scores update dynamically with market conditions
 Colors automatically adjust based on price position
 All settings are saved with chart layout
 
═════════════════════════════════════════════════════════════════════════
Version: 3.0 | Build 2025.10
License: GNU GPL v3.0
© 2025 TwistedHWAY
═════════════════════════════════════════════════════════════════════════
Keltner Channel Enhanced [DCAUT]█ Keltner Channel Enhanced  
 📊 ORIGINALITY & INNOVATION 
The Keltner Channel Enhanced represents an important advancement over standard Keltner Channel implementations by introducing dual flexibility in moving average selection for both the middle band and ATR calculation. While traditional Keltner Channels typically use EMA for the middle band and RMA (Wilder's smoothing) for ATR, this enhanced version provides access to 25+ moving average algorithms for both components, enabling traders to fine-tune the indicator's behavior to match specific market characteristics and trading approaches.
 Key Advancements: 
 
 Dual MA Algorithm Flexibility: Independent selection of moving average types for middle band (25+ options) and ATR smoothing (25+ options), allowing optimization of both trend identification and volatility measurement separately
 Enhanced Trend Sensitivity: Ability to use faster algorithms (HMA, T3) for middle band while maintaining stable volatility measurement with traditional ATR smoothing, or vice versa for different trading strategies
 Adaptive Volatility Measurement: Choice of ATR smoothing algorithm affects channel responsiveness to volatility changes, from highly reactive (SMA, EMA) to smoothly adaptive (RMA, TEMA)
 Comprehensive Alert System: Five distinct alert conditions covering breakouts, trend changes, and volatility expansion, enabling automated monitoring without constant chart observation
 Multi-Timeframe Compatibility: Works effectively across all timeframes from intraday scalping to long-term position trading, with independent optimization of trend and volatility components
 
This implementation addresses key limitations of standard Keltner Channels: fixed EMA/RMA combination may not suit all market conditions or trading styles. By decoupling the trend component from volatility measurement and allowing independent algorithm selection, traders can create highly customized configurations for specific instruments and market phases.
 📐 MATHEMATICAL FOUNDATION 
Keltner Channel Enhanced uses a three-component calculation system that combines a flexible moving average middle band with ATR-based (Average True Range) upper and lower channels, creating volatility-adjusted trend-following bands.
 Core Calculation Process: 
 1. Middle Band (Basis) Calculation: 
The basis line is calculated using the selected moving average algorithm applied to the price source over the specified period:
 
basis = ma(source, length, maType)
 
Supported algorithms include EMA (standard choice, trend-biased), SMA (balanced and symmetric), HMA (reduced lag), WMA, VWMA, TEMA, T3, KAMA, and 17+ others.
 2. Average True Range (ATR) Calculation: 
ATR measures market volatility by calculating the average of true ranges over the specified period:
 
trueRange = max(high - low, abs(high - close ), abs(low - close ))
atrValue = ma(trueRange, atrLength, atrMaType)
 
ATR smoothing algorithm significantly affects channel behavior, with options including RMA (standard, very smooth), SMA (moderate smoothness), EMA (fast adaptation), TEMA (smooth yet responsive), and others.
 3. Channel Calculation: 
Upper and lower channels are positioned at specified multiples of ATR from the basis:
 
upperChannel = basis + (multiplier × atrValue)
lowerChannel = basis - (multiplier × atrValue)
 
Standard multiplier is 2.0, providing channels that dynamically adjust width based on market volatility.
 Keltner Channel vs. Bollinger Bands - Key Differences: 
While both indicators create volatility-based channels, they use fundamentally different volatility measures:
 Keltner Channel (ATR-based): 
 
 Uses Average True Range to measure actual price movement volatility
 Incorporates gaps and limit moves through true range calculation
 More stable in trending markets, less prone to extreme compression
 Better reflects intraday volatility and trading range
 Typically fewer band touches, making touches more significant
 More suitable for trend-following strategies
 
 Bollinger Bands (Standard Deviation-based): 
 
 Uses statistical standard deviation to measure price dispersion
 Based on closing prices only, doesn't account for intraday range
 Can compress significantly during consolidation (squeeze patterns)
 More touches in ranging markets
 Better suited for mean-reversion strategies
 Provides statistical probability framework (95% within 2 standard deviations)
 
 Algorithm Combination Effects: 
The interaction between middle band MA type and ATR MA type creates different indicator characteristics:
 
 Trend-Focused Configuration (Fast MA + Slow ATR): Middle band uses HMA/EMA/T3, ATR uses RMA/TEMA, quick trend changes with stable channel width, suitable for trend-following
 Volatility-Focused Configuration (Slow MA + Fast ATR): Middle band uses SMA/WMA, ATR uses EMA/SMA, stable trend with dynamic channel width, suitable for volatility trading
 Balanced Configuration (Standard EMA/RMA): Classic Keltner Channel behavior, time-tested combination, suitable for general-purpose trend following
 Adaptive Configuration (KAMA + KAMA): Self-adjusting indicator responding to efficiency ratio, suitable for markets with varying trend strength and volatility regimes
 
 📊 COMPREHENSIVE SIGNAL ANALYSIS 
Keltner Channel Enhanced provides multiple signal categories optimized for trend-following and breakout strategies.
 Channel Position Signals: 
 Upper Channel Interaction: 
 
 Price Touching Upper Channel: Strong bullish momentum, price moving more than typical volatility range suggests, potential continuation signal in established uptrends
 Price Breaking Above Upper Channel: Exceptional strength, price exceeding normal volatility expectations, consider adding to long positions or tightening trailing stops
 Price Riding Upper Channel: Sustained strong uptrend, characteristic of powerful bull moves, stay with trend and avoid premature profit-taking
 Price Rejection at Upper Channel: Momentum exhaustion signal, consider profit-taking on longs or waiting for pullback to middle band for reentry
 
 Lower Channel Interaction: 
 
 Price Touching Lower Channel: Strong bearish momentum, price moving more than typical volatility range suggests, potential continuation signal in established downtrends
 Price Breaking Below Lower Channel: Exceptional weakness, price exceeding normal volatility expectations, consider adding to short positions or protecting against further downside
 Price Riding Lower Channel: Sustained strong downtrend, characteristic of powerful bear moves, stay with trend and avoid premature covering
 Price Rejection at Lower Channel: Momentum exhaustion signal, consider covering shorts or waiting for bounce to middle band for reentry
 
 Middle Band (Basis) Signals: 
 Trend Direction Confirmation: 
 
 Price Above Basis: Bullish trend bias, middle band acts as dynamic support in uptrends, consider long positions or holding existing longs
 Price Below Basis: Bearish trend bias, middle band acts as dynamic resistance in downtrends, consider short positions or avoiding longs
 Price Crossing Above Basis: Potential trend change from bearish to bullish, early signal to establish long positions
 Price Crossing Below Basis: Potential trend change from bullish to bearish, early signal to establish short positions or exit longs
 
 Pullback Trading Strategy: 
 
 Uptrend Pullback: Price pulls back from upper channel to middle band, finds support, and resumes upward, ideal long entry point
 Downtrend Bounce: Price bounces from lower channel to middle band, meets resistance, and resumes downward, ideal short entry point
 Basis Test: Strong trends often show price respecting the middle band as support/resistance on pullbacks
 Failed Test: Price breaking through middle band against trend direction signals potential reversal
 
 Volatility-Based Signals: 
 Narrow Channels (Low Volatility): 
 
 Consolidation Phase: Channels contract during periods of reduced volatility and directionless price action
 Breakout Preparation: Narrow channels often precede significant directional moves as volatility cycles
 Trading Approach: Reduce position sizes, wait for breakout confirmation, avoid range-bound strategies within channels
 Breakout Direction: Monitor for price breaking decisively outside channel range with expanding width
 
 Wide Channels (High Volatility): 
 
 Trending Phase: Channels expand during strong directional moves and increased volatility
 Momentum Confirmation: Wide channels confirm genuine trend with substantial volatility backing
 Trading Approach: Trend-following strategies excel, wider stops necessary, mean-reversion strategies risky
 Exhaustion Signs: Extreme channel width (historical highs) may signal approaching consolidation or reversal
 
 Advanced Pattern Recognition: 
 Channel Walking Pattern: 
 
 Upper Channel Walk: Price consistently touches or exceeds upper channel while staying above basis, very strong uptrend signal, hold longs aggressively
 Lower Channel Walk: Price consistently touches or exceeds lower channel while staying below basis, very strong downtrend signal, hold shorts aggressively
 Basis Support/Resistance: During channel walks, price typically uses middle band as support/resistance on minor pullbacks
 Pattern Break: Price crossing basis during channel walk signals potential trend exhaustion
 
 Squeeze and Release Pattern: 
 
 Squeeze Phase: Channels narrow significantly, price consolidates near middle band, volatility contracts
 Direction Clues: Watch for price positioning relative to basis during squeeze (above = bullish bias, below = bearish bias)
 Release Trigger: Price breaking outside narrow channel range with expanding width confirms breakout
 Follow-Through: Measure squeeze height and project from breakout point for initial profit targets
 
 Channel Expansion Pattern: 
 
 Breakout Confirmation: Rapid channel widening confirms volatility increase and genuine trend establishment
 Entry Timing: Enter positions early in expansion phase before trend becomes overextended
 Risk Management: Use channel width to size stops appropriately, wider channels require wider stops
 
 Basis Bounce Pattern: 
 
 Clean Bounce: Price touches middle band and immediately reverses, confirms trend strength and entry opportunity
 Multiple Bounces: Repeated basis bounces indicate strong, sustainable trend
 Bounce Failure: Price penetrating basis signals weakening trend and potential reversal
 
 Divergence Analysis: 
 
 Price/Channel Divergence: Price makes new high/low while staying within channel (not reaching outer band), suggests momentum weakening
 Width/Price Divergence: Price breaks to new extremes but channel width contracts, suggests move lacks conviction
 Reversal Signal: Divergences often precede trend reversals or significant consolidation periods
 
 Multi-Timeframe Analysis: 
Keltner Channels work particularly well in multi-timeframe trend-following approaches:
 Three-Timeframe Alignment: 
 
 Higher Timeframe (Weekly/Daily): Identify major trend direction, note price position relative to basis and channels
 Intermediate Timeframe (Daily/4H): Identify pullback opportunities within higher timeframe trend
 Lower Timeframe (4H/1H): Time precise entries when price touches middle band or lower channel (in uptrends) with rejection
 
 Optimal Entry Conditions: 
 
 Best Long Entries: Higher timeframe in uptrend (price above basis), intermediate timeframe pulls back to basis, lower timeframe shows rejection at middle band or lower channel
 Best Short Entries: Higher timeframe in downtrend (price below basis), intermediate timeframe bounces to basis, lower timeframe shows rejection at middle band or upper channel
 Risk Management: Use higher timeframe channel width to set position sizing, stops below/above higher timeframe channels
 
 🎯 STRATEGIC APPLICATIONS 
Keltner Channel Enhanced excels in trend-following and breakout strategies across different market conditions.
 Trend Following Strategy: 
 Setup Requirements: 
 
 Identify established trend with price consistently on one side of basis line
 Wait for pullback to middle band (basis) or brief penetration through it
 Confirm trend resumption with price rejection at basis and move back toward outer channel
 Enter in trend direction with stop beyond basis line
 
 Entry Rules: 
 Uptrend Entry: 
 
 Price pulls back from upper channel to middle band, shows support at basis (bullish candlestick, momentum divergence)
 Enter long on rejection/bounce from basis with stop 1-2 ATR below basis
 Aggressive: Enter on first touch; Conservative: Wait for confirmation candle
 
 Downtrend Entry: 
 
 Price bounces from lower channel to middle band, shows resistance at basis (bearish candlestick, momentum divergence)
 Enter short on rejection/reversal from basis with stop 1-2 ATR above basis
 Aggressive: Enter on first touch; Conservative: Wait for confirmation candle
 
 Trend Management: 
 
 Trailing Stop: Use basis line as dynamic trailing stop, exit if price closes beyond basis against position
 Profit Taking: Take partial profits at opposite channel, move stops to basis
 Position Additions: Add to winners on subsequent basis bounces if trend intact
 
 Breakout Strategy: 
 Setup Requirements: 
 
 Identify consolidation period with contracting channel width
 Monitor price action near middle band with reduced volatility
 Wait for decisive breakout beyond channel range with expanding width
 Enter in breakout direction after confirmation
 
 Breakout Confirmation: 
 
 Price breaks clearly outside channel (upper for longs, lower for shorts), channel width begins expanding from contracted state
 Volume increases significantly on breakout (if using volume analysis)
 Price sustains outside channel for multiple bars without immediate reversal
 
 Entry Approaches: 
 
 Aggressive: Enter on initial break with stop at opposite channel or basis, use smaller position size
 Conservative: Wait for pullback to broken channel level, enter on rejection and resumption, tighter stop
 
 Volatility-Based Position Sizing: 
Adjust position sizing based on channel width (ATR-based volatility):
 
 Wide Channels (High ATR): Reduce position size as stops must be wider, calculate position size using ATR-based risk calculation: Risk / (Stop Distance in ATR × ATR Value)
 Narrow Channels (Low ATR): Increase position size as stops can be tighter, be cautious of impending volatility expansion
 ATR-Based Risk Management: Use ATR-based risk calculations, position size = 0.01 × Capital / (2 × ATR), use multiples of ATR (1-2 ATR) for adaptive stops
 
 Algorithm Selection Guidelines: 
Different market conditions benefit from different algorithm combinations:
 
 Strong Trending Markets: Middle band use EMA or HMA, ATR use RMA, capture trends quickly while maintaining stable channel width
 Choppy/Ranging Markets: Middle band use SMA or WMA, ATR use SMA or WMA, avoid false trend signals while identifying genuine reversals
 Volatile Markets: Middle band and ATR both use KAMA or FRAMA, self-adjusting to changing market conditions reduces manual optimization
 Breakout Trading: Middle band use SMA, ATR use EMA or SMA, stable trend with dynamic channels highlights volatility expansion early
 Scalping/Day Trading: Middle band use HMA or T3, ATR use EMA or TEMA, both components respond quickly
 Position Trading: Middle band use EMA/TEMA/T3, ATR use RMA or TEMA, filter out noise for long-term trend-following
 
 📋 DETAILED PARAMETER CONFIGURATION 
Understanding and optimizing parameters is essential for adapting Keltner Channel Enhanced to specific trading approaches.
 Source Parameter: 
 
 Close (Most Common): Uses closing price, reflects daily settlement, best for end-of-day analysis and position trading, standard choice
 HL2 (Median Price): Smooths out closing bias, better represents full daily range in volatile markets, good for swing trading
 HLC3 (Typical Price): Gives more weight to close while including full range, popular for intraday applications, slightly more responsive than HL2
 OHLC4 (Average Price): Most comprehensive price representation, smoothest option, good for gap-prone markets or highly volatile instruments
 
 Length Parameter: 
Controls the lookback period for middle band (basis) calculation:
 
 Short Periods (10-15): Very responsive to price changes, suitable for day trading and scalping, higher false signal rate
 Standard Period (20 - Default): Represents approximately one month of trading, good balance between responsiveness and stability, suitable for swing and position trading
 Medium Periods (30-50): Smoother trend identification, fewer false signals, better for position trading and longer holding periods
 Long Periods (50+): Very smooth, identifies major trends only, minimal false signals but significant lag, suitable for long-term investment
 
 Optimization by Timeframe:  1-15 minute charts use 10-20 period, 30-60 minute charts use 20-30 period, 4-hour to daily charts use 20-40 period, weekly charts use 20-30 weeks.
 ATR Length Parameter: 
Controls the lookback period for Average True Range calculation, affecting channel width:
 
 Short ATR Periods (5-10): Very responsive to recent volatility changes, standard is 10 (Keltner's original specification), may be too reactive in whipsaw conditions
 Standard ATR Period (10 - Default): Chester Keltner's original specification, good balance between responsiveness and stability, most widely used
 Medium ATR Periods (14-20): Smoother channel width, ATR 14 aligns with Wilder's original ATR specification, good for position trading
 Long ATR Periods (20+): Very smooth channel width, suitable for long-term trend-following
 
 Length vs. ATR Length Relationship:  Equal values (20/20) provide balanced responsiveness, longer ATR (20/14) gives more stable channel width, shorter ATR (20/10) is standard configuration, much shorter ATR (20/5) creates very dynamic channels.
 Multiplier Parameter: 
Controls channel width by setting ATR multiples:
 
 Lower Values (1.0-1.5): Tighter channels with frequent price touches, more trading signals, higher false signal rate, better for range-bound and mean-reversion strategies
 Standard Value (2.0 - Default): Chester Keltner's recommended setting, good balance between signal frequency and reliability, suitable for both trending and ranging strategies
 Higher Values (2.5-3.0): Wider channels with less frequent touches, fewer but potentially higher-quality signals, better for strong trending markets
 
 Market-Specific Optimization:  High volatility markets (crypto, small-caps) use 2.5-3.0 multiplier, medium volatility markets (major forex, large-caps) use 2.0 multiplier, low volatility markets (bonds, utilities) use 1.5-2.0 multiplier.
 MA Type Parameter (Middle Band): 
Critical selection that determines trend identification characteristics:
 
 EMA (Exponential Moving Average - Default): Standard Keltner Channel choice, Chester Keltner's original specification, emphasizes recent prices, faster response to trend changes, suitable for all timeframes
 SMA (Simple Moving Average): Equal weighting of all data points, no directional bias, slower than EMA, better for ranging markets and mean-reversion
 HMA (Hull Moving Average): Minimal lag with smooth output, excellent for fast trend identification, best for day trading and scalping
 TEMA (Triple Exponential Moving Average): Advanced smoothing with reduced lag, responsive to trends while filtering noise, suitable for volatile markets
 T3 (Tillson T3): Very smooth with minimal lag, excellent for established trend identification, suitable for position trading
 KAMA (Kaufman Adaptive Moving Average): Automatically adjusts speed based on market efficiency, slow in ranging markets, fast in trends, suitable for markets with varying conditions
 
 ATR MA Type Parameter: 
Determines how Average True Range is smoothed, affecting channel width stability:
 
 RMA (Wilder's Smoothing - Default): J. Welles Wilder's original ATR smoothing method, very smooth, slow to adapt to volatility changes, provides stable channel width
 SMA (Simple Moving Average): Equal weighting, moderate smoothness, faster response to volatility changes than RMA, more dynamic channel width
 EMA (Exponential Moving Average): Emphasizes recent volatility, quick adaptation to new volatility regimes, very responsive channel width changes
 TEMA (Triple Exponential Moving Average): Smooth yet responsive, good balance for varying volatility, suitable for most trading styles
 
 Parameter Combination Strategies: 
 
 Conservative Trend-Following: Length 30/ATR Length 20/Multiplier 2.5, MA Type EMA or TEMA/ATR MA Type RMA, smooth trend with stable wide channels, suitable for position trading
 Standard Balanced Approach: Length 20/ATR Length 10/Multiplier 2.0, MA Type EMA/ATR MA Type RMA, classic Keltner Channel configuration, suitable for general purpose swing trading
 Aggressive Day Trading: Length 10-15/ATR Length 5-7/Multiplier 1.5-2.0, MA Type HMA or EMA/ATR MA Type EMA or SMA, fast trend with dynamic channels, suitable for scalping and day trading
 Breakout Specialist: Length 20-30/ATR Length 5-10/Multiplier 2.0, MA Type SMA or WMA/ATR MA Type EMA or SMA, stable trend with responsive channel width
 Adaptive All-Conditions: Length 20/ATR Length 10/Multiplier 2.0, MA Type KAMA or FRAMA/ATR MA Type KAMA or TEMA, self-adjusting to market conditions
 
 Offset Parameter: 
Controls horizontal positioning of channels on chart. Positive values shift channels to the right (future) for visual projection, negative values shift left (past) for historical analysis, zero (default) aligns with current price bars for real-time signal analysis. Offset affects only visual display, not alert conditions or actual calculations.
 📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES 
Keltner Channel Enhanced provides improvements over standard implementations while maintaining proven effectiveness.
 Response Characteristics: 
 
 Standard EMA/RMA Configuration: Moderate trend lag (approximately 0.4 × length periods), smooth and stable channel width from RMA smoothing, good balance for most market conditions
 Fast HMA/EMA Configuration: Approximately 60% reduction in trend lag compared to EMA, responsive channel width from EMA ATR smoothing, suitable for quick trend changes and breakouts
 Adaptive KAMA/KAMA Configuration: Variable lag based on market efficiency, automatic adjustment to trending vs. ranging conditions, self-optimizing behavior reduces manual intervention
 
 Comparison with Traditional Keltner Channels: 
 Enhanced Version Advantages: 
 
 Dual Algorithm Flexibility: Independent MA selection for trend and volatility vs. fixed EMA/RMA, separate tuning of trend responsiveness and channel stability
 Market Adaptation: Choose configurations optimized for specific instruments and conditions, customize for scalping, swing, or position trading preferences
 Comprehensive Alerts: Enhanced alert system including channel expansion detection
 
 Traditional Version Advantages: 
 
 Simplicity: Fewer parameters, easier to understand and implement
 Standardization: Fixed EMA/RMA combination ensures consistency across users
 Research Base: Decades of backtesting and research on standard configuration
 
 When to Use Enhanced Version:  Trading multiple instruments with different characteristics, switching between trending and ranging markets, employing different strategies, algorithm-based trading systems requiring customization, seeking optimization for specific trading style and timeframe.
 When to Use Standard Version:  Beginning traders learning Keltner Channel concepts, following published research or trading systems, preferring simplicity and standardization, wanting to avoid optimization and curve-fitting risks.
 Performance Across Market Conditions: 
 
 Strong Trending Markets: EMA or HMA basis with RMA or TEMA ATR smoothing provides quicker trend identification, pullbacks to basis offer excellent entry opportunities
 Choppy/Ranging Markets: SMA or WMA basis with RMA ATR smoothing and lower multipliers, channel bounce strategies work well, avoid false breakouts
 Volatile Markets: KAMA or FRAMA with EMA or TEMA, adaptive algorithms excel by automatic adjustment, wider multipliers (2.5-3.0) accommodate large price swings
 Low Volatility/Consolidation: Channels narrow significantly indicating consolidation, algorithm choice less impactful, focus on detecting channel width contraction for breakout preparation
 
 Keltner Channel vs. Bollinger Bands - Usage Comparison: 
 Favor Keltner Channels When:  Trend-following is primary strategy, trading volatile instruments with gaps, want ATR-based volatility measurement, prefer fewer higher-quality channel touches, seeking stable channel width during trends.
 Favor Bollinger Bands When:  Mean-reversion is primary strategy, trading instruments with limited gaps, want statistical framework based on standard deviation, need squeeze patterns for breakout identification, prefer more frequent trading opportunities.
 Use Both Together:  Bollinger Band squeeze + Keltner Channel breakout is powerful combination, price outside Bollinger Bands but inside Keltner Channels indicates moderate signal, price outside both indicates very strong signal, Bollinger Bands for entries and Keltner Channels for trend confirmation.
 Limitations and Considerations: 
 General Limitations: 
 
 Lagging Indicator: All moving averages lag price, even with reduced-lag algorithms
 Trend-Dependent: Works best in trending markets, less effective in choppy conditions
 No Direction Prediction: Indicates volatility and deviation, not future direction, requires confirmation
 
 Enhanced Version Specific Considerations: 
 
 Optimization Risk: More parameters increase risk of curve-fitting historical data
 Complexity: Additional choices may overwhelm beginning traders
 Backtesting Challenges: Different algorithms produce different historical results
 
 Mitigation Strategies: 
 
 Use Confirmation: Combine with momentum indicators (RSI, MACD), volume, or price action
 Test Parameter Robustness: Ensure parameters work across range of values, not just optimized ones
 Multi-Timeframe Analysis: Confirm signals across different timeframes
 Proper Risk Management: Use appropriate position sizing and stops
 Start Simple: Begin with standard EMA/RMA before exploring alternatives
 
 Optimal Usage Recommendations: 
 For Maximum Effectiveness: 
 
 Start with standard EMA/RMA configuration to understand classic behavior
 Experiment with alternatives on demo account or paper trading
 Match algorithm combination to market condition and trading style
 Use channel width analysis to identify market phases
 Combine with complementary indicators for confirmation
 Implement strict risk management using ATR-based position sizing
 Focus on high-quality setups rather than trading every signal
 Respect the trend: trade with basis direction for higher probability
 
 Complementary Indicators: 
 
 RSI or Stochastic: Confirm momentum at channel extremes
 MACD: Confirm trend direction and momentum shifts
 Volume: Validate breakouts and trend strength
 ADX: Measure trend strength, avoid Keltner signals in weak trends
 Support/Resistance: Combine with traditional levels for high-probability setups
 Bollinger Bands: Use together for enhanced breakout and volatility analysis
 
 USAGE NOTES 
This indicator is designed for technical analysis and educational purposes. Keltner Channel Enhanced has limitations and should not be used as the sole basis for trading decisions. While the flexible moving average selection for both trend and volatility components provides valuable adaptability across different market conditions, algorithm performance varies with market conditions, and past characteristics do not guarantee future results.
Key considerations:
 
 Always use multiple forms of analysis and confirmation before entering trades
 Backtest any parameter combination thoroughly before live trading
 Be aware that optimization can lead to curve-fitting if not done carefully
 Start with standard EMA/RMA settings and adjust only when specific conditions warrant
 Understand that no moving average algorithm can eliminate lag entirely
 Consider market regime (trending, ranging, volatile) when selecting parameters
 Use ATR-based position sizing and risk management on every trade
 Keltner Channels work best in trending markets, less effective in choppy conditions
 Respect the trend direction indicated by price position relative to basis line
 
The enhanced flexibility of dual algorithm selection provides powerful tools for adaptation but requires responsible use, thorough understanding of how different algorithms behave under various market conditions, and disciplined risk management.






















